text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Portfolio.Shared.ViewModels
{
public class TechnologyViewModel
{
public TechnologyViewModel() { }
public TechnologyViewModel(Technology technology)
{
Id = technology.Id;
Name = technology.Name;
Slug = technology.Slug;
Projects = technology.ProjectTechnologies
.Select(pt => new BasicProject(pt.Project))
.ToList();
}
public int Id { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public IList<BasicProject> Projects { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatternsApp.FoodCostTaxCalculator
{
public interface IDeliveryTaxCalculator
{
double CalculateTax(double price);
}
}
|
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using Discord;
using System.Text.RegularExpressions;
using Discord.WebSocket;
using System.Timers;
using LucaasBetterBot;
namespace LucaasBetterBot.Modules
{
public class ModDatabase : ModuleBase<SocketCommandContext>
{
static string ModLogsPath = $"{Environment.CurrentDirectory}\\Data\\Modlogs.json";
static internal System.Timers.Timer autoSlowmode = new System.Timers.Timer() { Enabled = false, AutoReset = true, Interval = 1000 };
static ModlogsJson currentLogs { get; set; }
static Dictionary<ulong, int> sList = new Dictionary<ulong, int>();
static DiscordSocketClient _client;
static Dictionary<ulong, int> currentSlowmodeList = new Dictionary<ulong, int>();
public static async Task Start(SocketGuild guild, DiscordSocketClient client)
{
currentLogs = new ModlogsJson() { Users = new List<User>() };
_client = client;
if (!File.Exists(ModLogsPath)) { File.Create(ModLogsPath).Close(); }
//load logs
currentLogs = LoadModLogs();
//create muted role if it doesnt exist
//change text channel perms for muted role if not set
client.MessageReceived += AutoSlowmode;
//autoSlowmode.Enabled = true;
autoSlowmode.Elapsed += AutoSlowmode_Elapsed;
}
private static async void AutoSlowmode_Elapsed(object sender, ElapsedEventArgs e)
{
if (Global.AutoSlowmodeToggle)
{
foreach (var item in sList.ToList())
{
if (item.Value >= Global.AutoSlowmodeTrigger)
{
var chan = _client.GetGuild(Global.GuildID).GetTextChannel(item.Key);
var aChan = _client.GetGuild(Global.GuildID).GetTextChannel(664606058592993281);
var mLink = await chan.GetMessagesAsync(1).FlattenAsync();
if (chan.SlowModeInterval > 0) //the channel has slowmode already
{
if (currentSlowmodeList.Keys.Contains(chan.Id))
currentSlowmodeList[chan.Id] = currentSlowmodeList[chan.Id] + 5;
else
currentSlowmodeList.Add(chan.Id, chan.SlowModeInterval);
}
EmbedBuilder b = new EmbedBuilder()
{
Color = Color.Orange,
Title = "Auto Alert",
Fields = new List<EmbedFieldBuilder>() { { new EmbedFieldBuilder() { Name = "Reason", Value = $"Message limit of {Global.AutoSlowmodeTrigger}/sec reached" } }, { new EmbedFieldBuilder() { Name = "Channel", Value = $"<#{chan.Id}>" } }, { new EmbedFieldBuilder() { Name = "Message Link", Value = mLink.First().GetJumpUrl() } } }
};
if (chan.SlowModeInterval >= 5)
await chan.ModifyAsync(x => x.SlowModeInterval = 5 + chan.SlowModeInterval);
else
await chan.ModifyAsync(x => x.SlowModeInterval = 5);
await aChan.SendMessageAsync("", false, b.Build());
System.Timers.Timer lt = new System.Timers.Timer()
{
Interval = 60000,
};
sList.Remove(item.Key);
lt.Enabled = true;
lt.Elapsed += (object s, ElapsedEventArgs arg) =>
{
if (currentSlowmodeList.Keys.Contains(chan.Id))
chan.ModifyAsync(x => x.SlowModeInterval = currentSlowmodeList[chan.Id]);
else
chan.ModifyAsync(x => x.SlowModeInterval = 0);
};
}
else
{
sList[item.Key] = 0;
sList.Remove(item.Key);
}
}
}
}
private static async Task AutoSlowmode(SocketMessage arg)
{
if (sList.ContainsKey(arg.Channel.Id))
{
sList[arg.Channel.Id]++;
}
else
{
sList.Add(arg.Channel.Id, 1);
}
}
static ModlogsJson LoadModLogs()
{
try
{
var d = JsonConvert.DeserializeObject<ModlogsJson>(File.ReadAllText(ModLogsPath));
if(d == null) { throw new Exception(); }
return d;
}
catch(Exception ex)
{
return new ModlogsJson() { Users = new List<User>() };
}
}
static public void SaveModLogs()
{
string json = JsonConvert.SerializeObject(currentLogs, Formatting.Indented);
File.WriteAllText(ModLogsPath, json);
}
public class ModlogsJson
{
public List<User> Users { get; set; }
}
public class User
{
public List<UserModLogs> Logs { get; set; }
public ulong userId { get; set; }
public string username { get; set; }
}
public class UserModLogs
{
public string Reason { get; set; }
public Action Action { get; set; }
public ulong ModeratorID { get; set; }
public string Date { get; set; }
}
public enum Action
{
Warned,
Kicked,
Banned,
Muted
}
static async Task AddModlogs(ulong userID, Action action, ulong ModeratorID, string reason, string username)
{
if(currentLogs.Users.Any(x => x.userId == userID))
{
currentLogs.Users[currentLogs.Users.FindIndex(x => x.userId == userID)].Logs.Add(new UserModLogs()
{
Action = action,
ModeratorID = ModeratorID,
Reason = reason,
Date = DateTime.UtcNow.ToString("r")
});
}
else
{
currentLogs.Users.Add(new User()
{
Logs = new List<UserModLogs>()
{
{ new UserModLogs(){
Action = action,
ModeratorID = ModeratorID,
Reason = reason,
Date = DateTime.UtcNow.ToString("r")
} }
},
userId = userID,
username = username
});
}
SaveModLogs();
}
public async Task<bool> HasPerms(SocketGuildUser user)
{
if (user.Guild.GetRole(Global.ModeratorRoleID).Position <= user.Hierarchy)
return true;
else
return false;
}
public async Task CreateAction(string[] args, Action type, SocketCommandContext curContext)
{
if (!HasPerms(curContext.Guild.GetUser(curContext.Message.Author.Id)).Result)
{
await curContext.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "You do not have permission to execute this command",
Description = "You do not have the valid permission to execute this command",
Color = Color.Red
}.Build());
return;
}
string typeName = Enum.GetName(typeof(Action), type);
string user, reason;
if (args.Length == 1)
{
await curContext.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Give me a reason!",
Description = "You need to provide a reason",
Color = Color.Red
}.Build());
}
if (args.Length == 0)
{
await curContext.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = $"Who do you want to {typeName}?",
Description = "Mention someone or provide an id!",
Color = Color.Red
}.Build());
}
if (args.Length > 1)
{
user = args[0];
reason = string.Join(' ', args).Replace(user + " ", "");
Regex r = new Regex("(\\d{18})");
if (!r.IsMatch(user))
{
await curContext.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Invalid ID",
Description = "The ID you provided is invalid!",
Color = Color.Red
}.Build());
return;
}
ulong id;
try
{
id = Convert.ToUInt64(r.Match(user).Groups[1].Value);
}
catch(Exception ex)
{
await curContext.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Invalid ID",
Description = "The ID you provided is invalid!",
Color = Color.Red
}.Build());
return;
}
var usr = curContext.Guild.GetUser(id);
if (usr == null)
{
await curContext.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Invalid ID",
Description = "The ID you provided is invalid!",
Color = Color.Red
}.Build());
return;
}
await AddModlogs(id, type, curContext.Message.Author.Id, reason, usr.ToString());
Embed b = new EmbedBuilder()
{
Title = $"You have been **{typeName}** on **{curContext.Guild.Name}**",
Fields = new List<EmbedFieldBuilder>()
{
{ new EmbedFieldBuilder(){
Name = "Moderator",
Value = curContext.Message.Author.ToString(),
IsInline = true
} },
{new EmbedFieldBuilder()
{
Name = "Reason",
Value = reason,
IsInline = true
} }
}
}.Build();
Embed b2 = new EmbedBuilder()
{
Title = $"Successfully **{typeName}** user **{usr.ToString()}**",
Fields = new List<EmbedFieldBuilder>()
{
{ new EmbedFieldBuilder(){
Name = "Moderator",
Value = curContext.Message.Author.ToString(),
IsInline = true
} },
{new EmbedFieldBuilder()
{
Name = "Reason",
Value = reason,
IsInline = true
} }
}
}.Build();
await usr.SendMessageAsync("", false, b);
await curContext.Channel.SendMessageAsync("", false, b2);
if (type is Action.Kicked)
await usr.KickAsync(reason);
if (type is Action.Banned)
await usr.BanAsync(7, reason);
}
}
[Command("warn")]
public async Task warn(params string[] args)
{
await CreateAction(args, Action.Warned, Context);
}
[Command("kick")]
public async Task kick(params string[] args)
{
await CreateAction(args, Action.Kicked, Context);
}
[Command("ban")]
public async Task ban(params string[] args)
{
await CreateAction(args, Action.Banned, Context);
}
[Command("mute")]
public async Task mute(params string[] args)
{
if (!HasPerms(Context.Guild.GetUser(Context.Message.Author.Id)).Result)
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "You do not have permission to execute this command",
Description = "You do not have the valid permission to execute this command",
Color = Color.Red
}.Build());
return;
}
if(args.Length == 1)
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Give me a time!",
Description = $"if you wanted to mute for 10 minutes use `{Global.Prefix}mute <user> 10m`",
Color = Color.Red
}.Build());
return;
}
if(args.Length == 2)
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Give me a Reason!",
Description = $"You need to provide a reason",
Color = Color.Red
}.Build());
return;
}
if(args.Length > 2)
{
string[] formats = { @"h\h", @"s\s", @"m\m\ s\s", @"h\h\ m\m\ s\s", @"m\m", @"h\h\ m\m" };
string user, time, reason;
user = args[0];
time = args[1];
Regex r = new Regex("(\\d{18})");
if (!r.IsMatch(user))
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Invalid ID",
Description = "The ID you provided is invalid!",
Color = Color.Red
}.Build());
return;
}
ulong id;
try
{
id = Convert.ToUInt64(r.Match(user).Groups[1].Value);
}
catch (Exception ex)
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Invalid ID",
Description = "The ID you provided is invalid!",
Color = Color.Red
}.Build());
return;
}
var usr = Context.Guild.GetUser(id);
reason = string.Join(' ', args).Replace($"{user} {time} ", "");
TimeSpan t = TimeSpan.ParseExact(time, formats, null);
Timer tmr = new Timer()
{
AutoReset = false,
Interval = t.TotalMilliseconds
};
string guildName = Context.Guild.Name;
await usr.AddRoleAsync(Context.Guild.GetRole(Global.MutedRoleID));
tmr.Elapsed += async (object send, ElapsedEventArgs arg) =>
{
try
{
await usr.RemoveRoleAsync(Context.Guild.GetRole(Global.MutedRoleID));
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
await usr.SendMessageAsync($"**You have been unmuted on {guildName}**");
};
Embed b = new EmbedBuilder()
{
Title = $"You have been **Muted** on **{guildName}** for **{t.ToString()}",
Fields = new List<EmbedFieldBuilder>()
{
{ new EmbedFieldBuilder(){
Name = "Moderator",
Value = Context.Message.Author.ToString(),
IsInline = true
} },
{new EmbedFieldBuilder()
{
Name = "Reason",
Value = reason,
IsInline = true
} }
}
}.Build();
await usr.SendMessageAsync("", false, b);
await AddModlogs(id, Action.Muted, Context.Message.Author.Id, reason, usr.ToString());
tmr.Enabled = true;
}
}
[Command("modlogs")]
public async Task Modlogs(string mention)
{
if (!HasPerms(Context.Guild.GetUser(Context.Message.Author.Id)).Result)
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "You do not have permission to execute this command",
Description = "You do not have the valid permission to execute this command",
Color = Color.Red
}.Build());
return;
}
Regex r = new Regex("(\\d{18})");
ulong id;
try
{
id = Convert.ToUInt64(r.Match(mention).Groups[1].Value);
}
catch(Exception ex)
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = "Invalid ID",
Description = "The ID you provided is invalid!",
Color = Color.Red
}.Build());
return;
}
//var user = Context.Guild.GetUser(id);
//if (user == null)
//{
// await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
// {
// Title = "Invalad ID",
// Description = "The ID you provided is invalad!",
// Color = Color.Red
// }.Build());
// return;
//}
if (currentLogs.Users.Any(x => x.userId == id))
{
var user = currentLogs.Users[currentLogs.Users.FindIndex(x => x.userId == id)];
var logs = user.Logs;
EmbedBuilder b = new EmbedBuilder()
{
Title = $"Modlogs for **{user.username}** ({id})",
Color = Color.Green,
Fields = new List<EmbedFieldBuilder>()
};
foreach(var log in logs)
{
b.Fields.Add(new EmbedFieldBuilder()
{
IsInline = false,
Name = Enum.GetName(typeof(Action), log.Action),
Value = $"Reason: {log.Reason}\nModerator: <@{log.ModeratorID}>\nDate: {log.Date}"
});
}
await Context.Channel.SendMessageAsync("", false, b.Build());
}
else
{
await Context.Channel.SendMessageAsync("", false, new Discord.EmbedBuilder()
{
Title = $"Modlogs for ({id})",
Description = "This user has no logs! :D",
Color = Color.Green
}.Build());
return;
}
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace streamdeck_client_csharp.Events
{
public class KeyPayload
{
[JsonProperty("settings")]
public JObject Settings { get; private set; }
[JsonProperty("coordinates")]
public Coordinates Coordinates { get; private set; }
[JsonProperty("state")]
public uint State { get; private set; }
[JsonProperty("userDesiredState")]
public uint UserDesiredState { get; private set; }
[JsonProperty("isInMultiAction")]
public bool IsInMultiAction { get; private set; }
}
}
|
#if !EXCLUDE_CODEGEN
#pragma warning disable 162
#pragma warning disable 219
#pragma warning disable 414
#pragma warning disable 649
#pragma warning disable 693
#pragma warning disable 1591
#pragma warning disable 1998
[assembly: global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.1.0.0")]
[assembly: global::Orleans.CodeGeneration.OrleansCodeGenerationTargetAttribute("MWMROrleansGrains, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")]
namespace MWMROrleansGrains
{
using global::Orleans.Async;
using global::Orleans;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.1.0.0"), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.SerializerAttribute(typeof (global::MWMROrleansGrains.StatefulGrainState)), global::Orleans.CodeGeneration.RegisterSerializerAttribute]
internal class OrleansCodeGenMWMROrleansGrains_StatefulGrainStateSerializer
{
private static readonly global::System.Reflection.FieldInfo field0 = typeof (global::MWMROrleansGrains.StatefulGrainState).@GetField("currentContext", (System.@Reflection.@BindingFlags.@Public | System.@Reflection.@BindingFlags.@NonPublic | System.@Reflection.@BindingFlags.@Instance));
private static readonly global::System.Func<global::MWMROrleansGrains.StatefulGrainState, global::MWMROrleansInterfaces.Context> getField0 = (global::System.Func<global::MWMROrleansGrains.StatefulGrainState, global::MWMROrleansInterfaces.Context>)global::Orleans.Serialization.SerializationManager.@GetGetter(field0);
private static readonly global::System.Action<global::MWMROrleansGrains.StatefulGrainState, global::MWMROrleansInterfaces.Context> setField0 = (global::System.Action<global::MWMROrleansGrains.StatefulGrainState, global::MWMROrleansInterfaces.Context>)global::Orleans.Serialization.SerializationManager.@GetReferenceSetter(field0);
[global::Orleans.CodeGeneration.CopierMethodAttribute]
public static global::System.Object DeepCopier(global::System.Object original)
{
global::MWMROrleansGrains.StatefulGrainState input = ((global::MWMROrleansGrains.StatefulGrainState)original);
global::MWMROrleansGrains.StatefulGrainState result = new global::MWMROrleansGrains.StatefulGrainState();
result.@Etag = input.@Etag;
result.@Prefs = input.@Prefs;
result.@readers = input.@readers;
result.@writers = input.@writers;
setField0(result, getField0(input));
global::Orleans.@Serialization.@SerializationContext.@Current.@RecordObject(original, result);
return result;
}
[global::Orleans.CodeGeneration.SerializerMethodAttribute]
public static void Serializer(global::System.Object untypedInput, global::Orleans.Serialization.BinaryTokenStreamWriter stream, global::System.Type expected)
{
global::MWMROrleansGrains.StatefulGrainState input = (global::MWMROrleansGrains.StatefulGrainState)untypedInput;
global::Orleans.Serialization.SerializationManager.@SerializeInner(input.@Etag, stream, typeof (global::System.String));
global::Orleans.Serialization.SerializationManager.@SerializeInner(input.@Prefs, stream, typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::System.String>));
global::Orleans.Serialization.SerializationManager.@SerializeInner(input.@readers, stream, typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::MWMROrleansInterfaces.ConsistencyLevel>));
global::Orleans.Serialization.SerializationManager.@SerializeInner(input.@writers, stream, typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::MWMROrleansInterfaces.ConsistencyLevel>));
global::Orleans.Serialization.SerializationManager.@SerializeInner(getField0(input), stream, typeof (global::MWMROrleansInterfaces.Context));
}
[global::Orleans.CodeGeneration.DeserializerMethodAttribute]
public static global::System.Object Deserializer(global::System.Type expected, global::Orleans.Serialization.BinaryTokenStreamReader stream)
{
global::MWMROrleansGrains.StatefulGrainState result = new global::MWMROrleansGrains.StatefulGrainState();
global::Orleans.@Serialization.@DeserializationContext.@Current.@RecordObject(result);
result.@Etag = (global::System.String)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.String), stream);
result.@Prefs = (global::System.Collections.Generic.IDictionary<global::System.String, global::System.String>)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::System.String>), stream);
result.@readers = (global::System.Collections.Generic.IDictionary<global::System.String, global::MWMROrleansInterfaces.ConsistencyLevel>)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::MWMROrleansInterfaces.ConsistencyLevel>), stream);
result.@writers = (global::System.Collections.Generic.IDictionary<global::System.String, global::MWMROrleansInterfaces.ConsistencyLevel>)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::MWMROrleansInterfaces.ConsistencyLevel>), stream);
setField0(result, (global::MWMROrleansInterfaces.Context)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::MWMROrleansInterfaces.Context), stream));
return (global::MWMROrleansGrains.StatefulGrainState)result;
}
public static void Register()
{
global::Orleans.Serialization.SerializationManager.@Register(typeof (global::MWMROrleansGrains.StatefulGrainState), DeepCopier, Serializer, Deserializer);
}
static OrleansCodeGenMWMROrleansGrains_StatefulGrainStateSerializer()
{
Register();
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.1.0.0"), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.SerializerAttribute(typeof (global::MWMROrleansInterfaces.Context)), global::Orleans.CodeGeneration.RegisterSerializerAttribute]
internal class OrleansCodeGenMWMROrleansInterfaces_ContextSerializer
{
private static readonly global::System.Reflection.FieldInfo field1 = typeof (global::MWMROrleansInterfaces.Context).@GetField("id", (System.@Reflection.@BindingFlags.@Public | System.@Reflection.@BindingFlags.@NonPublic | System.@Reflection.@BindingFlags.@Instance));
private static readonly global::System.Func<global::MWMROrleansInterfaces.Context, global::System.Int64> getField1 = (global::System.Func<global::MWMROrleansInterfaces.Context, global::System.Int64>)global::Orleans.Serialization.SerializationManager.@GetGetter(field1);
private static readonly global::Orleans.Serialization.SerializationManager.ValueTypeSetter<global::MWMROrleansInterfaces.Context, global::System.Int64> setField1 = (global::Orleans.Serialization.SerializationManager.ValueTypeSetter<global::MWMROrleansInterfaces.Context, global::System.Int64>)global::Orleans.Serialization.SerializationManager.@GetValueSetter(field1);
private static readonly global::System.Reflection.FieldInfo field0 = typeof (global::MWMROrleansInterfaces.Context).@GetField("timestamp", (System.@Reflection.@BindingFlags.@Public | System.@Reflection.@BindingFlags.@NonPublic | System.@Reflection.@BindingFlags.@Instance));
private static readonly global::System.Func<global::MWMROrleansInterfaces.Context, global::System.DateTime> getField0 = (global::System.Func<global::MWMROrleansInterfaces.Context, global::System.DateTime>)global::Orleans.Serialization.SerializationManager.@GetGetter(field0);
private static readonly global::Orleans.Serialization.SerializationManager.ValueTypeSetter<global::MWMROrleansInterfaces.Context, global::System.DateTime> setField0 = (global::Orleans.Serialization.SerializationManager.ValueTypeSetter<global::MWMROrleansInterfaces.Context, global::System.DateTime>)global::Orleans.Serialization.SerializationManager.@GetValueSetter(field0);
[global::Orleans.CodeGeneration.CopierMethodAttribute]
public static global::System.Object DeepCopier(global::System.Object original)
{
global::MWMROrleansInterfaces.Context input = ((global::MWMROrleansInterfaces.Context)original);
global::MWMROrleansInterfaces.Context result = default (global::MWMROrleansInterfaces.Context);
setField1(ref result, getField1(input));
setField0(ref result, getField0(input));
global::Orleans.@Serialization.@SerializationContext.@Current.@RecordObject(original, result);
return result;
}
[global::Orleans.CodeGeneration.SerializerMethodAttribute]
public static void Serializer(global::System.Object untypedInput, global::Orleans.Serialization.BinaryTokenStreamWriter stream, global::System.Type expected)
{
global::MWMROrleansInterfaces.Context input = (global::MWMROrleansInterfaces.Context)untypedInput;
global::Orleans.Serialization.SerializationManager.@SerializeInner(getField1(input), stream, typeof (global::System.Int64));
global::Orleans.Serialization.SerializationManager.@SerializeInner(getField0(input), stream, typeof (global::System.DateTime));
}
[global::Orleans.CodeGeneration.DeserializerMethodAttribute]
public static global::System.Object Deserializer(global::System.Type expected, global::Orleans.Serialization.BinaryTokenStreamReader stream)
{
global::MWMROrleansInterfaces.Context result = default (global::MWMROrleansInterfaces.Context);
setField1(ref result, (global::System.Int64)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Int64), stream));
setField0(ref result, (global::System.DateTime)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.DateTime), stream));
return (global::MWMROrleansInterfaces.Context)result;
}
public static void Register()
{
global::Orleans.Serialization.SerializationManager.@Register(typeof (global::MWMROrleansInterfaces.Context), DeepCopier, Serializer, Deserializer);
}
static OrleansCodeGenMWMROrleansInterfaces_ContextSerializer()
{
Register();
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "1.1.0.0"), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.SerializerAttribute(typeof (global::MWMROrleansGrains.WITWDMetadataGrainState)), global::Orleans.CodeGeneration.RegisterSerializerAttribute]
internal class OrleansCodeGenMWMROrleansGrains_WITWDMetadataGrainStateSerializer
{
private static readonly global::System.Reflection.FieldInfo field0 = typeof (global::MWMROrleansGrains.WITWDMetadataGrainState).@GetField("numInstances", (System.@Reflection.@BindingFlags.@Public | System.@Reflection.@BindingFlags.@NonPublic | System.@Reflection.@BindingFlags.@Instance));
private static readonly global::System.Func<global::MWMROrleansGrains.WITWDMetadataGrainState, global::System.Int32> getField0 = (global::System.Func<global::MWMROrleansGrains.WITWDMetadataGrainState, global::System.Int32>)global::Orleans.Serialization.SerializationManager.@GetGetter(field0);
private static readonly global::System.Action<global::MWMROrleansGrains.WITWDMetadataGrainState, global::System.Int32> setField0 = (global::System.Action<global::MWMROrleansGrains.WITWDMetadataGrainState, global::System.Int32>)global::Orleans.Serialization.SerializationManager.@GetReferenceSetter(field0);
[global::Orleans.CodeGeneration.CopierMethodAttribute]
public static global::System.Object DeepCopier(global::System.Object original)
{
global::MWMROrleansGrains.WITWDMetadataGrainState input = ((global::MWMROrleansGrains.WITWDMetadataGrainState)original);
global::MWMROrleansGrains.WITWDMetadataGrainState result = new global::MWMROrleansGrains.WITWDMetadataGrainState();
result.@Etag = input.@Etag;
result.@replicas = input.@replicas;
setField0(result, getField0(input));
global::Orleans.@Serialization.@SerializationContext.@Current.@RecordObject(original, result);
return result;
}
[global::Orleans.CodeGeneration.SerializerMethodAttribute]
public static void Serializer(global::System.Object untypedInput, global::Orleans.Serialization.BinaryTokenStreamWriter stream, global::System.Type expected)
{
global::MWMROrleansGrains.WITWDMetadataGrainState input = (global::MWMROrleansGrains.WITWDMetadataGrainState)untypedInput;
global::Orleans.Serialization.SerializationManager.@SerializeInner(input.@Etag, stream, typeof (global::System.String));
global::Orleans.Serialization.SerializationManager.@SerializeInner(input.@replicas, stream, typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::System.DateTime>));
global::Orleans.Serialization.SerializationManager.@SerializeInner(getField0(input), stream, typeof (global::System.Int32));
}
[global::Orleans.CodeGeneration.DeserializerMethodAttribute]
public static global::System.Object Deserializer(global::System.Type expected, global::Orleans.Serialization.BinaryTokenStreamReader stream)
{
global::MWMROrleansGrains.WITWDMetadataGrainState result = new global::MWMROrleansGrains.WITWDMetadataGrainState();
global::Orleans.@Serialization.@DeserializationContext.@Current.@RecordObject(result);
result.@Etag = (global::System.String)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.String), stream);
result.@replicas = (global::System.Collections.Generic.IDictionary<global::System.String, global::System.DateTime>)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Collections.Generic.IDictionary<global::System.String, global::System.DateTime>), stream);
setField0(result, (global::System.Int32)global::Orleans.Serialization.SerializationManager.@DeserializeInner(typeof (global::System.Int32), stream));
return (global::MWMROrleansGrains.WITWDMetadataGrainState)result;
}
public static void Register()
{
global::Orleans.Serialization.SerializationManager.@Register(typeof (global::MWMROrleansGrains.WITWDMetadataGrainState), DeepCopier, Serializer, Deserializer);
}
static OrleansCodeGenMWMROrleansGrains_WITWDMetadataGrainStateSerializer()
{
Register();
}
}
}
#pragma warning restore 162
#pragma warning restore 219
#pragma warning restore 414
#pragma warning restore 649
#pragma warning restore 693
#pragma warning restore 1591
#pragma warning restore 1998
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareAuthKeyLoader.Kmm
{
public enum Status : byte
{
CommandWasPerformed,
CommandCouldNotBePerformed,
ItemDoesNotExist,
InvalidMessageId,
InvalidChecksumOrMac,
OutOfMemory,
CouldNotDecryptMessage,
InvalidMessageNumber,
InvalidKeyId,
InvalidAlgorithmId,
InvalidMfId,
ModuleFailure,
MiAllZeros,
Keyfail,
InvalidWacnIdOrSystemId,
InvalidSubscriberId,
Unknown = 0xFF
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Kingdee.CAPP.Solidworks.RoutingPlugIn
{
public partial class NewProcess : Form
{
private string _routingId;
RoutingProcessRelationContext rprConext = null;
public event EventHandler<ProcessEventArgs> AddProcess;
public NewProcess(string routingId)
{
InitializeComponent();
_routingId = routingId;
rprConext = new RoutingProcessRelationContext(DbConfig.Connection);
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Dispose();
GC.Collect();
}
private void btnConfirm_Click(object sender, EventArgs e)
{
CProcess cprocess = new CProcess();
cprocess.OperId = Guid.NewGuid().ToString();
cprocess.Name = tbxProcessName.Text.Trim();
cprocess.Code = tbxProcessCode.Text.Trim();
cprocess.CreateDate = DateTime.Now.ToString();
cprocess.Creator = "FFB0AC2D-C1B5-49E2-89B2-F4058523DF18";
cprocess.Remark = "";
cprocess.UpdateDate = DateTime.Now.ToString();
cprocess.UpdatePerson = "FFB0AC2D-C1B5-49E2-89B2-F4058523DF18";
RoutingProcessRelation routingProcessRelation = new RoutingProcessRelation();
routingProcessRelation.RelationId = Guid.NewGuid().ToString();
routingProcessRelation.OperId = cprocess.OperId;
routingProcessRelation.RoutingId = _routingId;
routingProcessRelation.Seq = 1;
routingProcessRelation.WorkcenterId = "";
routingProcessRelation.Persons = 1;
routingProcessRelation.ProcessTime = 0;
routingProcessRelation.ProcessTimeUnit = 1;
routingProcessRelation.LaborCosts = "0";
routingProcessRelation.OperCosts = "";
routingProcessRelation.ProcessCosts = "0";
routingProcessRelation.Creator = "FFB0AC2D-C1B5-49E2-89B2-F4058523DF18";
routingProcessRelation.CreateDate = DateTime.Now.ToString();
routingProcessRelation.UpdateDate = DateTime.Now.ToString();
routingProcessRelation.UpdatePerson = "FFB0AC2D-C1B5-49E2-89B2-F4058523DF18";
try
{
rprConext.Processes.InsertOnSubmit(cprocess);
rprConext.RoutingProcessRelation.InsertOnSubmit(routingProcessRelation);
rprConext.SubmitChanges();
MessageBox.Show("新增工序成功!");
this.Close();
/// 新增工序到右边工序树下
if (ProcessLine.CurrentProcessLine != null)
{
AddProcess += new EventHandler<ProcessEventArgs>(ProcessLine.CurrentProcessLine.CurrentProcess_AddProcess);
}
/************************************************************************/
/* 触发事件
/************************************************************************/
if(AddProcess != null)
{
AddProcess(this, new ProcessEventArgs()
{
ProcessName = tbxProcessName.Text.Trim(),
ProcessId = cprocess.OperId
});
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
} |
using JhinBot.Interface;
namespace JhinBot.Validators.Implementation
{
public class ConfirmValidator : IValidator
{
private string _errorMsg;
public ConfirmValidator(string errorMsg)
{
_errorMsg = errorMsg;
}
public (bool success, string errorMsg) Validate(string input)
{
var lowerCaseInput = input.ToLower();
return (lowerCaseInput == "y", _errorMsg);
}
}
}
|
using Chess.v4.Models.Enums;
using System.Collections.Generic;
namespace Chess.v4.Models
{
public class GameMetaData
{
public string Annotator { get; set; }
public string Black { get; set; }
public string BlackELO { get; set; }
public string Date { get; set; }
public string ECO { get; set; }
public string Event { get; set; }
public string Filename { get; set; }
public string ID { get; set; }
public SortedList<int, string> Moves { get; set; } = new SortedList<int, string>();
public string Remark { get; set; }
public string Result { get; set; }
public string Round { get; set; }
public string Site { get; set; }
public string Source { get; set; }
public string White { get; set; }
public string WhiteELO { get; set; }
public string GetValue(MetaType metaType)
{
var value = this.GetType().GetProperty(metaType.ToString()).GetValue(this, null);
return value.ToString();
}
public string GetValue(string propertyName)
{
string retval = string.Empty;
var propInfo = this.GetType().GetProperty(propertyName);
try
{
var value = propInfo.GetValue(this, null);
retval = value.ToString();
}
catch
{
}
return retval;
}
public void SetValue(MetaType metaType, string value)
{
switch (metaType)
{
case MetaType.Event:
this.Event = value;
break;
case MetaType.Site:
this.Site = value;
break;
case MetaType.Date:
this.Date = value;
break;
case MetaType.Round:
this.Round = value;
break;
case MetaType.White:
this.White = value;
break;
case MetaType.Black:
this.Black = value;
break;
case MetaType.Result:
this.Result = value;
break;
case MetaType.WhiteElo:
this.WhiteELO = value;
break;
case MetaType.BlackElo:
this.BlackELO = value;
break;
case MetaType.ECO:
this.ECO = value;
break;
case MetaType.Annotator:
this.Annotator = value;
break;
case MetaType.Source:
this.Source = value;
break;
case MetaType.Remark:
this.Remark = value;
break;
case MetaType.Filename:
this.Filename = value;
break;
case MetaType.ID:
this.ID = value;
break;
}
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using Library.Interfaces;
using Library.Model;
namespace LibraryTest
{
[TestClass]
public class DataRepositoryTests
{
private MockRepository mockRepository;
private Mock<IDataFiller> mockDataFiller;
[TestInitialize]
public void TestInitialize()
{
this.mockRepository = new MockRepository(MockBehavior.Loose);
this.mockDataFiller = this.mockRepository.Create<IDataFiller>();
}
[TestCleanup]
public void TestCleanup()
{
this.mockRepository.VerifyAll();
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong key of book which we want to get from collection.")]
public void getItemWithWrongKey()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.getItem("");
Assert.Fail();
}
[TestMethod]
public void getItemWithGoodKey()
{
DataRepository dataRepository = this.CreateDataRepository();
Item item = new Book("", null, 0, "");
dataRepository.AddItem(item);
Assert.AreEqual<Item>(item, dataRepository.getItem(item.Id));
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong key of book which we want to remove from collection.")]
public void removeItemWithWrongKey()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.removeItem("");
Assert.Fail();
}
[TestMethod]
public void removeItemWithGoodKey()
{
DataRepository dataRepository = this.CreateDataRepository();
Item item = new Book("", null, 0, "");
dataRepository.AddItem(item);
Assert.AreEqual<int>(1, dataRepository.getAllItems().Count);
dataRepository.removeItem(item.Id);
Assert.AreEqual<int>(0, dataRepository.getAllItems().Count);
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong key of book which we want to update from collection.")]
public void updateItemWithWrongKey()
{
DataRepository dataRepository = this.CreateDataRepository();
Item item1 = new Book("", null, 0, "");
Item item2 = new Book("", null, 0, "");
dataRepository.AddItem(item1);
dataRepository.updateItem("osakdokaskda", item2);
Assert.Fail();
}
[TestMethod]
public void updateItemWithGoodKey()
{
DataRepository dataRepository = this.CreateDataRepository();
Item item1 = new Book("", null, 0, "");
Item item2 = new Book("", null, 0, "");
dataRepository.AddItem(item1);
Assert.AreEqual<Item>(item1, dataRepository.getItem(item1.Id));
dataRepository.updateItem(item1.Id, item2);
Assert.AreEqual<Item>(item2, dataRepository.getItem(item1.Id));
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of person which we want to get from collection.")]
public void getPersonWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.getPerson(1);
Assert.Fail();
}
[TestMethod]
public void getPersonWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Reader reader = new Reader("", "", 0, "");
dataRepository.addPerson(reader);
Assert.AreEqual<Person>(reader, dataRepository.getPerson(0));
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of person which we want to remove from collection.")]
public void removePersonWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.removePerson(1);
Assert.Fail();
}
[TestMethod]
public void removePersonWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader = new Reader("", "", 0, "");
dataRepository.addPerson(reader);
Assert.AreEqual<int>(1, dataRepository.getAllPeople().Count);
dataRepository.removePerson(0);
Assert.AreEqual<int>(0, dataRepository.getAllPeople().Count);
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of person which we want to update from collection.")]
public void updatePersonWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader1 = new Reader("", "", 0, "");
Person reader2 = new Reader("", "", 0, "");
dataRepository.addPerson(reader1);
dataRepository.updatePerson(1, reader2);
Assert.Fail();
}
[TestMethod]
public void updatePersonWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader1 = new Reader("", "", 0, "");
Person reader2 = new Reader("", "", 0, "");
dataRepository.addPerson(reader1);
Assert.AreEqual<Person>(reader1, dataRepository.getPerson(0));
dataRepository.updatePerson(0, reader2);
Assert.AreEqual<Person>(reader2, dataRepository.getPerson(0));
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of event which we want to get from collection.")]
public void getEventWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.getEvent(1);
Assert.Fail();
}
[TestMethod]
public void getEventWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader = new Reader("", "", 0, "");
Item book = new Book("", null, 0, "");
StateDescription state = new BookDescription(book, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
Event ev = new Rental(state, reader, DateTime.Now);
dataRepository.addEvent(ev);
Assert.AreEqual<Event>(ev, dataRepository.getEvent(0));
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of event which we want to remove from collection.")]
public void removeEventWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.removeEvent(1);
Assert.Fail();
}
[TestMethod]
public void removeEventWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader = new Reader("", "", 0, "");
Item book = new Book("", null, 0, "");
StateDescription state = new BookDescription(book, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
Event ev = new Rental(state, reader, DateTime.Now);
dataRepository.addEvent(ev);
Assert.AreEqual<int>(1, dataRepository.getAllEvents().Count);
dataRepository.removeEvent(0);
Assert.AreEqual<int>(0, dataRepository.getAllEvents().Count);
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of event which we want to update from collection.")]
public void updateEventWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader = new Reader("", "", 0, "");
Item book = new Book("", null, 0, "");
StateDescription state = new BookDescription(book, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
Event ev = new Rental(state, reader, DateTime.Now);
dataRepository.updateEvent(1, ev);
Assert.Fail();
}
[TestMethod]
public void updateEventWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader1 = new Reader("", "", 0, "");
Person reader2 = new Reader("", "", 0, "");
Item book1 = new Book("", null, 0, "");
Item book2 = new Book("", null, 0, "");
StateDescription state1 = new BookDescription(book1, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
StateDescription state2 = new BookDescription(book2, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
Event ev1 = new Rental(state1, reader1, DateTime.Now);
Event ev2 = new Rental(state2, reader2, DateTime.Now);
dataRepository.addEvent(ev1);
Assert.AreEqual<Event>(ev1, dataRepository.getEvent(0));
dataRepository.updateEvent(0, ev2);
Assert.AreEqual<Event>(ev2, dataRepository.getEvent(0));
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of state description which we want to get from collection.")]
public void getStateWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.getStateDescription(1);
Assert.Fail();
}
[TestMethod]
public void getStateWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader = new Reader("", "", 0, "");
Item book = new Book("", null, 0, "");
StateDescription state = new BookDescription(book, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
dataRepository.addStateDescription(state);
Assert.AreEqual<StateDescription>(state, dataRepository.getStateDescription(0));
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of state description which we want to remove from collection.")]
public void removeStateWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
dataRepository.removeStateDescription(1);
Assert.Fail();
}
[TestMethod]
public void removeStateWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader = new Reader("", "", 0, "");
Item book = new Book("", null, 0, "");
StateDescription state = new BookDescription(book, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
dataRepository.addStateDescription(state);
Assert.AreEqual<int>(1, dataRepository.getAllStateDescriptions().Count);
dataRepository.removeStateDescription(0);
Assert.AreEqual<int>(0, dataRepository.getAllStateDescriptions().Count);
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException), "Wrong ID of state description which we want to update from collection.")]
public void updateStateWithWrongId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader = new Reader("", "", 0, "");
Item book = new Book("", null, 0, "");
StateDescription state = new BookDescription(book, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
dataRepository.updateStateDescription(1, state);
Assert.Fail();
}
[TestMethod]
public void updateStateWithGoodId()
{
DataRepository dataRepository = this.CreateDataRepository();
Person reader1 = new Reader("", "", 0, "");
Person reader2 = new Reader("", "", 0, "");
Item book1 = new Book("", null, 0, "");
Item book2 = new Book("", null, 0, "");
StateDescription state1 = new BookDescription(book1, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
StateDescription state2 = new BookDescription(book2, "", new DateTime(1990, 1, 1), Purpose.All, Kind.Criminal);
dataRepository.addStateDescription(state1);
Assert.AreEqual<StateDescription>(state1, dataRepository.getStateDescription(0));
dataRepository.updateStateDescription(0, state2);
Assert.AreEqual<StateDescription>(state2, dataRepository.getStateDescription(0));
}
private DataRepository CreateDataRepository()
{
return new DataRepository(this.mockDataFiller.Object);
}
}
} |
//Raimundo Jose Oliveira da Silva
//Robô desenvolvido em C# - Visual Studio 2019
//Referência: https://robocode.sourceforge.io/docs/robocode.dotnet/Index.html
using Robocode;
using System.Drawing;
namespace FNL
{
public class MyRobot : Robot
{
//Método inicial do MyRobot
public override void Run()
{
//Característica/aparência do robô
SetColors(
Color.Black,
Color.Black,
Color.FromArgb(150, 0, 150));
while (true)
{
Ahead(200);
TurnGunRight(180);
_ = (Rules.MAX_VELOCITY);
TurnRight(90);
}
}
//Quando o MyRobot identifica um adversário
public override void OnScannedRobot (ScannedRobotEvent e)
{
//Caso a distância seja menor do que 0, variar intensidade do tiro
if (e.Distance < 50)
{
Fire(Rules.MAX_BULLET_POWER);
}
else
{
Stop();
Fire(1);
Fire(Rules.MAX_BULLET_POWER);
}
Scan();
}
//Quando o MyRobot é atingido, revida com intensidade variada
public void OnHitRobot(HitRobotEvent e)
{
//Verificando o adversário
if (e.Bearing >= 0)
{
TurnRight(1);
Back(100);
Fire(5);
}
else
{
TurnRight(-1);
}
TurnRight(e.Bearing);
//Mensurando o intesndade do tiro
if (e.Energy > 30)
{
Fire(3);
}
else if (e.Energy > 20)
{
Fire(2);
}
else if (e.Energy > 10)
{
Fire(1);
}
else if (e.Energy > 5)
{
Fire(5);
}
//Avançando para colisão
Ahead(50);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Juicy.WindowsService.AutoUpdates
{
public sealed class AutoUpdateTask : PeriodicalTask
{
readonly static log4net.ILog Log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public AutoUpdateTask(string serviceName, string updaterExePath)
: this("AutoUpdate", serviceName, updaterExePath)
{
}
public AutoUpdateTask(string taskName, string serviceName, string updaterExePath)
: base(taskName)
{
this.serviceName = serviceName;
updUtil = new UpdateUtil(updaterExePath);
}
private string serviceName;
private UpdateUtil updUtil;
public override void Execute()
{
List<string> updates = updUtil.GetUpdatedProgramFiles();
if(updates.Count > 0)
{
string msg = "The files below have newer versions:" + Environment.NewLine;
foreach(string f in updates)
msg += " " + f + Environment.NewLine;
Log.Info(msg);
//now fire the updater and wait to be be killed
updUtil.StartUpdater(this.serviceName);
}
}
}
}
|
using ComInLan.Model.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace ComInLan.Model
{
public class CServer : BaseModel, IServer
{
//--------------Created from packet------------------//
public string Id { get; set; }
public string Name { get; set; }
public int Port { get; set; }
public CServer()
{
Refresh();
State = ServerState.None;
}
//--------------Created by app------------------//
public IPAddress Address { get; set; }
private ServerState _state;
public ServerState State
{
get { return _state; }
set
{
_state = value;
StateChanged?.Invoke(this);
}
}
public string Checksum { get; private set; }
public long RefreshTime { get; private set; }
//--------------Methods------------------//
public void CalculateChecksum()
{
Checksum = CalculateChecksum(Id + Name);
}
public void Refresh()
{
RefreshTime = GetCurrentUnixTimestamp();
}
//--------------Events------------------//
public event ServerStateEventHandler StateChanged;
public event SeverDataEventHandler DataReceived;
public void CallIDataReceived(String data)
{
DataReceived?.Invoke(this, data);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace InfinityCode.OnlineMapsExamples
{
/// <summary>
/// Class control the map for the Tileset.
/// Tileset - a dynamic mesh, created at runtime.
/// </summary>
[Serializable]
[AddComponentMenu("Infinity Code/Online Maps/Controls/Tileset")]
public class MapManagerAPI : MonoBehaviour {
public OnlineMapsControlBase3D abc;
public GameObject bcd;
// Use this for initialization
void Start () {
OnlineMapsMarker3D marker = abc.AddMarker3D(new Vector2(-6.27074973995987f,106.932347372895f), bcd);
}
// Update is called once per frame
void Update () {
}
}
} |
using System.Linq;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Models;
namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort
{
public class BulkUploadAddAndApproveDraftApprenticeshipsViewModelMapper : IMapper<BulkUploadAddAndApproveDraftApprenticeshipsResponse, BulkUploadAddAndApproveDraftApprenticeshipsViewModel>
{
public Task<BulkUploadAddAndApproveDraftApprenticeshipsViewModel> Map(BulkUploadAddAndApproveDraftApprenticeshipsResponse source)
{
var viewModel = new BulkUploadAddAndApproveDraftApprenticeshipsViewModel
{
BulkUploadDraftApprenticeshipsViewModel = source.BulkUploadAddAndApproveDraftApprenticeshipResponse
.Select(r => new BulkUploadDraftApprenticeshipViewModel
{
CohortReference = r.CohortReference,
NumberOfApprenticeships = r.NumberOfApprenticeships,
EmployerName = r.EmployerName
}).ToList()
};
return Task.FromResult(viewModel);
}
}
}
|
using Entitas;
[Game]
public sealed class FieldMovedComponent : IComponent
{
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class Rekensom
{
public static int minSom(int getal1, int getal2)
{
return getal1 - getal2;
}
public int plusSom(int getal1, int getal2)
{
return getal2 + getal1;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using System.Linq;
public class GameManager : MonoBehaviourPunCallbacks
{
[Header("Stats")]
[HideInInspector]
public bool gameEnded = false; // has the game ended?
public float timeToWin; // time a player needs to hold the hat for in order to win
public float invincibleDuration; // how long after a player gets the hat, are they invincible?
private float hatPickupTime; // the time the hat was picked up by the current player
[Header("Players")]
public string playerPrefabLocation; // player prefab path in the Resources folder
public Transform[] spawnPoints; // array of player spawn points
[HideInInspector]
public PlayerController[] players; // array of all players
[HideInInspector]
public int playerWithHat; // id of the player who currently has the hat
private int playersInGame; // number of players currently in the Game scene
// instance
public static GameManager instance;
void Awake()
{
// set the instance to this script
instance = this;
}
void Start()
{
players = new PlayerController[PhotonNetwork.PlayerList.Length];
photonView.RPC("ImInGame", RpcTarget.AllBuffered);
}
// when a player loads into the game scene - tell everyone
[PunRPC]
void ImInGame()
{
playersInGame++;
// when all the players are in the scene - spawn the players
if (playersInGame == PhotonNetwork.PlayerList.Length)
SpawnPlayer();
}
// spawns a player and initializes it
void SpawnPlayer()
{
// instantiate the player across the network
GameObject playerObj = PhotonNetwork.Instantiate(playerPrefabLocation, spawnPoints[Random.Range(0, spawnPoints.Length)].position, Quaternion.identity, 0);
// get the player script
PlayerController playerScript = playerObj.GetComponent<PlayerController>();
// initialize the player
playerScript.photonView.RPC("Initialize", RpcTarget.All, PhotonNetwork.LocalPlayer);
}
// is the player able to take the hat at this current time?
public bool CanGetHat()
{
if (Time.time > hatPickupTime + invincibleDuration) return true;
else return false;
}
// called when a player hits the hatted player - gives them the hat
[PunRPC]
public void GiveHat(int playerId, bool initialGive = false)
{
// remove the hat from the currently hatted player
if (!initialGive)
GetPlayer(playerWithHat).SetHat(false);
// give the hat to the new player
playerWithHat = playerId;
GetPlayer(playerId).SetHat(true);
hatPickupTime = Time.time;
}
// returns the player who has the requested id
public PlayerController GetPlayer(int playerId)
{
return players.First(x => x.playerID == playerId);
}
// returns the player of the requested GameObject
public PlayerController GetPlayer(GameObject playerObject)
{
return players.First(x => x.gameObject == playerObject);
}
[PunRPC]
void WinGame(int playerId)
{
gameEnded = true;
PlayerController player = GetPlayer(playerId);
Invoke("GoBackToMenu", 3.0f);
GameUI.instance.SetWinText(player.photonPlayer.NickName);
}
void GoBackToMenu()
{
PhotonNetwork.LeaveRoom();
NetworkManager.instance.ChangeScene("Menu");
}
} |
using NfePlusAlpha.Application.ViewModels.Apoio;
using NfePlusAlpha.Infra.Data.Retorno;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace NfePlusAlpha.Application.ViewModels.ViewModel
{
public class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
{
//Propriedade usada como apoio ao metodo ForcarValidacao,
//Para que só seja executado o forçar no gravar
public bool blnValidarPreGravar = false;
public ViewModelBase()
{
this.arrErros = new ObservableCollection<string>();
}
#region INotifyPropertyChanged method plus event
public event PropertyChangedEventHandler PropertyChanged = delegate { };
/// <summary>
/// Notifica que a propriedade informada foi alterada. Se não informado a propriedade, todas as propriedades serão marcadas como alterada
/// </summary>
protected void RaisePropertyChanged(string propertyName)
{
if (propertyName != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
else
{
//se for passado nulo, todas as propriedades da viewmodel serão indicadas como alteradas
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(null));
}
}
}
#endregion
#region INotifyDataErrorInfo methods and helpers
private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
public void SetError(string propertyName, string errorMessage)
{
if (!_errors.ContainsKey(propertyName))
_errors.Add(propertyName, new List<string> { errorMessage });
RaiseErrorsChanged(propertyName);
RaisePropertyChanged("HasErrors");
}
protected void ClearError(string propertyName)
{
if (_errors.ContainsKey(propertyName))
{
_errors.Remove(propertyName);
RaiseErrorsChanged(propertyName);
RaisePropertyChanged("HasErrors");
}
}
protected void ClearAllErrors()
{
var errors = _errors.Select(error => error.Key).ToList();
foreach (var propertyName in errors)
ClearError(propertyName);
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { };
public void RaiseErrorsChanged(string propertyName)
{
if (propertyName != null)
{
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}
public IEnumerable GetErrors(string propertyName)
{
if (propertyName == null) return null;
return _errors.ContainsKey(propertyName)
? _errors[propertyName]
: null;
}
public bool HasErrors
{
get { return _errors.Count > 0; }
}
public Dictionary<string, List<string>> RetornaTodosErros()
{
return _errors;
}
#endregion
#region Tratamentos de Erros
private Dictionary<int, List<string>> arrTodosErros = new Dictionary<int, List<string>>();
public ObservableCollection<string> arrErros { get; set; }
public void AtualizaErros()
{
arrErros.Clear();
var errors = arrTodosErros.Select(error => error.Value).ToList();
foreach (var objValue in errors)
foreach (string strErro in objValue)
arrErros.Add(strErro);
}
public void AdicionaErros(object objItem)
{
int intId = objItem.GetHashCode();
if (arrTodosErros.ContainsKey(intId))
arrTodosErros[intId].Clear();
else
arrTodosErros.Add(intId, new List<string>());
Dictionary<string, List<string>> _errors = (Dictionary<string, List<string>>)((ViewModelBase)objItem).RetornaTodosErros();
var errors = _errors.Select(error => error.Value).ToList();
foreach (var propertyValue in errors)
foreach (string strErro in propertyValue)
arrTodosErros[intId].Add(strErro);
this.AtualizaErros();
}
public void RemoveErros(object objItem)
{
int intId = objItem.GetHashCode();
if (arrTodosErros.ContainsKey(intId))
{
arrTodosErros.Remove(intId);
this.AtualizaErros();
}
}
/// <summary>
/// Metodo chamado para realizar a validação de erros segundo os DataAnotations
/// </summary>
/// <param name="strProp">Nome da propriedade</param>
/// <param name="objValue">Valor da Propriedade a ser setada</param>
public void ValidaErro(object objValue, [CallerMemberName] string strProp = "")
{
if (!blnValidarPreGravar)
ClearError(strProp);
try
{
Validator.ValidateProperty(objValue, new ValidationContext(this) { MemberName = strProp });
}
catch (ValidationException ve)
{
SetError(strProp, ve.Message);
}
catch (Exception exa)
{
SetError(strProp, exa.Message);
}
}
public void ValidaCpfCnpj(string strCpfCnpj, [CallerMemberName] string strProp = "")
{
strCpfCnpj = Util.RemoveSimbolos(strCpfCnpj);
if (strCpfCnpj.Length == 11 || strCpfCnpj.Length == 14)
{
if (strCpfCnpj.Length == 11)
{
if (!Util.ValidaCpf(strCpfCnpj))
{
this.SetError(strProp, "CPF inválido.");
}
}
else
{
if (!Util.ValidaCnpj(strCpfCnpj))
{
this.SetError(strProp, "CNPJ inválido.");
}
}
}
else
{
this.SetError(strProp, "CPF/CNPJ inválido.");
}
}
IEnumerable INotifyDataErrorInfo.GetErrors(string propertyName)
{
if (!string.IsNullOrEmpty(propertyName))
{
if (_errors.ContainsKey(propertyName) && (_errors[propertyName] != null) && _errors[propertyName].Count > 0)
return _errors[propertyName].ToList();
else
return null;
}
else
return _errors.SelectMany(err => err.Value.ToList());
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelpButton : MonoBehaviour {
public GameObject help;
public void OpenHelp(){
help.SetActive(!help.activeSelf);
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using ProjectTrackingServices.Models;
namespace ProjectTrackingServices.Controllers
{
[EnableCors(origins: "http://localhost:1630", headers: "*", methods: "*")]
public class PTEmployeesController : ApiController
{
// GET: api/PTEmployeesController
[Route("api/ptemployees")]
public HttpResponseMessage Get()
{
var employees = EmployeesRepository.GetAllEmployees();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return response;
}
[Route("api/ptemployees/{name:alpha}")]
public HttpResponseMessage SearchByName(string name)
{
var employees= EmployeesRepository.SearchEmployeesByName(name);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return response;
}
// GET: api/PTEmployeesController/5
[Route("api/ptemployees/{id?}")]
public HttpResponseMessage GetEmployee(int? id)
{
var emp = EmployeesRepository.GetEmployee(id);
var response = Request.CreateResponse(HttpStatusCode.OK, emp);
return response;
}
// POST: api/PTEmployeesController
[Route("api/employees")]
public HttpResponseMessage Post([FromBody]Employee e)
{
var emp = EmployeesRepository.InsertEmployee(e);
var response = Request.CreateResponse(HttpStatusCode.OK, emp);
return response;
}
// PUT: api/PTEmployeesController/5
[Route("api/employees")]
public HttpResponseMessage Put(Employee e)
{
var emp = EmployeesRepository.UpdateEmployee(e);
var response = Request.CreateResponse(HttpStatusCode.OK, emp);
return response;
}
// DELETE: api/PTEmployeesController/5
[Route("api/employees")]
public HttpResponseMessage Delete(int id)
{
var emp = EmployeesRepository.DeleteEmployee(id);
var response = Request.CreateResponse(HttpStatusCode.OK, emp);
return response;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class KeyBindingUIManager : MonoBehaviour
{
public const string TAG = "KeyBindingUI";
[SerializeField] [Range(2f,50f)]private float _RequestTimeOut;
[SerializeField] private Text _InstructionalText;
private Coroutine _RequestTimeoutCoroutine;
private KeyCode lastKeyPressed;
private bool _runEvent;
private KeyBindingText _eventObject;
// Start is called before the first frame update
void Start()
{
// _InstructionalText.enabled = false;
_InstructionalText.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
private void OnGUI()
{
if (_runEvent)
{
Event e = Event.current;
if (e.isKey)
{
lastKeyPressed = e.keyCode;
_eventObject.setText(e.keyCode.ToString());
KeyBindingsManager.instance.getKeyBindings().setBindings(_eventObject.getBindingType(), e.keyCode);
this.StopKeyBindingEvent();
Debug.Log("Detected key code: " + e.keyCode);
}
}
}
public void StartKeyBindingEvent(KeyBindingText text)
{
Debug.Log("Started");
_eventObject = text;
_InstructionalText.gameObject.SetActive(true);
_runEvent = true;
if (_RequestTimeoutCoroutine == null)
{
_RequestTimeoutCoroutine = StartCoroutine(RequestTimeout());
}
}
public void StopKeyBindingEvent()
{
Debug.Log("Event Stopped");
_eventObject = null;
_runEvent = false;
_InstructionalText.gameObject.SetActive(false);
if (_RequestTimeoutCoroutine != null)
{
StopCoroutine(_RequestTimeoutCoroutine);
}
}
private IEnumerator RequestTimeout()
{
yield return new WaitForSeconds(_RequestTimeOut);
}
}
|
/*
* interestcalctest
*
* Teste simples de API swagger in .net core.
*
* OpenAPI spec version: 1.0.0
* Contact: anjomar@gmail.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using IO.Swagger.Attributes;
using Test.Models.Lib;
namespace IO.Swagger.Controllers
{
/// <summary>
/// Controler principal e único
/// </summary>
public class DefaultApiController : Controller
{
/// <summary>
/// Calcula juros
/// </summary>
/// <param name="valorinicial">Valor inicial a ser usado no cálculo</param>
/// <param name="meses">Número de meses</param>
/// <response code="200">Status 200</response>
[HttpGet]
[Route("/calculajuros")]
[ValidateModelState]
[SwaggerOperation("CalculajurosGet")]
[SwaggerResponse(statusCode: 200, type: typeof(decimal?), description: "Status 200")]
public virtual IActionResult CalculajurosGet([FromQuery]decimal? valorinicial, [FromQuery]int? meses)
{
InterestCalc calc = new InterestCalc(valorinicial.Value, meses.Value);
return StatusCode(200, calc.Calc());
}
/// <summary>
/// Calcula os juros
/// </summary>
/// <param name="initialValue">Valor inicial</param>
/// <param name="months">Número de meses</param>
/// <param name="interest">Taxa de juros ao mês</param>
/// <response code="200">Status 200</response>
[HttpGet]
[Route("/interestcalc/{initialValue}/{months}/{interest}")]
[ValidateModelState]
[SwaggerOperation("InterestcalcInitialValueMonthsInterestGet")]
[SwaggerResponse(statusCode: 200, type: typeof(decimal?), description: "Status 200")]
public virtual IActionResult InterestcalcInitialValueMonthsInterestGet([FromRoute][Required]decimal? initialValue, [FromRoute][Required]int? months, [FromRoute][Required]decimal? interest)
{
InterestCalc calc = new InterestCalc(initialValue.Value, months.Value, interest.Value);
return StatusCode(200, calc.Calc());
}
/// <summary>
/// Mostra o fonte
/// </summary>
/// <response code="200">Status 200</response>
[HttpGet]
[Route("/showmethecode")]
[ValidateModelState]
[SwaggerOperation("ShowmethecodeGet")]
[SwaggerResponse(statusCode: 200, type: typeof(string), description: "Status 200")]
public virtual IActionResult ShowmethecodeGet() => StatusCode(200, "https://github.com/ocult/interestcalctest");
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shipwreck.TypeScriptModels.Decompiler.Transformations;
using System;
namespace Shipwreck.TypeScriptModels.Decompiler
{
[TestClass]
public class EventConventionTest
{
private class Auto
{
public event EventHandler TestEvent;
public void OnTestEvent()
=> TestEvent?.Invoke(this, EventArgs.Empty);
}
private class Custom
{
public event EventHandler TestEvent
{
add { }
remove { }
}
}
[TestMethod]
public void EventDeclarationTest_Auto()
{
var t = new TypeTranslationContext<Auto>();
Assert.IsNotNull(t.GetField("$ev_TestEvent"));
Assert.IsNotNull(t.GetMethod("$addev_TestEvent"));
Assert.IsNotNull(t.GetMethod("$remev_TestEvent"));
}
[TestMethod]
public void EventDeclarationTest_Custom()
{
var t = new TypeTranslationContext<Custom>();
Assert.IsNull(t.GetField("$ev_TestEvent"));
Assert.IsNotNull(t.GetMethod("$addev_TestEvent"));
Assert.IsNotNull(t.GetMethod("$remev_TestEvent"));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* ****************
*
* りんごの葉っぱ部分を作成
*
* ****************/
public class AppleLeefBehaviour : MonoBehaviour {
// Use this for initialization
Vector3[] vertices;
int[] triangles, _triangles;
int n = 40;
int h = 25;
int i, j, N;
float mgf = 0.39f, m = 20;
float num, NUM;
Mesh mesh;
private MeshFilter mf;
[SerializeField]
private Material _mat;
void setInitialVertices() {
vertices = new Vector3[5 * n];
//vertices = new Vector3[2 * n];
for (i = 0; i < n; i++) {
vertices [i] = new Vector3 (mgf * i / m, mgf * (Mathf.Exp (-Mathf.Pow ((i - h) / m, 2)) - Mathf.Exp (-Mathf.Pow (h / m, 2))));
vertices [i].z = 0.1f + 0.1f * Mathf.Cos (Mathf.PI * i / m);
vertices [i + n] = new Vector3 (mgf * i / m, 0.5f * mgf * (Mathf.Exp (-Mathf.Pow ((i - h) / m, 2)) - Mathf.Exp (-Mathf.Pow (h / m, 2))));
vertices [i + n].z = -0.3f + 0.1f * Mathf.Cos (Mathf.PI * i / m);
vertices [i + 2 * n] = new Vector3 (mgf * i / m, 0);
vertices [i + 2 * n].z = +0.1f * Mathf.Cos (Mathf.PI * i / m);
vertices [i + 3 * n] = new Vector3 (mgf * i / m, -0.5f * mgf * (Mathf.Exp (-Mathf.Pow ((i - h) / m, 2)) - Mathf.Exp (-Mathf.Pow (h / m, 2))));
vertices [i + 3 * n].z = -0.3f + 0.1f * Mathf.Cos (Mathf.PI * i / m);
vertices [i + 4 * n] = new Vector3 (mgf * i / m, -mgf * (Mathf.Exp (-Mathf.Pow ((i - h) / m, 2)) - Mathf.Exp (-Mathf.Pow (h / m, 2))));
vertices [i + 4 * n].z = 0.1f + 0.1f * Mathf.Cos (Mathf.PI * i / m);
}
}
void setInitialTriangles() {
triangles = new int[0];
for (i = 0; i < n - 1; i++) {
for (j = 0; j < 4; j++) {
N = triangles.Length;
_triangles = new int[N + 6];
System.Array.Copy (triangles, _triangles, triangles.Length);
_triangles [N ] = (j + 1) * n + i;
_triangles [N + 1] = j * n + i;
_triangles [N + 2] = (j + 1) * n + i + 1; //j = 1, i = n-2の時、3n-1
_triangles [N + 3] = (j + 1) * n + i + 1;
_triangles [N + 4] = j * n + i;
_triangles [N + 5] = j * n + i + 1;
triangles = _triangles;
}
}
}
// Use this for initialization
void Start () {
mesh = new Mesh ();
setInitialVertices ();
mesh.vertices = vertices;
setInitialTriangles ();
mesh.triangles = triangles;
/* メッシュとレンダラーのおまじない */
mesh.RecalculateNormals ();
mf = GetComponent<MeshFilter> ();
mf.sharedMesh = mesh;
var renderer = GetComponent<MeshRenderer> ();
renderer.material = _mat;
}
// Update is called once per frame
void Update () {
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Tkm1_Gm3_Main : MonoBehaviour {
//dar ebteda' az safhe hazf shavand
public GameObject bigPhone;
public Image water;
// Use this for initialization
void Start () {
//bigPhone.SetActive (false);
water.enabled=false;
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using EnduroLibrary;
namespace EnduroTrackReader
{
public interface ITrackReader
{
IEnumerable<TrackPoint> GetAllPoints();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PagosCredijal
{
public class Address
{
public String addressType;
public String myAddress;
public String betweenStreets;
public String colony;
public String city;
public String CP;
public String reference;
public Address(String addressType, String myAddress, String betweenStreets, String colony, String city, String CP, String reference)
{
this.addressType = addressType;
this.myAddress = myAddress;
this.betweenStreets = betweenStreets;
this.colony = colony;
this.city = city;
this.CP = CP;
this.reference = reference;
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
namespace gView.Drawing.Pro.Filters
{
public class ExtractChannel : BaseFilter
{
public static readonly ExtractChannel R = new ExtractChannel(RGB.R);
public static readonly ExtractChannel G = new ExtractChannel(RGB.G);
public static readonly ExtractChannel B = new ExtractChannel(RGB.B);
public static readonly ExtractChannel A = new ExtractChannel(RGB.A);
private short channel = RGB.R;
private Dictionary<PixelFormat, PixelFormat> _formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
public override Dictionary<PixelFormat, PixelFormat> FormatTranslations
{
get { return _formatTranslations; }
}
public short Channel
{
get { return channel; }
set
{
if (
(value != RGB.R) && (value != RGB.G) &&
(value != RGB.B) && (value != RGB.A)
)
{
throw new ArgumentException("Invalid channel is specified.");
}
channel = value;
}
}
public ExtractChannel()
{
// initialize format translation dictionary
_formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format8bppIndexed;
_formatTranslations[PixelFormat.Format32bppRgb] = PixelFormat.Format8bppIndexed;
_formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format8bppIndexed;
_formatTranslations[PixelFormat.Format48bppRgb] = PixelFormat.Format16bppGrayScale;
_formatTranslations[PixelFormat.Format64bppArgb] = PixelFormat.Format16bppGrayScale;
}
public ExtractChannel(short channel) : this()
{
this.Channel = channel;
}
protected override unsafe void ProcessFilter(BitmapData sourceData, BitmapData destinationData)
{
// get width and height
int width = sourceData.Width;
int height = sourceData.Height;
int pixelSize = Image.GetPixelFormatSize(sourceData.PixelFormat) / 8;
if ((channel == RGB.A) && (pixelSize != 4) && (pixelSize != 8))
{
throw new Exception("Can not extract alpha channel from none ARGB image.");
}
if (pixelSize <= 4)
{
int srcOffset = sourceData.Stride - width * pixelSize;
int dstOffset = destinationData.Stride - width;
// do the job
byte* src = (byte*)sourceData.Scan0.ToPointer();
byte* dst = (byte*)destinationData.Scan0.ToPointer();
// allign source pointer to the required channel
src += channel;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, src += pixelSize, dst++)
{
*dst = *src;
}
src += srcOffset;
dst += dstOffset;
}
}
else
{
pixelSize /= 2;
byte* srcBase = (byte*)sourceData.Scan0.ToPointer();
byte* dstBase = (byte*)destinationData.Scan0.ToPointer();
int srcStride = sourceData.Stride;
int dstStride = destinationData.Stride;
// for each line
for (int y = 0; y < height; y++)
{
ushort* src = (ushort*)(srcBase + y * srcStride);
ushort* dst = (ushort*)(dstBase + y * dstStride);
// allign source pointer to the required channel
src += channel;
// for each pixel
for (int x = 0; x < width; x++, src += pixelSize, dst++)
{
*dst = *src;
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ProjetoAutoEscola
{
public partial class Teste : Form
{
public Teste(String nome)
{
InitializeComponent();
txtNome.Text = nome;
}
public Teste(String pagamento)
{
InitializeComponent();
txtNome.Text = nome;
}
private void Teste_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
}
}
}
|
public class Solution {
public bool IsPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += n & 1;
n >>= 1;
}
return cnt == 1;
}
} |
using UnityEngine;
using System.Collections;
public class TileFogController : TileController {
public override void Interact()
{
GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerController>().AddXP(1);
Deactivate ();
base.Interact ();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
using UnityEngine.Tilemaps;
/// <summary>
/// Class for generating levels.
/// OOP Challenge:
/// GameManager is currently very tightly coupled with this.
/// Try resolving it.
/// </summary>
public class LevelGenerator : MonoBehaviour {
public GameObject[] battleChunks;
public GameObject[] obstacleChunks;
public GameObject[] enemies;
public GameObject[] pickups;
[HideInInspector] public int chunkCount = 0;
[HideInInspector] public int chunksDestroyed = 0;
private int chunksBeforeBattle = 3;
private List<Vector3> availableTiles = new List<Vector3>();
private List<Vector3> entityTiles = new List<Vector3>();
private List<GameObject> chunkList = new List<GameObject>();
public int CHUNK_ROWS = 15;
public int CHUNK_COLUMNS = 15;
// Stores the level
public Transform level;
/// <summary>
/// Initializes the level. Spawns an initial chunk.
/// </summary>
/// <param name="difficultyLevel">The initial difficulty of the game.</param>
public void InitLevel(int difficultyLevel) {
chunkCount = 0;
chunksDestroyed = 0;
SpawnChunk(difficultyLevel);
}
/// <summary>
/// Spawns a new level chunk ahead of the player.
/// </summary>
/// <param name="difficultyLevel">Difficulty level of the chunk to be spawned.
/// Enemies are more numerous as difficulty increases.</param>
public void SpawnChunk(float difficultyLevel) {
int enemiesToSpawn;
GameObject spawnChunk;
// Determines type of chunk to spawn and enemy count
if (chunkCount % chunksBeforeBattle == 0) {
spawnChunk = battleChunks[Random.Range(0, battleChunks.Length)];
enemiesToSpawn = (int)difficultyLevel;
}
else {
spawnChunk = obstacleChunks[Random.Range(0, obstacleChunks.Length)];
enemiesToSpawn = (int)Mathf.Ceil(Mathf.Log(difficultyLevel, 2));
}
// Generates a new grid of available tiles minus the wall tiles
GenerateTilePositions(spawnChunk);
// Instantiates the chunk itself
GameObject chunkInstance = Instantiate(spawnChunk, new Vector3(0, chunkCount * CHUNK_ROWS, 0f), Quaternion.identity) as GameObject;
chunkInstance.transform.SetParent(level);
chunkList.Add(chunkInstance);
// Gets the entity list of the spawned chunk
Transform entityList = chunkInstance.transform.Find("Entities");
// TODO: Decides how many pickups to spawn, this is a placeholder
int pickupsToSpawn = 1;
// Spawns in enemies
// Spawns in pickups
chunkCount++;
}
/// <summary>
/// Destroys the rearmost chunk behind the player.
/// This is done to avoid clutter.
/// </summary>
public void DestroyEarliestChunk() {
Destroy(chunkList[0]);
chunkList.RemoveAt(0);
chunksDestroyed++;
}
/// <summary>
/// Destroys the entire level.
/// </summary>
public void DestroyLevel() {
foreach (Transform child in level) {
GameObject.Destroy(child.gameObject);
}
}
/// <summary>
/// Determines where entities can spawn within a chunk by scanning for walls.
/// Open tile locations are temporarily stored in the availableTiles list.
/// </summary>
/// <param name="spawnChunk">The chunk to scan for spawnpoints.</param>
void GenerateTilePositions(GameObject spawnChunk) {
availableTiles.Clear();
// Gets the walls from the chunk to be spawned
GameObject walls = spawnChunk.transform.Find("Walls").gameObject;
Tilemap wallTilemap = walls.GetComponent<Tilemap>();
for (int x = 0; x < CHUNK_COLUMNS; x++) {
for (int y = 0; y < CHUNK_ROWS; y++) {
// If the tile does not exist in the wall tilemap, add it into list of available tiles
Vector3Int tileTBAdded = new Vector3Int(x, y, 0);
if (!wallTilemap.HasTile(tileTBAdded))
availableTiles.Add((Vector3)tileTBAdded);
}
}
}
/// <summary>
/// Randomly generates entity spawnpoints from available tiles.
/// Tiles to be spawned are temporarily stored in the entityTiles list.
/// </summary>
/// <param name="entitiesToSpawn">The number of entities to spawn</param>
void GenerateEntityPositions(int entitiesToSpawn) {
entityTiles.Clear();
for (int i = 0; i < entitiesToSpawn; i++) {
// Gets a random tile
Vector3 entitySpawnLocation = availableTiles[Random.Range(0, availableTiles.Count)];
entityTiles.Add(entitySpawnLocation);
// Removes tile from pool
availableTiles.Remove(entitySpawnLocation);
}
}
/// <summary>
/// Spawns enemies into the current chunk.
/// </summary>
/// <param name="enemiesToSpawn">Number of enemies to spawn.</param>
/// <param name="entityList">Transform which is to parent the spawned Enemies.</param>
void spawnEnemies(int enemiesToSpawn, Transform entityList) {
// Generates positions for spawning enemies.
GenerateEntityPositions(enemiesToSpawn);
for (int i = 0; i < enemiesToSpawn; i++) {
Vector3 enemyPos = entityTiles[i];
GameObject spawnedEnemy = enemies[Random.Range(0, enemies.Length)];
enemyPos.y += (chunkCount * CHUNK_ROWS);
GameObject enemyInstance = Instantiate(spawnedEnemy, enemyPos, Quaternion.identity) as GameObject;
enemyInstance.transform.SetParent(entityList);
}
}
/// <summary>
/// Spawns pickups into a given chunk.
/// </summary>
/// <param name="pickupsToSpawn">Number of pickups to spawn.</param>
/// <param name="entityList">Transform which is to parent the spawned Pickups.</param>
void spawnPickups(int pickupsToSpawn, Transform entityList) {
// Generates positions for spawning enemies.
GenerateEntityPositions(pickupsToSpawn);
for (int i = 0; i < entityTiles.Count; i++) {
Vector3 pickupPos = entityTiles[i];
GameObject spawnedPickup = pickups[Random.Range(0, pickups.Length)];
pickupPos.y += (chunkCount * CHUNK_ROWS);
GameObject pickupInstance = Instantiate(spawnedPickup, pickupPos, Quaternion.identity) as GameObject;
pickupInstance.transform.SetParent(entityList);
}
}
}
|
using System;
namespace EngageNet.Exceptions
{
[Serializable]
public class UnsupportedProviderFeatureException : ResponseException
{
public UnsupportedProviderFeatureException(int errorCode, string message, Exception inner)
: base(errorCode, message, inner)
{
}
public UnsupportedProviderFeatureException(int errorCode, string message)
: base(errorCode, message, null)
{
}
public UnsupportedProviderFeatureException()
{
}
}
} |
using System;
namespace Pounds_to_Dollars
{
class Program
{
static void Main(string[] args)
{
decimal inputDollars = decimal.Parse(Console.ReadLine());
decimal outputPounds = inputDollars * 1.31m;
Console.WriteLine($"{outputPounds:f3}");
}
}
}
|
namespace Ezphera.TimerScore
{
using UnityEngine;
[DisallowMultipleComponent]
[RequireComponent(typeof(Timer))]
[RequireComponent(typeof(ScoreManager))]
public class BaseGameManager : MonoBehaviour
{
/// <summary>
/// The BaseGameManager in scene
/// </summary>
public static BaseGameManager instance;
/// <summary>
/// The timer controller
/// </summary>
public Timer timer;
/// <summary>
/// The score manager
/// </summary>
public ScoreManager scoreManager;
protected virtual void Awake()
{
instance = this;
if (timer == null) timer = Timer.instance;
if (scoreManager == null) scoreManager = ScoreManager.instance;
}
protected virtual void OnEnable()
{
timer.OnPlay += OnPlayTimer; //Callback on start timer
timer.OnPaused += OnPausedTimer; //Callback on pause
timer.OnRelease += OnReleasedTimer; //Callback on release
timer.OnEnd += OnEndTimer; //Callback on End timer
timer.OnStop += OnStopTimer; //Callback on stop the timer
scoreManager.OnChanged += OnScoreChanged; //Callback on pause
}
protected virtual void OnDisable()
{
timer.OnPlay -= OnPlayTimer;
timer.OnPaused -= OnPausedTimer;
timer.OnRelease -= OnReleasedTimer;
timer.OnEnd -= OnEndTimer;
timer.OnStop -= OnStopTimer;
scoreManager.OnChanged -= OnScoreChanged;
}
public virtual void StartGame()
{
timer.Play();
}
protected virtual void OnPlayTimer() { }
protected virtual void OnPausedTimer() { }
protected virtual void OnReleasedTimer() { }
protected virtual void OnStopTimer() { }
protected virtual void OnEndTimer() { }
protected virtual void OnScoreChanged(float oldScore, float newScore) { }
public virtual void AddScore(float score) { scoreManager.Add(score); }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace ProyectoBolera
{
static class Conexion
{
public static DataSet getQuery(string cmd)
{
DataSet ds = null;
try
{
MySqlConnection conexion = new MySqlConnection("server=127.0.0.1;database=bolera;Uid=root;pwd=;");
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd, conexion);
DataSet dsAux = new DataSet();
adapter.Fill(dsAux);
ds = dsAux;
}
catch (Exception e)
{
MessageBox.Show("Ha ocurrido un problema:\n" + e.Message);
}
return ds;
}
}
}
|
using DesignPatternsApp.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatternsApp.FoodMenu
{
public class RestaurantOperator
{
private readonly string RestaurantID;
FoodMenu foodMenu;
public RestaurantOperator(string RestaurantID)
{
this.RestaurantID = RestaurantID;
}
public List<FoodMenuModel> PrintFoodMenu()
{
foodMenu = new FoodMenu(RestaurantID);
IIterator restaurantFoodMenu = foodMenu.CreateFoodMenuIterator();
return PrintFoodMenu(restaurantFoodMenu);
}
public List<FoodMenuModel> PrintFoodMenu(IIterator iterator)
{
Console.WriteLine("Food Menu");
Console.WriteLine("*********************************");
List<FoodMenuModel> foodMenu = new List<FoodMenuModel>();
while (iterator.HasNext())
{
FoodMenuModel foodMenuItem = (FoodMenuModel)iterator.Next();
foodMenu.Add(foodMenuItem);
Console.WriteLine("*********************************");
Console.WriteLine($"Food ID : {foodMenuItem.FoodID}");
Console.WriteLine($"Food Name : {foodMenuItem.FoodName}");
Console.WriteLine($"Cuisine : {foodMenuItem.Cuisine}");
Console.WriteLine($"Price : {foodMenuItem.Price}");
Console.WriteLine($"Rating : {foodMenuItem.Rating}");
}
return foodMenu;
}
}
}
|
using System.Collections;
using SimpleJSON;using System.Collections.Generic;
using System.Security;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class contentPage : MonoBehaviour
{
public string EventID, Title, Description, ImageURL, M1, M2, M3, M4, M5,F1,F2,F3,F4,F5,F6,F7,F8, QS, QR;
public Button complete_button1,complete_button2,complete_button3,complete_button4,complete_button5,complete_button6,complete_button7,complete_button8;
public GameObject M1GO, M2GO, M3GO, M4GO, M5GO,EventGO,RedeemCodeHandle;
public RawImage Rimage;
public Text TitleText, DescriptionText, M1Text, M2Text, M3Text, M4Text, M5Text,PP1,PP2,PP3,PP4,PP5;
public string M1Quantity,M2Quantity,M3Quantity,M4Quantity,M5Quantity,P1Quantity,P2Quantity,P3Quantity,P4Quantity,P5Quantity;
// Use this for initialization
void Start()
{
StartCoroutine (CachedLoad ());
}
IEnumerator CachedLoad()
{
yield return new WaitForSeconds(.6f);
if (File.Exists(Application.persistentDataPath + EventID + ".jpg"))
{print("cached");
byte[] byteArray = File.ReadAllBytes(Application.persistentDataPath + EventID + ".jpg");
Texture2D texture = new Texture2D(9,9);
texture.LoadImage(byteArray);
texture.filterMode = FilterMode.Point;
Rimage.texture = texture;
}
else
{print("download");
WWW www = new WWW(ImageURL);
yield return www;
Texture2D texture = www.texture;
texture.filterMode = FilterMode.Point;
Rimage.texture = texture;
byte[] bytes = texture.EncodeToJPG();
File.WriteAllBytes(Application.persistentDataPath+EventID+".jpg",bytes);
}
}
// Update is called once per frame
void Update()
{
}
void OnDisable()
{
Debug.Log("PrintOnDisable: script was disabled");
}
void OnEnable()
{
//Debug.Log("PrintOnEnable: script was enabled");
StartCoroutine(LoadNewsDetail());
}
IEnumerator LoadNewsDetail()
{EventGO.SetActive (true);
yield return new WaitForSeconds(0.3f);
var url = "http://139.59.100.192/PH/GetQuestID";
var form = new WWWForm();
form.AddField("ID",EventID);
form.AddField("PID",PlayerPrefs.GetString(Link.ID));
WWW www = new WWW(url,form);
yield return www;
Debug.Log(www.text);
if (www.error == null)
{
var jsonString = JSON.Parse(www.text);
Debug.Log(jsonString["data"][0]["QS1"]);
int ResCode = int.Parse(jsonString["code"]);
print (jsonString ["data"] [0] ["Qcode1"] + "1");
switch (ResCode)
{
case 9:
print ("pop up expired event");
EventGO.SetActive (false);
break;
case 8:
print ("pop up expired event");
complete_button1.interactable = false;
complete_button2.interactable = false;
complete_button3.interactable = false;
complete_button4.interactable = false;
complete_button5.interactable = false;
complete_button6.interactable = false;
EventGO.SetActive (false);
break;
case 7:
print ("Whadya want?");
EventGO.SetActive (false);
break;
case 6:
print ("nothing to see yet");
EventGO.SetActive (false);
break;
case 1:
M1Quantity = jsonString ["data"] [0] ["MissionC1"];
M2Quantity = jsonString ["data"] [0] ["MissionC2"];
M3Quantity = jsonString ["data"] [0] ["MissionC3"];
M4Quantity = jsonString ["data"] [0] ["MissionC4"];
M5Quantity = jsonString ["data"] [0] ["MissionC5"];
P1Quantity = jsonString ["data"] [0] ["PlayerC1"];
P2Quantity = jsonString ["data"] [0] ["PlayerC2"];
P3Quantity = jsonString ["data"] [0] ["PlayerC3"];
P4Quantity = jsonString ["data"] [0] ["PlayerC4"];
P5Quantity = jsonString ["data"] [0] ["PlayerC5"];
M1Text.text = jsonString ["data"] [0] ["Mission1"];
M2Text.text = jsonString ["data"] [0] ["Mission2"];
M3Text.text = jsonString ["data"] [0] ["Mission3"];
M4Text.text = jsonString ["data"] [0] ["Mission4"];
M5Text.text = jsonString ["data"] [0] ["Mission5"];
PP1.text = P1Quantity + "/" + M1Quantity;
PP2.text = P2Quantity + "/" + M2Quantity;
PP3.text = P3Quantity + "/" + M3Quantity;
PP4.text = P4Quantity + "/" + M4Quantity;
PP5.text = P5Quantity + "/" + M5Quantity;
TitleText.text = jsonString ["data"] [0] ["Title"];
DescriptionText.text = jsonString ["data"] [0] ["Description"];
M1 = jsonString["data"][0]["QS1"];
M2 = jsonString["data"][0]["QS2"];
M3 = jsonString["data"][0]["QS3"];
M4 = jsonString["data"][0]["QS4"];
M5 = jsonString["data"][0]["QS5"];
F1 = jsonString["data"][0]["Q1OK"];
F2 = jsonString["data"][0]["Q2OK"];
F3 = jsonString["data"][0]["Q3OK"];
F4 = jsonString["data"][0]["Q4OK"];
F5 = jsonString["data"][0]["Q5OK"];
F6 = jsonString["data"][0]["QC1"];
F7 = jsonString["data"][0]["QC2"];
F8 = jsonString["data"][0]["QC3"];
if (F1 == "1")
{
complete_button1.interactable = true;
complete_button1.onClick.AddListener(delegate {Complete(jsonString["data"][0]["Qcode1"]+"1"); });
}
else
{
complete_button1.interactable = false;
}
if (F2 == "1")
{
complete_button2.interactable = true;
complete_button2.onClick.AddListener(delegate {Complete(jsonString["data"][0]["Qcode2"]+"2"); });
}
else
{
complete_button2.interactable = false;
}
if (F3 == "1")
{
complete_button3.interactable = true;
complete_button3.onClick.AddListener(delegate {Complete(jsonString["data"][0]["Qcode3"]+"3"); });
}
else
{
complete_button3.interactable = false;
}
if (F4 == "1")
{
complete_button4.interactable = true;
complete_button4.onClick.AddListener(delegate {Complete(jsonString["data"][0]["Qcode4"]+"4"); });
}
else
{
complete_button4.interactable = false;
}
if (F5 == "1")
{
complete_button5.interactable = true;
complete_button5.onClick.AddListener(delegate {Complete(jsonString["data"][0]["Qcode5"]+"5"); });
}
else
{
complete_button5.interactable = false;
}
if (F6 == "1")
{
complete_button6.interactable = true;
complete_button6.onClick.AddListener(delegate {Complete("81"); });
}
else
{
complete_button6.interactable = false;
}
if (F7 == "1")
{
complete_button7.interactable = true;
complete_button7.onClick.AddListener(delegate {Complete("82"); });
}
else
{
complete_button7.interactable = false;
}
if (F8 == "1")
{
complete_button8.interactable = true;
complete_button8.onClick.AddListener(delegate {Complete("83"); });
}
else
{
complete_button8.interactable = false;
}
M1GO.SetActive(M1 == "1");
M2GO.SetActive(M2 == "1");
M3GO.SetActive(M3 == "1");
M4GO.SetActive(M4 == "1");
M5GO.SetActive(M5 == "1");
EventGO.SetActive (false);
break;
default:
print ("NaN");
break;
}
}
}
public void Complete(string Qtype)
{
StartCoroutine(RedeemIt(Qtype));
}
IEnumerator RedeemIt(string QType)
{
yield return new WaitForSeconds(0.3f);
var url = "http://139.59.100.192/PH/ClaimMission";
var form = new WWWForm();
form.AddField("ID", EventID);
form.AddField("PID", PlayerPrefs.GetString(Link.ID));
form.AddField("QType", QType);
form.AddField("DID",PlayerPrefs.GetString(Link.DEVICE_ID));
WWW www = new WWW(url, form);
yield return www;
Debug.Log(www.text);
if (www.error == null)
{
var jsonString = JSON.Parse(www.text);
//Debug.Log(jsonString["data"][0]["QS1"]);
int ResCode = int.Parse(jsonString["code"]);
switch (ResCode)
{
case 9:
print("pop up already sent it");
RedeemCodeHandle.SetActive(true);
RedeemCodeHandle.transform.Find ("Text").GetComponent<Text> ().text = "Event Expired,\n Please Close this page.";
break;
case 8:
print("pop up expired event");
RedeemCodeHandle.SetActive(true);
RedeemCodeHandle.transform.Find ("Text").GetComponent<Text> ().text = "Event Expired,\n Please Close this page.";
break;
case 77:
print("Whadya want?");
RedeemCodeHandle.SetActive(true);
RedeemCodeHandle.transform.Find ("Text").GetComponent<Text> ().text = "Already Taken,\n wait till tommorrow.";
StartCoroutine(LoadNewsDetail());
break;
case 6:
print("nothing to see yet");
break;
case 1:
RedeemCodeHandle.SetActive(true);
RedeemCodeHandle.transform.Find ("Text").GetComponent<Text> ().text = "Done,\n Check your inbox.";
StartCoroutine(LoadNewsDetail());
print("check inbox");
break;
default:
break;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using BankAppCore.DataTranferObjects;
using BankAppCore.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using static BankAppCore.Data.EFContext.EFContext;
namespace BankAppCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ClientController : ControllerBase
{
private ClientService clientService;
public ClientController(ShopContext shopContext)
{
clientService = new ClientService(shopContext);
}
[HttpGet]
[Authorize(Roles = "employee")]
[Route("get")]
public IEnumerable<ClientDTO> GetClients()
{
return clientService.getAllClients();
}
[HttpGet]
[Route("getid")]
[Authorize(Roles = "employee")]
public ClientDTO GetClientById(string id)
{
return clientService.getClientById(id);
}
[HttpPost]
[Route("create")]
[Authorize(Roles = "employee")]
public ClientDTO CreateClient(ClientDTO clientDTO)
{
clientService.createClient(clientDTO);
return clientDTO;
}
[HttpDelete]
[Route("delete")]
[Authorize(Roles = "employee")]
public void DeleteClient(string id)
{
clientService.deleteClient(id);
}
[HttpPut]
[Route("update")]
[Authorize(Roles = "employee")]
public void UpdateClient(ClientDTO clientDTO)
{
clientService.changeClient(clientDTO.SocialSecurityNumber, clientDTO);
}
[HttpPost]
[Route("add_account")]
[Authorize(Roles = "employee")]
public void LinkAccount(string ssn, int accountid)
{
clientService.addAccountToClient(ssn, accountid);
}
[HttpPost]
[Route("remove_account")]
[Authorize(Roles = "employee")]
public void UnlinkAccount(string ssn, int accountid)
{
clientService.deleteAccountFromClient(ssn, accountid);
}
}
} |
using NUnit.Framework;
using Cards;
using System;
using System.Diagnostics;
namespace CardsTests
{
public class CardTests
{
private Card two, ten, jack, queen, king, ace;
[SetUp]
public void Setup()
{
two = new Card('2', 'h');
ten = new Card('t', 's');
jack = new Card('j', 'c');
queen = new Card('Q', 'd');
king = new Card('K', 'd');
ace = new Card('a', 'd');
}
[Test]
public void TestCtor()
{
Assert.AreEqual('2', two.Rank);
Assert.AreEqual('H', two.Suit);
Assert.AreEqual('T', ten.Rank);
Assert.AreEqual('S', ten.Suit);
Assert.AreEqual('J', jack.Rank);
Assert.AreEqual('C', jack.Suit);
Assert.AreEqual('Q', queen.Rank);
Assert.AreEqual('D', queen.Suit);
Assert.AreEqual('K', king.Rank);
Assert.AreEqual('D', king.Suit);
Assert.AreEqual('A', ace.Rank);
Assert.AreEqual('D', ace.Suit);
Assert.Throws<ArgumentException>(() => new Card('1', 'h'));
Assert.Throws<ArgumentException>(() => new Card('2', 'f'));
}
[Test]
public void TestBasicProps()
{
Assert.IsTrue(two.IsNumeric);
Assert.IsFalse(two.IsFace);
Assert.IsFalse(two.IsAce);
Assert.IsTrue(ten.IsNumeric);
Assert.IsFalse(ten.IsFace);
Assert.IsFalse(ten.IsAce);
Assert.IsFalse(jack.IsNumeric);
Assert.IsTrue(jack.IsFace);
Assert.IsFalse(jack.IsAce);
Assert.IsFalse(king.IsNumeric);
Assert.IsTrue(king.IsFace);
Assert.IsFalse(king.IsAce);
Assert.IsFalse(ace.IsNumeric);
Assert.IsFalse(ace.IsFace);
Assert.IsTrue(ace.IsAce);
}
[Test]
public void TestStrProps()
{
Assert.AreEqual("2", two.RankString);
Assert.AreEqual("10", ten.RankString);
Assert.AreEqual("Jack", jack.RankString);
Assert.AreEqual("Queen", queen.RankString);
Assert.AreEqual("King", king.RankString);
Assert.AreEqual("Ace", ace.RankString);
Assert.AreEqual("Hearts", two.SuitString);
Assert.AreEqual("Spades", ten.SuitString);
Assert.AreEqual("Clubs", jack.SuitString);
Assert.AreEqual("Diamonds", queen.SuitString);
}
[Test]
public void TestToString()
{
Assert.AreEqual("10 of Spades", ten.ToString());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace ASPNETCoreBSON.Model
{
public class Mercury
{
[BsonId]
public ObjectId _id { get; set; }
public DateTime DateTimeStart { get; set; }
public double? Hg { get; set; }
public string unit { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraEditors;
using IRAP.Global;
using IRAP.Client.User;
using IRAP.Entity.MDM;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.GUI.CAS.UserControls
{
public partial class ucDeviceFailureModes : DevExpress.XtraEditors.XtraUserControl
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private string t133Code = "";
public ucDeviceFailureModes()
{
InitializeComponent();
}
public string T133Code
{
get
{
if (cboEquipmentList.SelectedItem == null)
return "";
else
{
return (cboEquipmentList.SelectedItem as AndonCallObject).Code;
}
}
set
{
t133Code = value;
if (t133Code != "")
{
for (int i = 0; i < cboEquipmentList.Properties.Items.Count; i++)
{
AndonCallObject device = cboEquipmentList.Properties.Items[i] as AndonCallObject;
if (device.Code == t133Code)
{
cboEquipmentList.SelectedIndex = i;
cboEquipmentList.Enabled = false;
break;
}
}
}
else
{
cboEquipmentList.Enabled = true;
}
}
}
public int FailureModeLeafID
{
get
{
int idx = grdvAndonCallObjects.GetFocusedDataSourceRowIndex();
if (idx < 0)
return 0;
else
{
return (grdAndonCallObjects.DataSource as List<AndonCallObject>)[idx].LeafID;
}
}
}
private void GetDeviceList()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
int errCode = 0;
string errText = "";
List<AndonCallObject> devices = new List<AndonCallObject>();
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
IRAPMDMClient.Instance.ufn_GetList_AndonCallObjects(
IRAPUser.Instance.CommunityID,
1325156,
0,
0,
IRAPUser.Instance.SysLogID,
ref devices,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
{
foreach (AndonCallObject device in devices)
cboEquipmentList.Properties.Items.Add(device);
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private void ucDeviceFailureModes_Load(object sender, EventArgs e)
{
if (!DesignMode)
GetDeviceList();
}
private void cboEquipmentList_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboEquipmentList.SelectedItem != null)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
AndonCallObject selectedEquipment =
cboEquipmentList.SelectedItem as AndonCallObject;
t133Code = selectedEquipment.Code;
int errCode = 0;
string errText = "";
List<AndonCallObject> failureModeList =
new List<AndonCallObject>();
IRAPMDMClient.Instance.ufn_GetList_AndonCallObjects(
IRAPUser.Instance.CommunityID,
1325156,
0,
selectedEquipment.LeafID,
IRAPUser.Instance.SysLogID,
ref failureModeList,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
{
IRAPMessageBox.Instance.Show(
string.Format("({0}){1}", errCode, errText),
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
grdAndonCallObjects.DataSource = null;
return;
}
grdAndonCallObjects.DataSource = failureModeList;
for (int i = 0; i < grdvAndonCallObjects.Columns.Count; i++)
{
grdvAndonCallObjects.Columns[i].BestFit();
}
grdvAndonCallObjects.OptionsView.RowAutoHeight = true;
grdvAndonCallObjects.LayoutChanged();
}
catch (Exception error)
{
grdAndonCallObjects.DataSource = null;
WriteLog.Instance.Write(error.Message, strProcedureName);
IRAPMessageBox.Instance.Show(
error.Message,
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
}
}
|
namespace BettingSystem.Domain.Betting.Factories.Matches
{
using System;
using Exceptions;
using Models.Matches;
internal class MatchFactory : IMatchFactory
{
private readonly Status defaultMatchStatus = Status.NotStarted;
private readonly Statistics defaultMatchStatistics = new(homeScore: null, awayScore: null);
private DateTime matchStartDate = default!;
private bool isStartDateSet = false;
public IMatchFactory WithStartDate(DateTime startDate)
{
this.matchStartDate = startDate;
this.isStartDateSet = true;
return this;
}
public Match Build()
{
if (!this.isStartDateSet)
{
throw new InvalidMatchException("Start Date must have a value");
}
return new Match(
this.matchStartDate,
this.defaultMatchStatistics,
this.defaultMatchStatus);
}
public Match Build(DateTime startDate)
=> this.WithStartDate(startDate).Build();
}
}
|
using ContestsPortal.Domain.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContestsPortal.Domain.DataAccess.Providers.Interfaces
{
public interface IProgrammingLanguageProvider
{
Task<IList<ProgrammingLanguage>> GetAllProgrammingLanguagesAsync();
Task<ProgrammingLanguage> GetProgrammingLanguageAsync(int languageId);
Task<IdentityResult> AddProgrammingLanguageAsync(ProgrammingLanguage newLanguage);
Task<IdentityResult> DeleteContestAsync(int languageId);
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class cooldownUI : MonoBehaviour {
public AnitoMovement onCooldown;
public Image image;
void Start(){
onCooldown = GameObject.Find ("proto_anito").GetComponent<AnitoMovement> ();
image = GetComponent<Image> ();
}
// Update is called once per frame
void Update () {
if (onCooldown.activated == true) {
image.fillAmount = Mathf.Lerp (image.fillAmount,1.0f, Time.deltaTime * 1f);
}
}
}
|
using System.Web.Mvc;
namespace LiveTest.Controllers
{
public class MouseController : Controller
{
// GET: Mouse
public ActionResult Index(int? id)
{
return View(id);
}
[HttpGet]
public ActionResult About()
{
return View();
}
}
} |
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Service.Contracts;
using SiemensCommunity.Adapters;
using SiemensCommunity.Models;
using System.Net;
using System.Threading.Tasks;
namespace SiemensCommunity.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
private readonly IAccountService _accountService;
private readonly UserAdapter _userAdapter = new UserAdapter();
public AccountController(IAccountService accountService)
{
_accountService = accountService;
}
[HttpPost("register")]
public async Task<IActionResult> Register(UserRegisterCredentials registerCredentials)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
else
{
var returnedUserId = await _accountService.RegisterAsync(_userAdapter.Adapt(registerCredentials));
if (returnedUserId != 0)
{
return Ok(returnedUserId);
}
else
{
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
}
[HttpPost("login")]
public async Task<IActionResult> Login(UserLoginCredentials userLoginCredentials)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
else
{
var responseLogin =await _accountService.VerifyLoginAsync(_userAdapter.Adapt(userLoginCredentials));
if (responseLogin)
return Ok();
else return BadRequest();
}
}
[HttpPost("forgotPassword")]
public async Task<IActionResult> ForgotPassword(string email)
{
var result = await _accountService.ForgotPasswordAsync(email);
if (result == true)
{
return Ok();
}
else
{
return BadRequest();
}
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using RepositoryAndUnitOfWork.Contracts;
using RepositoryAndUnitOfWork.Data;
using RepositoryAndUnitOfWork.Models;
namespace RepositoryAndUnitOfWork.Controllers
{
public class UsersController : Controller
{
private readonly IUnitOfWork _uow;
public UsersController(IUnitOfWork uow)
{
_uow = uow;
}
// GET: Users
public async Task<IActionResult> Index()
{
return View(await _uow.UserRepository.GetAllAsync());
}
// GET: Users/Details/5
public async Task<IActionResult> Details(int? id,CancellationToken cancellationToken)
{
if (id == null)
{
return NotFound();
}
var user = await _uow.UserRepository
.GetByIdAsync(cancellationToken,id);
if (user == null)
{
return NotFound();
}
return View(user);
}
// GET: Users/Create
public IActionResult Create()
{
return View();
}
// POST: Users/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name")] User user)
{
if (ModelState.IsValid)
{
_uow.UserRepository.Add(user);
await _uow.CommitAsync();
return RedirectToAction(nameof(Index));
}
return View(user);
}
// GET: users/Edit/5
public async Task<IActionResult> Edit(int? id,CancellationToken cancellationToken)
{
if (id == null)
{
return NotFound();
}
var user = await _uow.UserRepository.GetByIdAsync(cancellationToken, id);
if (user == null)
{
return NotFound();
}
return View(user);
}
// POST: users/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] User user)
{
if (id != user.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_uow.UserRepository.Update(user);
await _uow.CommitAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserExists(user.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(user);
}
// GET: users/Delete/5
public async Task<IActionResult> Delete(int? id,CancellationToken cancellationToken)
{
if (id == null)
{
return NotFound();
}
var user = await _uow.UserRepository
.GetByIdAsync(cancellationToken, id);
if (user == null)
{
return NotFound();
}
return View(user);
}
// POST: users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id,CancellationToken cancellationToken)
{
var user = await _uow.UserRepository.GetByIdAsync(cancellationToken, id);
_uow.UserRepository.Delete(user);
await _uow.CommitAsync();
return RedirectToAction(nameof(Index));
}
private bool UserExists(int id)
{
var user = _uow.UserRepository.GetById(id);
return user != null;
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using gView.DataSources.Fdb.MSSql;
using gView.Framework.IO;
using gView.Framework.system;
using gView.Framework.UI;
using gView.Framework.UI.Dialogs;
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
namespace gView.DataSources.Fdb.UI.MSSql
{
public partial class FormCreateSQLFeatureDatabase : Form
{
private IExplorerObject _resultExObject = null;
private AdvancedSettings _advancedSettings = new AdvancedSettings();
public FormCreateSQLFeatureDatabase()
{
InitializeComponent();
cmbType.SelectedIndex = 0;
SqlServerLocator locator = new SqlServerLocator();
string[] servers = locator.GetServers();
if (servers != null)
{
foreach (string server in servers)
{
cmbServer.Items.Add(server);
}
}
}
private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
{
lUser.Enabled = lPassword.Enabled = txtUser.Enabled = txtPassword.Enabled = (cmbType.SelectedIndex == 0);
}
private void chkCreateConnection_CheckedChanged(object sender, EventArgs e)
{
txtObject.Enabled = chkCreateConnection.Checked;
}
public string ConnectionString
{
get
{
switch (cmbType.SelectedIndex)
{
case 0:
return "server=" + cmbServer.Text + ";uid=" + txtUser.Text + ";pwd=" + txtPassword.Text;
case 1:
return "server=" + cmbServer.Text + ";Trusted_Connection=True;";
}
return "";
}
}
public string FullConnectionString
{
get
{
switch (cmbType.SelectedIndex)
{
case 0:
return "server=" + cmbServer.Text + ";database=" + txtDatabase.Text + ";uid=" + txtUser.Text + ";pwd=" + txtPassword.Text;
case 1:
return "server=" + cmbServer.Text + ";database=" + txtDatabase.Text + ";Trusted_Connection=True;";
}
return "";
}
}
public bool CreateFromMDF
{
get { return chkUseFile.Checked; }
}
public string MdfFilename
{
get { return txtFilename.Text; }
}
async private void btnOK_Click(object sender, EventArgs e)
{
try
{
Cursor = Cursors.WaitCursor;
SqlFDB fdb = new SqlFDB();
if (CreateFromMDF && MdfFilename != String.Empty)
{
await fdb.Open(ConnectionString);
if (!fdb.Create(txtDatabase.Text, MdfFilename))
{
MessageBox.Show(fdb.LastErrorMessage, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
await fdb.Open(ConnectionString);
UserData parameters = _advancedSettings.ToUserData();
if (btnOnlyRepository.Checked)
{
parameters.SetUserData("CreateDatabase", false);
}
if (!fdb.Create(txtDatabase.Text, parameters))
{
MessageBox.Show(fdb.LastErrorMessage, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (chkCreateReplicationDatamodel.Checked == true)
{
if (!await gView.Framework.Offline.Replication.CreateRelicationModel(fdb))
{
MessageBox.Show("RepliCreateRelicationModel failed:\n", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
if (chkCreateConnection.Checked)
{
string connStr = FullConnectionString;
ConfigTextStream stream = new ConfigTextStream("sqlfdb_connections", true, true);
string id = txtObject.Text;
stream.Write(FullConnectionString, ref id);
stream.Close();
_resultExObject = new SqlFDBExplorerObject(null, id, FullConnectionString);
}
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("FATAL ERROR: " + ex.Message);
}
finally
{
Cursor = Cursors.Default;
}
}
public IExplorerObject ResultExplorerObject
{
get { return _resultExObject; }
}
private void txtDatabase_TextChanged(object sender, EventArgs e)
{
txtObject.Text = txtDatabase.Text;
}
private void chkUseFile_CheckedChanged(object sender, EventArgs e)
{
lFilename.Enabled = txtFilename.Enabled = btnGetMDF.Enabled = chkUseFile.Checked;
btnAdvanced.Enabled = chkCreateReplicationDatamodel.Enabled = !chkUseFile.Checked;
btnCreateDatabase.Enabled = btnOnlyRepository.Enabled = !chkUseFile.Checked;
if (chkUseFile.Checked == true)
{
btnOK.Enabled = txtFilename.Text.Trim() != String.Empty;
}
else
{
btnOK.Enabled = true;
}
}
private void btnGetMDF_Click(object sender, EventArgs e)
{
if (openMdfFileDialog.ShowDialog() == DialogResult.OK)
{
txtFilename.Text = openMdfFileDialog.FileName;
}
}
private void txtFilename_TextChanged(object sender, EventArgs e)
{
btnOK.Enabled = txtFilename.Text.Trim() != String.Empty;
}
private void btnAdvanced_Click(object sender, EventArgs e)
{
FormPropertyGrid grid = new FormPropertyGrid(_advancedSettings);
grid.ShowDialog();
}
#region Classes
class AdvancedSettings
{
private string _filename = String.Empty;
private string _name = String.Empty;
int _size = 0, _maxsize = 0, _filegrowth = 0;
[Category("File")]
[Editor(typeof(SaveMdfFileEditor), typeof(System.Drawing.Design.UITypeEditor))]
public string FILENAME
{
get { return _filename; }
set { _filename = value; }
}
[Category("Name")]
public string NAME
{
get { return _name; }
set { _name = value; }
}
[Category("Size")]
public int SIZE
{
get { return _size; }
set { _size = value; }
}
[Category("Size")]
public int MAXSIZE
{
get { return _maxsize; }
set { _maxsize = value; }
}
[Category("Size")]
public int FILEGROWTH
{
get { return _filegrowth; }
set { _filegrowth = value; }
}
public UserData ToUserData()
{
UserData ud = new UserData();
if (!String.IsNullOrEmpty(_name))
{
ud.SetUserData("NAME", _name);
}
if (!String.IsNullOrEmpty(_filename))
{
ud.SetUserData("FILENAME", _filename);
}
if (_size > 0)
{
ud.SetUserData("SIZE", _size.ToString());
}
if (_maxsize > 0)
{
ud.SetUserData("MAXSIZE", _maxsize.ToString());
}
if (_filegrowth > 0)
{
ud.SetUserData("FILEGROWTH", _filegrowth);
}
return ud;
}
}
class SaveMdfFileEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "MDF File (*.mdf)|*.mdf";
if (dlg.ShowDialog() == DialogResult.OK)
{
return dlg.FileName;
}
return value;
}
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenuController : MonoBehaviour
{
public Image mainPanel;
public Text highScore;
public Image optionsPanel;
public Image creditsPanel;
string highScoreText = "Player High Score: ";
void Start()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
highScore.text = highScoreText + XMLController.Instance.GetHighScore();
TogglePanel(optionsPanel, false);
TogglePanel(creditsPanel, false);
}
public void OnStartPressed()
{
if (XMLController.Instance.GetSecretStatus() == 1)
SceneManager.LoadScene("elsewhere");
else
SceneManager.LoadScene("neighborhood");
}
public void OnExitPressed()
{
Application.Quit();
}
public void OnOptionsPressed()
{
TogglePanel(mainPanel, false);
TogglePanel(optionsPanel, true);
}
public void OnOptionsBackPressed()
{
TogglePanel(optionsPanel, false);
TogglePanel(mainPanel, true);
}
public void OnCreditsPressed()
{
TogglePanel(mainPanel, false);
TogglePanel(creditsPanel, true);
}
public void OnCreditsBackPressed()
{
TogglePanel(creditsPanel, false);
TogglePanel(mainPanel, true);
}
void TogglePanel(Image panel, bool isOn)
{
panel.gameObject.SetActive(isOn);
for (int i = 0; i < panel.transform.childCount; i++)
{
panel.transform.GetChild(i).gameObject.SetActive(isOn);
}
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Escape))
Application.Quit();
}
}
|
using Microsoft.ML;
using Microsoft.ML.Data;
using System;
using System.Collections.Generic;
using System.Threading;
namespace ia_toniazo
{
class Program
{
static void Main(string[] args)
{
//var data = new CreateDataBySantaMaria().CreateData();
MLContext mlContext = new MLContext(seed:1);
var trainingData = Populate.Training();
var model = Train(mlContext, trainingData);
Evaluate(mlContext, model);
TestSinglePrediction(mlContext, model);
}
public static ITransformer Train(MLContext mlContext, List<DatasetModel> data)
{
IDataView dataView = mlContext.Data.LoadFromEnumerable<DatasetModel>(data);
var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: "Valor")
.Append(mlContext.Transforms.Concatenate("Features",
"TamanhoTotal",
"TamanhoPrivativo",
"Bairro",
"Suite",
"Quartos",
"Garagem"))
.Append(mlContext.Regression.Trainers.FastTreeTweedie(numberOfLeaves: 50, numberOfTrees: 250, minimumExampleCountPerLeaf: 80, learningRate: 0.9));
var model = pipeline.Fit(dataView);
return model;
}
private static void Evaluate(MLContext mlContext, ITransformer model)
{
var testeData = new List<DatasetModel>()
{
new DatasetModel(1, 42, 589000, 2, 1, 2, 99.7, 99.7),
new DatasetModel(1, 35, 190000, 2, 0, 1, 52.65, 59.29 ),
new DatasetModel(1, 11, 350000, 1, 0, 1, 36.03, 61.83 ),
new DatasetModel(1, 24, 650000, 2, 1, 2, 113.2, 138.99),
new DatasetModel(1, 11, 300000, 0, 1, 1, 47.22, 60.76 ),
new DatasetModel(1, 35, 550000, 1, 1, 2, 134, 134 ),
new DatasetModel(1, 11, 379000, 2, 0, 1, 47.17, 96.13 ),
new DatasetModel(1, 24, 420000, 1, 1, 2, 69.59, 118.48),
new DatasetModel(1, 47, 230000, 2, 1, 1, 79.84, 125.79),
new DatasetModel(1, 16, 230000, 2, 0, 1, 48.3, 94 ),
new DatasetModel(1, 35, 190000, 2, 0, 1, 52.65, 59.29 ),
new DatasetModel(2, 11, 350000, 1, 0, 1, 36.03, 61.83 ),
new DatasetModel(3, 24, 650000, 2, 1, 2, 113.2, 138.99),
new DatasetModel(2, 11, 300000, 0, 1, 1, 47.22, 60.76 ),
new DatasetModel(3, 35, 550000, 1, 1, 2, 134, 134 ),
new DatasetModel(1, 47, 230000, 2, 1, 1, 79.84, 125.79),
new DatasetModel(1, 16, 230000, 2, 0, 1, 48.3, 94 ),
new DatasetModel(1, 11, 318000, 1, 0, 0, 36.03, 61.83 ),
new DatasetModel(1, 42, 589000, 2, 1, 2, 99.7, 99.7),
new DatasetModel(1, 35, 190000, 2, 0, 1, 52.65, 59.29 ),
};
IDataView dataView = mlContext.Data.LoadFromEnumerable<DatasetModel>(testeData);
var predictions = model.Transform(dataView);
var metrics = mlContext.Regression.Evaluate(predictions, "Label", "Score");
Console.WriteLine();
Console.WriteLine($"*************************************************");
Console.WriteLine($"* Metricas de Analise de testes com {testeData.Count} itens ");
Console.WriteLine($"*------------------------------------------------");
Console.WriteLine($"* Coeficiente de determinação: {metrics.RSquared}");
Console.WriteLine($"* Raiz quadrada do erro-médio: {metrics.RootMeanSquaredError}");
Console.WriteLine($"* Função de perda : {metrics.LossFunction}");
Console.WriteLine($"* Erro Quadrático Médio: {metrics.MeanSquaredError}");
Console.WriteLine($"* Erro médio absoluto: {metrics.MeanAbsoluteError}");
Console.WriteLine($"*************************************************");
}
private static void TestSinglePrediction(MLContext mlContext, ITransformer model)
{
var predictionFunction = mlContext.Model.CreatePredictionEngine<DatasetModel, Prediction>(model);
var simpleOffer = new DatasetModel()
{
TamanhoTotal = 59F,
TamanhoPrivativo = 52F,
Bairro = (int) Bairro.Centro,
Quartos = 2,
Suite = 0,
Garagem = 1,
Valor = 0F
};
var prediction = predictionFunction.Predict(simpleOffer);
Console.WriteLine($"***************************************************");
Console.WriteLine($"Teste de previsão: Tamanho:{simpleOffer.TamanhoTotal} = {(((prediction.Valor) * simpleOffer.TamanhoTotal) / 10)}");
Console.WriteLine($"**************************************************");
Thread.Sleep(30000);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp.Functions
{
internal class Lambda
{
internal void Do()
{
#region 戻り値のない関数を実行するラムダ式
output("戻り値のないラムダ式を実行する");
Action lambda1 = () => output("excute lambda noparam");
doActionLambda(lambda1);
Action<string> lambda2 = (msg) => output($"excute lambda param:msg->{msg}");
doActionLambda<string>(lambda2, "hello");
Action<string, int> lambda3 = (str, num) => output($"excute lambda param:str->{str} , num->{num}");
doActionLambda<string, int>(lambda3, "hello", 1);
#endregion
#region 戻り値のある関数を実行するラムダ式
output("戻り値があるラムダ式を実行する");
Func<string> lambda4 = () => "lambda4";
doFuncLambda<string>(lambda4);
Func<int, string> lambda5 = (num) => "lambda" + Convert.ToString(num);
doFuncLambda<int, string>(lambda5, 5);
Func<string, int, string> lambda6 = (str, num) => str + Convert.ToString(num);
doFuncLambda<string, int, string>(lambda6, "lambda", 6);
#endregion
#region ループで使用するラムダ式
var agelist = new List<int>(new int[] { 0, 1, 2, 3, 4, 5 });
output($"agelist -> {string.Join(',', agelist)}");
agelist.ForEach(age => output($"agelist.ForEach age -> {age}"));
agelist.Sort((age1, age2) => age2 - age1);
output($"agelist desc -> {string.Join(',', agelist)}");
agelist.Sort((age1, age2) => age1 - age2);
output($"agelist asc -> {string.Join(',', agelist)}");
bool isexist = agelist.Exists(age => age == 2);
output($"agelist.Exists(age == 2) return -> {isexist}");
isexist = agelist.Exists(age => age == 10);
output($"agelist.Exists(age == 10) return -> {isexist}");
#endregion
}
private void output(string value)
{
Console.WriteLine(value);
}
private void doActionLambda(Action lambda)
{
lambda();
}
private void doActionLambda<T>(Action<T> lambda, T msg)
{
lambda(msg);
}
private void doActionLambda<T1, T2>(Action<T1, T2> lambda, T1 param1, T2 param2)
{
lambda(param1, param2);
}
private void doFuncLambda<TResult>(Func<TResult> lambda)
{
TResult result = lambda();
output($"excute lambda noparam return -> {result.ToString()}");
}
private void doFuncLambda<T1, TResult>(Func<T1, TResult> lambda, T1 param1)
{
TResult result = lambda(param1);
output($"excute lambda param1->{param1}, return -> {result.ToString()}");
}
private void doFuncLambda<T1, T2, TResult>(Func<T1, T2, TResult> lambda, T1 param1, T2 param2)
{
TResult result = lambda(param1, param2);
output($"excute lambda param1->{param1}, param2->{param2}, return -> {result.ToString()}");
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class OnOffBotton : MonoBehaviour {
GameObject panel;
bool isOpen = false;
// Use this for initialization
void Start () {
//Button button = this.GetComponent <Button> ();
panel = GameObject.Find("SettingPanel");
}
// Update is called once per frame
void Update () {
panel.SetActive(isOpen);
}
public void OnBottonClick() {
if (!isOpen) {
isOpen = true;
return;
}
isOpen = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using AxisEq.CustomerDisplays;
namespace AxisEq
{
public class WincorCustomerDisplay : AbstractCustomerDisplay
{
public override int InitEncoding(int codepage)
{
// CodePage = codepage;
return 0;
}
public override int Open(string portName, string baudRate)
{
try
{
Sp = new SerialPort(portName, Convert.ToInt32(baudRate), Parity.Odd);
Sp.Open();
byte[] buf = new byte[] { 27, 82, 41 };
Sp.Write(buf, 0, 3);
return 0;
}
catch (Exception)
{
return 1;
}
}
public override int Close()
{
if (Sp != null)
if (Sp.IsOpen) Sp.Close();
return 0;
}
public override int Clear()
{
byte[] buf = new byte[] { 27, 91, 50, 74 };
Sp.Write(buf, 0, buf.Length);
return 0;
}
public override int TextXy(int x, int y, string text)
{
try
{
//Cursor position
byte[] buf = new byte[] { 27, 91, 0, 59, 0, 72 };
buf[2] = Encoding.GetEncoding(866).GetBytes((y).ToString())[0];
buf[4] = Encoding.GetEncoding(866).GetBytes((x).ToString())[0];
Sp.Write(buf, 0, buf.Length);
for (int i = 0; i < text.Length; i++)
{
buf[0] = Encoding.GetEncoding(866).GetBytes(text)[i];
Sp.Write(buf, 0, 1);
}
}
catch (Exception)
{
return 1;
}
return 0;
}
}
}
|
#version 430
layout(local_size_x = 32, local_size_y = 32) in;
layout(binding = 0) uniform sampler3D volumeDataTexture;
layout(binding = 1) uniform sampler3D volumeFloodSDF;
//layout(binding= 1) uniform sampler3D volumeColorTexture;
//layout(binding= 2) uniform sampler2D currentTextureColor;
layout(binding = 0, rgba16f) uniform image3D volumeData; // Gimage3D, where G = i, u, or blank, for int, u int, and floats respectively
layout(binding = 1, rgba32f) uniform image2DArray refVertex;
layout(binding = 2, rgba32f) uniform image2DArray refNormal;
uniform mat4 cameraPoses[4];
uniform int numberOfCameras;
//layout(binding = 1, r32f) uniform image2D volumeSlice;
//layout(binding = 3, rgba32f) uniform image2D volumeSliceNorm;
//layout(binding = 2, rgba32f) uniform image3D volumeColor;
//layout(std430, binding= 2) buffer posTsdf3D // ouput
//{
// vec4 PositionTSDF [];
//};
//layout(std430, binding= 3) buffer norm3D // ouput
//{
// vec4 NormalTSDF [];
//};
uniform mat4 view; // == raycast pose * invK
uniform float nearPlane;
uniform float farPlane;
uniform float step;
uniform float largeStep;
uniform vec3 volDim;
uniform vec3 volSize;
vec3 getVolumePosition(uvec3 p)
{
return vec3((p.x + 0.5f) * volDim.x / volSize.x, (p.y + 0.5f) * volDim.y / volSize.y, (p.z + 0.5f) * volDim.z / volSize.z);
}
vec3 rotate(mat4 M, vec3 V)
{
// glsl and glm [col][row]
return vec3(dot(vec3(M[0][0], M[1][0], M[2][0]), V),
dot(vec3(M[0][1], M[1][1], M[2][1]), V),
dot(vec3(M[0][2], M[1][2], M[2][2]), V));
}
vec3 opMul(mat4 M, vec3 v)
{
return vec3(
dot(vec3(M[0][0], M[1][0], M[2][0]), v) + M[3][0],
dot(vec3(M[0][1], M[1][1], M[2][1]), v) + M[3][1],
dot(vec3(M[0][2], M[1][2], M[2][2]), v) + M[3][2]);
}
float vs(uvec3 pos)
{
//vec4 data = imageLoad(volumeData, ivec3(pos));
//return data.x; // convert short to float
return imageLoad(volumeData, ivec3(pos)).x;
}
float interpVol(vec3 pos)
{
vec3 scaled_pos = vec3((pos.x * volSize.x / volDim.x) - 0.5f, (pos.y * volSize.y / volDim.y) - 0.5f, (pos.z * volSize.z / volDim.z) - 0.5f);
ivec3 base = ivec3(floor(scaled_pos));
vec3 factor = fract(scaled_pos);
ivec3 lower = max(base, ivec3(0));
ivec3 upper = min(base + ivec3(1), ivec3(volSize) - ivec3(1));
return (
((vs(uvec3(lower.x, lower.y, lower.z)) * (1 - factor.x) + vs(uvec3(upper.x, lower.y, lower.z)) * factor.x) * (1 - factor.y)
+ (vs(uvec3(lower.x, upper.y, lower.z)) * (1 - factor.x) + vs(uvec3(upper.x, upper.y, lower.z)) * factor.x) * factor.y) * (1 - factor.z)
+ ((vs(uvec3(lower.x, lower.y, upper.z)) * (1 - factor.x) + vs(uvec3(upper.x, lower.y, upper.z)) * factor.x) * (1 - factor.y)
+ (vs(uvec3(lower.x, upper.y, upper.z)) * (1 - factor.x) + vs(uvec3(upper.x, upper.y, upper.z)) * factor.x) * factor.y) * factor.z
) * 0.00003051944088f;
}
float interpDistance(vec3 pos, inout bool interpolated)
{
//vec3 scaled_pos = vec3((pos.x * volSize.x / volDim.x) - 0.5f, (pos.y * volSize.y / volDim.y) - 0.5f, (pos.z * volSize.z / volDim.z) - 0.5f);
float i = pos.x;
float j = pos.y;
float k = pos.z;
float w_sum = 0.0;
float sum_d = 0.0;
ivec3 current_voxel;
float w = 0;
float volume;
int a_idx;
interpolated = false;
for (int i_offset = 0; i_offset < 2; i_offset++)
{
for (int j_offset = 0; j_offset < 2; j_offset++)
{
for (int k_offset = 0; k_offset < 2; k_offset++)
{
current_voxel.x = int(i) + i_offset;
current_voxel.y = int(j) + j_offset;
current_voxel.z = int(k) + k_offset;
volume = abs(current_voxel.x - i) + abs(current_voxel.y - j) + abs(current_voxel.z - k);
vec4 data = imageLoad(volumeData, current_voxel);
if (data.y > 0)
{
interpolated = true;
// if (volume < 0.00001)
// {
// return float (data.x * 0.00003051944088f);
// }
w = 1.0f / volume;
w_sum += float(w);
sum_d += float(w) * float(data.x * 0.00003051944088f);
}
}
}
}
return sum_d / w_sum;
}
vec4 raycast(uvec2 pos, int camera)
{
vec3 origin = vec3(cameraPoses[camera][3][0], cameraPoses[camera][3][1], cameraPoses[camera][3][2]);
//vec3 direction = rotate(view, vec3(pos.x, pos.y, 1.0f));
vec3 direction = vec3((cameraPoses[camera] * vec4(pos.x, pos.y, 1.0f, 0.0f)).xyz);
// intersect ray with a box
// http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter3.htm
// compute intersection of ray with all six bbox planes
vec3 invR = vec3(1.0f, 1.0f, 1.0f) / direction;
vec3 tbot = -1.0f * invR * origin;
vec3 ttop = invR * (volDim - origin);
// re-order intersections to find smallest and largest on each axis
vec3 tmin = min(ttop, tbot);
vec3 tmax = max(ttop, tbot);
// find the largest tmin and the smallest tmax
float largest_tmin = max(max(tmin.x, tmin.y), max(tmin.x, tmin.z));
float smallest_tmax = min(min(tmax.x, tmax.y), min(tmax.x, tmax.z));
// check against near and far plane
float tnear = max(largest_tmin, nearPlane);
float tfar = min(smallest_tmax, farPlane);
if (tnear < tfar)
{
// first walk with largesteps until we found a hit
float t = tnear;
float stepsize = largeStep;
//float f_t = volume.interp(origin + direction * t); // do a sampler3D?
//vec3 tPos = (origin + direction * t);
//vec3 scaled_pos = vec3((tPos.x * volSize.x / volDim.x), (tPos.y * volSize.y / volDim.y), (tPos.z * volSize.z / volDim.z));
//vec3 base = floor(scaled_pos);
// vec4 interpData = texture(volumeDataTexture, vec3(origin + direction * t) / volDim.x); // volume texture reads should just be 0 - 1
// ivec4 interpData = texture(volumeDataTexture, base / volSize.x); // volume texture reads should just be 0 - 1
//float f_t = interpData.x;
//float f_t = float(interpData.x) * 0.00003051944088f;
bool isInterp;
float f_t = interpVol(vec3(origin + direction * t));
//vec3 tPos = (origin + direction * t);
//vec3 scaled_pos = vec3((tPos.x * volSize.x / volDim.x) - 0.5f, (tPos.y * volSize.y / volDim.y) - 0.5f, (tPos.z * volSize.z / volDim.z) - 0.5f);
//float f_t = interpDistance(scaled_pos, isInterp);
// float currWeight = 0;
float f_tt = 0;
if (f_t >= 0)
{ // ups, if we were already in it, then don't render anything here
for (; t < tfar; t += stepsize)
{
//f_tt = volume.interp(origin + direction * t); // another sampler3d
//vec4 d1 = texture(volumeDataTexture, vec3(origin + direction * t) / volDim.x); // if volDim is square!!!
//ivec4 d1 = texture(volumeDataTexture, vec3(origin + direction * t) / volDim.x); // if volDim is square!!!
//currWeight = d1.z;
//f_tt = d1.x;
//f_tt = float(d1.x) * 0.00003051944088f;
f_tt = interpVol(vec3(origin + direction * t));
//tPos = (origin + direction * t);
//scaled_pos = vec3((tPos.x * volSize.x / volDim.x) - 0.5f, (tPos.y * volSize.y / volDim.y) - 0.5f, (tPos.z * volSize.z / volDim.z) - 0.5f);
//f_tt = interpDistance(scaled_pos, isInterp);
if (f_tt < 0) // got it, jump out of inner loop
{
//imageStore(volumeSliceNorm, ivec2(pos), vec4(1, 0, 0, 1));
break; //
}
if (f_tt < 0.8f)
{
stepsize = step;
}
f_t = f_tt;
}
if (f_tt < 0) // got it, calculate accurate intersection
{
t = t + stepsize * f_tt / (f_t - f_tt);
return vec4(origin + direction * t, t);
}
}
}
return vec4(0.0f, 0.0f, 0.0f, 0.0f);
}
vec3 getGradient(vec4 hit)
{
vec3 scaled_pos = vec3((hit.x * volSize.x / volDim.x) - 0.5f, (hit.y * volSize.y / volDim.y) - 0.5f, (hit.z * volSize.z / volDim.z) - 0.5f);
ivec3 baseVal = ivec3(floor(scaled_pos));
vec3 factor = fract(scaled_pos);
ivec3 lower_lower = max(baseVal - ivec3(1), ivec3(0));
ivec3 lower_upper = max(baseVal, ivec3(0));
ivec3 upper_lower = min(baseVal + ivec3(1), ivec3(volSize) - ivec3(1));
ivec3 upper_upper = min(baseVal + ivec3(2), ivec3(volSize) - ivec3(1));
ivec3 lower = lower_upper;
ivec3 upper = upper_lower;
vec3 gradient;
gradient.x =
(((vs(uvec3(upper_lower.x, lower.y, lower.z)) - vs(uvec3(lower_lower.x, lower.y, lower.z))) * (1 - factor.x)
+ (vs(uvec3(upper_upper.x, lower.y, lower.z)) - vs(uvec3(lower_upper.x, lower.y, lower.z))) * factor.x) * (1 - factor.y)
+ ((vs(uvec3(upper_lower.x, upper.y, lower.z)) - vs(uvec3(lower_lower.x, upper.y, lower.z))) * (1 - factor.x)
+ (vs(uvec3(upper_upper.x, upper.y, lower.z)) - vs(uvec3(lower_upper.x, upper.y, lower.z))) * factor.x) * factor.y) * (1 - factor.z)
+ (((vs(uvec3(upper_lower.x, lower.y, upper.z)) - vs(uvec3(lower_lower.x, lower.y, upper.z))) * (1 - factor.x)
+ (vs(uvec3(upper_upper.x, lower.y, upper.z)) - vs(uvec3(lower_upper.x, lower.y, upper.z))) * factor.x) * (1 - factor.y)
+ ((vs(uvec3(upper_lower.x, upper.y, upper.z)) - vs(uvec3(lower_lower.x, upper.y, upper.z))) * (1 - factor.x)
+ (vs(uvec3(upper_upper.x, upper.y, upper.z)) - vs(uvec3(lower_upper.x, upper.y, upper.z))) * factor.x) * factor.y) * factor.z;
gradient.y =
(((vs(uvec3(lower.x, upper_lower.y, lower.z)) - vs(uvec3(lower.x, lower_lower.y, lower.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, upper_lower.y, lower.z)) - vs(uvec3(upper.x, lower_lower.y, lower.z))) * factor.x) * (1 - factor.y)
+ ((vs(uvec3(lower.x, upper_upper.y, lower.z)) - vs(uvec3(lower.x, lower_upper.y, lower.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, upper_upper.y, lower.z)) - vs(uvec3(upper.x, lower_upper.y, lower.z))) * factor.x) * factor.y) * (1 - factor.z)
+ (((vs(uvec3(lower.x, upper_lower.y, upper.z)) - vs(uvec3(lower.x, lower_lower.y, upper.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, upper_lower.y, upper.z)) - vs(uvec3(upper.x, lower_lower.y, upper.z))) * factor.x) * (1 - factor.y)
+ ((vs(uvec3(lower.x, upper_upper.y, upper.z)) - vs(uvec3(lower.x, lower_upper.y, upper.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, upper_upper.y, upper.z)) - vs(uvec3(upper.x, lower_upper.y, upper.z))) * factor.x) * factor.y) * factor.z;
gradient.z =
(((vs(uvec3(lower.x, lower.y, upper_lower.z)) - vs(uvec3(lower.x, lower.y, lower_lower.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, lower.y, upper_lower.z)) - vs(uvec3(upper.x, lower.y, lower_lower.z))) * factor.x) * (1 - factor.y)
+ ((vs(uvec3(lower.x, upper.y, upper_lower.z)) - vs(uvec3(lower.x, upper.y, lower_lower.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, upper.y, upper_lower.z)) - vs(uvec3(upper.x, upper.y, lower_lower.z))) * factor.x) * factor.y) * (1 - factor.z)
+ (((vs(uvec3(lower.x, lower.y, upper_upper.z)) - vs(uvec3(lower.x, lower.y, lower_upper.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, lower.y, upper_upper.z)) - vs(uvec3(upper.x, lower.y, lower_upper.z))) * factor.x) * (1 - factor.y)
+ ((vs(uvec3(lower.x, upper.y, upper_upper.z)) - vs(uvec3(lower.x, upper.y, lower_upper.z))) * (1 - factor.x)
+ (vs(uvec3(upper.x, upper.y, upper_upper.z)) - vs(uvec3(upper.x, upper.y, lower_upper.z))) * factor.x) * factor.y) * factor.z;
return gradient * vec3(volDim.x / volSize.x, volDim.y / volSize.y, volDim.z / volSize.z) * (0.5f * 0.00003051944088f);
}
void main()
{
// ivec2 depthSize = ivec2(512, 424);// imageSize(depthImage);
uvec2 pix = gl_GlobalInvocationID.xy;
for (int camera = 0; camera < numberOfCameras; camera++)
{
vec4 hit = raycast(pix, camera);
if (hit.w > 0)
{
// vec4 currentColor = texture(currentTextureColor, vec2(pix.x / 1920.0f, pix.y / 1080.0f));
// imageStore(volumeColor, ivec3(hit.xyz), currentColor);
//imageStore(volumeSlice, ivec2(pix), vec4(mod(hit.w * 10.f, 1.0f), 0, 0, 0));
// PositionTSDF[(pix.y * depthSize.x) + pix.x] = vec4(hit.xyz, 1.0f); // hit.w = hit.z + zshift
imageStore(refVertex, ivec3(pix, camera), vec4(hit.xyz, 1.0f));
vec3 surfNorm = getGradient(hit);// volume.grad(make_float3(hit));
if (length(surfNorm) == 0)
{
//imageStore(volumeSliceNorm, ivec2(pix), vec4(0, 0, 0, 0));
imageStore(refNormal, ivec3(pix, camera), vec4(0.0f));
// NormalTSDF[(pix.y * depthSize.x) + pix.x] = vec4(0);
}
else
{
//imageStore(volumeSliceNorm, ivec2(pix), currentColor);
//imageStore(volumeSliceNorm, ivec2(pix), vec4(normalize(surfNorm), 0.0f));
// NormalTSDF[(pix.y * depthSize.x) + pix.x] = vec4(normalize(surfNorm), 0.0f);
imageStore(refNormal, ivec3(pix, camera), vec4(normalize(surfNorm), 1.0f));
}
}
else
{
//imageStore(volumeSlice, ivec2(pix), vec4(hit.z / 2.0f, 0, 0, 0));
//imageStore(volumeSliceNorm, ivec2(pix), vec4(0, 0, 0, 0));
imageStore(refVertex, ivec3(pix, camera), vec4(0.0f));
imageStore(refNormal, ivec3(pix, camera), vec4(0.0f));
//PositionTSDF[(pix.y * depthSize.x) + pix.x] = vec4(0);
// NormalTSDF[(pix.y * depthSize.x) + pix.x] = vec4(0, 0, 0, 0); // set x = 2??
}
}
//vec3 pos = opMul(invTrack, getVolumePosition(pix));
//vec3 cameraX = opMul(K, pos);
//vec3 delta = rotate(invTrack, vec3(0.0f, 0.0f, volDim.z / volSize.z));
//vec3 cameraDelta = rotate(K, delta);
}
// USEFUL SANITY CHECKING STUFF
// vec4 interpData = texture(volumeDataTexture, vec3(pix / 256.0f, 2)); // texture float reads are from 0 - 1
//vec4 interpData = texelFetch(volumeDataTexture, ivec3(pix, 0), 0);
// vec4 interpData = imageLoad(volumeData, ivec3(pix, 0));
//if (interpData.x > -5.0f && interpData.x < 0.0f)
//{
// imageStore(volumeSlice, ivec2(pix), vec4(0.5f, 0, 0, 0));
//}
//if (interpData.x > 0.0f && interpData.x < 5.0f)
//{
// imageStore(volumeSlice, ivec2(pix), vec4(0.25f, 0, 0, 0));
//} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Http;
using System.Data.Entity;
using chat.Models;
using chat.Sources.Files;
using chat.Sources.Startup;
using System.Configuration;
namespace chat
{
public class Global:HttpApplication
{
void Application_Start(object sender,EventArgs e)
{
if(!(Database.Exists(ConfigurationManager.ConnectionStrings[ "DataContext" ].ConnectionString)))
{
//resets user directories after recreation database
Directories.Reset();
}
//drops and creates new database if model data is changes
Database.SetInitializer<DataContext>(new DropCreateDatabaseIfModelChanges<DataContext>());
//fills database with default data
Seed.Genders();
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(Register);
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name :"Default",
url :"{controller}/{action}/{id}",
defaults :new { controller = "Profile",action = "Page",id = UrlParameter.Optional }
);
}
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name :"DefaultApi",
routeTemplate :"api/{controller}/{id}",
defaults :new { id = RouteParameter.Optional }
);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RPG
{
class InventarKlasse
{
private static InventarKlasse global;
private List<string> items;
public void Item_mehr(string name)
{
items.Add(name);
}
public int Itemszählen()
{
int zählen = items.Count;
return zählen;
}
public void ItemEntfernen(string name)
{
int x;
while ((x = items.IndexOf(name)) >= 0)
items.RemoveAt(x);
}
public bool Item (string name)
{
return items.Contains(name);
}
public void Itemsanzeigen()
{
for (int x = 0; x < items.Count; x++)
{
Console.WriteLine(items[x]);
}
}
public InventarKlasse()
{
items = new List<string>();
}
public static InventarKlasse globalesInventar()
{
if(global == null)
global = new InventarKlasse();
return global;
}
}
} |
using UnityEngine;
using System.Collections;
public class StoryController : MonoBehaviour
{
private float timer = 0.0f;
public float storyInterval = 4.0f;
private int currentSlide = -1;
[SerializeField]
private MenuManager menuManager = null;
[SerializeField]
private GameObject[] slides = null;
private bool inputSkip = false;
void Start ()
{
}
void OnEnable()
{
if(this.slides != null && this.slides.Length > 0)
{
this.currentSlide = 0;
this.timer = 0.0f;
this.slides[0].SetActive(true);
}else{
menuManager.OnButtonMainMenu();
}
}
void Update ()
{
this.timer += Time.deltaTime;
if(Input.touchCount > 0 || Input.GetMouseButton(0) || Input.GetMouseButton(1))
{
if(!this.inputSkip)
{
this.timer -= this.storyInterval;
if (this.timer < 0.0f) this.timer = 0.0f;
NextSlide();
}
this.inputSkip = true;
}else{
this.inputSkip = false;
}
if(this.timer > this.storyInterval)
{
this.timer -= this.storyInterval;
NextSlide();
}
}
void NextSlide()
{
this.slides[this.currentSlide].SetActive(false);
++this.currentSlide;
int slidesCount = this.slides.Length;
if (this.currentSlide >= slidesCount)
{
this.menuManager.OnButtonNewGame();
}
else
{
this.slides[this.currentSlide].SetActive(true);
}
}
}
|
using CarManageSystem.helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
namespace CarManageSystem.handler.FuelingCard
{
/// <summary>
/// InputTable 的摘要说明
/// </summary>
public class InputTable : IHttpHandler,IRequiresSessionState
{
static Regex number = new Regex("^[0-9]*$");
public void ProcessRequest(HttpContext context)
{
var currentUser = CheckHelper.RoleCheck(context, 1);
if (currentUser == null)
return;
context.Response.ContentType = "text/plain";
var path = ImageHelper.GetFullFilePath(context.Request.Files["gasInf"]);
dynamic json = new JObject();
json.state = "success";
//处理表格数据 保存到数据库
//读入所有数据,
var dt = ExcelHelper.Import(path);
var rows = dt.AsEnumerable().Where(s => number.Match(s[0].ToString()).Success);
//查找详细信息 , 已存在的不保存
//0 卡号 1持卡人 2交易时间 3交易类型 4金额 5油品 6数量 7单价 8奖励积分 9余额 10 地点
using (cmsdbEntities cms = new cmsdbEntities())
{
var dbMainCard = cms.mainfuelingcard.ToList();
var dbAssociate = cms.associatecardinfo.ToList();
foreach (var row in rows)
{
var mainCard = dbMainCard.FirstOrDefault(s => s.AssociateCardId == row[0].ToString());
//如果主卡中没有绑定此副卡信息,略过
if(mainCard==null)
{
continue;
}
//如果主卡信息的持卡人为空,则增加持卡人信息
if (string.IsNullOrEmpty(mainCard.Cardholder))
{
mainCard.Cardholder = row[1].ToString();
}
var associate = dbAssociate.FirstOrDefault(s => s.AssociateCardId == row[0].ToString() && Convert.ToDateTime(s.TradeTime) == Convert.ToDateTime(row[2]));
//如果副卡信息中已存在此条记录,略过
if (associate!=null)
{
continue;
}
//新增记录
var Associate = new associatecardinfo()
{
AssociateCardId = row[0].ToString(),
CardHolder = row[1].ToString(),
TradeTime = Convert.ToDateTime(row[2]),
TradeType = row[3].ToString(),
Amount = Convert.ToDecimal(row[4]),
OilProduct = row[5].ToString(),
Count = Convert.ToDouble(row[6]),
Price = Convert.ToDecimal(row[7]),
BonusPoints = Convert.ToDouble(row[8]),
Balance = Convert.ToDecimal(row[9]),
Place = row[10].ToString(),
guid=Guid.NewGuid().ToString()
};
cms.associatecardinfo.Add(Associate);
//type 为5 代表加油花费
var cost = new carcostregister()
{
Type = 5,
CarNumber = cms.mainfuelingcard.FirstOrDefault(s => s.AssociateCardId == Associate.AssociateCardId).CarNumber,
Cost = Associate.Amount,
Id = Associate.guid
};
cms.carcostregister.Add(cost);
}
cms.SaveChanges();
cms.Dispose();
context.Response.Write(json.ToString());
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
namespace DChild.Gameplay.Combat
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class AttackTypeAttribute : Attribute
{
private AttackType m_type;
public AttackTypeAttribute(AttackType m_type)
{
this.m_type = m_type;
}
public AttackType type => m_type;
}
} |
using UnityEngine;
using System.Collections;
public class NengLiangLiZiCtrl : MonoBehaviour {
public float MvSpeed = 0.7f;
Transform AimTran;
Transform LiZiTran;
float TimeSpawn;
// Use this for initialization
void Start()
{
TimeSpawn = Time.realtimeSinceStartup;
AimTran = WaterwheelCameraCtrl.GetInstance().NengLiangAimTran;
LiZiTran = transform;
}
// Update is called once per frame
void Update()
{
float dis = Vector3.Distance(LiZiTran.position, AimTran.position);
if (dis <= 0.5f || Time.realtimeSinceStartup - TimeSpawn > 8f) {
XingXingCtrl.GetInstance().AddStarNum();
Destroy(gameObject);
return;
}
Vector3 forwardVal = AimTran.position - LiZiTran.position;
float valSpeed = WaterwheelPlayerCtrl.GetInstance().GetMoveSpeed();
valSpeed = (valSpeed / (3.6f * 30)) + MvSpeed;
Vector3 mvPos = forwardVal.normalized * valSpeed;
LiZiTran.position += mvPos;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;
[ExecuteInEditMode]
public class FileListGenerator : MonoBehaviour
{
public string fullGameExeName = "";
public string gameBuildPath = "";
public string serverFileListURL = "";
string localFileListPath = "";
public bool openFileListOnComplete;
public enum OperatingSystem
{
Windows,
Mac,
Linux
}
public OperatingSystem buildOperatingSystem;
public void AttemptFileListGeneration()
{
if (gameBuildPath == "" || fullGameExeName == "")
{
UnityEngine.Debug.Log("Verify Game Build Path and Full Exe Name (ex. Game.exe)");
return;
}
ThreadStart threadStart = delegate
{
GenerateFileList();
};
//if(serverFileListURL == "")
new Thread(threadStart).Start();
// else
//GenerateFileList();
}
void GenerateFileList()
{
bool downloadedServerFileList = false;
gameBuildPath = gameBuildPath.Replace(@"\", "/");
Dictionary<string, string> serverFiles = new Dictionary<string, string>();
if (serverFileListURL != "")
{
//Accepts all SSL Certificates
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
using (WebClient wc = new WebClient())
{
try
{
string _serverPath = System.IO.Path.Combine(gameBuildPath, "serverfileList.txt");
_serverPath = _serverPath.Replace(@"\", "/");
wc.DownloadFile(serverFileListURL, _serverPath);
downloadedServerFileList = true;
string[] _files = WriteSafeReadAllLines(_serverPath);
for (int i = 1; i < _files.Length; i++)
{
_files[i] = _files[i].Replace(@"\", "/");
string[] _md5split = _files[i].Split('\t');
serverFiles.Add(_md5split[0], _md5split[1]);
}
File.Delete(_serverPath);
}
catch (Exception e)
{
UnityEngine.Debug.Log("Failed to download server fileList due to " + e.ToString());
downloadedServerFileList = false;
}
}
}
localFileListPath = Path.Combine(gameBuildPath, "fileList.txt");
string updatedFilesPath = System.IO.Path.Combine(gameBuildPath, "updatedfileList.txt");
string[] _AllFiles = Directory.GetFiles(gameBuildPath, "*", SearchOption.AllDirectories);
TextWriter tw = new StreamWriter(localFileListPath, false);
TextWriter twUpdatedFiles = new StreamWriter(updatedFilesPath, false);
string _exePath = System.IO.Path.Combine(gameBuildPath, fullGameExeName);
if (buildOperatingSystem == OperatingSystem.Mac)
_exePath = System.IO.Path.Combine(gameBuildPath, fullGameExeName + @".app/Contents/MacOS/" + fullGameExeName);
using (var md5 = MD5.Create())
{
UnityEngine.Debug.Log("Exepath is " + _exePath);
using (var stream = File.OpenRead(_exePath))
{
string _md5 = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
tw.WriteLine(_md5);
}
}
twUpdatedFiles.WriteLine("Files necessary to upload to the server.");
twUpdatedFiles.WriteLine("fileList.txt");
// long startGenerationTime = DateTime.UtcNow.Ticks;
//UnityEngine.Debug.Log("Start Generation Time is " + startGenerationTime);
foreach (string s in _AllFiles)
{
string t = s.Replace(@"\", "/");
t = t.Replace(gameBuildPath + "/", "");
t = t.Replace(gameBuildPath, "");
//Add Exceptions if you have items in build output folder that you do not want in final. Uncomment if statement and add your exceptions.
//Example !t.StartsWith(@"Logs\") && !t.EndsWith("Thumbs.db")
if (!t.Contains("fileList.txt") && !t.Contains("output_log.txt"))
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(s))
{
string _md5 = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
string creationDateString = File.GetLastWriteTimeUtc(s).ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
tw.WriteLine(t + "\t" + _md5 + "\t" + creationDateString);
if (serverFiles.ContainsKey(t) && downloadedServerFileList)
{
if (_md5 != serverFiles[t])
{
UnityEngine.Debug.Log(t + " must be uploaded to server.");
twUpdatedFiles.WriteLine(t);
}
}
else
{
twUpdatedFiles.WriteLine(t);
UnityEngine.Debug.Log(t + " must be uploaded to server.");
}
}
}
}
}
//UnityEngine.Debug.Log("End Generation time is " + DateTime.UtcNow.Ticks);
//TimeSpan elapsed = new TimeSpan(DateTime.UtcNow.Ticks - startGenerationTime);
//UnityEngine.Debug.Log("Total Generation time for DateTime Check is " + elapsed.TotalSeconds + " seconds.");
tw.Close();
twUpdatedFiles.Close();
UnityEngine.Debug.Log("File List Created in Build Output Folder");
if (openFileListOnComplete)
Process.Start(localFileListPath);
}
public string[] WriteSafeReadAllLines(String path)
{
using (var csv = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(csv))
{
List<string> file = new List<string>();
while (!sr.EndOfStream)
{
file.Add(sr.ReadLine());
}
return file.ToArray();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyDropController : MonoBehaviour
{
[SerializeField] private GameObject[] dropArray;
[SerializeField] private int dropChance;
public void Drop()
{
if (Random.Range(0, 99) < dropChance)
{
Instantiate(dropArray[Random.Range(0, dropArray.Length)], transform.position, Quaternion.identity);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ModificardorEfectos : MonoBehaviour
{
[SerializeField]
private PowerUps modifierPrefab;
bool inGround;
//private void Start()
//{
// Destroy(gameObject, 5f);
//}
void Update()
{
if (!inGround)
{
transform.position += Vector3.down * Time.deltaTime * 2;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Jugador")
{
PowerUpsManager.Instance.AddPowerUps(modifierPrefab);
Destroy(gameObject);
}
if (collision.gameObject.tag == "Abajo")
{
inGround = true;
Destroy(gameObject, 5);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Uintra.Core.Search.Indexers.Diagnostics.Models;
namespace Uintra.Core.Search.Indexers.Diagnostics
{
public class IndexerDiagnosticService : IIndexerDiagnosticService
{
public IndexerDiagnosticService()
{
}
public IndexedModelResult GetFailedResult(
string message,
string indexName
) =>
new IndexedModelResult
{
Success = false,
Message = message,
IndexedName = indexName,
IndexedItems = 0
};
public IndexedModelResult GetSuccessResult<T>(
string indexName,
IEnumerable<T> items
) =>
new IndexedModelResult
{
Success = true,
IndexedName = indexName,
IndexedItems = items.Count(),
Message = string.Empty
};
}
} |
namespace SharpStore.Contracts
{
public interface IHtml
{
string Print(string url);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MoneyShare.Models;
using MoneyShare.Repos;
using MoneyShare.ViewModels;
using SignInResult = Microsoft.AspNetCore.Identity.SignInResult;
namespace MoneyShare.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
private SignInManager<MemberModel> _signInManager;
private UserManager<MemberModel> _userManager;
private IMemberServices _memberServices;
private IConfiguration _configuration;
// private static string _LoginFailureMessage = "Login Failed.";
public LoginController(
SignInManager<MemberModel> signInManager,
UserManager<MemberModel> userManager,
IMemberServices memberServices,
IConfiguration configuration)
{
_signInManager = signInManager;
_userManager = userManager;
_memberServices = memberServices;
_configuration = configuration;
}
[HttpPost]
public async Task<ActionResult> Post([FromBody] LoginRequestViewModel model)
{
if (string.IsNullOrWhiteSpace(model.Username) || string.IsNullOrWhiteSpace(model.Password))
{
return new UnauthorizedResult();
}
MemberModel member = await _userManager.FindByNameAsync(model.Username);
if (member != null)
{
SignInResult result = await _signInManager.CheckPasswordSignInAsync(member, model.Password, false);
if (result.Succeeded)
{
// await _signInManager.SignInAsync(member, false);
await _memberServices.SendTwoFactorCodeAsync(member);
return new OkResult();
}
}
return new UnauthorizedResult();
}
}
} |
using System;
using EPI.HashTables;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.HashTables
{
[TestClass]
public class SmallestSequentialSubarrayCoveringSetUnitTest
{
[TestMethod]
public void FindSmallestSequentialSubarrayCoveringSet()
{
SmallestSequentialSubarrayCoveringSet.FindSmallestSequentialSubarrayOfKeywords(new[]
{"apple", "banana", "apple", "apple", "dog", "cat", "apple", "dog", "banana", "apple", "cat", "dog" },
new[] { "dog", "apple" }
).ShouldBeEquivalentTo(new Tuple<int, int>(4, 6));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DemoLibrary.Models;
using DemoLibrary.Queries;
using MediatR;
namespace DemoLibrary.Handlers
{
// the requesthandler has to be query or command
public class GetPersonByIdHandler : IRequestHandler<GetPersonByIdQuery, PersonModel>
{
private readonly IMediator _mediator;
public GetPersonByIdHandler(IMediator mediator)
{
_mediator = mediator;
}
// what we did here was unique, as we called other handler to get list then we chose from that list
// alternatively we could have had created a method inclass to retrive by id, or just got list with out using mediator to get list
public async Task<PersonModel> Handle(GetPersonByIdQuery request, CancellationToken cancellationToken)
{
// I can reroute here to other layers like persistence, and database, or other services call even
var results = await _mediator.Send(new GetPersonListQuery());
var output = results.FirstOrDefault(x => x.Id == request.Id);
return output;
}
}
}
|
using ClearBank.DeveloperTest.Services;
using ClearBank.DeveloperTest.Types;
using FluentAssertions;
using Moq;
using Xunit;
namespace ClearBank.DeveloperTest.Tests
{
public class PaymentServiceShould
{
private readonly Mock<IAccountService> _accountService;
private readonly Mock<IPaymentsValidationService> _paymentsValidationService;
private readonly PaymentService _paymentService;
public PaymentServiceShould()
{
_accountService = new Mock<IAccountService>();
_paymentsValidationService = new Mock<IPaymentsValidationService>();
_paymentService = new PaymentService(_accountService.Object, _paymentsValidationService.Object);
}
[Fact]
public void MakePaymentWithSuccess_GivenValidPayment()
{
_accountService.Setup(service => service.GetAccount(It.IsAny<string>()))
.Returns(new Account());
_paymentsValidationService.Setup(service => service.ValidatePayment(It.IsAny<Account>(), It.IsAny<decimal>(), It.IsAny<PaymentScheme>()))
.Returns(true);
var result = _paymentService.MakePayment(new MakePaymentRequest());
result.Success.Should().BeTrue();
}
[Fact]
public void UpdateAccount_GivenValidPayment()
{
_accountService.Setup(service => service.GetAccount(It.IsAny<string>()))
.Returns(new Account());
_paymentsValidationService.Setup(service => service.ValidatePayment(It.IsAny<Account>(), It.IsAny<decimal>(), It.IsAny<PaymentScheme>()))
.Returns(true);
_paymentService.MakePayment(new MakePaymentRequest());
_accountService .Verify(service => service.UpdateAccount(
It.IsAny<Account>(),
It.IsAny<decimal>()), Times.Once);
}
[Fact]
public void FailMakingPayment_GivenInvalidPayment()
{
_accountService
.Setup(service => service.GetAccount(It.IsAny<string>()))
.Returns(new Account());
_paymentsValidationService.Setup(service => service.ValidatePayment(It.IsAny<Account>(), It.IsAny<decimal>(), It.IsAny<PaymentScheme>()))
.Returns(false);
var result = _paymentService.MakePayment(new MakePaymentRequest());
result.Success.Should().BeFalse();
}
[Fact]
public void NotUpdateAccount_GivenInvalidPayment()
{
_accountService
.Setup(service => service.GetAccount(It.IsAny<string>()))
.Returns(new Account());
_paymentsValidationService.Setup(service => service.ValidatePayment(It.IsAny<Account>(), It.IsAny<decimal>(), It.IsAny<PaymentScheme>()))
.Returns(false);
_paymentService.MakePayment(new MakePaymentRequest());
_accountService.Verify(service => service.UpdateAccount(
It.IsAny<Account>(),
It.IsAny<decimal>()), Times.Never);
}
}
}
|
using Dapper;
using Oracle.DataAccess.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBatchService
{
/// <summary>
/// OracleDBAccess
/// </summary>
public class OracleDBAccess : IDisposable
{
//属性定义
public const string SQLFMT_DATE = "yyyy-MM-dd"; //统一时间字符串格式
public const string SQLFMT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";//统一时间字符串格式
public const string SQLFMT_DATE_TIMESTAMP = "yyyy-MM-dd HH:mi:ss.ffffff";//oracle中带毫秒时间格式
//属性定义
public const string SqlfmtDateTime = "yyyy-MM-dd HH:mm:ss";//统一时间字符串格式
public const string SqlfmtDateTimePlusT = "yyyy-MM-ddTHH:mm:ss";//统一时间字符串格式
public const string SqlfmtDate = "yyyy-MM-dd";
public const string SqlfmtTime = "HH:mm:ss";
public const string DatefmtYyyymmdd = "yyyyMMdd";
private OracleConnection myConnection; //数据库连接对象
private OracleCommand myCommand; //数据库命令对象
private OracleTransaction myTrans; //数据库事务对象
private OracleDataReader myReader; //数据读取器对象
private string _savedSQL;
public string CommandText
{
get { return _savedSQL; }
set { _savedSQL = value == null ? "" : value; }
}
public IDbCommand dbCommand
{
get
{
return myCommand;
}
set
{
myCommand = value == null ? new OracleCommand() : (OracleCommand)value;
}
}
#region sql语句处理静态方法
/// <summary>
/// 给一个字符串加上数据库相关的引号
/// </summary>
/// <param name="str">未加引号前的字符串</param>
/// <returns>加引号后的字符串</returns>
public static string GetSingleQuote(string str)
{
if (str == null)
{
return "''";
}
return "'" + str + "'";
}
/// <summary>
/// 将指定的时刻转换为SQL标准的日期字符串(含引号,时分秒部分截断)
/// </summary>
/// <param name="dt1">输入的时刻</param>
/// <returns>对应的日期字符串</returns>
public static string StringDate(DateTime dt1)
{
return GetSingleQuote(dt1.ToString(SQLFMT_DATE));
}
/// <summary>
/// 将指定的时刻转换为SQL标准的日期时间字符串(含引号)
/// </summary>
/// <param name="dt1">输入的时刻</param>
/// <returns>对应的日期时间字符串</returns>
//作废:用ToDbDatetime(DateTime dt1)代替 by lhy
//public static string StrDateTime(DateTime dt1)
//{
// return GetSingleQuote(dt1.ToString(SQLFMT_DATE_TIME));
//}
/// <summary>
/// 将数据对象转换为数据库所识别的字符串,null/undefined等效为NULL
/// </summary>
/// <param name="obj">待转换的字符串</param>
/// <returns>准许为NULL的数据库值的字符串表示</returns>
public static string DBString(object obj)
{
return obj == null ? "NULL" : obj.ToString();
}
/// <summary>
/// 将数据对象转换为带单引号的字符串,null/undefined等效为NULL
/// </summary>
/// <param name="str">待转换的字符串</param>
/// <returns>准许为NULL的数据库值的带单引号字符串表示</returns>
public static string DBStringWithSingleQuote(string str)
{
return str == null ? "NULL" : GetSingleQuote(str.ToString().Trim());
}
/// <summary>
/// 将指定的时间戳字段的日期部分查询,解析为时间段查询,以运用索引
/// </summary>
/// <param name="fieldName">时间戳字段名</param>
/// <param name="date1">日期</param>
/// <returns>查询条件</returns>
public static string DateToTimestampRange(string fieldName, DateTime date1)
{
return " " + fieldName + " >= to_timestamp('" + date1.ToString(SQLFMT_DATE) + " 00:00:00.000000','yyyy-mm-dd hh24:mi:ss.ff') AND "
+ fieldName + " <= to_timestamp('" + date1.ToString(SQLFMT_DATE) + " 23:59:59.999999','yyyy-mm-dd hh24:mi:ss.ff') ";
}
public static string ToTimestampFromStartDate(DateTime date0)
{
return "to_timestamp('" + date0.ToString(SQLFMT_DATE) + " 00:00:00.000000','yyyy-mm-dd hh24:mi:ss.ff')";
}
public static string ToTimestampFromEndDate(DateTime date1)
{
return "to_timestamp('" + date1.ToString(SQLFMT_DATE) + " 23:59:59.999999','yyyy-mm-dd hh24:mi:ss.ff')";
}
/// <summary>
/// 根据SQL查询语句生成查询结果统计语句
/// </summary>
/// <param name="selectStr">SQL查询语句</param>
/// <returns>SQL查询结果统计语句</returns>
public static string SelectResultCounting(string selectStr)
{
if (selectStr == null || selectStr == "")
{
return null;
}
string countStr = "SELECT COUNT(*) FROM (";
string temp = selectStr.ToUpper();
int Pos = -1;
if ((Pos = temp.IndexOf("FROM ")) < 0)
{
return null;
}
if ((temp = temp.Substring(0, Pos)) == null)
{
return null;
}
if ((Pos = temp.IndexOf("SELECT ")) < 0)
{
return null;
}
countStr += selectStr;
if ((Pos = countStr.IndexOf(";")) < 0)
{
countStr += ")";
}
else
{
countStr = countStr.Substring(0, Pos) + ")";
}
return countStr;
}
public static string ToDbDatetime(DateTime dtime, string dateType)
{
if (dateType == SQLFMT_DATE_TIME)
return string.Format(" to_date('{0}','yyyy-mm-dd hh24:mi:ss')", dtime.ToString(dateType));
else if (dateType == SQLFMT_DATE)
return string.Format(" to_date('{0}','yyyy-mm-dd')", dtime.ToString(dateType));
else if (dateType == SQLFMT_DATE_TIMESTAMP)
return string.Format("to_timestamp('{0}','yyyy-mm-dd hh24:mi:ss.ff')", dtime.ToString(dateType));
else
return "";
}
public static string ToDbDatetime(string datestr)
{
return string.Format(" to_date('{0}','yyyy-mm-dd hh24:mi:ss')", datestr);
}
//替换DBAccessBase.ToDbDatetime(DateTime dt1) ORACLE匹配格式
public static string ToDbDatetime(DateTime dtime)
{
return string.Format(" to_date('{0}','yyyy-mm-dd hh24:mi:ss')", dtime.ToString(SQLFMT_DATE_TIME));
}
/// <summary>
/// 根据SQL查询语句生成对应限制结果数量查询语句
/// </summary>
/// <param name="selectStr">SQL查询语句</param>
/// <param name="limit">限制结果数量</param>
/// <returns>SQL限制结果数量查询语句</returns>
public static string LimitSelectResult(string selectStr, int limit)
{
if (selectStr == null || selectStr == "" || limit <= 0)
{
return null;
}
string countStr = "";
string temp = selectStr.ToUpper();
int Pos = -1;
if ((Pos = temp.IndexOf("FROM ")) < 0)
{
return null;
}
if ((temp = temp.Substring(0, Pos)) == null)
{
return null;
}
if ((Pos = temp.IndexOf("SELECT ")) < 0)
{
return null;
}
countStr += selectStr;
if ((Pos = countStr.IndexOf(";")) < 0)
{
countStr += " ";
}
else
{
countStr = countStr.Substring(0, Pos) + " ";
}
//countStr += " FETCH FIRST " + limit + " ROWS ONLY;";
if (countStr.IndexOf("WHERE") < 0)
{
countStr += "WHERE ROWNUM<=" + limit;
}
else
{
countStr += "AND ROWNUM<=" + limit;
}
return countStr;
}
/// <summary>
/// 取排序后的第一条记录
/// </summary>
/// <param name="inputs">查询字段</param>
/// <param name="sql">子查询语句</param>
/// <returns></returns>
public static string GetFirstRowSqlString(string inputs, string sql)
{
return string.Format("select {0} from ({1}) where rownum=1", inputs, sql);
}
#endregion
/// <summary>
/// Oracle数据库操作类 构造函数:建立数据库连接对象和执行操作的上下文环境
/// </summary>
public OracleDBAccess()
{
try
{
myConnection = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["oracleConnString"].ToString());
myConnection.Open();
myCommand = new OracleCommand();
myCommand.Connection = myConnection;
}
catch (Exception ex)
{
throw ex;
}
}
public OracleDBAccess(string userID, string password)
{
OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder(System.Configuration.ConfigurationManager.ConnectionStrings["oracleConnString"].ToString());
sb.UserID = userID;
sb.Password = password;
myConnection = new OracleConnection(sb.ConnectionString);
myConnection.Open();
myCommand = new OracleCommand();
myCommand.Connection = myConnection;
}
/// <summary>
/// 析构函数,强制回收垃圾单元
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// 析构函数,结束前执行的处理
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing)
{
try
{
if (myConnection.State == ConnectionState.Open)
{
myConnection.Close();
}
}
catch (Exception err)
{
//UNRESOLVED! how to report the error?
Console.WriteLine("关闭数据库连接出现异常!\r\n " + err.Message);
}
}
/// <summary>
/// 开启数据库事务
/// </summary>
public void BeginTransaction()
{
try
{
//之所以使用较低的隔离级别ReadCommitted,是为了减少死锁和提高并发性:
//通过update原子操作,在table_operationlog上加记录锁,足可有效隔离事务
myTrans = myConnection.BeginTransaction(IsolationLevel.ReadCommitted);
myCommand.Transaction = myTrans;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 事务数据库提交
/// </summary>
public void CommitTransaction()
{
try
{
myTrans.Commit();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 数据库事务回滚
/// </summary>
public void RollbackTransaction()
{
try
{
if (myReader != null && !myReader.IsClosed)
myReader.Close();
myCommand.Cancel(); // if any pending
myTrans.Rollback();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 取消正在执行的命令(例如,一个复杂的或返回大数据集的查询)
/// 如果没有需要取消的内容,那么不会发生任何情况。
/// 但是,如果在执行命令并且尝试取消时失败,那么将不会生成异常。
/// </summary>
public void CancelCommand()
{
if (myReader != null && !myReader.IsClosed)
myReader.Close();
// Just cancel command would not close the reader.
// Cancel command does not close the reader, so next ExecuteNonQuery will fail.
if (myCommand != null)
myCommand.Cancel();
}
/// <summary>
/// 执行ORACLE数据库非查询语句
/// </summary>
/// <param name="strCmd">待执行的数据库命令,应为U,A,D而非R操作</param>
/// <returns>返回值为1,或者抛出异常</returns>
public int ExecuteNonQuery(string strCmd)
{
myCommand.CommandText = _savedSQL = strCmd;
return myCommand.ExecuteNonQuery();
}
/// <summary>
/// 按给定的固定字符串查询
/// </summary>
/// <param name="strCmd">查询语句</param>
/// <returns>实现IDataReader接口的数据序列</returns>
public IDataReader ExecuteReader(string strCmd)
{
myCommand.CommandText = _savedSQL = strCmd;
myReader = myCommand.ExecuteReader();
return myReader;
}
/// <summary>
/// 执行只返回一个字段的查询
/// </summary>
/// <param name="strCmd">查询语句</param>
/// <returns>一个数据库值对象</returns>
public object ExecuteScalar(string strCmd)
{
myCommand.CommandText = _savedSQL = strCmd;
return myCommand.ExecuteScalar();
}
/// <summary>
/// 执行数据库查询语句,返回一个标量对象
/// </summary>
/// <param name="strCmd">所要执行的查询语句</param>
/// <param name="result">出口参数,所查询的第一条(通常为唯一一条)记录的第一个字段(应为唯一字段)的值</param>
/// <returns>true如果查到一条记录,false如果未找到或字段值为NULL</returns>
public bool GetScalar(string strCmd, ref Object result)
{
OracleCommand rCommand = new OracleCommand(strCmd, myConnection);
result = rCommand.ExecuteScalar();
return (result != null);
}
/// <summary>
/// 准备执行参数化的SQL语句
/// </summary>
/// <param name="strCmd">带参数的SQL命令</param>
public void PrepareSQL(string strCmd)
{
myCommand.CommandText = strCmd;
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Clear();
}
/// <summary>
/// 准备执行参数化的SQL语句
/// </summary>
/// <param name="strCmd">带参数的SQL命令</param>
public void PrepareSQL(string strCmd, CommandType commandtype)
{
myCommand.CommandText = strCmd;
myCommand.CommandType = commandtype;
myCommand.Parameters.Clear();
}
/// <summary>
/// 给准备执行的语句增加参数
/// </summary>
/// <param name="paramName">参数名称</param>
/// <param name="paramType">参数类型</param>
/// <param name="value">参数的值</param>
/// <param name="sizes">参数大小,可选</param>
public void AddParameterToDbCommand(string paramName, OracleDbType paramType, object value, params int[] sizes)
{
try
{
OracleParameter param = new OracleParameter(paramName, paramType);
if (sizes.Length > 0 && sizes[0] > 0)
{
param.Size = sizes[0];
}
//if (paramType == DbType.Date)//ORACLE数据库只有日期时间类型
//{
// if (value is DateTime)
// param.Value = DB2Date.Parse(((DateTime)value).ToString("yyyy-MM-dd"));
// else
// throw new Exception("Invalid parameter");
//}
//else
//{
// }
//if (myCommand.CommandType == CommandType.StoredProcedure)
//{
// param.Direction = ParameterDirection.Input;
//}
param.Value = value;
myCommand.Parameters.Add(param);
}
catch (Exception e)
{
}
}
public void AddParameterToDbCommand(string name, ParameterDirection parameterDirection, DbType paramType, Nullable<int> size, object value)
{
OracleParameter parameter = new OracleParameter(name, paramType);
if (size.HasValue)
parameter.Size = (int)size;
parameter.Value = value;
parameter.Direction = parameterDirection;
myCommand.Parameters.Add(parameter);
}
public void AddOutParameterToDbCommand(string paramName
, OracleDbType paramType
, params int[] sizes)
{
OracleParameter param = new OracleParameter(paramName, paramType);
if (sizes.Length > 0 && sizes[0] > 0)
param.Size = sizes[0];
param.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(param);
}
public object GetParameterToDbCommand(string paramName)
{
object result = myCommand.Parameters[paramName].Value.ToString();
return result;
}
/// <summary>
/// 根据可选的命令行为模式选项,返回只读数据序列
/// </summary>
/// <param name="cbs"></param>
/// <returns></returns>
public IDataReader ExecuteReader(params CommandBehavior[] cbs)
{
try
{
myCommand.CommandText = _savedSQL = CommandText;
myReader = cbs.Length > 0 ? myCommand.ExecuteReader(cbs[0]) : myCommand.ExecuteReader();
return myReader;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 执行只返回一个字段的查询
/// </summary>
/// <returns>一个数据库值对象</returns>
public object ExecuteScalar()
{
myCommand.CommandText = _savedSQL = CommandText;
return myCommand.ExecuteScalar();
}
/// <summary>
/// 执行ORACLE数据库非查询语句
/// </summary>
/// <returns>返回值为1,或者抛出异常</returns>
public int ExecuteNonQuery()
{
myCommand.CommandText = _savedSQL = CommandText;
return myCommand.ExecuteNonQuery();
}
/// <summary>
/// 获得指定数据表的数据集版本号(从行记录的最大版本号中所得)
/// </summary>
/// <param name="tableName">有version字段的数据表名称</param>
/// <returns>下一个数据集版本号,为"1"如果尚无数据行记录</returns>
/// <remarks>有可能抛出数据库异常</remarks>
public string NextDatasetVersion(string tableName)
{
_savedSQL = myCommand.CommandText = "SELECT MAX(VERSION) + 1 FROM " + tableName;
//
object result = myCommand.ExecuteScalar();
if (result == null || result.ToString().Equals(String.Empty))
return "1";
return result.ToString();
}
/// <summary>
/// dapper按条件查询
/// </summary>
/// <typeparam name="T">返回集合类型</typeparam>
/// <param name="sql">sql</param>
/// <param name="param">参数</param>
/// <returns>List<T></returns>
public List<T> QuerySql<T>(string sql,object param)
{
try
{
return myConnection.Query<T>(sql, param).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 关联查询
/// </summary>
/// <typeparam name="TFirst"></typeparam>
/// <typeparam name="TSecond"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="sql"></param>
/// <param name="func"></param>
/// <returns></returns>
public List<TReturn> QueryMultiple<TFirst,TSecond,TReturn>(string sql,Func<TFirst, TSecond, TReturn> func)
{
return myConnection.Query<TFirst, TSecond, TReturn>(sql, func, null, null, true, splitOn: "ID").ToList();
}
/// <summary>
/// dapper执行非查询语句
/// </summary>
/// <param name="sql">sql</param>
/// <param name="param">参数</param>
/// <returns>int</returns>
public int ExecuteSql(string sql, object param)
{
try
{
return myConnection.Execute(sql, param, myTrans);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 处理OracleException
/// </summary>
/// <param name="ex">Exception 实例</param>
/// <returns>ReturnResult</returns>
public ReturnResult HandleOracleException(Exception ex)
{
bool isOracleException = ex is OracleException;
if (!isOracleException)
return (int)ReturnResult.NotOracleException;
string sqlState = (((OracleException)ex).Errors[0]).Number.ToString();
if (sqlState == ((int)ReturnResult.OracleUniqueConstraintException).ToString())
return ReturnResult.OracleUniqueConstraintException;
else if (sqlState == ((int)ReturnResult.OracleTimeoutOccurredException).ToString())
return ReturnResult.OracleTimeoutOccurredException;
else if(sqlState== ((int)ReturnResult.OracleDeadlockDetectedException).ToString())
return ReturnResult.OracleDeadlockDetectedException;
else if (sqlState == ((int)ReturnResult.OracleMaximumNumberOfSessionsExceededException).ToString())
return ReturnResult.OracleMaximumNumberOfSessionsExceededException;
else
return ReturnResult.OracleOtherException;
}
}
}
|
using UnityEngine;
public interface Character {
// the functions should describe the input that causes the move, not the move itself.
// neutral light would be for neutral movement (no left, right or up input) and light attack button.
void neutralLight(GameObject collider, GameObject hitter);
void neutralHeavy(GameObject collider, GameObject hitter);
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System.Linq
{
public static class EnumerableExtension
{
public static IList<IEnumerable<TSource>> Paging<TSource>(this IEnumerable<TSource> source, int size)
{
if (size < 0) throw new ArgumentOutOfRangeException();
IList<IEnumerable<TSource>> result = new List<IEnumerable<TSource>>();
int index = 0, left = source.Count();
while (left > 0)
{
result.Add(source.Skip(index * size).Take(left >= size ? size : left));
index++;
left = left - size;
}//end while
return result;
}
public static IEnumerable<TSource> Paging<TSource>(this IEnumerable<TSource> source, int size, int index)
{
if (size <= 0) throw new ArgumentOutOfRangeException();
if (index < 0) throw new ArgumentOutOfRangeException();
int has = index * size;
has = has >= source.Count() ? source.Count() : has;
int left = source.Count() - has;
left = left >= 0 ? left : 0;
IEnumerable<TSource> result = source.Skip(has).Take(left >= size ? size : left);
return result;
}
}//end class
}//end namespace
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using DataAccessLayer;
namespace BLL
{
public class RoleBusiness : IBusiness<Role>
{
UnitOfWork _uof;
Employee emp;
public RoleBusiness(Employee employee)
{
emp = employee;
_uof = new UnitOfWork();
}
public bool Add(Role item)
{
if (item != null)
{
if (string.IsNullOrEmpty(item.Name))
{
throw new Exception("Role Adı Girilmelidir.");
}
if (true)
{
_uof.RoleRepository.Add(item);
return _uof.ApplyChanges();
}
}
return false;
}
public bool Remove(Role item)
{
if (item != null)
{
_uof.RoleRepository.Remove(item);
return _uof.ApplyChanges();
}
return false;
}
public bool Update(Role item)
{
_uof.RoleRepository.Update(item);
return _uof.ApplyChanges();
}
public Role Get(int id)
{
if (id > 0)
{
return _uof.RoleRepository.Get(id);
}
else
{
throw new Exception("Id'nin 0 dan büyük olması gerekmektedir");
}
}
public ICollection<Role> GetAll()
{
if (_uof.RoleRepository.GetAll().Count > 0)
{
return _uof.RoleRepository.GetAll();
}
else
{
throw new Exception("İstediğiniz listede kayıt bulunmamaktadır");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoLP2
{
public enum EstadoVenta
{
anulado,
activa
}
}
|
using UnityEngine;
using System.Collections;
using Erf;
using System.IO;
using System;
public class ErfInitialization : MonoBehaviour {
// Use this for initialization
void Start () {
}
// zaladowanie biblioteki erf do kontekstu
void Awake() {
// Debug.LogWarning("Ustawienia: "+MainMenu.gameSettings.gameMode.ToString()+" / "+MainMenu.gameSettings.gameDifficulty.ToString());
ErfLogger.SetLoggingEnabled (true);
ErfLogger.SetAllStreamsToLoggingFile (@"d://debug.txt");
Debug.Log ("Initializing ERF for ErfDemo, trying to load "+Directory.GetCurrentDirectory()+"\\MSIBallErf.dll");
ErfContext context = ErfContext.GetInstance ();
testMSIBallErf ();
Debug.Log ("Library successfully loaded");
}
void testMSIBallErf()
{
try {
ExternalComponentLibrary library = ErfContext.GetInstance ().LoadComponentLibrary ("MSIBallErf.dll");
if (library == null) {
Debug.LogError("Could not load MSIBallErf library");
return;
}
} catch (Exception e)
{
Debug.Log (e.Message);
return;
}
//init:
ExternalExpert msiBallEmotionModel = ErfContext.GetInstance ().FindExpert ("MSIBallEmotionModel");
CharacterModel playerModel = new CharacterModel ();
playerModel.RegisterExpert (msiBallEmotionModel);
//collision:
EecEvent timeElapsedEvent = new EecEvent ((int)GameEvent.STD_TIME_ELAPSED);
timeElapsedEvent.AddValue ("NO_OF_COLLISIONS", Variant.Create (2));
timeElapsedEvent.AddValue ("CURRENT_SPEED", Variant.Create (7.0f));
playerModel.HandleEvent (timeElapsedEvent);
//odpowiedz z erf
float fear = playerModel.GetEmotionVector ().GetValue (OccEmotions.FEAR).AsFloat();
//przeliczenie na poziom trudnosci
if(fear > 0.0f)
Debug.Log ("FIRST I WAS AFRAID, I WAS PETRIFIED!");
else
Debug.Log ("I AM FEARLESS! I AM DEATH! I AM FIRE!");
}
}
|
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
class LittleJohn
{
static void Main()
{
//string patternSmall = @"(?<!>)(>)----->(?!>)";
//string patternMed = @"(?<!>)(>>)----->(?!>)";
//string patternLarg = @"(?<!>)(>>>)----->>(?!>)";
StringBuilder inputTxt = new StringBuilder();
string pattern = @"(>>>----->>)|(>>----->)|(>----->)";
int smallNum = 0, mediumNum = 0, largeNum = 0;
for (int i = 1; i <= 4; i++)
{
inputTxt.Append(String.Format(" {0}",Console.ReadLine()));
}
Regex rxRegex = new Regex(pattern);
MatchCollection matches = rxRegex.Matches(inputTxt.ToString());
foreach (Match match in matches)
{
if (!string.IsNullOrEmpty(match.Groups[1].Value))
{
largeNum++;
}
else if (!string.IsNullOrEmpty(match.Groups[2].Value))
{
mediumNum++;
}
else
{
smallNum++;
}
}
int num = int.Parse(smallNum.ToString() + mediumNum.ToString() + largeNum.ToString());
string binary = Convert.ToString(num, 2);
string reversed = Reverse(binary);
string lastBinStr = binary + reversed;
decimal finalNum = Convert.ToInt32(lastBinStr, 2);
Console.WriteLine(finalNum);
}
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
} |
namespace Zoo
{
class Hippo : Animal, IHerbivor
{
public void Start()
{
name = "Elsa";
}
public void EatLeaves()
{
Speak("nomnomnom");
}
public override void SayHello()
{
base.SayHello();
text.text = "splash";
}
}
}
|
using System.Collections.Generic;
using ODL.ApplicationServices.DTOModel;
namespace ODL.ApplicationServices.Validation
{
public class AdressInputValidator : Validator<AdressInputDTO>
{
// TODO: OBS! Vid persistering måste vi verifiera att vi har uppdateringsinfo ifall detta objekt redan finns i db, eftersom det då är en uppdatering!?
// Alt. låt uppdateringinfo vara NOT NULL (samma som skapandeinfo vid ny) ?
public AdressInputValidator()
{
RequireMetadata();
}
public override List<ValidationError> Validate(AdressInputDTO subject)
{
var allErrors = base.Validate(subject);
var personEllerResultatenhet = subject.AvserPerson ^ subject.AvserResultatenhet; // Exclusive OR
if (!personEllerResultatenhet)
allErrors.Add(new ValidationError("Adressen måste ange antingen en person eller en resultatenhet."));
else if(subject.AvserPerson && subject.Personnummer.Length != 12)
allErrors.Add(new ValidationError("Personnumret som angivits för adressen är ej giltigt."));
else if (subject.AvserResultatenhet && subject.KostnadsstalleNr.Length != 6)
allErrors.Add(new ValidationError("Kostnadsställenumret som angivits för adressen ej giltigt."));
var gatuadress = subject.GatuadressInput;
var epostadress = subject.EpostInput;
var telefon = subject.TelefonInput;
var endastEnAngiven = (gatuadress != null) ^ (epostadress != null) ^ (telefon != null);
if (!endastEnAngiven)
allErrors.Add(new ValidationError("Endast en av gatuadress, epostadress eller telefon får anges!"));
else if (gatuadress != null)
new GatuadressInputValidator().Validate(gatuadress, allErrors);
else if (epostadress != null)
new EpostInputValidator().Validate(epostadress, allErrors);
else if (telefon != null)
new TelefonInputValidator().Validate(telefon, allErrors);
return allErrors;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Compent.Extensions;
using Compent.Shared.Logging.Contract;
using Compent.Shared.Search.Contract;
using Compent.Shared.Search.Contract.Helpers;
using Compent.Shared.Search.Elasticsearch;
using Compent.Shared.Search.Elasticsearch.SearchHighlighting;
using Elasticsearch.Net;
using Nest;
using Newtonsoft.Json.Linq;
using Uintra.Core.Search.Entities;
using Uintra.Core.Search.Extensions;
using Uintra.Core.Search.Queries.DeleteByType;
using Uintra.Features.Search;
namespace Uintra.Core.Search.Repository
{
public class UintraSearchRepository<T> : SearchRepository<T>, IUintraSearchRepository<T> where T : class, ISearchDocument
{
private readonly IIndexContext<T> indexContext;
private readonly IElasticClientWrapper client;
protected override string PipelineId => nameof(T);
public UintraSearchRepository(
IElasticClientWrapper client,
IIndexContext<T> indexContext,
SpecificationAbstractFactory<T> searchSpecificationFactory,
ILog<SearchRepository> log,
ISearchHighlightingHelper searchHighlightingHelper)
: base(client, indexContext, searchSpecificationFactory, log, searchHighlightingHelper)
{
this.client = client;
this.indexContext = indexContext;
}
public override async Task<string> IndexAsync(T item)
{
if (item == null) return default(string);
var response = await client
.IndexAsync<T>(item, x => x.Index(indexContext.IndexName.Name).Refresh(Refresh.False))
.ConfigureAwait(false);
return !response.IsFail() && !response.Id.IsEmpty() ? response.Id : default(string);
}
public override async Task<int> IndexAsync(IEnumerable<T> items)
{
var itemsList = items.AsList();
if (itemsList.IsEmpty()) return default(int);
var descriptor = new BulkDescriptor();
foreach (var entity in itemsList)
{
descriptor.Index<T>(x => x
.Id(entity.Id)
.Index(indexContext.IndexName.Name)
.Document(entity)
);
}
if (items.Any() && items.First() is SearchableDocument)
descriptor.Pipeline(SearchConstants.AttachmentsPipelineName).Refresh(Refresh.WaitFor);
else
descriptor.Refresh(Refresh.WaitFor);
var response = await client.BulkAsync(descriptor).ConfigureAwait(false);
return response.IsValid && response.Items.HasValue() ? response.Items.Count : default(int);
}
}
public class UintraSearchRepository : SearchRepository, IUintraSearchRepository
{
private readonly SpecificationAbstractFactory<SearchDocument> searchSpecificationFactory;
private readonly IElasticClientWrapper client;
private readonly ILog<SearchRepository> log;
private readonly IndexHelper indexHelper;
private readonly ISearchHighlightingHelper searchHighlightingHelper;
private readonly ISearchDocumentTypeHelper searchDocumentTypeHelper;
public UintraSearchRepository(
SpecificationAbstractFactory<SearchDocument> searchSpecificationFactory,
IElasticClientWrapper client,
ILog<SearchRepository> log,
IndexHelper indexHelper,
ISearchHighlightingHelper searchHighlightingHelper,
ISearchDocumentTypeHelper searchDocumentTypeHelper)
: base(searchSpecificationFactory, client, log, indexHelper, searchHighlightingHelper, searchDocumentTypeHelper)
{
this.searchSpecificationFactory = searchSpecificationFactory;
this.client = client;
this.log = log;
this.indexHelper = indexHelper;
this.searchHighlightingHelper = searchHighlightingHelper;
this.searchDocumentTypeHelper = searchDocumentTypeHelper;
}
//public override async Task<ISearchResult<ISearchDocument>> SearchAsync<TQuery>(TQuery query, string culture)
//{
// var specification = searchSpecificationFactory.CreateSearchSpecification(query, culture);
// var searchDescriptor = specification.Descriptor.AllIndices();
//
// //searchDescriptor.RequestConfiguration(r => r.DisableDirectStreaming());
//
// var response = await client.SearchAsync<JObject>(searchDescriptor).ConfigureAwait(false);
//
// var res = response.DebugInformation;
//
// if (response.IsFail())
// {
// LogError(response);
// return new Compent.Shared.Search.Contract.SearchResult<ISearchDocument>();
// }
//
// return MapToResult(response);
//}
//protected override Type GetSearchType(string indexName)
//{
// var clearIndexName = indexHelper.TrimPrefix(indexName);
// var type = searchDocumentTypeHelper.Get(clearIndexName);
// return type;
//}
protected override ISearchResult<ISearchDocument> MapToResult(ISearchResponse<JObject> response)
{
var highlightedResponse = searchHighlightingHelper.HighlightResponse(response);
var documents = highlightedResponse.Hits
.Select(hit =>
{
var searchType = GetSearchType(hit.Index);
return (SearchableBase)hit.Source.ToObject(searchType);
});
var result = new Entities.SearchResult<SearchableBase>()
{
Documents = documents,
TotalCount = (int)response.Total,
TypeFacets = response.Aggregations.GetGlobalFacets(SearchConstants.SearchFacetNames.Types)
};
return result;
}
public async Task<Entities.SearchResult<SearchableBase>> SearchAsyncTyped<TQuery>(TQuery query) where TQuery : ISearchQuery<SearchDocument>
{
// TODO: Search. Localization?
var result = (await base.SearchAsync(query, String.Empty)) as Entities.SearchResult<SearchableBase>;
return result;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ControlVideoMouse : MonoBehaviour, IPointerEnterHandler {
Animator controlAnim;
// Use this for initialization
void Start () {
controlAnim = GameObject.Find("Controles").GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
}
public void OnPointerEnter(PointerEventData eventData) {
controlAnim.SetTrigger("show");
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NewUser : MonoBehaviour
{
[SerializeField]
InputField name;
[SerializeField]
InputField password;
[SerializeField]
InputField email;
void Start()
{
password.inputType = InputField.InputType.Password;
}
void Update()
{
}
public void Next()
{
PersistentData.UserName = name.text;
Application.LoadLevel("Interests");
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartLib;
using KartLib.Views;
using KartObjects;
namespace KartSystem
{
public partial class DiscountReasonView : KartUserControl, IDiscountReasonView
{
public DiscountReasonView()
{
InitializeComponent();
ViewObjectType = ObjectType.DiscountReasons;
Preseneter = new DiscountCartPresenter(this);
}
public IList<DiscountReason> DiscountReasons
{
get;
set;
}
public override void InitView()
{
base.InitView();
discountReasonBindingSource.DataSource = DiscountReasons;
}
public override void RefreshView()
{
base.RefreshView();
discountReasonBindingSource.DataSource = DiscountReasons;
}
DiscountReasonEditor _ce;
/// <summary>
/// Переопределяет унаследованный метод редактирования элемента.
/// если addMode==true создаёт нового кассира и открывает редактор для задания его свойств,
/// иначе открывает редактор для изменения св-в выбранного в верхней таблице кассира.
/// </summary>
public override void EditorAction(bool addMode)
{
if (addMode)
{
DiscountReason newUser = new DiscountReason();
Saver.SaveToDb<DiscountReason>(newUser);
_ce = new DiscountReasonEditor(newUser);
if (_ce.ShowDialog() == DialogResult.OK)
{
DiscountReasons.Add(newUser);
RefreshView();
ActiveEntity = newUser;
}
else
{
DiscountReasons.Remove(newUser);
Saver.DeleteFromDb<DiscountReason>(newUser);
}
RefreshView();
gcDiscountReasons.RefreshDataSource();
}
else
{
if (discountReasonBindingSource.Current == null) return;
_ce = new DiscountReasonEditor(discountReasonBindingSource.Current as DiscountReason);
if (_ce.ShowDialog() == DialogResult.OK)
{
RefreshView();
gcDiscountReasons.RefreshDataSource();
};
}
}
/// <summary>
/// Переопределяет унаследованный метод удаления элемента.
/// Удаляет выдбанного в верхней таблице кассира.
/// </summary>
public override void DeleteItem(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
DiscountReason gk = discountReasonBindingSource.Current as DiscountReason;
if (gk != null)
{
if (MessageBox.Show(this, "Вы уверены что хотите удалить причину скидки" + gk.Name, "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{
Saver.DeleteFromDb<DiscountReason>(gk);
DiscountReasons.Remove(gk);
gcDiscountReasons.RefreshDataSource();
}
}
}
private void gvDiscountReasons_DoubleClick(object sender, EventArgs e)
{
//EditorAction(false);
EditAction(this, null);
}
public override bool RecordSelected
{
get { return discountReasonBindingSource.Current != null; }
}
public override bool IsEditable
{
get
{
return true;
}
}
public override bool IsInsertable
{
get
{
return true;
}
}
public override bool UseSubmenu
{
get
{
return false;
}
}
public override bool IsDeletable
{
get
{
return true;
}
}
public override bool IsPrintable
{
get
{
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Models;
namespace A4AeroCrud.DTOS
{
public class ApplicationProfile : Profile
{
public ApplicationProfile()
{
CreateMap<BusinessCreateDto, BusinessEntity>();
CreateMap<BusinessEditDto, BusinessEntity>();
}
}
}
|
using System;
using System.Threading.Tasks;
namespace DataAccess.Users
{
public interface IDeleteUserCommand
{
Task ExecuteAsync(Guid userId);
}
}
|
using MahApps.Metro.Controls;
using MinecraftToolsBoxSDK;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
namespace MinecraftToolsBox.Commands
{
/// <summary>
/// BasicCommands.xaml 的交互逻辑
/// </summary>
public partial class EntityCommands : DockPanel, ICommandGenerator
{
bool stop = false;
CommandsGeneratorTemplate CmdGenerator;
public EntityCommands(CommandsGeneratorTemplate cmdGenerator)
{
InitializeComponent();
LocX_sp.setNeighbour(null, LocZ_sp);
LocZ_sp.setNeighbour(LocX_sp, null);
LocX_tp.setNeighbour(null, LocY_tp);
LocY_tp.setNeighbour(LocX_tp, LocZ_tp);
LocZ_tp.setNeighbour(LocY_tp, null);
CmdGenerator = cmdGenerator;
}
public string GenerateCommand()
{
switch (menu.SelectedIndex)
{
case 0: return "/kill " + EntitySelector.GetEntity();
case 1: return Spreadplayers();
case 2: return Tp();
case 3: return GetEffect();
case 4: return Me();
}
return "";
}
string Spreadplayers()
{
string center = "";
string kt = "";
if (sp_center_tilde.IsChecked == true) center = "~" + LocX_sp.Text + " ~" + LocZ_sp.Text;
else center =LocX_sp.Text + " " + LocZ_sp.Text;
if (keepTeam.IsChecked == true) kt = "true"; else kt = "false";
if (area.Value < separation.Value) area.Value = separation.Value + 1;
return "/spreadplayers " + center + " " + separation.Value + " " + area.Value + " " + kt + " " + EntitySelector.GetEntity();
}
string Tp()
{
if (c1.IsChecked == true) return "/tp " + EntitySelector.GetEntity() + " " + tp_tar.Text;
else
{
string destination = "";
string rotation = "";
if (tp_tilde.IsChecked == true) destination = "~" + LocX_tp.Text + " ~" + LocY_tp.Text + " ~" + LocZ_tp.Text;
else destination = LocX_tp.Text + " " + LocY_tp.Text + " " + LocZ_tp.Text;
if (tiled_angle.IsChecked == true) rotation = "~" + xrot.Value + " ~" + yrot.Value;
else rotation = xrot.Value + " " + yrot.Value;
return "/tp " + EntitySelector.GetEntity() + " " + destination + " " + rotation;
}
}
private string GetEffect()
{
string show = "";
if (showParticle.IsChecked == true) show = " true"; else show = " false";
TreeViewItem e = (TreeViewItem)effect.SelectedItem;
if (e == eff1 || e == eff2 || e == eff3 || e == eff4 || e == eff5 || e == null) return "请选择效果";
return "/effect " + EntitySelector.GetEntity()+" minecraft:"+e.Name+" "+time.Value+" "+level.Value+show;
}
private string Me()
{
return "/me " + me.Text;
}
private void MeAdd_Click(object sender, RoutedEventArgs e)
{
int i = me.SelectionStart;
string txt = " " + EntitySelector.GetEntity() + " ";
me.SelectionLength = 0;
me.SelectedText = txt;
}
private void MaxTime_Click(object sender, RoutedEventArgs e)
{
time.Value = 1000000;
}
private void Clear_Click(object sender, RoutedEventArgs e1)
{
string show = "";
if (showParticle.IsChecked == true) show = " true"; else show = " false";
TreeViewItem e = (TreeViewItem)effect.SelectedItem;
if (e == eff1 || e == eff2 || e == eff3 || e == eff4 || e == eff5 || e == null) { CmdGenerator.AddCommand("请选择效果"); return; }
CmdGenerator.AddCommand("/effect " + EntitySelector.GetEntity() + " minecraft:" + e.Name + " 0 " + level.Value + show);
}
private void EffectClear_Click(object sender, RoutedEventArgs e)
{
CmdGenerator.AddCommand("/effect "+EntitySelector.GetEntity()+" clear");
}
private void Effect_change(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeViewItem item =(TreeViewItem) effect.SelectedItem;
if (item == eff1 || item == eff2 || item == eff3 || item == eff4 || item == eff5) return;
string name = item.Name;
effect_pre.Source = new BitmapImage(new Uri(Environment.CurrentDirectory + "/images/effect/"+name+".png"));
}
private void HamburgerMenu_ItemClick(object sender, ItemClickEventArgs e)
{
menu.Content = e.ClickedItem;
}
private void Checked(object sender, RoutedEventArgs e)
{
if (c1 == null || c2 == null || stop) return;
stop = true;
c1.IsChecked = false;
c2.IsChecked = false;
(sender as RadioButton).IsChecked = true;
stop = false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ContentPatcher.Framework.Conditions;
using ContentPatcher.Framework.Patches;
using ContentPatcher.Framework.Tokens;
using Pathoschild.Stardew.Common.Utilities;
using StardewModdingAPI;
namespace ContentPatcher.Framework.Commands
{
/// <summary>Handles the 'patch' console command.</summary>
internal class CommandHandler
{
/*********
** Fields
*********/
/// <summary>Encapsulates monitoring and logging.</summary>
private readonly IMonitor Monitor;
/// <summary>Manages loaded tokens.</summary>
private readonly TokenManager TokenManager;
/// <summary>Manages loaded patches.</summary>
private readonly PatchManager PatchManager;
/// <summary>A callback which immediately updates the current condition context.</summary>
private readonly Action UpdateContext;
/// <summary>A regex pattern matching asset names which incorrectly include the Content folder.</summary>
private readonly Regex AssetNameWithContentPattern = new Regex(@"^Content[/\\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>A regex pattern matching asset names which incorrectly include an extension.</summary>
private readonly Regex AssetNameWithExtensionPattern = new Regex(@"(\.\w+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>A regex pattern matching asset names which incorrectly include the locale code.</summary>
private readonly Regex AssetNameWithLocalePattern = new Regex(@"^\.(?:de-DE|es-ES|ja-JP|pt-BR|ru-RU|zh-CN)(?:\.xnb)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
/*********
** Accessors
*********/
/// <summary>The name of the root command.</summary>
public string CommandName { get; } = "patch";
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="tokenManager">Manages loaded tokens.</param>
/// <param name="patchManager">Manages loaded patches.</param>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="updateContext">A callback which immediately updates the current condition context.</param>
public CommandHandler(TokenManager tokenManager, PatchManager patchManager, IMonitor monitor, Action updateContext)
{
this.TokenManager = tokenManager;
this.PatchManager = patchManager;
this.Monitor = monitor;
this.UpdateContext = updateContext;
}
/// <summary>Handle a console command.</summary>
/// <param name="args">The command arguments.</param>
/// <returns>Returns whether the command was handled.</returns>
public bool Handle(string[] args)
{
string subcommand = args.FirstOrDefault();
string[] subcommandArgs = args.Skip(1).ToArray();
switch (subcommand?.ToLower())
{
case null:
case "help":
return this.HandleHelp(subcommandArgs);
case "summary":
return this.HandleSummary();
case "update":
return this.HandleUpdate();
default:
this.Monitor.Log($"The '{this.CommandName} {args[0]}' command isn't valid. Type '{this.CommandName} help' for a list of valid commands.");
return false;
}
}
/*********
** Private methods
*********/
/****
** Commands
****/
/// <summary>Handle the 'patch help' command.</summary>
/// <param name="args">The subcommand arguments.</param>
/// <returns>Returns whether the command was handled.</returns>
private bool HandleHelp(string[] args)
{
// generate command info
var helpEntries = new InvariantDictionary<string>
{
["help"] = $"{this.CommandName} help\n Usage: {this.CommandName} help\n Lists all available {this.CommandName} commands.\n\n Usage: {this.CommandName} help <cmd>\n Provides information for a specific {this.CommandName} command.\n - cmd: The {this.CommandName} command name.",
["summary"] = $"{this.CommandName} summary\n Usage: {this.CommandName} summary\n Shows a summary of the current conditions and loaded patches.",
["update"] = $"{this.CommandName} update\n Usage: {this.CommandName} update\n Imediately refreshes the condition context and rechecks all patches."
};
// build output
StringBuilder help = new StringBuilder();
if (!args.Any())
{
help.AppendLine(
$"The '{this.CommandName}' command is the entry point for Content Patcher commands. These are "
+ "intended for troubleshooting and aren't intended for players. You use it by specifying a more "
+ $"specific command (like 'help' in '{this.CommandName} help'). Here are the available commands:\n\n"
);
foreach (var entry in helpEntries.OrderByIgnoreCase(p => p.Key))
{
help.AppendLine(entry.Value);
help.AppendLine();
}
}
else if (helpEntries.TryGetValue(args[0], out string entry))
help.AppendLine(entry);
else
help.AppendLine($"Unknown command '{this.CommandName} {args[0]}'. Type '{this.CommandName} help' for available commands.");
// write output
this.Monitor.Log(help.ToString());
return true;
}
/// <summary>Handle the 'patch summary' command.</summary>
/// <returns>Returns whether the command was handled.</returns>
private bool HandleSummary()
{
StringBuilder output = new StringBuilder();
// add condition summary
output.AppendLine();
output.AppendLine("=====================");
output.AppendLine("== Global tokens ==");
output.AppendLine("=====================");
{
// get data
IToken[] tokens =
(
from token in this.TokenManager.GetTokens(enforceContext: false)
let subkeys = token.GetSubkeys().ToArray()
let rootValues = !token.RequiresSubkeys ? token.GetValues(token.Name).ToArray() : new string[0]
let multiValue =
subkeys.Length > 1
|| rootValues.Length > 1
|| (subkeys.Length == 1 && token.GetValues(subkeys[0]).Count() > 1)
orderby multiValue, token.Name.Key // single-value tokens first, then alphabetically
select token
)
.ToArray();
int labelWidth = tokens.Max(p => p.Name.Key.Length);
// print table header
output.AppendLine($" {"token name".PadRight(labelWidth)} | value");
output.AppendLine($" {"".PadRight(labelWidth, '-')} | -----");
// print tokens
foreach (IToken token in tokens)
{
output.Append($" {token.Name.Key.PadRight(labelWidth)} | ");
if (!token.IsReady)
output.AppendLine("[ ] n/a");
else if (token.RequiresSubkeys)
{
bool isFirst = true;
foreach (TokenName name in token.GetSubkeys().OrderByIgnoreCase(key => key.Subkey))
{
if (isFirst)
{
output.Append("[X] ");
isFirst = false;
}
else
output.Append($" {"".PadRight(labelWidth, ' ')} | ");
output.AppendLine($":{name.Subkey}: {string.Join(", ", token.GetValues(name))}");
}
}
else
output.AppendLine("[X] " + string.Join(", ", token.GetValues(token.Name).OrderByIgnoreCase(p => p)));
}
}
output.AppendLine();
// add patch summary
var patches = this.GetAllPatches()
.GroupByIgnoreCase(p => p.ContentPack.Manifest.Name)
.OrderByIgnoreCase(p => p.Key);
output.AppendLine(
"=====================\n"
+ "== Content patches ==\n"
+ "=====================\n"
+ "The following patches were loaded. For each patch:\n"
+ " - 'loaded' shows whether the patch is loaded and enabled (see details for the reason if not).\n"
+ " - 'conditions' shows whether the patch matches with the current conditions (see details for the reason if not). If this is unexpectedly false, check (a) the conditions above and (b) your Where field.\n"
+ " - 'applied' shows whether the target asset was loaded and patched. If you expected it to be loaded by this point but it's false, double-check (a) that the game has actually loaded the asset yet, and (b) your Targets field is correct.\n"
+ "\n"
);
foreach (IGrouping<string, PatchInfo> patchGroup in patches)
{
ModTokenContext tokenContext = this.TokenManager.TrackLocalTokens(patchGroup.First().ContentPack.Pack);
output.AppendLine($"{patchGroup.Key}:");
output.AppendLine("".PadRight(patchGroup.Key.Length + 1, '-'));
// print tokens
{
IToken[] localTokens = tokenContext
.GetTokens(localOnly: true, enforceContext: false)
.Where(p => p.Name.Key != ConditionType.HasFile.ToString()) // no value to display
.ToArray();
if (localTokens.Any())
{
output.AppendLine();
output.AppendLine(" Local tokens:");
foreach (IToken token in localTokens.OrderBy(p => p.Name))
{
if (token.RequiresSubkeys)
{
foreach (TokenName name in token.GetSubkeys().OrderBy(p => p))
output.AppendLine($" {name}: {string.Join(", ", token.GetValues(name))}");
}
else
output.AppendLine($" {token.Name}: {string.Join(", ", token.GetValues(token.Name))}");
}
}
}
// print patches
output.AppendLine();
output.AppendLine(" loaded | conditions | applied | name + details");
output.AppendLine(" ------- | ---------- | ------- | --------------");
foreach (PatchInfo patch in patchGroup.OrderByIgnoreCase(p => p.ShortName))
{
// log checkbox and patch name
output.Append($" [{(patch.IsLoaded ? "X" : " ")}] | [{(patch.MatchesContext ? "X" : " ")}] | [{(patch.IsApplied ? "X" : " ")}] | {patch.ShortName}");
// log raw target (if not in name)
if (!patch.ShortName.Contains($"{patch.Type} {patch.RawTargetAsset}"))
output.Append($" | {patch.Type} {patch.RawTargetAsset}");
// log parsed target if tokenised
if (patch.MatchesContext && patch.ParsedTargetAsset != null && patch.ParsedTargetAsset.Tokens.Any())
output.Append($" | => {patch.ParsedTargetAsset.Value}");
// log reason not applied
string errorReason = this.GetReasonNotLoaded(patch, tokenContext);
if (errorReason != null)
output.Append($" // {errorReason}");
// log common issues
if (errorReason == null && patch.IsLoaded && !patch.IsApplied && patch.ParsedTargetAsset?.Value != null)
{
string assetName = patch.ParsedTargetAsset.Value;
List<string> issues = new List<string>();
if (this.AssetNameWithContentPattern.IsMatch(assetName))
issues.Add("shouldn't include 'Content/' prefix");
if (this.AssetNameWithExtensionPattern.IsMatch(assetName))
{
var match = this.AssetNameWithExtensionPattern.Match(assetName);
issues.Add($"shouldn't include '{match.Captures[0]}' extension");
}
if (this.AssetNameWithLocalePattern.IsMatch(assetName))
issues.Add("shouldn't include language code (use conditions instead)");
if (issues.Any())
output.Append($" | hint: asset name may be incorrect ({string.Join("; ", issues)}).");
}
// end line
output.AppendLine();
}
output.AppendLine(); // blank line between groups
}
this.Monitor.Log(output.ToString());
return true;
}
/// <summary>Handle the 'patch update' command.</summary>
/// <returns>Returns whether the command was handled.</returns>
private bool HandleUpdate()
{
this.UpdateContext();
return true;
}
/****
** Helpers
****/
/// <summary>Get basic info about all patches, including those which couldn't be loaded.</summary>
public IEnumerable<PatchInfo> GetAllPatches()
{
foreach (IPatch patch in this.PatchManager.GetPatches())
yield return new PatchInfo(patch);
foreach (DisabledPatch patch in this.PatchManager.GetPermanentlyDisabledPatches())
yield return new PatchInfo(patch);
}
/// <summary>Get a human-readable reason that the patch isn't applied.</summary>
/// <param name="patch">The patch to check.</param>
/// <param name="tokenContext">The token context for the content pack.</param>
private string GetReasonNotLoaded(PatchInfo patch, IContext tokenContext)
{
if (patch.IsApplied)
return null;
// load error
if (!patch.IsLoaded)
return $"not loaded: {patch.ReasonDisabled}";
// uses tokens not available in the current context
{
IList<TokenName> tokensOutOfContext = patch
.TokensUsed
.Union(patch.ParsedConditions.Keys)
.Where(p => !tokenContext.GetToken(p, enforceContext: false).IsReady)
.OrderByIgnoreCase(p => p.ToString())
.ToArray();
if (tokensOutOfContext.Any())
return $"uses tokens not available right now: {string.Join(", ", tokensOutOfContext)}";
}
// conditions not matched
if (!patch.MatchesContext && patch.ParsedConditions != null)
{
string[] failedConditions = (
from condition in patch.ParsedConditions.Values
orderby condition.Name.ToString()
where !condition.IsMatch(tokenContext)
select $"{condition.Name} ({string.Join(", ", condition.Values)})"
).ToArray();
if (failedConditions.Any())
return $"conditions don't match: {string.Join(", ", failedConditions)}";
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FdDecode
{
public class HeaderSecurity
{
/// <summary>
/// 加密方法
/// </summary>
/// <param name="text"></param>
/// <param name="key"></param>
/// <returns></returns>
public string Encrypt(string text, string key)
{
var targetKey = MD5Creater.getKey(key);
return MD5Creater.Encrypt_DES(text, targetKey);
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="text"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public string Decrypt(string text, string sKey)
{
var key = MD5Creater.getKey(sKey);
return MD5Creater.Decrypt_DES(text, key);
}
}
}
|
using System;
using static System.Math;
using System.Collections.Generic;
using System.Diagnostics;
namespace lab1
{
public static class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Воронова Ольга Александровна ИУ5-33Б");
double[] coef = new double [3];
if (args.Length == 0)
{
for (int i = 0; i < 3; i++)
{
coef[i] = ReadCoef(i);
while (coef[0] == 0)
{
Console.WriteLine("Введите число неравное нулю");
coef[i] = ReadCoef(i);
}
}
}
else
{
for (int i = 0; i < 3; i++)
{
if (!double.TryParse(args[i], out coef[i]))
{
Console.WriteLine("Неправильные параметры командной строки");
Process.GetCurrentProcess().Kill();
}
}
}
List<double> roots = Solve(coef);
Console.Write("Ответ: ");
WriteAnswer(roots);
}
static double ReadCoef(int pos)
{
string valueString;
double valueDouble;
bool flag;
do
{
Console.Write("Введите коэффицент при x^" + (4 - 2 * pos) + ": ");
valueString = Console.ReadLine();
flag = double.TryParse(valueString, out valueDouble);
if (!flag)
{
Console.WriteLine("Введите вещественное число");
}
} while (!flag);
return valueDouble;
}
static List<double> Solve(double[] coef)
{
List<double> roots = new List<double>();
double D = coef[1] * coef[1] - 4 * coef[0] * coef[2];
if (D < 0)
{
return roots;
}
if (D == 0)
{
double replacedVariable = - coef[1] / (2 * coef[0]);
if (replacedVariable < 0)
{
return roots;
}
if (replacedVariable == 0)
{
roots.Add(0);
return roots;
}
roots.Add(Sqrt(replacedVariable));
roots.Add(-Sqrt(replacedVariable));
return roots;
}
double root1 = (- coef[1] + Sqrt(D)) / (2 * coef[0]);
double root2 = (- coef[1] - Sqrt(D)) / (2 * coef[0]);
if (root1 == 0)
{
roots.Add(0);
}
else if (root1 > 0)
{
roots.Add(Sqrt(root1));
roots.Add(- Sqrt(root1));
}
if (root2 == 0)
{
roots.Add(0);
}
else if (root2 > 0)
{
roots.Add(Sqrt(root2));
roots.Add(- Sqrt(root2));
}
return roots;
}
static void WriteAnswer(List<double> roots)
{
if (roots.Count == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Нет корней");
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
foreach (var i in roots)
{
Console.Write(i + " ");
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraPrinting;
namespace SDI_LCS
{
public partial class Form_Work_Log : DevExpress.XtraBars.Ribbon.RibbonForm
{
Form1 Main;
string[] D_CommandID = new string[500];
public Form_Work_Log()
{
InitializeComponent();
}
public Form_Work_Log(Form1 CS_Main)
{
Main = CS_Main;
InitializeComponent();
for(int i = 0; i < 500; i ++)
{
D_CommandID[i] = "";
}
}
public void Init_Work_GridView() // 그리드뷰 설정
{
gridView1.Columns[0].Caption = "콜시간";
gridView1.Columns[1].Caption = "작 업 명";
gridView1.Columns[2].Caption = "제 품 명";
gridView1.Columns[3].Caption = "출 발 지";
gridView1.Columns[4].Caption = "도 착 지";
gridView1.Columns[5].Caption = "차량 번호";
gridView1.Columns[6].Caption = "할당 시간";
gridView1.Columns[7].Caption = "대기-출발";
gridView1.Columns[8].Caption = "적재-완료";
gridView1.Columns[9].Caption = "완료-출발";
gridView1.Columns[10].Caption = "이재-완료";
gridView1.Columns[11].Caption = "종료 시간";
gridView1.Columns[12].Caption = "작업 상태";
gridView1.Columns[13].Caption = "이동시간-적재";
gridView1.Columns[14].Caption = "작업시간-적재";
gridView1.Columns[15].Caption = "이동시간-이재";
gridView1.Columns[16].Caption = "작업시간-이재";
gridView1.Columns[17].Caption = "최종작업시간";
}
private void Form_Work_Log_Shown(object sender, EventArgs e)
{
Main.CS_Work_DB.Select_MCS_Command_Info_Log_View();
}
private void simpleButton7_Click(object sender, EventArgs e)
{
Close();
}
private void simpleButton2_Click(object sender, EventArgs e)
{
}
private void simpleButton1_Click(object sender, EventArgs e)
{
string DataTime = "";
DataTime = dateEdit1.Text;
if(DataTime != "")
{
XlsxExportOptionsEx xlsxOptions = new XlsxExportOptionsEx();
xlsxOptions.ShowGridLines = true; // 라인출력
Grid_Work_Log.ExportToXlsx("C:\\작업로그\\(" + DataTime + ")_Work_Log.xlsx", xlsxOptions);
}
}
private void simpleButton3_Click(object sender, EventArgs e)
{
}
private void dateEdit1_EditValueChanged(object sender, EventArgs e)
{
}
private void simpleButton2_Click_1(object sender, EventArgs e)
{
}
private void simpleButton2_Click_2(object sender, EventArgs e)
{
string DataTime = "";
DataTime = dateEdit1.Text;
if(DataTime != "")
{
Main.CS_Work_DB.Select_MCS_Command_Info_Log_View(DataTime);
}
}
}
} |
using GzipMT.Abstractions;
using GzipMT.DataStructures;
using System.IO;
using System.IO.Compression;
using System.Linq;
namespace GzipMT.Application.GZip
{
public class DecompressionWorker : Worker<CompressedBlock, UncompressedBlock>
{
private readonly int _bufferSizeBytes;
public DecompressionWorker(IQueue<CompressedBlock> inputQueue,
IQueue<UncompressedBlock> outputQueue, int bufferSizeBytes)
: base(inputQueue, outputQueue)
{
_bufferSizeBytes = bufferSizeBytes;
}
protected override UncompressedBlock CreateOutputBlock(CompressedBlock block)
{
var buffer = new byte[_bufferSizeBytes];
int readBytes;
using (var inputMemory = new MemoryStream(block.Data))
using (var gZipStream = new GZipStream(inputMemory, CompressionMode.Decompress))
{
readBytes = gZipStream.Read(buffer, 0, _bufferSizeBytes);
}
var item = new UncompressedBlock
{
Data = readBytes == _bufferSizeBytes ? buffer : buffer.Take(readBytes).ToArray()
};
return item;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Chess.Data.Entities;
namespace Chess.Data.Piece
{
public class Rook : ChessPiece
{
public Rook()
{
ScoreValue = 500;
}
public override IEnumerable<Move> GetValidMoves(Square[][] board)
{
var legalMoves = new List<Move>();
if (!CurrentColumn.HasValue || !CurrentRow.HasValue || !Alive) return legalMoves;
var column = CurrentColumn.Value;
var row = CurrentRow.Value;
var endPositions = new List<Tuple<int, int>>();
GetVerticalMoves(board, column, row, endPositions);
GetHorizontalMoves(board, row, column, endPositions);
legalMoves.AddRange(endPositions.Select(p => SetupNewMove(p.Item1, p.Item2)));
return legalMoves;
}
public override bool IsLegalMove(Square[][] board, Move move, IEnumerable<Move> pastMoves = null)
{
ValidateNotAttackingSameTeam(board, move);
if (move.RowChange != 0 && move.ColumnChange != 0)
throw new Exception("You only move horizontal or vertical with a rook.");
if (HasCollision(board, move))
throw new Exception("There is a piece between you and your destination.");
return true;
}
}
} |
using UnityEngine;
using System.Collections;
namespace DPYM
{
namespace PC
{
/* 键位绑定器,给固定的操作绑定键位 */
public class KeyBinder
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using GeoSearch.CSWQueryServiceReference;
namespace GeoSearch
{
public class SBAVocabularyTree : INotifyPropertyChanged
{
public const string SBA_Disasters = "Disasters";
public const string SBA_Disasters_PollutionEvents = "Pollution Events";
public const string SBA_Disasters_CoastalHazards = "Coastal Hazards";
public const string SBA_Disasters_SeaAndLakeIce = "Sea and Lake Ice";
public const string SBA_Disasters_TropicalCyclones = "Tropical Cyclones";
public const string SBA_Disasters_ExtremeWeather = "Extreme Weather";
public const string SBA_Disasters_Flood = "Flood";
public const string SBA_Disasters_Landslides = "Landslides";
public const string SBA_Disasters_Volcanoes = "Volcanoes";
public const string SBA_Disasters_Earthquakes = "Earthquakes";
public const string SBA_Disasters_WildlandFires = "Wildland Fires";
public const string SBA_Health = "Health";
public const string SBA_Health_InfectiousDiseases = "Infectious Diseases";
public const string SBA_Health_Cancer = "Cancer";
public const string SBA_Health_RespiratoryProblems = "Respiratory Problems";
public const string SBA_Health_EnvironmentalStress = "Environmental Stress";
public const string SBA_Health_Nutrition = "Nutrition";
public const string SBA_Health_Accidentals = "Accidentals";
public const string SBA_Health_BirthDefect = "Birth Defect";
public const string SBA_Energy = "Energy";
public const string SBA_Energy_OilGas = "Oil & Gas";
public const string SBA_Energy_RefiningTransport = "Refining & Transport";
public const string SBA_Energy_RenewableEnergy = "Renewable Energy";
public const string SBA_Energy_ElectricityGeneration = "Electricity Generation";
public const string SBA_Energy_GlobalEnergy = "Global Energy";
public const string SBA_Climate = "Climate";
public const string SBA_Climate_Understanding = "Understanding";
public const string SBA_Climate_Assessing = "Assessing";
public const string SBA_Climate_Predicting = "Predicting";
public const string SBA_Climate_AdaptingTo = "Adapting to";
public const string SBA_Climate_Mitigating = "Mitigating";
public const string SBA_Water = "Water";
public const string SBA_Water_WaterCycle = "Water Cycle";
public const string SBA_Water_ResourceManagement = "Resource Management";
public const string SBA_Water_ImpactsOfHumans = "Impacts of Humans";
public const string SBA_Water_Biogeochemistry = "Biogeochemistry";
public const string SBA_Water_Ecosystem = "Ecosystem";
public const string SBA_Water_LandUsePlanning = "Land Use Planning";
public const string SBA_Water_ProductionOfFood = "Production of Food";
public const string SBA_Water_WeatherPrediction = "Weather Prediction";
public const string SBA_Water_FloodPrediction = "Flood Prediction";
public const string SBA_Water_DroughtPrediction = "Drought Prediction";
public const string SBA_Water_ClimatePrediction = "Climate Prediction";
public const string SBA_Water_HumanHealth = "Human Health";
public const string SBA_Water_FisheriesAndHabitat = "Fisheries and Habitat";
public const string SBA_Water_Management = "Management";
public const string SBA_Water_TelecomunicationNavigation = "Telecomunication Navigation";
public const string SBA_Weather = "Weather";
public const string SBA_Weather_Nowcasting0_2hs = "Nowcasting 0 - 2 hs";
public const string SBA_Weather_ShortRange2_72hs = "Short Range 2 - 72 hs";
public const string SBA_Weather_MediumRange3_10days = "Medium Range 3 - 10 days";
public const string SBA_Weather_Extended10_30days = "Extended 10 - 30 days";
public const string SBA_Ecosystems = "Ecosystems";
public const string SBA_Ecosystems_LandRiverCoastOcean = "Land, River, Coast & Ocean";
public const string SBA_Ecosystems_AgricultureFisheriesForestry = "Agriculture, Fisheries, Forestry";
public const string SBA_Ecosystems_CarbonCycle = "Carbon Cycle";
public const string SBA_Agriculture = "Agriculture";
public const string SBA_Agriculture_FoodSecurity = "Food Security";
public const string SBA_Agriculture_Fisheries = "Fisheries";
public const string SBA_Agriculture_TimberFuelFiber = "Timber, Fuel & Fiber";
public const string SBA_Agriculture_EconomyTrade = "Economy & Trade";
public const string SBA_Agriculture_GrazingSystems = "Grazing Systems";
public const string SBA_Biodiversity = "Biodiversity";
public const string SBA_Biodiversity_Conservation = "Conservation";
public const string SBA_Biodiversity_InvasiveSpecies = "Invasive Species";
public const string SBA_Biodiversity_MigratorySpecies = "Migratory Species";
public const string SBA_Biodiversity_NaturalResources = "Natural Resources";
public string Name { get; set; }
public string PictureURL { get; set; }
public ObservableCollection<SBAVocabularyTree> Children { get; set; }
public SBAVocabularyTree Parent { get; set; }
public string SBAVocabularyID { get; set; }
public string Description { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private bool isSelectedValue = false;
public bool isSelected
{
get
{
return this.isSelectedValue;
}
set
{
if (value != this.isSelectedValue)
{
this.isSelectedValue = value;
NotifyPropertyChanged("isSelected");
}
}
}
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public SBAVocabularyTree(string name, string description, string pictureUrl, bool select, string id, ObservableCollection<SBAVocabularyTree> children)
{
Name = name;
PictureURL = pictureUrl;
Children = children;
isSelected = select;
SBAVocabularyID = id;
Description = description;
if (Children != null)
foreach (SBAVocabularyTree r in Children)
{
r.Parent = this;
}
}
public static ObservableCollection<SBAVocabularyTree> getSBAVocabularyList()
{
SBAVocabularyTree PollutionEvents = new SBAVocabularyTree(SBA_Disasters_PollutionEvents, SBA_Disasters_PollutionEvents, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_PollutionEvents, null);
SBAVocabularyTree CoastalHazards = new SBAVocabularyTree(SBA_Disasters_CoastalHazards, SBA_Disasters_CoastalHazards, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_CoastalHazards, null);
SBAVocabularyTree SeaAndLakeIce = new SBAVocabularyTree(SBA_Disasters_SeaAndLakeIce, SBA_Disasters_SeaAndLakeIce, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_SeaAndLakeIce, null);
SBAVocabularyTree TropicalCyclones = new SBAVocabularyTree(SBA_Disasters_TropicalCyclones, SBA_Disasters_TropicalCyclones, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_TropicalCyclones, null);
SBAVocabularyTree ExtremeWeather = new SBAVocabularyTree(SBA_Disasters_ExtremeWeather, SBA_Disasters_ExtremeWeather, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_ExtremeWeather, null);
SBAVocabularyTree Flood = new SBAVocabularyTree(SBA_Disasters_Flood, SBA_Disasters_Flood, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_Flood, null);
SBAVocabularyTree Landslides = new SBAVocabularyTree(SBA_Disasters_Landslides, SBA_Disasters_Landslides, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_Landslides, null);
SBAVocabularyTree Volcanoes = new SBAVocabularyTree(SBA_Disasters_Volcanoes, SBA_Disasters_Volcanoes, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_Volcanoes, null);
SBAVocabularyTree Earthquakes = new SBAVocabularyTree(SBA_Disasters_Earthquakes, SBA_Disasters_Earthquakes, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_Earthquakes, null);
SBAVocabularyTree WildlandFires = new SBAVocabularyTree(SBA_Disasters_WildlandFires, SBA_Disasters_WildlandFires, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Disasters_WildlandFires, null);
ObservableCollection<SBAVocabularyTree> DisastersList = new ObservableCollection<SBAVocabularyTree> { PollutionEvents, CoastalHazards, SeaAndLakeIce, TropicalCyclones, ExtremeWeather, Flood, Landslides, Volcanoes, Earthquakes, WildlandFires};
SBAVocabularyTree Disasters = new SBAVocabularyTree(SBA_Disasters, SBA_Disasters, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Disasters, DisastersList);
SBAVocabularyTree InfectiousDiseases = new SBAVocabularyTree(SBA_Health_InfectiousDiseases, SBA_Health_InfectiousDiseases, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Health_InfectiousDiseases, null);
SBAVocabularyTree Cancer = new SBAVocabularyTree(SBA_Health_Cancer, SBA_Health_Cancer, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Health_Cancer, null);
SBAVocabularyTree RespiratoryProblems = new SBAVocabularyTree(SBA_Health_RespiratoryProblems, SBA_Health_RespiratoryProblems, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Health_RespiratoryProblems, null);
SBAVocabularyTree EnvironmentalStress = new SBAVocabularyTree(SBA_Health_EnvironmentalStress, SBA_Health_EnvironmentalStress, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Health_EnvironmentalStress, null);
SBAVocabularyTree Nutrition = new SBAVocabularyTree(SBA_Health_Nutrition, SBA_Health_Nutrition, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Health_Nutrition, null);
SBAVocabularyTree Accidentals = new SBAVocabularyTree(SBA_Health_Accidentals, SBA_Health_Accidentals, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Health_Accidentals, null);
SBAVocabularyTree BirthDefect = new SBAVocabularyTree(SBA_Health_BirthDefect, SBA_Health_BirthDefect, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Health_BirthDefect, null);
ObservableCollection<SBAVocabularyTree> HealthList = new ObservableCollection<SBAVocabularyTree> { InfectiousDiseases, Cancer, RespiratoryProblems, EnvironmentalStress, Nutrition, Accidentals, BirthDefect};
SBAVocabularyTree Health = new SBAVocabularyTree(SBA_Health, SBA_Health, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Health, HealthList);
SBAVocabularyTree OilGas = new SBAVocabularyTree(SBA_Energy_OilGas, SBA_Energy_OilGas, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Energy_OilGas, null);
SBAVocabularyTree RefiningTransport = new SBAVocabularyTree(SBA_Energy_RefiningTransport, SBA_Energy_RefiningTransport, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Energy_RefiningTransport, null);
SBAVocabularyTree RenewableEnergy = new SBAVocabularyTree(SBA_Energy_RenewableEnergy, SBA_Energy_RenewableEnergy, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Energy_RenewableEnergy, null);
SBAVocabularyTree ElectricityGeneration = new SBAVocabularyTree(SBA_Energy_ElectricityGeneration, SBA_Energy_ElectricityGeneration, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Energy_ElectricityGeneration, null);
SBAVocabularyTree GlobalEnergy = new SBAVocabularyTree(SBA_Energy_GlobalEnergy, SBA_Energy_GlobalEnergy, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Energy_GlobalEnergy, null);
ObservableCollection<SBAVocabularyTree> EnergyList = new ObservableCollection<SBAVocabularyTree> { OilGas, RefiningTransport, RenewableEnergy, ElectricityGeneration, GlobalEnergy};
SBAVocabularyTree Energy = new SBAVocabularyTree(SBA_Energy, SBA_Energy, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Energy, EnergyList);
SBAVocabularyTree Understanding = new SBAVocabularyTree(SBA_Climate_Understanding, SBA_Climate_Understanding, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Climate_Understanding, null);
SBAVocabularyTree Assessing = new SBAVocabularyTree(SBA_Climate_Assessing, SBA_Climate_Assessing, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Climate_Assessing, null);
SBAVocabularyTree Predicting = new SBAVocabularyTree(SBA_Climate_Predicting, SBA_Climate_Predicting, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Climate_Predicting, null);
SBAVocabularyTree AdaptingTo = new SBAVocabularyTree(SBA_Climate_AdaptingTo, SBA_Climate_AdaptingTo, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Climate_AdaptingTo, null);
SBAVocabularyTree Mitigating = new SBAVocabularyTree(SBA_Climate_Mitigating, SBA_Climate_Mitigating, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Climate_Mitigating, null);
ObservableCollection<SBAVocabularyTree> ClimateList = new ObservableCollection<SBAVocabularyTree> { Understanding, Assessing, Predicting, AdaptingTo, Mitigating };
SBAVocabularyTree Climate = new SBAVocabularyTree(SBA_Climate, SBA_Climate, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Climate, ClimateList);
SBAVocabularyTree WaterCycle = new SBAVocabularyTree(SBA_Water_WaterCycle, SBA_Water_WaterCycle, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_WaterCycle, null);
SBAVocabularyTree ResourceManagement = new SBAVocabularyTree(SBA_Water_ResourceManagement, SBA_Water_ResourceManagement, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_ResourceManagement, null);
SBAVocabularyTree ImpactsOfHumans = new SBAVocabularyTree(SBA_Water_ImpactsOfHumans, SBA_Water_ImpactsOfHumans, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_ImpactsOfHumans, null);
SBAVocabularyTree Biogeochemistry = new SBAVocabularyTree(SBA_Water_Biogeochemistry, SBA_Water_Biogeochemistry, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_Biogeochemistry, null);
SBAVocabularyTree Ecosystem = new SBAVocabularyTree(SBA_Water_Ecosystem, SBA_Water_Ecosystem, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_Ecosystem, null);
SBAVocabularyTree LandUsePlanning = new SBAVocabularyTree(SBA_Water_LandUsePlanning, SBA_Water_LandUsePlanning, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_LandUsePlanning, null);
SBAVocabularyTree ProductionOfFood = new SBAVocabularyTree(SBA_Water_ProductionOfFood, SBA_Water_ProductionOfFood, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_ProductionOfFood, null);
SBAVocabularyTree WeatherPrediction = new SBAVocabularyTree(SBA_Water_WeatherPrediction, SBA_Water_WeatherPrediction, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_WeatherPrediction, null);
SBAVocabularyTree FloodPrediction = new SBAVocabularyTree(SBA_Water_FloodPrediction, SBA_Water_FloodPrediction, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_FloodPrediction, null);
SBAVocabularyTree DroughtPrediction = new SBAVocabularyTree(SBA_Water_DroughtPrediction, SBA_Water_DroughtPrediction, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_DroughtPrediction, null);
SBAVocabularyTree ClimatePrediction = new SBAVocabularyTree(SBA_Water_ClimatePrediction, SBA_Water_ClimatePrediction, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_ClimatePrediction, null);
SBAVocabularyTree HumanHealth = new SBAVocabularyTree(SBA_Water_HumanHealth, SBA_Water_HumanHealth, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_HumanHealth, null);
SBAVocabularyTree FisheriesAndHabitat = new SBAVocabularyTree(SBA_Water_FisheriesAndHabitat, SBA_Water_FisheriesAndHabitat, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_FisheriesAndHabitat, null);
SBAVocabularyTree Management = new SBAVocabularyTree(SBA_Water_Management, SBA_Water_Management, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_Management, null);
SBAVocabularyTree TelecomunicationNavigation = new SBAVocabularyTree(SBA_Water_TelecomunicationNavigation, SBA_Water_TelecomunicationNavigation, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Water_TelecomunicationNavigation, null);
ObservableCollection<SBAVocabularyTree> WaterList = new ObservableCollection<SBAVocabularyTree> { WaterCycle, ResourceManagement, ImpactsOfHumans, Biogeochemistry, Ecosystem,
LandUsePlanning, ProductionOfFood, ProductionOfFood, FloodPrediction, DroughtPrediction,
ClimatePrediction, HumanHealth, FisheriesAndHabitat, Management, TelecomunicationNavigation};
SBAVocabularyTree Water = new SBAVocabularyTree(SBA_Water, SBA_Water, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Water, WaterList);
SBAVocabularyTree Nowcasting0_2hs = new SBAVocabularyTree(SBA_Weather_Nowcasting0_2hs, SBA_Weather_Nowcasting0_2hs, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Weather_Nowcasting0_2hs, null);
SBAVocabularyTree ShortRange2_72hs = new SBAVocabularyTree(SBA_Weather_ShortRange2_72hs, SBA_Weather_ShortRange2_72hs, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Weather_ShortRange2_72hs, null);
SBAVocabularyTree MediumRange3_10days = new SBAVocabularyTree(SBA_Weather_MediumRange3_10days, SBA_Weather_MediumRange3_10days, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Weather_MediumRange3_10days, null);
SBAVocabularyTree Extended10_30days = new SBAVocabularyTree(SBA_Weather_Extended10_30days, SBA_Weather_Extended10_30days, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Weather_Extended10_30days, null);
ObservableCollection<SBAVocabularyTree> WeatherList = new ObservableCollection<SBAVocabularyTree> { Nowcasting0_2hs, ShortRange2_72hs, MediumRange3_10days, Extended10_30days };
SBAVocabularyTree Weather = new SBAVocabularyTree(SBA_Weather, SBA_Weather, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Weather, WeatherList);
SBAVocabularyTree LandRiverCoastOcean = new SBAVocabularyTree(SBA_Ecosystems_LandRiverCoastOcean, SBA_Ecosystems_LandRiverCoastOcean, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Ecosystems_LandRiverCoastOcean, null);
SBAVocabularyTree AgricultureFisheriesForestry = new SBAVocabularyTree(SBA_Ecosystems_AgricultureFisheriesForestry, SBA_Ecosystems_AgricultureFisheriesForestry, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Ecosystems_AgricultureFisheriesForestry, null);
SBAVocabularyTree CarbonCycle = new SBAVocabularyTree(SBA_Ecosystems_CarbonCycle, SBA_Ecosystems_CarbonCycle, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Ecosystems_CarbonCycle, null);
ObservableCollection<SBAVocabularyTree> EcosystemsList = new ObservableCollection<SBAVocabularyTree> { LandRiverCoastOcean, AgricultureFisheriesForestry, CarbonCycle};
SBAVocabularyTree Ecosystems = new SBAVocabularyTree(SBA_Ecosystems, SBA_Ecosystems, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Ecosystems, EcosystemsList);
SBAVocabularyTree FoodSecurity = new SBAVocabularyTree(SBA_Agriculture_FoodSecurity, SBA_Agriculture_FoodSecurity, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Agriculture_FoodSecurity, null);
SBAVocabularyTree Fisheries = new SBAVocabularyTree(SBA_Agriculture_Fisheries, SBA_Agriculture_Fisheries, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Agriculture_Fisheries, null);
SBAVocabularyTree TimberFuelFiber = new SBAVocabularyTree(SBA_Agriculture_TimberFuelFiber, SBA_Agriculture_TimberFuelFiber, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Agriculture_TimberFuelFiber, null);
SBAVocabularyTree EconomyTrade = new SBAVocabularyTree(SBA_Agriculture_EconomyTrade, SBA_Agriculture_EconomyTrade, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Agriculture_EconomyTrade, null);
SBAVocabularyTree GrazingSystems = new SBAVocabularyTree(SBA_Agriculture_GrazingSystems, SBA_Agriculture_GrazingSystems, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Agriculture_GrazingSystems, null);
ObservableCollection<SBAVocabularyTree> AgricultureList = new ObservableCollection<SBAVocabularyTree> { FoodSecurity, Fisheries, TimberFuelFiber, EconomyTrade, GrazingSystems };
SBAVocabularyTree Agriculture = new SBAVocabularyTree(SBA_Agriculture, SBA_Agriculture, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Agriculture, AgricultureList);
SBAVocabularyTree Conservation = new SBAVocabularyTree(SBA_Biodiversity_Conservation, SBA_Biodiversity_Conservation, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Biodiversity_Conservation, null);
SBAVocabularyTree InvasiveSpecies = new SBAVocabularyTree(SBA_Biodiversity_InvasiveSpecies, SBA_Biodiversity_InvasiveSpecies, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Biodiversity_InvasiveSpecies, null);
SBAVocabularyTree MigratorySpecies = new SBAVocabularyTree(SBA_Biodiversity_MigratorySpecies, SBA_Biodiversity_MigratorySpecies, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Biodiversity_MigratorySpecies, null);
SBAVocabularyTree NaturalResources = new SBAVocabularyTree(SBA_Biodiversity_NaturalResources, SBA_Biodiversity_NaturalResources, "/GeoSearch;component/images/SBAVocabulariess/map.png", true, SBA_Biodiversity_NaturalResources, null);
ObservableCollection<SBAVocabularyTree> BiodiversityList = new ObservableCollection<SBAVocabularyTree> { Conservation, InvasiveSpecies, MigratorySpecies, NaturalResources};
SBAVocabularyTree Biodiversity = new SBAVocabularyTree(SBA_Biodiversity, SBA_Biodiversity, "/GeoSearch;component/images/resourceTypes/map.png", true, SBA_Biodiversity, BiodiversityList);
//ObservableCollection<SBAVocabularyTree> list = new ObservableCollection<SBAVocabularyTree> { Disasters, Health, Energy, Climate, Water, Weather, Ecosystems, Agriculture, Biodiversity };
ObservableCollection<SBAVocabularyTree> list = new ObservableCollection<SBAVocabularyTree> { Agriculture, Biodiversity, Climate, Disasters, Ecosystems, Energy, Health, Water, Weather};
return list;
}
public static SBAVocabulary createSBAVocabularyFromTreeNode(SBAVocabularyTree vt)
{
SBAVocabulary root = new SBAVocabulary();
root.Name = vt.Name;
root.isSelected = vt.isSelected;
root.SBAVocabularyID = vt.SBAVocabularyID;
if (vt.Children != null)
{
root.Children = new ObservableCollection<SBAVocabulary>();
foreach (SBAVocabularyTree rtt in vt.Children)
{
SBAVocabulary rt = createSBAVocabularyFromTreeNode(rtt);
root.Children.Add(rt);
}
}
return root;
}
}
}
|
using OxyPlot.WindowsForms;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PterodactylCharts
{
public partial class Graph : Form
{
public Graph()
{
InitializeComponent();
}
public void GraphData(bool showGraph, GraphElements graphElements, GraphSettings graphSettings, string path)
{
GraphObject = new GraphEngine(showGraph, graphElements, graphSettings, path);
PlotView myPlot = GraphObject.ChartCreator();
Controls.Add(myPlot);
}
public string Create()
{
string reportPart = GraphObject.Create();
return reportPart;
}
public void Export()
{
GraphObject.Export();
}
public GraphEngine GraphObject { get; set; }
public Bitmap ExportBitmap()
{
return GraphObject.ExportBitmap();
}
}
}
|
using System;
using System.Web.UI;
using System.Text;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace Resume_Builder
{
public partial class index : Page
{
//Method to grab the user input for personal information
internal string contactInfo()
{
//Mutable string for adding user inputs
StringBuilder contactForm = new StringBuilder();
//Content to be appended to string builder
string firstName = firstNameInput.Text;
string lastName = lastNameInput.Text;
string number = numberInput.Text;
string email = emailInput.Text;
string address = addressInput.Text;
string linkOne = linkOneInput.Text;
string linkTwo = linkTwoInput.Text;
if (firstName.Length > 0 && lastName.Length > 0)
{
//FullName
contactForm.Append(firstName);
contactForm.Append(' ');
contactForm.Append(lastName);
//New Line
contactForm.Append('\n');
}
if (number.Length > 0)
{
//phone number
contactForm.Append(number);
//New Line
contactForm.Append('\n');
}
if (email.Length > 0)
{
//email
contactForm.Append(email);
//New Line
contactForm.Append('\n');
}
if (address.Length > 0)
{
//address
contactForm.Append(address);
//New Line
contactForm.Append('\n');
}
if (linkOne.Length > 0)
{
//linkOne
contactForm.Append(linkOne);
//New Line
contactForm.Append('\n');
}
if (linkTwo.Length > 0)
{
//link Two
contactForm.Append(linkTwo);
//New Line
contactForm.Append('\n');
}
string form = contactForm.ToString();
return form;
}
//Skills one category grabber
internal string skillsCatOne()
{
StringBuilder addColon = new StringBuilder();
string skillCatOne = categoryOneInput.Text;
addColon.Append(skillCatOne);
addColon.Append(':');
string catOne = addColon.ToString();
return catOne;
}
//User input for skill category one
internal string sOne()
{
StringBuilder appendString = new StringBuilder();
string skills = skillsOneInput.Text;
appendString.Append(skills);
string skillOne = appendString.ToString();
return skillOne;
}
//gets the next category input
internal string skillsCatTwo()
{
StringBuilder appendString = new StringBuilder();
string skillsCatTwo = categoryTwoInput.Text;
appendString.Append(skillsCatTwo);
appendString.Append(':');
string finalString = appendString.ToString();
return finalString;
}
//Represents the skills two input
internal string sTwo()
{
StringBuilder appendString = new StringBuilder();
string skillsTwo = skillsTwoInput.Text;
appendString.Append(skillsTwo);
string finalString = appendString.ToString();
return finalString;
}
//Category three input
internal string skillsCatThree()
{
StringBuilder appendString = new StringBuilder();
string skillsCatThree = categoryThreeInput.Text;
appendString.Append(skillsCatThree);
appendString.Append(':');
string finalString = appendString.ToString();
return finalString;
}
//Represents the skills Three input
internal string sThree()
{
StringBuilder appendString = new StringBuilder();
string skillsThree = skillsThreeInput.Text;
appendString.Append(skillsThree);
string finalString = appendString.ToString();
return finalString;
}
//Category Four input
internal string skillsCatFour()
{
StringBuilder appendString = new StringBuilder();
string skillsCatFour = categoryFourInput.Text;
appendString.Append(skillsCatFour);
appendString.Append(':');
string finalString = appendString.ToString();
return finalString;
}
//Represents the skills four input
internal string sFour()
{
StringBuilder appendString = new StringBuilder();
string skillsFour = skillsFourInput.Text;
appendString.Append(skillsFour);
string finalString = appendString.ToString();
return finalString;
}
//Experience Functions
//Experience One
internal string experienceOne()
{
StringBuilder appendString = new StringBuilder();
string title = titleOneInput.Text;
string employer = employerOneInput.Text;
string location = locationOneInput.Text;
appendString.Append(title);
appendString.Append(", ");
appendString.Append(employer);
appendString.Append(", ");
appendString.Append(location);
appendString.Append(":");
string finalString = appendString.ToString();
return finalString;
}
//Description One
internal string desOne()
{
StringBuilder appendString = new StringBuilder();
StringBuilder appendLine = new StringBuilder();
string description = descriptionOneInput.Text;
string[] newLine = description.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach(var line in newLine)
{
int lineLength = line.Length;
//Max line width is ~90 characters
appendString.Append("-");
for (var i = 0; i <= (lineLength / 90); i += 1)
{
appendLine.Clear();
int charIndex = (i + 1) * 90;
if ((lineLength / charIndex) != 0)
{
while(line[charIndex].ToString() != " ")
{
charIndex -= 1;
if (charIndex == 0)
{
charIndex = (i + 1) * 90;
break;
}
}
appendLine.Append(line);
appendLine.Insert(charIndex, Environment.NewLine + " ");
appendString.Append(appendLine);
}
else if ((lineLength / charIndex) == 0 && i == 0)
{
appendString.Append(line);
}
}
appendString.Append("\n");
}
string finalString = appendString.ToString();
return finalString;
}
//Experience two
internal string experienceTwo()
{
StringBuilder appendString = new StringBuilder();
string title = titleTwoInput.Text;
string employer = employerTwoInput.Text;
string location = locationTwoInput.Text;
appendString.Append(title);
appendString.Append(", ");
appendString.Append(employer);
appendString.Append(", ");
appendString.Append(location);
appendString.Append(":");
string finalString = appendString.ToString();
return finalString;
}
//Description Two
internal string desTwo()
{
StringBuilder appendString = new StringBuilder();
StringBuilder appendLine = new StringBuilder();
string description = descriptionTwoInput.Text;
string[] newLine = description.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach(var line in newLine)
{
int lineLength = line.Length;
//Max line width is ~90 characters
appendString.Append("-");
for (var i = 0; i <= (lineLength / 90); i += 1)
{
appendLine.Clear();
int charIndex = (i + 1) * 90;
if ((lineLength / charIndex) != 0)
{
while(line[charIndex].ToString() != " ")
{
charIndex -= 1;
if (charIndex == 0)
{
charIndex = (i + 1) * 90;
break;
}
}
appendLine.Append(line);
appendLine.Insert(charIndex, Environment.NewLine + " ");
appendString.Append(appendLine);
}
else if ((lineLength / charIndex) == 0 && i == 0)
{
appendString.Append(line);
}
}
appendString.Append("\n");
}
string finalString = appendString.ToString();
return finalString;
}
//Experience Three
internal string experienceThree()
{
StringBuilder appendString = new StringBuilder();
string title = titleThreeInput.Text;
string employer = employerThreeInput.Text;
string location = locationThreeInput.Text;
appendString.Append(title);
appendString.Append(", ");
appendString.Append(employer);
appendString.Append(", ");
appendString.Append(location);
appendString.Append(":");
string finalString = appendString.ToString();
return finalString;
}
//Description Three
internal string desThree()
{
StringBuilder appendString = new StringBuilder();
StringBuilder appendLine = new StringBuilder();
string description = descriptionThreeInput.Text;
string[] newLine = description.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in newLine)
{
int lineLength = line.Length;
//Max line width is ~90 characters
appendString.Append("-");
for (var i = 0; i <= (lineLength / 90); i += 1)
{
//Clears the string builder to make sure that strings don't overlap
appendLine.Clear();
int charIndex = (i + 1) * 90;
//Checks if line needs to be split up
if ((lineLength / charIndex) != 0)
{
//Makes sure that new lines are inserted at spaces
while (line[charIndex].ToString() != " ")
{
charIndex -= 1;
if (charIndex == 0)
{
charIndex = (i + 1) * 90;
break;
}
}
appendLine.Append(line);
appendLine.Insert(charIndex, Environment.NewLine + " ");
appendString.Append(appendLine);
}
//Appends line if line was not over 90 characters
else if ((lineLength / charIndex) == 0 && i == 0)
{
appendString.Append(line);
}
}
appendString.Append("\n");
}
string finalString = appendString.ToString();
return finalString;
}
//Education Methods
//Education One Type information
internal string educationOne()
{
StringBuilder appendString = new StringBuilder();
string name = schoolOneInput.Text;
string location = schoolLocationOneInput.Text;
string degree = degreeOneInput.Text;
appendString.Append(name);
appendString.Append(", ");
appendString.Append(location);
appendString.Append(", ");
appendString.Append(degree);
appendString.Append(":");
string finalString = appendString.ToString();
return finalString;
}
//Education One Description
internal string edDescOne()
{
StringBuilder appendString = new StringBuilder();
StringBuilder appendLine = new StringBuilder();
string description = edDescriptionOneInput.Text;
int charIndex;
string[] newLine = description.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in newLine)
{
int lineLength = line.Length;
//Max line width is ~90 characters
appendString.Append("\t");
for (var i = 0; i <= (lineLength / 85); i += 1)
{
//Clears the string builder to make sure that strings don't overlap
appendLine.Clear();
if (i == 0)
{
charIndex = (i + 1) * 85;
}
else
{
charIndex = (i + 1) * 90;
}
//Checks if line needs to be split up
if ((lineLength / charIndex) != 0)
{
//Makes sure that new lines are inserted at spaces
while (line[charIndex].ToString() != " ")
{
charIndex -= 1;
if (charIndex == 0)
{
charIndex = (i + 1) * 90;
break;
}
}
appendLine.Append(line);
appendLine.Insert(charIndex, Environment.NewLine + " ");
appendString.Append(appendLine);
}
//Appends line if line was not over 85 characters
else if ((lineLength / charIndex) == 0 && i == 0)
{
appendString.Append(line);
}
}
appendString.Append("\n");
}
string finalString = appendString.ToString();
return finalString;
}
//Education Two Type information
internal string educationTwo()
{
StringBuilder appendString = new StringBuilder();
string name = schoolTwoInput.Text;
string location = schoolLocationTwoInput.Text;
string degree = degreeTwoInput.Text;
appendString.Append(name);
appendString.Append(", ");
appendString.Append(location);
appendString.Append(", ");
appendString.Append(degree);
appendString.Append(":");
string finalString = appendString.ToString();
return finalString;
}
//Education Two Description
internal string edDescTwo()
{
StringBuilder appendString = new StringBuilder();
StringBuilder appendLine = new StringBuilder();
string description = edDescriptionTwoInput.Text;
int charIndex;
string[] newLine = description.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in newLine)
{
int lineLength = line.Length;
//Max line width is ~90 characters
appendString.Append("\t");
for (var i = 0; i <= (lineLength / 85); i += 1)
{
//Clears the string builder to make sure that strings don't overlap
appendLine.Clear();
if (i == 0)
{
charIndex = (i + 1) * 85;
}
else
{
charIndex = (i + 1) * 90;
}
//Checks if line needs to be split up
if ((lineLength / charIndex) != 0)
{
//Makes sure that new lines are inserted at spaces
while (line[charIndex].ToString() != " ")
{
charIndex -= 1;
if (charIndex == 0)
{
charIndex = (i + 1) * 90;
break;
}
}
appendLine.Append(line);
appendLine.Insert(charIndex, Environment.NewLine + " ");
appendString.Append(appendLine);
}
//Appends line if line was not over 85 characters
else if ((lineLength / charIndex) == 0 && i == 0)
{
appendString.Append(line);
}
}
appendString.Append("\n");
}
string finalString = appendString.ToString();
return finalString;
}
//Generates random number for resume
internal string randNum()
{
StringBuilder appendString = new StringBuilder();
Random r = new Random();
int rNumOne = r.Next(0, 10);
int rNumTwo = r.Next(0, 20);
int rNumThree = r.Next(0, 40);
int rNumFour = r.Next(0, 80);
int rNumFive = r.Next(0, 160);
int rNumSix = r.Next(0, 320);
appendString.Append(rNumOne.ToString());
appendString.Append(rNumTwo.ToString());
appendString.Append(rNumThree.ToString());
appendString.Append(rNumFour.ToString());
appendString.Append(rNumFive.ToString());
appendString.Append(rNumSix.ToString());
string finalNum = appendString.ToString();
return finalNum;
}
//On button click take user input and save it to the server as a pdf and then redirect to webpage containing pdf document
protected void PdfDownloader_Click(object sender, EventArgs e)
{
//Creates PDF document to add to
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
//Chooses Font
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f);
PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
//Align Center
PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center);
//Align left
PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left);
//Displays skills header
PdfFont headerFont = new PdfFont(PdfFontFamily.Helvetica, 18f, PdfFontStyle.Bold);
//Displays skills section
PdfFont underlined = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Underline);
//Positioning variables
float fontHeight = font.Size;//Measures size of font
float hFontHeight = headerFont.Size;//Measures size of header font
float y = (contactInfo().Split('\n').Length * fontHeight);//base y coordinate
float x = page.Canvas.ClientSize.Width / 2;//X-Coordinate half the page
//Skills position variables
int iSkills = 0;//counts how many skills items are currently displayed
float xIndent = page.Canvas.ClientSize.Width / 20;//All skills category x coordinates
float xIndentTwo = xIndent + 20;//skills x coordinate
float ySkillsHeader = y ;//Skills Header position
float ySkillsCatOne = ySkillsHeader + hFontHeight + 5;//Category one position
float ySkillsOne = ySkillsCatOne + fontHeight + 5;//skills one y coordinate
float ySkillsCatTwo = ySkillsOne + fontHeight + 5;//cat two
float ySkillsTwo = ySkillsCatTwo + fontHeight + 5;//skills two
float ySkillsCatThree = ySkillsTwo + fontHeight + 5;//cat three
float ySkillsThree = ySkillsCatThree + fontHeight + 5;//skills three
float ySkillsCatFour = ySkillsThree + fontHeight + 5;//cat Four
float ySkillsFour = ySkillsCatFour + fontHeight + 5;//skills four
//Displays contact info
page.Canvas.DrawString(contactInfo(), font, brush, x, 0, centerAlignment);
if (skillsCatOne()[0] != ':')
{
//Skills
page.Canvas.DrawString("Skills", headerFont, brush, 0, ySkillsHeader, leftAlignment);
//Category One
page.Canvas.DrawString(skillsCatOne(), underlined, brush, xIndent, ySkillsCatOne, leftAlignment);
//Skills One
page.Canvas.DrawString(sOne(), font, brush, xIndentTwo, ySkillsOne, leftAlignment);
iSkills += 1;
if (skillsCatTwo()[0] != ':')
{
//Category Two
page.Canvas.DrawString(skillsCatTwo(), underlined, brush, xIndent, ySkillsCatTwo, leftAlignment);
//Skills Two
page.Canvas.DrawString(sTwo(), font, brush, xIndentTwo, ySkillsTwo, leftAlignment);
iSkills += 1;
if (skillsCatThree()[0] != ':')
{
//Category Three
page.Canvas.DrawString(skillsCatThree(), underlined, brush, xIndent, ySkillsCatThree, leftAlignment);
//Skills Three
page.Canvas.DrawString(sThree(), font, brush, xIndentTwo, ySkillsThree, leftAlignment);
iSkills += 1;
if (skillsCatFour()[0] != ':')
{
//Category Four
page.Canvas.DrawString(skillsCatFour(), underlined, brush, xIndent, ySkillsCatFour, leftAlignment);
//Skills Four
page.Canvas.DrawString(sFour(), font, brush, xIndentTwo, ySkillsFour, leftAlignment);
iSkills += 1;
}
}
}
}
//Experience counter variable
int iExperience = 0;
//Experience position Variables
float yExperience = y;
if (iSkills != 0)
{
yExperience = ((y + hFontHeight) + (iSkills * 2 * 5) + ((fontHeight * 2) * iSkills));
}
float yExpOne = yExperience + 30;//Experience title info one
float yExpDesOne = yExpOne + 15;//Experience description position one
float yExpTwo = yExpDesOne + (desOne().Split('\n').Length * font.Height);//Experience position two
float yExpDesTwo = yExpTwo + 15;//Experience description position two
float yExpThree = yExpDesTwo + (desTwo().Split('\n').Length * font.Height);//Experience position three
float yExpDesThree = yExpThree + 15;
//Experience Sections
if (experienceOne()[0] != ',')
{
page.Canvas.DrawString("Experience", headerFont, brush, 0, yExperience, leftAlignment);
page.Canvas.DrawString(experienceOne(), underlined, brush, xIndent, yExpOne, leftAlignment);
page.Canvas.DrawString(desOne(), font, brush, xIndentTwo, yExpDesOne, leftAlignment);
iExperience += 1;
if (experienceTwo()[0] != ',')
{
page.Canvas.DrawString(experienceTwo(), underlined, brush, xIndent, yExpTwo, leftAlignment);
page.Canvas.DrawString(desTwo(), font, brush, xIndentTwo, yExpDesTwo, leftAlignment);
iExperience += 1;
if (experienceThree()[0] != ',')
{
page.Canvas.DrawString(experienceThree(), underlined, brush, xIndent, yExpThree, leftAlignment);
page.Canvas.DrawString(desThree(), font, brush, xIndentTwo, yExpDesThree, leftAlignment);
iExperience += 1;
}
}
}
//Education exprience variables
float yEducation = y;
if (iExperience == 1)
{
yEducation = yExpTwo;
}
else if (iExperience == 2)
{
yEducation = yExpThree;
}
else if (iExperience == 3)
{
yEducation = yExpDesThree + ((desTwo().Split('\n').Length) * font.Height) + 5;
}
else if (iSkills != 0)
{
yEducation = ((y + hFontHeight) + (iSkills * 2 * 5) + ((fontHeight * 2) * iSkills));
}
float yEdOne = yEducation + 30;//y coordinate of education one
float yEdDescOne = yEdOne + 15;
float yEdTwo = yEdDescOne + ((edDescOne().Split('\n').Length) * font.Height) + 5;//y coordinate of education two
float yEdDescTwo = yEdTwo + 15;
//Education Sections
if (educationOne()[0] != ',')
{
page.Canvas.DrawString("Education", headerFont, brush, 0, yEducation, leftAlignment);
page.Canvas.DrawString(educationOne(), underlined, brush, xIndent, yEdOne, leftAlignment);
page.Canvas.DrawString(edDescOne(), font, brush, xIndentTwo, yEdDescOne, leftAlignment);
if (educationTwo()[0] != ',')
{
page.Canvas.DrawString(educationTwo(), underlined, brush, xIndent, yEdTwo, leftAlignment);
page.Canvas.DrawString(edDescTwo(), font, brush, xIndentTwo, yEdDescTwo, leftAlignment);
}
}
//Saves randNum() method to a variable
string rNumber = randNum();
//Saves file to resume folder on server
doc.SaveToFile(Server.MapPath("~/Resume/" + rNumber + ".pdf"));
doc.Close();
//Redirects user to view of their pdf to optionally download or print
Response.Redirect("~/Resume/" + rNumber + ".pdf");
}
}
} |
namespace LoneWolf.Migration.Code
{
public class CombatSkill : GeneratorBase
{
public CombatSkill()
: base(
@"^.*([0-9]) point.*<span class=""smallcaps"">COMBAT SKILL</span>.*$",
@".add(new ModifyCombatSkill({0}))")
{
}
}
}
|
namespace XH.Infrastructure.Domain.UnitOfWorks
{
public interface IUnitOfWork
{
}
}
|
using System;
using System.Collections.Generic;
namespace Core.Entities
{
public partial class RVipTicket
{
public int RVipTicketId { get; set; }
public DateTime Date { get; set; }
public string Img { get; set; }
public bool? FirstPage { get; set; }
public string Alt { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.