text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Library.Helper
{
public class Funcs
{
public dynamic ParseValue(string val)
{
string stringval;
int intval;
float floatval;
if (float.TryParse(val, out floatval))
{
return floatval;
};
if (Int32.TryParse(val, out intval))
{
return intval;
};
return val;
}
}
}
|
using bringpro.Data;
using bringpro.Web.Domain;
using bringpro.Web.Enums;
using bringpro.Web.Models.Requests;
using bringpro.Web.Models.Responses;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace bringpro.Web.Services
{
public class WebsiteSettingsServices : BaseService
{
public static List<WebsiteSettings> GetWebsiteSettingsBySlug(int WebsiteId, List<string> Slugs)
{
List<WebsiteSettings> list = new List<WebsiteSettings>();
{
DataProvider.ExecuteCmd(GetConnection, "dbo.WebsiteSettings_GetSettingsBySlug"
, inputParamMapper: delegate (SqlParameterCollection paramCollection)
{
paramCollection.AddWithValue("@WebsiteId", WebsiteId);
SqlParameter s = new SqlParameter("@Slug", SqlDbType.Structured);
if (Slugs != null && Slugs.Any())
{
s.Value = new NVarcharTable(Slugs);
}
paramCollection.Add(s);
}, map: delegate (IDataReader reader, short set)
{
WebsiteSettings ws = new WebsiteSettings();
int startingIndex = 0;
ws.Id = reader.GetSafeInt32(startingIndex++);
ws.SettingsId = reader.GetSafeInt32(startingIndex++);
ws.WebsiteId = reader.GetSafeInt32(startingIndex++);
ws.SettingsValue = reader.GetSafeString(startingIndex++);
ws.UserId = reader.GetSafeString(startingIndex++);
ws.MediaId = reader.GetSafeInt32(startingIndex++);
ws.DateAdded = reader.GetSafeDateTime(startingIndex++);
ws.DateModified = reader.GetSafeDateTime(startingIndex++);
Website w = new Website();
w.Id = reader.GetSafeInt32(startingIndex++);
w.Name = reader.GetSafeString(startingIndex++);
w.Slug = reader.GetSafeString(startingIndex++);
w.Description = reader.GetSafeString(startingIndex++);
w.Url = reader.GetSafeString(startingIndex++);
w.MediaId = reader.GetSafeInt32(startingIndex++);
w.DateCreated = reader.GetSafeDateTime(startingIndex++);
w.DateModified = reader.GetSafeDateTime(startingIndex++);
ws.Website = w;
Settings s = new Settings();
s.Id = reader.GetSafeInt32(startingIndex++);
s.Category = reader.GetSafeEnum<SettingsCategory>(startingIndex++);
s.Name = reader.GetSafeString(startingIndex++);
s.DateCreated = reader.GetSafeDateTime(startingIndex++);
s.DateModified = reader.GetSafeDateTime(startingIndex++);
s.SettingType = reader.GetSafeEnum<SettingsType>(startingIndex++);
s.Description = reader.GetSafeString(startingIndex++);
s.SettingSlug = reader.GetSafeString(startingIndex++);
s.SettingSection = reader.GetSafeEnum<SettingsSection>(startingIndex++);
ws.Setting = s;
Media m = new Media();
m.Id = reader.GetSafeInt32(startingIndex++);
m.Url = reader.GetSafeString(startingIndex++);
m.MediaType = reader.GetSafeInt32(startingIndex++);
m.UserId = reader.GetSafeString(startingIndex++);
m.Title = reader.GetSafeString(startingIndex++);
m.Description = reader.GetSafeString(startingIndex++);
m.ExternalMediaId = reader.GetSafeInt32(startingIndex++);
m.FileType = reader.GetSafeString(startingIndex++);
m.DateCreated = reader.GetSafeDateTime(startingIndex++);
m.DateModified = reader.GetSafeDateTime(startingIndex++);
if (m.Id != 0)
{
ws.Media = m;
}
if (list == null)
{
list = new List<WebsiteSettings>();
}
list.Add(ws);
}
);
return list;
}
}
public static Dictionary<string, WebsiteSettings> getWebsiteSettingsDictionaryBySlug(int websiteId, List<string> Slugs)
{
Dictionary<string, WebsiteSettings> dict = null;
List<WebsiteSettings> list = GetWebsiteSettingsBySlug(websiteId, Slugs);
if (list != null)
{
dict = new Dictionary<string, WebsiteSettings>();
foreach (var setting in list)
{
dict.Add(setting.Setting.SettingSlug, setting);
}
}
return dict;
}
}
} |
/*
* Experimental script. This scripts creates a Generate Cinemachine Skeleton Track button in the Experimental scene.
*/
using UnityEngine;
using UnityEditor;
namespace Riggingtools.Skeletons
{
[CustomEditor(typeof(BRRigMoveManager))]
public class SpawnSkeletonTrack : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
BRRigMoveManager moveManager = (BRRigMoveManager)target;
if(GUILayout.Button("Generate Skeleton Track"))
{
moveManager.AddPluginLoaderMoveTrack();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _14.Dictionary
{
class Dictionary
{
static void Main(string[] args)
{
/*A dictionary is stored as a sequence of text lines containing words and their explanations.
Write a program that enters a word and translates it by using the dictionary. */
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string[] keyWords = { ".NET", "CLR", "namespace", "string", "object" };
string[] explanation =
{
"platform for applications from Microsoft",
"managed execution environment for .NET",
"hierarchical organization of classes",
"represents text as a series of Unicode characters",
"the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy"
};
for (int i = 0; i < keyWords.Length; i++)
{
dictionary.Add(keyWords[i].ToUpper(), explanation[i]);
}
Console.WriteLine("This dictionary consist of the words: .NET, CLR, namespace, string and object. Enter one of this words for explanation: ");
string inputWord = Console.ReadLine();
try
{
Console.WriteLine("{0} - {1}", inputWord, dictionary[inputWord.ToUpper()]);
}
catch (KeyNotFoundException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Tilemaps;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
private Tilemap map;
private GameObject pacStudent;
private GameUIManager manager;
private AudioSource backgroundaudio;
// Start is called before the first frame update
void Start()
{
map = GameObject.FindGameObjectWithTag("Map").GetComponentInChildren<Tilemap>();
pacStudent = GameObject.FindGameObjectWithTag("Player");
manager = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameUIManager>();
backgroundaudio = GameObject.Find("BackgroundSource").GetComponent<AudioSource>();
StartCoroutine("StartGame");
}
// Update is called once per frame
void Update()
{
}
IEnumerator StartGame()
{
pacStudent.GetComponent<PacStudentController>().enabled = false;
Text display = GameObject.Find("GameMessage").GetComponent<Text>();
display.enabled = true;
display.text = "3";
yield return new WaitForSeconds(1);
display.text = "2";
yield return new WaitForSeconds(1);
display.text = "1";
yield return new WaitForSeconds(1);
display.text = "GO!";
yield return new WaitForSeconds(1);
display.enabled = false;
pacStudent.GetComponent<PacStudentController>().enabled = true;
manager.gameStart = true;
backgroundaudio.GetComponent<MusicPlayer>().PlayNormalBackground();
}
public void GameOver()
{
manager.gameStart = false;
int PreviousScore = PlayerPrefs.GetInt("HighScore", 0);
float PreviousTime = PlayerPrefs.GetFloat("GameTime", 0);
if (manager.Score > PreviousScore || (manager.Score == PreviousScore && manager.gameTime < PreviousTime))
{
PlayerPrefs.SetInt("HighScore", manager.Score);
PlayerPrefs.SetFloat("GameTime", manager.gameTime);
PlayerPrefs.Save();
}
backgroundaudio.enabled = false;
pacStudent.SetActive(false);
backgroundaudio.GetComponent<MusicPlayer>().enabled = false;
StartCoroutine("ShowGameOverScreen");
}
IEnumerator ShowGameOverScreen()
{
GameObject.Find("GameMessage").GetComponent<Text>().enabled = true;
GameObject.Find("GameMessage").GetComponent<Text>().text = "Game Over!";
yield return new WaitForSeconds(3);
SceneManager.LoadSceneAsync(0);
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Drawing;
using System.Drawing.Imaging;
namespace Tivo.Hme.Samples
{
class Pictures : HmeApplicationHandler
{
private const int ShowTime = 4000;
private static readonly TimeSpan FadeTime = TimeSpan.FromMilliseconds(1250);
private static List<string> imageNames = new List<string>();
private Application _application;
private ImageView _foreground;
private ImageView _background;
private Timer _timer;
private int _currentImageIndex = 0;
static Pictures()
{
string imagePath = Properties.Settings.Default.ImagePath;
foreach (string imageFileName in System.IO.Directory.GetFiles(imagePath, "*.jpg", System.IO.SearchOption.AllDirectories))
{
string imageName = Guid.NewGuid().ToString();
using (Image image = GetScaledImage(imageFileName, 640, 480))
{
Application.Images.Add(imageName, image, ImageFormat.Jpeg);
}
imageNames.Add(imageName);
}
}
private static Image GetScaledImage(string imageFileName, int maxWidth, int maxHeight)
{
Image original = Image.FromFile(imageFileName);
// no scaling if it fits in requested size
if (original.Width <= maxWidth && original.Height <= maxHeight)
return original;
double scale = Math.Max((double)original.Width / maxWidth, (double)original.Height / maxHeight);
Bitmap scaledBitmap = new Bitmap(original, (int)(original.Width * scale), (int)(original.Height * scale));
original.Dispose();
return scaledBitmap;
}
public override void OnApplicationStart(HmeApplicationStartArgs e)
{
_application = e.Application;
View root = new View();
root.Bounds = new Rectangle(0, 0, 640, 480);
_foreground = new ImageView(null, ImageLayout.BestFit);
_foreground.Bounds = root.Bounds;
_background = new ImageView(null, ImageLayout.BestFit);
_background.Bounds = root.Bounds;
// add the background first because it is behind the foreground
root.Children.Add(_background);
root.Children.Add(_foreground);
_application.Root = root;
_timer = new Timer(DisplayNextImage, null, 0, ShowTime);
}
public override void OnApplicationEnd()
{
_timer.Dispose();
}
public void DisplayNextImage(object state)
{
using (SuspendPainting suspend = new SuspendPainting(_application.Root))
{
if (_background.ImageResource != null)
{
// release old images
_background.ImageResource.Close();
}
_background.ImageResource = _foreground.ImageResource;
_background.Transparency = 0;
_foreground.Transparency = 1;
_foreground.ImageResource = _application.GetImageResource(imageNames[_currentImageIndex]);
_foreground.Animate(Animation.Fade(0, 0, FadeTime));
_background.Animate(Animation.Fade(1, 0, FadeTime));
}
_currentImageIndex = (_currentImageIndex + 1) % imageNames.Count;
}
}
}
|
using System;
using System.Linq;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace aoc2019.Test
{
public class Test17
{
private readonly ITestOutputHelper _testOutputHelper;
public Test17(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[Fact]
public void FindIntersections()
{
var input = @"
..#..........
..#..........
#######...###
#.#...#...#.#
#############
..#...#...#..
..#####...^..".Trim();
var solver = new Day17();
var intersections = solver.FindIntersections(input);
intersections.Count.ShouldBe(4);
intersections[0].X.ShouldBe(2);
intersections[0].Y.ShouldBe(2);
intersections[1].X.ShouldBe(2);
intersections[1].Y.ShouldBe(4);
}
[Fact]
public void Calibrate()
{
var input = @"
..#..........
..#..........
#######...###
#.#...#...#.#
#############
..#...#...#..
..#####...^..".Trim();
var solver = new Day17();
var result = solver.Calibrate(input);
result.ShouldBe(76);
}
[Fact]
public void Solve()
{
var code = InputDataHelper.Get(17);
var computer = new IntCodeComputer(code);
computer.Run();
var output = computer.Output();
var input = new string(output.Select(l => (char) l).ToArray());
_testOutputHelper.WriteLine(input);
var solver = new Day17();
var result = solver.Calibrate(input);
_testOutputHelper.WriteLine(result.ToString());
}
[Theory]
[InlineData("L,6,L,2", "76, 44, 54, 44, 76, 44, 50, 10")]
public void Translate(string input, string expected)
{
var actual = Day17.Translate(input);
var comp = string.Join(", ", actual);
comp.ShouldBe(expected);
}
[Fact]
public void Part2()
{
var code = InputDataHelper.Get(17);
const string a = "R,8,L,12,R,8";
const string b = "R,12,L,8,R,10";
const string c = "R,8,L,8,L,8,R,8,R,10";
const string p = "A,B,B,A,C,A,A,C,B,C";
var solver = new Day17();
var result = solver.Solve(code, a, b, c, p);
_testOutputHelper.WriteLine(result);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Ability : BasicObjectInfo {
public float manaCost;
public float castRange;
public LayerMask collisionMask;
public abstract void Cast(Vector3 pos, Transform caster);
protected bool TryHit(Collider other)
{
if (((1 << other.gameObject.layer) & collisionMask) == 0)
{
return true;
}
return false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test4._19andtest4._20
{
class Program
{
static void Main(string[] args)
{
///////////////////// 试题4.19 /////////////////////
///
try {
Console.Write("请输入一个数值:");
int num = int.Parse(Console.ReadLine());
bool state = false;
if (num > 3)
{
for (int i = 2; i < num / 2+1; i++)
{
if (num % i == 0)
{
state = true;
break;
}
}
}
Console.WriteLine("您输入的数值:{0},{1}素数", num, state?"不是":"是");
} catch {
Console.WriteLine("输入的数值有误!!");
}
///////////////////// 试题4.20 /////////////////////
Console.WriteLine("欢迎乘坐地铁1号线,本次列车即将从始发站出发:");
int n = 4;// 要去达的站点数
for (int i = 1; i <= 18; i++)
{
if (i == n)
{
Console.WriteLine("列车即将抵达本次旅行的第{0}站,请下车的旅客做好下车准备。", i);
break;
}
else
{
Console.WriteLine("列车即将抵达本次旅行的第{0}站", i);
}
}
Console.ReadKey();
}
}
}
|
namespace E06_Four_DigitNumber
{
using System;
using System.Linq;
public class Four_DigitNumber
{
public static void Main(string[] args)
{
// Write a program that takes as input a four-digit number in format
// abcd (e.g. 2011) and performs the following:
// Calculates the sum of the digits (in our example 2 + 0 + 1 + 1 = 4).
// Prints on the console the number in reversed order: dcba (in our example 1102).
// Puts the last digit in the first position: dabc (in our example 1201).
// Exchanges the second and the third digits: acbd (in our example 2101).
// The number has always exactly 4 digits and cannot start with 0.
//
// Examples:
//
// n sum of digits reversed last digit in front second and third digits exchanged
// 2011 4 1102 1201 2101
// 3333 12 3333 3333 3333
// 9876 30 6789 6987 9786
string number = GetNumber();
Console.WriteLine();
Console.WriteLine("Sum of digits : {0}", SumDigits(number));
Console.WriteLine("Reversed digits : {0}", ReverseDigits(number));
Console.WriteLine("Last digit in front : {0}", LastDigitFirst(number));
Console.WriteLine("Second and third digits exchanged : {0}", SwapSecondAndThird(number));
Console.WriteLine();
}
private static string GetNumber()
{
int number = 0;
bool isNumber = false;
do
{
Console.Clear();
Console.WriteLine("Please, enter a four-digit number in format \"abcd\" !");
Console.WriteLine("The number must be exactly 4 digits and cannot start with 0.");
Console.Write("Please, enter a number: ");
isNumber = int.TryParse(Console.ReadLine(), out number);
}
while (isNumber == false || number < 1000 || number > 9999);
return number.ToString();
}
private static int SumDigits(string number)
{
int sum = 0;
foreach (var digit in number)
{
sum += int.Parse(digit.ToString());
}
return sum;
}
private static string ReverseDigits(string number)
{
string reversedDigits = string.Join("", number.Reverse());
return reversedDigits;
}
private static string LastDigitFirst(string number)
{
string lastDigitFirst = "" + number[number.Length - 1];
for (int i = 0; i < number.Length - 1; i++)
{
lastDigitFirst += number[i];
}
return lastDigitFirst;
}
private static string SwapSecondAndThird(string number)
{
return number[0].ToString() + number[2] + number[1] + number[3];
}
}
}
|
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.WebKey;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace KeyVaultConsumer
{
class Program
{
static void Main(string[] args)
{
var clientId = ConfigurationManager.AppSettings["ClientId"];
var certificateThumbprint = ConfigurationManager.AppSettings["CertificateThumbprint"];
var certificateStoreName = ConfigurationManager.AppSettings["CertificateStoreName"];
var certificateStoreLocation = ConfigurationManager.AppSettings["CertificateStoreLocation"];
var vaultAddress = ConfigurationManager.AppSettings["VaultAddress"];
var certificate = FindCertificateByThumbprint(certificateThumbprint, certificateStoreName, certificateStoreLocation);
var assertionCert = new ClientAssertionCertificate(clientId, certificate);
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(
(authority, resource, scope) => GetAccessTokenAsync(authority, resource, scope, assertionCert)));
var key = Guid.NewGuid().ToString();
AddItem(vaultAddress, keyVaultClient, key).GetAwaiter().GetResult();
var tags = ReadItem(vaultAddress, keyVaultClient, key).GetAwaiter().GetResult();
foreach (var t in tags)
{
Console.WriteLine($"{t.Key}: {t.Value}");
}
}
private static async Task<IDictionary<String, String>> ReadItem(string vaultAddress, KeyVaultClient keyVaultClient, String key)
{
var retrievedKey = await keyVaultClient.GetKeyAsync(vaultAddress, key);
return(retrievedKey.Tags);
}
private static async Task AddItem(string vaultAddress, KeyVaultClient keyVaultClient, String key)
{
var tags = new Dictionary<String, String>();
tags.Add("Key1", "Value1");
tags.Add("Key2", "Value2");
var createdKey = await keyVaultClient.CreateKeyAsync(vaultAddress, key, JsonWebKeyType.Rsa, tags: tags);
}
/// <summary>
/// Helper function to load an X509 certificate
/// </summary>
/// <param name="certificateThumbprint">Thumbprint of the certificate to be loaded</param>
/// <param name="certificateStoreName">Store name of the certificate to be loaded</param>
/// <param name="certificateStoreLocation">Store location of the certificate to be loaded</param>
/// <returns>X509 Certificate</returns>
/// <remarks>All input arguments are required, missing of an input argument result in an ArgumentNullException</remarks>
public static X509Certificate2 FindCertificateByThumbprint(string certificateThumbprint, string certificateStoreName, string certificateStoreLocation)
{
if (String.IsNullOrEmpty(certificateThumbprint))
throw new System.ArgumentNullException(nameof(certificateThumbprint));
if (String.IsNullOrEmpty(certificateStoreName))
throw new System.ArgumentNullException(nameof(certificateStoreName));
if (String.IsNullOrEmpty(certificateStoreLocation))
throw new System.ArgumentNullException(nameof(certificateStoreLocation));
X509Certificate2 appOnlyCertificate = null;
Enum.TryParse(certificateStoreName, out StoreName storeName);
Enum.TryParse(certificateStoreLocation, out StoreLocation storeLocation);
X509Store certStore = new X509Store(storeName, storeLocation);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
certificateThumbprint,
false);
// Get the first cert with the thumbprint
if (certCollection.Count > 0)
{
appOnlyCertificate = certCollection[0];
}
certStore.Close();
if (appOnlyCertificate == null)
{
throw new System.Exception(
string.Format("Could not find the certificate with thumbprint {0} in certificate store {1} in location {2}.", certificateThumbprint, certificateStoreName, certificateStoreLocation));
}
return appOnlyCertificate;
}
private static async Task<string> GetAccessTokenAsync(string authority, string resource, string scope, ClientAssertionCertificate assertionCert)
{
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, assertionCert).ConfigureAwait(false);
return result.AccessToken;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ImmedisHCM.Services.Core
{
public interface ISeederBase
{
void Seed();
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace AtarashiiMono.Framework.XNA
{
public interface IAmDrawable // yes I am
{
void Draw(GameTime gameTime, AmSpriteBatch graphics, int x = 0, int y = 0);
}
} |
using HangoutsDbLibrary.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI.Services
{
public interface IServiceActivity
{
void AddActivity(Activity activity);
List<Activity> GetAllActivities();
Activity GetActivityById(int id);
void UpdateActivity(Activity activity);
void DeleteActivity(Activity activity);
}
}
|
namespace Kers.Models.Repositories
{
public static class VehicleType{
public static int Personal = 1;
public static int County = 2;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataCenter.Data
{
public class _FuturesData
{
public double Price { get; set; }
public _FuturesData()
{
Price = double.NaN;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Queue.Models.Interface;
using Queue.Models.Repository;
using Queue.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using System.Data.SqlClient;
namespace Queue.Controllers
{
public class ClientController : Controller
{
private ApplicationUserManager UserManager
{
get
{
return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
}
IClientRepository ClientRepo;
IViewRepo ViewRepo;
string UID;
public ClientController(IClientRepository client, IViewRepo view)
{
ClientRepo = client;
ViewRepo = view;
}
// GET: Client
public ActionResult Index()
{
UID = UserManager.FindByName(User.Identity.Name).Id;
ViewBag.IsInQueue = ClientRepo.IsInQueue(UID);
ViewBag.IsProcessing = ClientRepo.IsProcessing(UID);
return View();
}
[ChildActionOnly]
public ActionResult QueryPartial()
{
List<QueryView> list = ViewRepo.SelectAllQuery();
return View(list);
}
[ChildActionOnly]
public ActionResult QueueInfo()
{
UID = UserManager.FindByName(User.Identity.Name).Id;
QueueView queue = ViewRepo.SelectQueueInfo(UID);
return View(queue);
}
public ActionResult EnterQueue(string QID)
{
UID = UserManager.FindByName(User.Identity.Name).Id;
if(ClientRepo.EnterQueue(UID,QID))
{
return RedirectToAction("Index");
}
return View("Error");
}
public ActionResult LeaveQueue()
{
UID = UserManager.FindByName(User.Identity.Name).Id;
if (ClientRepo.LeaveQueue(UID))
{
return RedirectToAction("Index");
}
return View("Error");
}
}
} |
namespace OmniSharp.Extensions.LanguageServer.Protocol
{
public static class ClientNames
{
public const string RegisterCapability = "client/registerCapability";
public const string UnregisterCapability = "client/unregisterCapability";
}
}
|
namespace AjLisp
{
using System;
using System.Collections.Generic;
using System.Text;
public static class Operations
{
public static new bool Equals(object obj1, object obj2)
{
if (obj1 == null)
return obj2 == null;
return obj1.Equals(obj2);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Webcam : MonoBehaviour{
public WebCamTexture mCamera = null;
public GameObject pCameraStream;
public int cwCamera = 0;
private float maxZoom = 10.0f;
private float minX;
private float minY;
private float maxX;
private float maxY;
private Texture2D snap = null;
private static Webcam webcam = null;
private Webcam(){}
public void Start(){
Webcam.getInstance();
}
public static Webcam getInstance(){
if (webcam == null) {
GameObject singleton = new GameObject ();
webcam = singleton.AddComponent<Webcam> ();
}
return webcam;
}
/// <summary>
/// Starts the camera
/// </summary>
public void startCamera() {
if (mCamera == null) {
snap = new Texture2D(0,0);
// get available webcam devices
WebCamDevice[] devices = WebCamTexture.devices;
if (devices.Length > 0) {
mCamera = new WebCamTexture (devices [0].name, 1920, 1920);
string pCameraStreamName = "pCameraStream";
pCameraStream = GameObject.Find (pCameraStreamName);
RawImage img = pCameraStream.GetComponent<RawImage> ();
img.texture = mCamera;
mCamera.Play ();
// rotate panel to match mobile orientation
cwCamera = 90;//mCamera.videoRotationAngle;
pCameraStream.transform.localRotation = Quaternion.AngleAxis (-cwCamera * 1f, Vector3.back);
img.uvRect = new Rect (1f, 0f, -1f, 1f);
if(Application.platform == RuntimePlatform.Android){
img.uvRect = new Rect (1f, 1f, -1f, -1f);
}
// scale to fit screen
RectTransform rectT = (RectTransform)pCameraStream.transform;
float width = rectT.rect.width;
float height = rectT.rect.height;
rectT.localScale = new Vector3 (height / width, width / height, 1f);
// set up zoom limits
minX = rectT.localScale.x;
minY = rectT.localScale.y;
maxX = maxZoom * minX;
maxY = maxZoom * minY;
}
} else {
mCamera.Play();
}
}
/// <summary>
/// Pinches and zooms the panel.
/// </summary>
public void pinchAndZoom(){
if (mCamera != null) {
// check that the player is using only two fingers
if (Input.touchCount == 2) {
//Tutorial obj = new Tutorial ();
//obj.changePanel ("pCameraStreamTutorial:deactivate,pAnalyzeButtonTutorial:activate");
// Store both touches.
Touch touchZero = Input.GetTouch (0);
Touch touchOne = Input.GetTouch (1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// Find the difference in the distances between each frame.
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
RectTransform rectT = (RectTransform)pCameraStream.transform;
// get current x and y
float currentX = rectT.localScale.x;
float currentY = rectT.localScale.y;
// get ratio of sides
float width = rectT.rect.width;
float height = rectT.rect.height;
float ratioXY = height / width;
// used to make it easier to zoom as the picture gets bigger
float mult = 0.001f + ((currentX - minX) * 0.002f);
// calculate difference
float diffX = -deltaMagnitudeDiff * mult * ratioXY;
float diffY = -deltaMagnitudeDiff * mult * (1 / ratioXY);
// calculate new x and y
float newX = rectT.localScale.x + diffX;
float newY = rectT.localScale.y + diffY;
// keep panel within min and max limits
if( minX <= newX && newX <= maxX && minY <= newY && newY <= maxY){
rectT.localScale = new Vector3 (newX, newY, 1f);
}
}
}
}
/// <summary>
/// Stops the camera.
/// </summary>
public void stopCamera(){
if (mCamera == null) return;
mCamera.Stop ();
}
public void resetCameraZoom(){
if (mCamera == null) return;
// reset the pinch and zoom of the camera and stop streaming it
RectTransform rectT = (RectTransform)pCameraStream.transform;
rectT.localScale = new Vector3 (minX, minY, 1f);
}
/// <summary>
/// Takes a snap shot of the camera stream
/// </summary>
public void TakeSnapShot()
{
if (mCamera == null) return;
Debug.Log("Taking a snapshot");
// crop the picture to fit with the scale of the pinch and zoom
RectTransform rectT = (RectTransform)pCameraStream.transform;
float width = mCamera.width;
float height = mCamera.height;
float currentX = rectT.localScale.x;
float percentCrop = ((currentX - minX) / (maxX - minX)) * ((maxZoom - 1)/maxZoom);
float newWidth = width * (1f - percentCrop);
float newHeight = height * (1f - percentCrop);
float midX = width / 2f;
float midY = height / 2f;
float newX = midX - newWidth / 2f;
float newY = midY - newHeight / 2f;
Color[] array = mCamera.GetPixels (Mathf.RoundToInt(newX), Mathf.RoundToInt(newY), Mathf.RoundToInt(newWidth), Mathf.RoundToInt(newHeight));
snap.Resize(Mathf.RoundToInt(newWidth), Mathf.RoundToInt(newHeight));//mCamera.width, mCamera.height);
snap.SetPixels(array);
snap.Apply();
HttpRequestManager.getInstance ().makeRequest (snap.EncodeToJPG ());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class Step
{
public bool Prepared { get; private set; }
public bool Assigned { get; set; }
public StepModel Model { get; }
public Dish Dish { get; }
public int TimeSpentSoFar = 0;
public Step(StepModel model, Dish dish)
{
Model = model;
Dish = dish;
Prepared = false;
Assigned = false;
}
public void Complete()
{
Prepared = true;
Dish.MarkStepCompleted();
}
}
}
|
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
private int health;
// Use this for initialization
void Start () {
health = 100;
}
// Update is called once per frame
void Update () {
}
public void takeDamage()
{
health -= 5;
}
public void addHealth()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoreComponents.Text.Extensions
{
public static class StringBuilderExtensions
{
public static string ToStringClear(this StringBuilder TheSB)
{
try
{
return TheSB.ToString();
}
finally
{
TheSB.Clear();
}
}
}
}
|
using System.Linq;
using Microsoft.EntityFrameworkCore;
using ServiceDesk.Api.Systems.Common.Implemetations.Handler;
using ServiceDesk.Infrastructure;
namespace ServiceDesk.Api.Systems.DirectorySystem.Handlers.Software
{
public class SoftwareHandler : GenericHandler<Core.Entities.DirectorySystem.Software>, ISoftwareHandler
{
public override void Delete(int entityId, ServiceDeskDbContext context, out bool isSuccess)
{
var software = context.Softwares.Find(entityId);
if (software != null)
{
UnattachRequests(software, context);
context.Softwares.Remove(software);
context.SaveChanges();
isSuccess = true;
}
else
{
isSuccess = false;
}
}
private void UnattachRequests(Core.Entities.DirectorySystem.Software software, ServiceDeskDbContext context)
{
var requests = software.SoftwareModules
.SelectMany(x => x.Requests)
.ToList();
foreach (var request in requests)
{
request.SoftwareModuleId = null;
}
context.Requests.UpdateRange(requests);
context.SaveChanges();
}
}
}
|
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace Kogane.Internal
{
internal sealed class TransformRotationGUI
{
//================================================================================
// 変数(readonly)
//================================================================================
private readonly object m_instance;
private readonly MethodInfo m_onEnableMethod;
private readonly MethodInfo m_rotationFieldMethod;
//================================================================================
// 関数
//================================================================================
/// <summary>
/// コンストラクタ
/// </summary>
public TransformRotationGUI()
{
var type = Type.GetType( "UnityEditor.TransformRotationGUI,UnityEditor" );
m_onEnableMethod = type.GetMethod( "OnEnable" );
m_rotationFieldMethod = type.GetMethod( "RotationField", new Type[] { } );
m_instance = Activator.CreateInstance( type );
}
/// <summary>
/// 有効になった時に呼び出します
/// </summary>
public void OnEnable( SerializedProperty property )
{
var parameters = new object[] { property, new GUIContent( string.Empty ) };
m_onEnableMethod.Invoke( m_instance, parameters );
}
/// <summary>
/// Inspector の GUI を描画します
/// </summary>
public void RotationField()
{
m_rotationFieldMethod.Invoke( m_instance, null );
}
}
} |
namespace Frontend.Core.Model.Interfaces
{
public interface IMod
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
string Name { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this object representes a dummy item (that is, not a real mod)
/// </summary>
/// <value>
/// <c>true</c> if [is dummy item]; otherwise, <c>false</c>.
/// </value>
bool IsDummyItem { get; set; }
}
} |
using Grpc.Core;
using Grpc.Core.Interceptors;
using Interceptortest;
using System;
using System.Threading.Tasks;
namespace Grpc1x
{
class Program
{
class InterceptorTestServiceImpl : InterceptorTestService.InterceptorTestServiceBase
{
public override Task<Response> UnaryMethod(Request request, ServerCallContext context)
{
// Throw an exception or set context.Status to an error.
throw new Exception("Server threw an error");
// context.Status = new Status(StatusCode.FailedPrecondition, "A precondition failed.");
}
public override async Task ServerStreamingMethod(Request request, IServerStreamWriter<Response> responseStream, ServerCallContext context)
{
for (int i = 0; i < 3; i++)
{
await responseStream.WriteAsync(new Response());
}
// Throw an exception or set context.Status to an error.
// throw new Exception("Server threw an error");
context.Status = new Status(StatusCode.FailedPrecondition, "A precondition failed.");
}
}
static Exception ErrorHandler(RpcException e)
{
// Custom error handling here.
if (e.StatusCode == StatusCode.FailedPrecondition)
{
return new ArgumentException("Client-side error: A precondition failed.");
}
else
{
return new InvalidOperationException("Client-side error: Something went wrong with the RPC.");
}
}
static void Main(string[] args)
{
const int port = 49875;
// Start server
Server server = new Server
{
Services = { InterceptorTestService.BindService(new InterceptorTestServiceImpl()) },
Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
};
server.Start();
// Connect client to server
var channel = new Channel($"127.0.0.1:{port}", ChannelCredentials.Insecure);
// Configure gRPC interceptor
var interceptor = new ErrorInterceptor(ErrorHandler);
var callInvoker = channel.Intercept(interceptor);
// Create client instance
var client = new InterceptorTestService.InterceptorTestServiceClient(callInvoker);
// Demonstrate custom error with streaming call.
var st = client.ServerStreamingMethod(new Request());
try
{
while (st.ResponseStream.MoveNext(default).Result)
{
}
var trailers = st.GetTrailers();
Console.WriteLine($"{trailers[0].Key}:{trailers[0].Value}");
}
catch (Exception e)
{
Console.WriteLine(e);
}
// Demonstrate custom error with async unary call.
try
{
client.UnaryMethodAsync(new Request()).ResponseAsync.Wait();
}
catch (Exception e)
{
Console.WriteLine(e);
}
// Demonstrate custom error with sync/blocking unary call.
try
{
client.UnaryMethod(new Request());
}
catch (Exception e)
{
Console.WriteLine(e);
}
// Stop server after key-press.
Console.WriteLine("server running. Press a key to stop");
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
namespace DotNetNuke.Tests.Integration.Executers.Dto
{
public class RolePermission
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public IList<Permission> Permissions { get; set; }
public bool Locked { get; set; }
public bool IsDefault { get; set; }
}
}
|
using SharpML.Recurrent.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpML.Recurrent.Networks
{
public class DropoutLayer
{
private double _dropout;
private Random _rng;
private int _inputSize;
private int _outputSize;
protected bool[] Dropped_OI { get; set; }
protected bool[] Dropped_OO { get; set; }
protected bool[] Dropped_O1 { get; set; }
public DropoutLayer(double dropout, int inputSize, int outputSize, Random rng)
{
_dropout = dropout;
_rng = rng;
_inputSize = inputSize;
_outputSize = outputSize;
}
public void GenerateDropout(bool training)
{
// Generate dropped
bool[] dropped = new bool[_outputSize];
if (training)
for (int i = 0; i < dropped.Length; ++i)
dropped[i] = _rng.NextDouble() > _dropout;
// Generate dropped array
Matrix oi = new Matrix(_outputSize, _inputSize);
Matrix oo = new Matrix(_outputSize, _outputSize);
Matrix o1 = new Matrix(_outputSize, 1);
for (int i = 0; i < dropped.Length; ++i)
if (dropped[i])
{
for (int col = 0; col < oi.Cols; ++col)
oi.SetDropped(i, col, true);
for (int col = 0; col < oo.Cols; ++col)
oo.SetDropped(i, col, true);
for (int col = 0; col < o1.Cols; ++col)
o1.SetDropped(i, col, true);
}
// Save dropped arrays
Dropped_OI = oi.Dropped;
Dropped_OO = oo.Dropped;
Dropped_O1 = o1.Dropped;
}
public void ScaleWeightsByDropout(Matrix m)
{
for (int i = 0; i < m.W.Length; ++i)
m.W[i] *= _dropout;
}
}
}
|
#region Copyright Syncfusion Inc. 2001-2015.
// Copyright Syncfusion Inc. 2001-2015. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.SfDataGrid;
using UIKit;
using System.Globalization;
using CoreGraphics;
namespace SampleBrowser
{
public class DataVirtualization:SampleView
{
#region Fields
SfDataGrid SfGrid;
#endregion
static bool UserInterfaceIdiomIsPhone {
get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; }
}
public DataVirtualization()
{
this.SfGrid = new SfDataGrid ();
this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns;
this.SfGrid.ItemsSource = new DataVirtualizationViewModel ().ViewSource;
this.SfGrid.ShowRowHeader = false;
this.SfGrid.HeaderRowHeight = 45;
this.SfGrid.RowHeight = 45;
this.SfGrid.AlternatingRowColor = UIColor.FromRGB (219, 219, 219);
this.control = this;
this.AddSubview (SfGrid);
}
void GridAutoGenerateColumns (object sender, AutoGeneratingColumnArgs e)
{
if (e.Column.MappingName == "EmployeeID") {
e.Column.HeaderText = "Employee ID";
} else if (e.Column.MappingName == "Name") {
e.Column.TextAlignment = UITextAlignment.Left;
e.Column.TextMargin = 10;
} else if (e.Column.MappingName == "ContactID") {
e.Column.HeaderText = "Contact ID";
} else if (e.Column.MappingName == "Gender") {
e.Column.TextAlignment = UITextAlignment.Left;
e.Column.TextMargin = 30;
} else if (e.Column.MappingName == "Title") {
e.Column.TextAlignment = UITextAlignment.Left;
e.Column.TextMargin = 10;
} else if (e.Column.MappingName == "SickLeaveHours") {
e.Column.HeaderText = "Sick Leave Hours";
} else if (e.Column.MappingName == "Salary") {
e.Column.Format = "C";
e.Column.CultureInfo = new CultureInfo ("en-US");
} else if (e.Column.MappingName == "BirthDate") {
e.Column.HeaderText = "Birth Date";
e.Column.TextMargin = 15;
e.Column.TextAlignment = UITextAlignment.Left;
e.Column.Format = "d";
}
}
public override void LayoutSubviews ()
{
this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height);
base.LayoutSubviews ();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace suc.calc.distance
{
public class GaodeParams
{
public string origin { get; set; }
public string destination { get; set; }
}
}
|
using FindSelf.Domain.Repositories;
using FindSelf.Infrastructure.Database;
using FindSelf.Infrastructure.DomainEventBus;
using FindSelf.Infrastructure.Idempotent;
using FindSelf.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
namespace FindSelf.Infrastructure
{
public static class LayerDIExtension
{
public static IServiceCollection AddInfrastructureLayer(this IServiceCollection services, Action<InfrastructureConfiguration> configure)
{
var config = new InfrastructureConfiguration();
configure(config);
var efLoggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
services.AddDbContext<FindSelfDbContext>(options => options.UseMySql(config.DbConnectionString)
.UseLoggerFactory(efLoggerFactory)
.EnableSensitiveDataLogging()
.EnableDetailedErrors());
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IMessageBoxRepository, MessageBoxRepository>();
services.AddScoped<IRequestManager, RequestManager>();
AddDomainEventBus(services);
return services;
}
private static void AddDomainEventBus(IServiceCollection services)
{
services.AddTransient<IDomainEventsDispatcher, DomainEventsDispatcher>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Web.Http;
namespace waimai
{
public class postJson
{
public string postDataStr;
public string finalStr;
public string buildJson(string geohash,string consumer_key)
{
postDataStr ="{\"requests\":[{\"method\":GET,\"url\":/v1/app_banners?full_image_path=1&geohash="+geohash+"},{\"method\":GET,\"url\":url=/v1/app_activities?consumer_key="+consumer_key+"&full_image_path=1&geohash="+geohash+"},{\"method\":GET,\"url\":url=/v1/restaurants?extras%5B%5D=food_activity&extras%5B%5D=restaurant_activity&full_image_path=1&geohash="+geohash+"&is_premium=1&limit=3&type=geohash},{\"method\":GET,\"url\":url=/v1/restaurants/count?geohash="+geohash+"&is_premium=1&type=geohash},{\"method\":GET,\"url\":url=/v1/restaurants?extras%5B%5D=food_activity&extras%5B%5D=restaurant_activity&full_image_path=1&geohash="+geohash+"&is_premium=0&limit=30&type=geohash},{\"method\":GET,\"url\":url=/v1/restaurants/count?geohash="+geohash+ "&is_premium=0&type=geohash}],\"timeout\":15000}";
return postDataStr;
//StringBuilder sb = new StringBuilder();
//for (int i = 0; i < str.Length; i++)
//{
// char c = str.ToCharArray()[i];
// switch (c)
// {
// case '\"':
// sb.Append("\\\""); break;
// case '\\':
// sb.Append("\\\\"); break;
// case '/':
// sb.Append("\\/"); break;
// case '\b':
// sb.Append("\\b"); break;
// case '\f':
// sb.Append("\\f"); break;
// case '\n':
// sb.Append("\\n"); break;
// case '\r':
// sb.Append("\\r"); break;
// case '\t':
// sb.Append("\\t"); break;
// default:
// sb.Append(c); break;
// }
//}
//str = sb.ToString();
//return true;
}
HttpWebRequest request;
public async void HttpPost(string Url)//HttpClient a,HttpResponseMessage msg,
{
request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json;charset=utf-8";
// byte[] postBytes = Encoding.UTF8.GetBytes(postDataStr);
// request.ContinueTimeout = 15000;
// //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
Stream myRequestStream = await request.GetRequestStreamAsync();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
myStreamWriter.Write(postDataStr);
// myRequestStream.Write(postBytes, 0, postBytes.Length);
await myStreamWriter.FlushAsync();
Debug.WriteLine(postDataStr);
var response = await request.GetResponseAsync();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Dispose();
myResponseStream.Dispose();
finalStr = retString;
}
}
}
|
using LogicBuilder.Attributes;
using System.Collections.Generic;
namespace Contoso.Parameters.Expansions
{
public class SelectExpandDefinitionParameters
{
public SelectExpandDefinitionParameters()
{
}
public SelectExpandDefinitionParameters
(
[Comments("Update fieldTypeSource first. List of fields to select when a subset of fields is required.")]
[ParameterEditorControl(ParameterControlType.ParameterSourcedPropertyInput)]
[NameValue(AttributeNames.PROPERTYSOURCEPARAMETER, "fieldTypeSource")]
List<string> selects,
[Comments("List of navigation properties to expand.")]
List<SelectExpandItemParameters> expandedItems,
[ParameterEditorControl(ParameterControlType.ParameterSourceOnly)]
[Comments("Fully qualified class name for the model type.")]
string fieldTypeSource = "Enrollment.Domain.Entities"
)
{
Selects = selects;
ExpandedItems = expandedItems;
}
public List<string> Selects { get; set; } = new List<string>();
public List<SelectExpandItemParameters> ExpandedItems { get; set; } = new List<SelectExpandItemParameters>();
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using durable_functions_sample.Shared;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Octokit;
namespace durable_functions_sample
{
public class Request
{
public string RepoName { get; set; }
public string[] Texts { get; set; }
}
public class DataItem
{
public Document Document { get; set; }
public string GithubIssueHtmlUrl { get; set; }
}
public static class AnalyseTextOrchestration
{
[FunctionName(nameof(AnalyseTextOrchestration))]
public static async Task<IEnumerable<string>> Run([OrchestrationTrigger] DurableOrchestrationContext context)
{
var request = context.GetInput<Request>();
var items = new Dictionary<string, DataItem>();
#region create a github repo
await context.CallActivityAsync(
functionName: nameof(Activities.CreateGithubRepoActivity),
input: request.RepoName);
#endregion
#region create github issue for every text item
var tasks = request.Texts
.Select(text =>
context.CallActivityAsync<(int issueNumber, string issueHtmlUrl)>(
functionName: nameof(Activities.CreateIssueAsyncActivity),
input: (text, request.RepoName)))
.ToList();
await Task.WhenAll(tasks);
for (var i = 0; i < request.Texts.Length; i++)
{
var (issueNumber, issueUrl) = tasks[i].Result;
items.Add(issueNumber.ToString(), new DataItem
{
Document = new Document
{
Id = issueNumber.ToString(),
Text = request.Texts[i],
Language = null,
},
GithubIssueHtmlUrl = issueUrl
});
}
#endregion
#region detect languages with cognitive services
var languages = await context.CallActivityAsync<IList<DetectLanguageResponse.Document>>(
functionName: nameof(Activities.DetectLanguagesActivity),
input: items.Select(i => i.Value.Document));
#endregion
#region add github labguage labels
foreach (var languageInfo in languages)
{
// set document language
items[languageInfo.Id].Document.Language = languageInfo.InferredLanguage;
await context.CallActivityAsync<Issue>(
functionName: nameof(Activities.AddGithubLabelAsyncActivity),
input: (int.Parse(languageInfo.Id),
request.RepoName,
languageInfo.InferredLanguageName));
}
#endregion
#region analyse sentiment with cognitive services
var sentiments = await context.CallActivityAsync<IList<AnalyseSentimentResponse.Document>>(
functionName: nameof(Activities.AnalyseSentimentActivity),
input: items.Select(i => i.Value.Document));
#endregion
#region add github sentiment labels
foreach (var sentimentInfo in sentiments)
{
await context.CallActivityAsync<Issue>(
functionName: nameof(Activities.AddGithubLabelAsyncActivity),
input: (int.Parse(sentimentInfo.Id),
request.RepoName,
sentimentInfo.InferredSentiment));
}
#endregion
// return all github issue urls
return items.Values.Select(v => v.GithubIssueHtmlUrl);
}
[FunctionName(nameof(AnalyseTextHttpHandler))]
public static async Task<IActionResult> AnalyseTextHttpHandler(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req, [OrchestrationClient] DurableOrchestrationClient orchestrationClient)
{
var requestBody = await req.ReadAsStringAsync();
var request = JsonConvert.DeserializeObject<Request>(requestBody);
var instanceId = await orchestrationClient.StartNewAsync("AnalyseTextOrchestration", request);
return new OkObjectResult(orchestrationClient.CreateHttpManagementPayload(instanceId));
}
}
}
|
using System;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using System.Text.RegularExpressions;
using CoreEngine;
namespace CoreEditor
{
[ExtendedInspectorDrawer(typeof(RegexPatternAttribute))]
public sealed class RegexPatternDrawerAttribute: IDrawer
{
string regexString;
Regex regex;
public RegexPatternDrawerAttribute( RegexPatternAttribute attribute )
{
this.regexString = attribute.regexString;
try
{
regex = new Regex( regexString );
}
catch (Exception e)
{
regex = new Regex(".*");
Debug.LogError( e.Message );
}
}
public bool DisplayProperty( SerializedProperty property, FieldInfo field, GUIContent label )
{
if ( property.propertyType == SerializedPropertyType.String )
return ExtendedInspectorDrawerAttribute.DrawProperty(IsValid(property.stringValue),label, ()=> EditorGUILayout.PropertyField (property, label),GetError(property.stringValue) );
return EditorGUILayout.PropertyField( property, label );
}
public bool IsValid( object value )
{
return regex.IsMatch( (string)value );
}
public string GetError( object value )
{
return string.Format( @"""{0}"" does not match regex ""{1}"".", (string)value, regexString );
}
public string Tooltip
{
get {
return "Regex Pattern:\n" + regexString;
}
}
}
}
|
using AutoMapper;
using ImmedisHCM.Data.Entities;
using ImmedisHCM.Services.Models.Core;
using NHibernate;
namespace ImmedisHCM.Services.Mapping
{
public class DepartmentMapping : Profile
{
public DepartmentMapping()
{
CreateMap<Department, DepartmentServiceModel>()
.ForMember(dest => dest.Employees, opts => opts.PreCondition(src => NHibernateUtil.IsInitialized(src.Employees)))
.ReverseMap();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DisplayEnergyBar : MonoBehaviour
{
public GameObject player;
public float value;
private Slider energyBar;
// Start is called before the first frame update
void Start()
{
energyBar = gameObject.GetComponent<Slider>();
if(energyBar != null){
Debug.Log("set energyBar, success");
}else{
Debug.Log("set energyBar, failed");
}
}
// Update is called once per frame
void Update()
{
value = player.GetComponent<PlayerManager>().energy/ player.GetComponent<PlayerManager>().maxEnergy;
energyBar.value = value;
}
}
|
using AutoDataReader.Entities;
using AutoDataReader.Repositories.Contracts;
using AutoDataReader.Service.Contracts;
using System;
using System.Collections.Generic;
namespace AutoDataReader.Service
{
public class WordService : IWordService
{
private readonly IWordRepository _repository;
public WordService(IWordRepository repository)
{
_repository = repository;
}
public void Create(Word word)
{
word.CreatedDate = DateTime.Now;
_repository.Create(word);
}
public void Delete(Word word)
{
_repository.Delete(word);
}
public Word Get(int id)
{
var result = _repository.Get(id);
return result;
}
public ICollection<Word> GetAll()
{
var results = _repository.GetAll();
return results;
}
public void Update(Word word)
{
_repository.Update(word);
}
}
}
|
namespace Contoso.Parameters.Expressions
{
public class NegateOperatorParameters : IExpressionParameter
{
public NegateOperatorParameters()
{
}
public NegateOperatorParameters(IExpressionParameter operand)
{
Operand = operand;
}
public IExpressionParameter Operand { get; set; }
}
} |
using System;
namespace ClockAngles
{
public static class AngleUtility
{
public static string Difference(double angle1, double angle2)
{
var diff = Math.Abs(angle1 - angle2);
if (diff > 180) diff = 360 - diff;
return string.Format("{0:0.00}", diff);
}
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace InformAppPlus.Servico
{
public class Falha
{
[JsonProperty("errors")]
public List<string> Erros { get; set; }
[JsonProperty("reference ")]
public List<string> Referencias { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class WitchBehavior : MonoBehaviour
{
//Raycast class;
Collider2D hit;
Rigidbody2D RB2D;
public GameObject playerObject;
PlayerInputScript PIS;
public GameObject upperCollisionBoxGameObj;
public GameObject lowerCollisionBoxGameObj;
public int startHealth;
public int currentHealth;
public int throwDamage;
public float invincibilityCooldownPeriod;
public float invincibilityCooldownCurrent;
public int invincibilityCooldownFlash = 0;
public float enemyHorizontalSpeed;
public SpriteRenderer spriteR;
public Color spriteColor;
public Collider2D slashHitBox;
public Collider2D heavyPunchHitBox;
public int slashDamageValue;
public float slashPushbackOnHit;
public float slashPushbackOnBlock;
public float slashReelLength;
public float slashBlockStunLength;
public int heavyPunchDamageValue;
public float heavyPunchPushbackOnHit;
public float heavyPunchPushbackOnBlock;
public float heavyPunchReelLength;
public float heavyPunchBlockStunLength;
public bool canAttack;
public bool isBlocking;
Animator witchAnim;
public Animator hitSparkAnimator;
public Animator blockSparkAnimator;
public float currentReelLengthCooldown;
public bool infiniteHealth;
public footsies.range currentFootsiesRange;
public bool isNotInAnimation;
public bool isGrounded;
public bool wasGroundedLastFrame;
public int attackDecisionRNG;
public byte attackDecisionRNGMin;
public byte attackDecisionRNGMax;
public byte bobAndWeaveRNGDecisionMin;
public byte bobAndWeaveNearRNGDecisionMin;
public byte bobAndWeaveMidRNGDecisionMin;
public byte bobAndWeaveFarRNGDecisionMin;
public byte bobAndWeaveRNGDecisionMax;
public byte bobAndWeaveNearRNGDecisionMax;
public byte bobAndWeaveMidRNGDecisionMax;
public byte bobAndWeaveFarRNGDecisionMax;
public float bobAndWeaveDistanceRNG;
public float bobAndWeaveDistanceRNGMin;
public float bobAndWeaveDistanceNearRNGMin;
public float bobAndWeaveDistanceMidRNGMin;
public float bobAndWeaveDistanceFarRNGMin;
public float bobAndWeaveDistanceRNGMax;
public float bobAndWeaveDistanceNearRNGMax;
public float bobAndWeaveDistanceMidRNGMax;
public float bobAndWeaveDistanceFarRNGMax;
public float bobAndWeaveDeadZoneMin;
public float bobAndWeaveDeadZoneNearMin;
public float bobAndWeaveDeadZoneMidMin;
public float bobAndWeaveDeadZoneFarMin;
public float bobAndWeaveDeadZoneMax;
public float bobAndWeaveDeadZoneNearMax;
public float bobAndWeaveDeadZoneMidMax;
public float bobAndWeaveDeadZoneFarMax;
public byte slashRNGMin;
public byte slashNearRNGMin;
public byte slashMidRNGMin;
public byte slashFarRNGMin;
public byte slashRNGMax;
public byte slashNearRNGMax;
public byte slashMidRNGMax;
public byte slashFarRNGMax;
public byte attack2RNGMin;
public byte attack2NearRNGMin;
public byte attack2MidRNGMin;
public byte attack2FarRNGMin;
public byte attack2RNGMax;
public byte attack2NearRNGMax;
public byte attack2MidRNGMax;
public byte attack2FarRNGMax;
public byte blockRNGMin;
public byte blockNearRNGMin;
public byte blockMidRNGMin;
public byte blockFarRNGMin;
public byte blockRNGMax;
public byte blockNearRNGMax;
public byte blockMidRNGMax;
public byte blockFarRNGMax;
public float actualMoveDistance;
public AudioSource audioSrc;
public AudioClip slashSoundEffect;
public AudioClip thudSoundEffect;
public float flipCoolDown = 0;
public float flipCoolDownMax;
public Collider2D lowerHurtbox;
public witchAIBlockerScript WAIBS;
public bool isBeingGrabbed = false;
public bool isBeingThrown = false;
public bool attackHasAlreadyHit = false;
public CurrentlyVisableObjects CVO;
public bool isDead = false;
public bool isDying = false;
public bool isKnockedDown = false;
// Use this for initialization
void Start()
{
PIS = GameObject.Find("PlayerCharacter").GetComponent<PlayerInputScript>();
currentHealth = startHealth;
spriteR = GetComponent<SpriteRenderer>();
witchAnim = GetComponent<Animator>();
spriteColor = spriteR.color;
invincibilityCooldownCurrent = 0;
RB2D = GetComponent<Rigidbody2D>();
audioSrc = GetComponentInParent<AudioSource>();
if (WAIBS == null) {
WAIBS = GetComponentInChildren<witchAIBlockerScript>();
}
if (CVO == null) {
CVO = FindObjectOfType<CurrentlyVisableObjects>();
}
canAttack = true;
}
// Update is called once per frame
void Update()
{
if (lowerHurtbox == null) {
Debug.LogError("lowerHurtbox is null!");
return;
}
if (hitSparkAnimator == null) {
Debug.LogError("hitSparkAnimator is null!");
return;
}
if (blockSparkAnimator == null) {
Debug.LogError("blockSparkAnimator is null!");
return;
}
if (CVO == null)
{
Debug.LogError("CVO script not assigned!");
return;
}
if (WAIBS == null)
{
Debug.LogError("WAIBS script not assigned!");
return;
}
if (upperCollisionBoxGameObj == null) {
Debug.LogError("upperCollisionBoxGameObj is null!");
return;
}
if (lowerCollisionBoxGameObj == null) {
Debug.LogError("lowerCollisionBoxGameObj is null!");
return;
}
if (isDead || isDying) {
return;
}
isNotInAnimation = isNotInAnimCheck();
// Is Visible to camera?
if (spriteR.isVisible) {
CVO.addObject(gameObject);
} else {
CVO.removeObject(gameObject);
}
// Footsies Stuff
if ((currentFootsiesRange != footsies.range.None || bobAndWeaveDistanceRNG != 0) && isNotInAnimation && !WAIBS.isCollidingWithAIBlocker)
{
if (bobAndWeaveDistanceRNG == 0)
{
canAttack = true;
attackDecisionRNG = UnityEngine.Random.Range(attackDecisionRNGMin, attackDecisionRNGMax);
}
// See if col2D's x is within range of the enemy's
if (attackDecisionRNG >= slashRNGMin && attackDecisionRNG <= slashRNGMax && canAttack)
{
canAttack = false;
witchAnim.SetBool("isSlashing", true);
audioSrc.clip = slashSoundEffect;
audioSrc.enabled = true;
audioSrc.Play();
}
else if (attackDecisionRNG >= attack2RNGMin && attackDecisionRNG <= attack2RNGMax && canAttack)
{
canAttack = false;
witchAnim.SetBool("isHeavyPunching", true);
audioSrc.clip = slashSoundEffect;
audioSrc.enabled = true;
audioSrc.Play();
}
else if (attackDecisionRNG >= blockRNGMin && attackDecisionRNG <= blockRNGMax && canAttack)
{
canAttack = false;
isBlocking = true;
witchAnim.SetBool("isBlocking", true);
}
else if (attackDecisionRNG >= bobAndWeaveRNGDecisionMin && attackDecisionRNG <= bobAndWeaveRNGDecisionMax && isNotInAnimation)
{
if (bobAndWeaveDistanceRNG == 0)
{
bobAndWeaveDistanceRNG = UnityEngine.Random.Range(bobAndWeaveDistanceRNGMin, bobAndWeaveDistanceRNGMax);
if (bobAndWeaveDistanceRNG >= bobAndWeaveDeadZoneMin && bobAndWeaveDistanceRNG <= bobAndWeaveDeadZoneMax) {
float distanceToMin = Math.Abs(bobAndWeaveDistanceRNG - bobAndWeaveDeadZoneMin);
float distanceToMax = Math.Abs(bobAndWeaveDeadZoneMax - bobAndWeaveDistanceRNG);
if (distanceToMin < distanceToMax) {
bobAndWeaveDistanceRNG = UnityEngine.Random.Range(bobAndWeaveDistanceRNGMin, bobAndWeaveDeadZoneMin);
// Debug.Log($"in dead zone. Closer to min. bobAndWeaveDistanceRNG: {bobAndWeaveDistanceRNG} min: {bobAndWeaveDeadZoneMin} max: {bobAndWeaveDeadZoneMax} distanceToMin: {distanceToMin} distanceToMax: {distanceToMax}");
} else {
bobAndWeaveDistanceRNG = UnityEngine.Random.Range(bobAndWeaveDeadZoneMax, bobAndWeaveDistanceRNGMax);
// Debug.Log($"in dead zone. Closer to max. bobAndWeaveDistanceRNG: {bobAndWeaveDistanceRNG} min: {bobAndWeaveDeadZoneMin} max: {bobAndWeaveDeadZoneMax} distanceToMin: {distanceToMin} distanceToMax: {distanceToMax}");
}
}
}
actualMoveDistance = Mathf.Clamp(bobAndWeaveDistanceRNG, -1 * enemyHorizontalSpeed, enemyHorizontalSpeed);
transform.position += new Vector3(actualMoveDistance * transform.localScale.x,
0,
0
) * Time.deltaTime;
bobAndWeaveDistanceRNG -= actualMoveDistance;
}
}
else if (currentFootsiesRange == footsies.range.None && isNotInAnimation)
{
transform.position += new Vector3(enemyHorizontalSpeed * transform.localScale.x,
0,
0
) * Time.deltaTime;
}
else
{
if (canAttack)
{
witchAnim.SetBool("isSlashing", false);
witchAnim.SetBool("isHeavyPunching", false);
witchAnim.SetBool("isBlocking", false);
witchAnim.SetBool("isBlockingAnAttack", false);
isBlocking = false;
}
}
if (currentReelLengthCooldown > 0)
{
currentReelLengthCooldown -= Time.deltaTime;
if (currentReelLengthCooldown <= 0)
{
reelStateExit();
}
}
if (invincibilityCooldownCurrent > 0)
{
spriteColor.a = invincibilityCooldownFlash;
invincibilityCooldownFlash = (invincibilityCooldownFlash * -1) + 1;
spriteR.color = spriteColor;
invincibilityCooldownCurrent -= Time.deltaTime;
if (invincibilityCooldownCurrent <= 0)
{
canAttack = true;
spriteColor.a = (float)255;
spriteR.color = spriteColor;
}
}
if (flipCoolDown > 0) {
flipCoolDown -= Time.deltaTime;
}
if (!wasGroundedLastFrame && isGrounded && isBeingThrown) {
throwStateExit();
}
wasGroundedLastFrame = isGrounded;
}
void disableIsPunching()
{
witchAnim.SetBool("isSlashing", false);
witchAnim.SetBool("isHeavyPunching", false);
}
void resetAttackHasAlreadyHit() {
attackHasAlreadyHit = false;
}
void flip()
{
Vector2 flipLocalScale = gameObject.transform.localScale;
flipLocalScale.x *= -1;
transform.localScale = flipLocalScale;
flipCoolDown = flipCoolDownMax;
}
void pushBack(float pushBackValue)
{
RB2D.velocity = (new Vector2(RB2D.velocity.x + pushBackValue, RB2D.velocity.y));
}
void attack(Collider2D hitBox, int damageValue, float pushbackOnBlock, float pushbackOnHit, float reelLength, float blockStunLength) {
if (attackHasAlreadyHit) {
return;
}
//hitbox stuff
Collider2D[] cols = Physics2D.OverlapBoxAll(hitBox.bounds.center, hitBox.bounds.size, 0f, LayerMask.GetMask("PlayerHurtbox"));
if (cols.Length > 0)
{
foreach (Collider2D c in cols)
{
attackHasAlreadyHit = true;
object[] args = { damageValue, transform.localScale.x * (PIS.isBlocking ? pushbackOnBlock : pushbackOnHit), reelLength, blockStunLength };
c.SendMessageUpwards("playerTakeDamage", args);
}
}
}
public void footsiesValsForCurrentRange() {
switch (currentFootsiesRange)
{
case footsies.range.Near:
slashRNGMin = slashNearRNGMin;
slashRNGMax = slashNearRNGMax;
attack2RNGMin = attack2NearRNGMin;
attack2RNGMax = attack2NearRNGMax;
blockRNGMin = blockNearRNGMin;
blockRNGMax = blockNearRNGMax;
bobAndWeaveRNGDecisionMin = bobAndWeaveNearRNGDecisionMin;
bobAndWeaveRNGDecisionMax = bobAndWeaveNearRNGDecisionMax;
bobAndWeaveDistanceRNGMin = bobAndWeaveDistanceNearRNGMin;
bobAndWeaveDistanceRNGMax = bobAndWeaveDistanceNearRNGMax;
bobAndWeaveDeadZoneMin = bobAndWeaveDeadZoneNearMin;
bobAndWeaveDeadZoneMax = bobAndWeaveDeadZoneNearMax;
break;
case footsies.range.Mid:
slashRNGMin = slashMidRNGMin;
slashRNGMax = slashMidRNGMax;
attack2RNGMin = attack2MidRNGMin;
attack2RNGMax = attack2MidRNGMax;
blockRNGMin = blockMidRNGMin;
blockRNGMax = blockMidRNGMax;
bobAndWeaveRNGDecisionMin = bobAndWeaveMidRNGDecisionMin;
bobAndWeaveRNGDecisionMax = bobAndWeaveMidRNGDecisionMax;
bobAndWeaveDistanceRNGMin = bobAndWeaveDistanceMidRNGMin;
bobAndWeaveDistanceRNGMax = bobAndWeaveDistanceMidRNGMax;
bobAndWeaveDeadZoneMin = bobAndWeaveDeadZoneMidMin;
bobAndWeaveDeadZoneMax = bobAndWeaveDeadZoneMidMax;
break;
case footsies.range.Far:
slashRNGMin = slashFarRNGMin;
slashRNGMax = slashFarRNGMax;
attack2RNGMin = attack2FarRNGMin;
attack2RNGMax = attack2FarRNGMax;
blockRNGMin = blockFarRNGMin;
blockRNGMax = blockFarRNGMax;
bobAndWeaveRNGDecisionMin = bobAndWeaveFarRNGDecisionMin;
bobAndWeaveRNGDecisionMax = bobAndWeaveFarRNGDecisionMax;
bobAndWeaveDistanceRNGMin = bobAndWeaveDistanceFarRNGMin;
bobAndWeaveDistanceRNGMax = bobAndWeaveDistanceFarRNGMax;
bobAndWeaveDeadZoneMin = bobAndWeaveDeadZoneFarMin;
bobAndWeaveDeadZoneMax = bobAndWeaveDeadZoneFarMax;
break;
default:
break;
}
}
//method for punching
public void slash()
{
attack(slashHitBox, slashDamageValue, slashPushbackOnBlock, slashPushbackOnHit, slashReelLength, slashBlockStunLength);
}
public void heavyPunch()
{
if (heavyPunchHitBox == null) {
Debug.LogError("heavyPunchHitBox is null!");
return;
}
attack(heavyPunchHitBox, heavyPunchDamageValue, heavyPunchPushbackOnBlock, heavyPunchPushbackOnHit, heavyPunchReelLength, heavyPunchBlockStunLength);
}
public void blockEnter() {
canAttack = false;
}
public void blockExit() {
isBlocking = false;
witchAnim.SetBool("isBlocking", false);
canAttack = true;
}
public void blockStunEnter() {
canAttack = false;
foreach (AnimatorControllerParameter parameter in witchAnim.parameters)
{
witchAnim.SetBool(parameter.name, false);
}
witchAnim.SetBool("isBlockingAnAttack", true);
}
public void enemyTakeDamage(object[] args)
{
attackHasAlreadyHit = false;
int damage = (int)args[0];
float pushBackDistance = (float)args[1];
float reelLength = (float)args[2];
float blockStunLength = (float)args[3];
AudioClip hitSoundEffect = (AudioClip)args[4];
AudioClip blockSoundEffect = (AudioClip)args[5];
if (currentHealth > 0 && invincibilityCooldownCurrent <= 0 && !isKnockedDown)
{
PIS.attackHasAlreadyHit = true;
if (isBlocking) {
currentReelLengthCooldown = blockStunLength;
blockSparkAnimator.SetBool("isActive", true);
witchAnim.SetBool("isBlockingAnAttack", true);
pushBack(blockStunLength);
audioSrc.clip = blockSoundEffect;
audioSrc.enabled = true;
audioSrc.Play();
} else {
if (!infiniteHealth)
currentHealth -= damage;
hitSparkAnimator.SetBool("isActive", true);
pushBack(pushBackDistance);
audioSrc.clip = hitSoundEffect;
// audioSrc.enabled = true;
audioSrc.Play();
reelStateEnter(reelLength);
if (currentHealth <= 0)
enemyDeath();
}
}
}
public void enemyTakeGrabAttackDamage(object[] args)
{
attackHasAlreadyHit = false;
int damage = (int)args[0];
AudioClip hitSoundEffect = (AudioClip)args[1];
if (currentHealth > 0 && invincibilityCooldownCurrent <= 0 && !isKnockedDown)
{
PIS.attackHasAlreadyHit = true;
if (!infiniteHealth)
currentHealth -= damage;
hitSparkAnimator.SetBool("isActive", true);
audioSrc.clip = hitSoundEffect;
// audioSrc.enabled = true;
audioSrc.Play();
if (currentHealth <= 0) {
PIS.grabAttackStateExit();
enemyDeath();
}
}
}
public void enemyGetGrabbed()
{
if (currentHealth > 0 && invincibilityCooldownCurrent <= 0 && !isKnockedDown)
{
grabStateEnter();
}
}
public void enemyGetThrown(object[] args)
{
if (args.Length < 2) {
Debug.LogError($"{this.name}: args.Length is less than 2!");
return;
}
throwDamage = (int)args[0];
Vector2 throwForce = (Vector2)args[1];
if (currentHealth > 0 && invincibilityCooldownCurrent <= 0 && !isKnockedDown)
{
throwStateEnter(throwForce);
}
}
public void enemyGetSweeped(object[] args)
{
attackHasAlreadyHit = false;
int damage = (int)args[0];
float pushBackDistance = (float)args[1];
float reelLength = (float)args[2];
float blockStunLength = (float)args[3];
AudioClip hitSoundEffect = (AudioClip)args[4];
AudioClip blockSoundEffect = (AudioClip)args[5];
if (currentHealth > 0 && invincibilityCooldownCurrent <= 0 && !isKnockedDown)
{
PIS.attackHasAlreadyHit = true;
if (isBlocking) {
currentReelLengthCooldown = blockStunLength;
blockSparkAnimator.SetBool("isActive", true);
witchAnim.SetBool("isBlockingAnAttack", true);
pushBack(blockStunLength);
audioSrc.clip = blockSoundEffect;
audioSrc.enabled = true;
audioSrc.Play();
} else {
if (!infiniteHealth)
currentHealth -= damage;
hitSparkAnimator.SetBool("isActive", true);
audioSrc.clip = hitSoundEffect;
audioSrc.Play();
knockDownEnter();
// reelStateEnter(reelLength);
if (currentHealth <= 0)
enemyDeath();
}
}
}
public void knockDownEnter() {
setAllBoolAnimParametersToFalse();
witchAnim.SetBool("isKnockedDown", true);
}
public void knockDownInvincibilityEnter() {
isKnockedDown = true;
upperCollisionBoxGameObj.layer = LayerMask.NameToLayer("OnlyInteractsWithWallsGround");
lowerCollisionBoxGameObj.layer = LayerMask.NameToLayer("OnlyInteractsWithWallsGround");
}
public void knockDownExit() {
isKnockedDown = false;
canAttack = true;
witchAnim.SetBool("isKnockedDown", false);
upperCollisionBoxGameObj.layer = LayerMask.NameToLayer("EnemyLayer");
lowerCollisionBoxGameObj.layer = LayerMask.NameToLayer("EnemyLayer");
}
//for the state that occurs right after receiving damage where acolyte is combo-able
public void reelStateEnter(float reelLength)
{
currentReelLengthCooldown = reelLength;
if (invincibilityCooldownCurrent <= 0)
{
foreach (AnimatorControllerParameter parameter in witchAnim.parameters)
{
string paramType = parameter.type.ToString();
string boolType = AnimatorControllerParameterType.Bool.ToString();
if (paramType == boolType) {
witchAnim.SetBool(parameter.name, false);
}
}
witchAnim.SetBool("isReeling", true);
witchAnim.Play("reel", 0, 0.0f);
}
}
public void reelStateExit()
{
witchAnim.SetBool("isReeling", false);
witchAnim.SetBool("isBlocking", false);
witchAnim.SetBool("isBlockingAnAttack", false);
isBlocking = false;
invincibilityCooldownCurrent = invincibilityCooldownPeriod;
if (invincibilityCooldownCurrent == 0) {
canAttack = true;
}
}
public void grabStateEnter()
{
setAllBoolAnimParametersToFalse();
isBlocking = false;
isBeingGrabbed = true;
canAttack = false;
witchAnim.SetBool("isBeingGrabbed", true);
}
public void throwStateEnter(Vector2 throwForce)
{
setAllBoolAnimParametersToFalse();
witchAnim.SetBool("isBeingThrown", true);
isBeingGrabbed = false;
isBeingThrown = true;
canAttack = false;
applyThrowForce(throwForce);
}
public void throwStateExit()
{
isBeingThrown = false;
applyThrowDamage();
if (!isDead && !isDying) {
knockDownEnter();
}
}
void applyThrowForce(Vector2 throwForce) {
upperCollisionBoxGameObj.layer = LayerMask.NameToLayer("InteractsWithEverythingButPlayer");
lowerCollisionBoxGameObj.layer = LayerMask.NameToLayer("InteractsWithEverythingButPlayer");
RB2D.AddForce(new Vector2(throwForce.x * transform.localScale.x, throwForce.y), ForceMode2D.Impulse);
}
void applyThrowDamage() {
if (thudSoundEffect == null) {
Debug.LogError($"{this.name}: thudSoundEffect is null!");
return;
}
if (currentHealth > 0 && invincibilityCooldownCurrent <= 0 && !isKnockedDown)
{
if (!infiniteHealth)
currentHealth -= throwDamage;
hitSparkAnimator.SetBool("isActive", true);
audioSrc.clip = thudSoundEffect;
// audioSrc.enabled = true;
audioSrc.Play();
if (currentHealth <= 0) {
enemyDeath();
}
}
}
public void grabStateExit()
{
isBeingGrabbed = false;
witchAnim.SetBool("isBeingGrabbed", false);
invincibilityCooldownCurrent = invincibilityCooldownPeriod;
}
public void enemyDeath()
{
CVO.removeObject(gameObject);
isDying = true;
witchAnim.SetBool("isDying", true);
// gameObject.SetActive(false);
}
public void setDeathVars() {
isDead = true;
witchAnim.SetBool("isDead", true);
upperCollisionBoxGameObj.layer = LayerMask.NameToLayer("OnlyInteractsWithWallsGround");
lowerCollisionBoxGameObj.layer = LayerMask.NameToLayer("OnlyInteractsWithWallsGround");
}
public void setCanAttackFalse()
{
canAttack = false;
}
public void resetCanAttack()
{
canAttack = true;
}
void OnCollisionStay2D(Collision2D col2D)
{
if (lowerHurtbox == null) {
Debug.LogError("lowerHurtbox is null!");
return;
}
if (isDead || isDying) {
return;
}
/*if (hit.GetComponent<Collider>().tag == "Player") {
playerObject.GetComponent<PlayerHealth> ().playerTakeDamage (1);
}*/
isNotInAnimation = isNotInAnimCheck();
float collisionTop = col2D.transform.position.y + col2D.collider.bounds.extents.y;
float characterBottom = transform.position.y - lowerHurtbox.bounds.extents.y;
bool isWall = col2D.gameObject.layer == LayerMask.NameToLayer("Wall");
bool isEnemy = col2D.gameObject.layer == LayerMask.NameToLayer("EnemyLayer");
bool isPlayer = col2D.gameObject.tag == "PlayerCharacter";
bool isNotOnIgnoreRaycastLayer = col2D.gameObject.layer != 2;
bool isFacingTowardsWall = (col2D.gameObject.transform.localPosition.x - transform.localPosition.x) * transform.localScale.x > 0;
bool facingOppositeDirections = col2D.transform.localScale.x * transform.localScale.x < 0;
if (isNotInAnimation && isNotOnIgnoreRaycastLayer && flipCoolDown <= 0 && currentFootsiesRange == footsies.range.None)
{
if (isWall && isFacingTowardsWall) {
flip();
} else if (isEnemy && facingOppositeDirections) {
flip();
}
}
}
void setAllBoolAnimParametersToFalse() {
foreach (AnimatorControllerParameter parameter in witchAnim.parameters)
{
string paramType = parameter.type.ToString();
string boolType = AnimatorControllerParameterType.Bool.ToString();
if (paramType == boolType) {
witchAnim.SetBool(parameter.name, false);
}
}
}
bool isNotInAnimCheck() {
return witchAnim.GetBool("isReeling") == false && witchAnim.GetBool("isSlashing") == false && witchAnim.GetBool("isHeavyPunching") == false && witchAnim.GetBool("isBlocking") == false && witchAnim.GetBool("isBlockingAnAttack") == false && witchAnim.GetBool("isKnockedDown") == false && witchAnim.GetBool("isBeingThrown") == false && !isBeingGrabbed;
}
}
|
namespace _08.ExtractSentences
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Write a program that extracts from a given text all sentences containing given word.
class ExtractSentences
{
static void Main()
{
string text = @"We are living in a yellow submarine. We don't have anything else.
Inside the submarine is very tight. So we are drinking all the day.
We will move out of it in 5 days.";
string word = "in";
Console.WriteLine(Extracter(text, word));
}
static string Extracter(string text, string word)
{
var splitedText = text.Split('.');
var extrackredSentenses = new StringBuilder();
for(int i = 0; i < splitedText.Length; i++)
{
char[] splitSign = {',',' '};
var wordsInSentense = splitedText[i].Split(splitSign);
foreach (var item in wordsInSentense)
{
if (item == word)
{
extrackredSentenses.Insert(extrackredSentenses.Length, splitedText[i]);
break;
}
}
}
return string.Join(" ", extrackredSentenses);
}
}
}
|
using System;
using DataStructures.SinglyLinkedList;
namespace DataStructures.Queue
{
public class myStack<T>
{
private T Top
{
get
{
return ll.Head.Data;
}
}
private mySinglyLinkedList<T> ll { get; set; }
public bool IsEmpty
{
get
{
return ll.IsEmpty;
}
}
public int Count
{
get
{
return ll.Count;
}
}
public void Push(T data)
{
ll.Add(data);
}
public T Pop()
{
T popped = Top;
ll.Delete(Top);
return popped;
}
public T Peek()
{
return Top;
}
public myStack()
{
ll = new mySinglyLinkedList<T>();
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Web.Models
{
public class Video
{
public Video()
{
Videos1 = new HashSet<Video>();
}
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required]
[DisplayName("Name")]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(50)]
[DisplayName("Video File")]
public string VideoFileName { get; set; }
[MaxLength(50)]
[DisplayName("Picture File")]
public string PicFileName { get; set; }
public string Description { get; set; }
public int? ParentId { get; set; }
public virtual ICollection<Video> Videos1 { get; set; }
public virtual Video Video1 { get; set; }
}
}
|
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Redmanmale.TelegramToRss.Crawler;
namespace Redmanmale.TelegramToRss
{
public static class Program
{
private static readonly EventWaitHandle ExitEvent = new AutoResetEvent(false);
private static readonly CancellationTokenSource CancellationToken = new CancellationTokenSource();
public static void Main(string[] args)
{
RunAsConsole(args);
}
private static void RunAsConsole(string[] args)
{
Console.WriteLine("Starting...");
Console.CancelKeyPress += OnCancelKeyPress;
var enableCrawler = args.Contains("-c");
var enableFeed = args.Contains("-f");
if (args.Contains("-h") || (!enableCrawler && !enableFeed))
{
Console.WriteLine("{0}TelegramToRss. Usage:{0}" +
" -c\tEnable crawler: retrieve new posts and save them to DB.{0}" +
" -f\tEnable web-API: serve RSS feed and CRUD for channels.{0}" +
" -h\tShow this help.",
Environment.NewLine);
return;
}
CrawlerManager crawlerManager = null;
if (enableCrawler)
{
var config = ConfigurationManager.GetConfiguration();
crawlerManager = new CrawlerManager(ConfigurationManager.CreateStorage(config),
ConfigurationManager.CreateCrawlingConfig(config));
Task.Run(() => crawlerManager
.RunAsync(CancellationToken.Token)
.ContinueWith(task => Console.WriteLine(task.Exception), CancellationToken.Token),
CancellationToken.Token);
}
IWebHost webHost = null;
if (enableFeed)
{
webHost = BuildWebHost();
Console.WriteLine("Started.");
webHost.Run();
}
else
{
Console.WriteLine("Started.");
ExitEvent.WaitOne();
}
Console.WriteLine("Stopping...");
if (enableCrawler)
{
crawlerManager.Stop();
}
if (enableFeed)
{
webHost.StopAsync(CancellationToken.Token).GetAwaiter().GetResult();
}
}
private static void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
ExitEvent.Set();
CancellationToken.Cancel();
}
private static IWebHost BuildWebHost() =>
WebHost.CreateDefaultBuilder()
.UseStartup<Startup>()
.Build();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Xml.Serialization;
using SCT_BL.SCT;
using SCT_SI.SCT;
using utilities;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Service));
[WebMethod]
public string HelloWorld()
{
logger.Info("Method : Hello World Start");
string result = "Hello World";
logger.Info("Method : Hello World Stop");
return result;
}
/// <summary>
/// This Method Authenticates the User
/// </summary>
/// <param name="UserId and UserPwd"></param>
/// <returns>
/// <paramref name="result"/> In case of Success
/// <paramref name="error"/> In case of Error
/// </returns>
/// <history>
/// Hari haran 22/08/2012 created
/// </history>
///
[WebMethod]
public SCT_AuthUser authenticateUser(string UserId, string UserPwd)
{
logger.Info("Method : authenticateUser Start");
logger.DebugFormat("Input parameter Id : {0} ", UserId);
logger.DebugFormat("Input parameter Password : {0} ", UserPwd);
try
{
SCT_AuthUser result = new SCT_AuthUser();
SCTInterface authUsr_SI = new SCTInterface();
result = authUsr_SI.authenticateUser_SI(UserId, UserPwd);
logger.Info("Method : authenticateUser Stop");
return result;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_AuthUser Error = new SCT_AuthUser();
Error.StatusFlag = 1;
Error.Message = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.Message);
logger.Error("Method : searchEmployee Stop");
return Error;
}
}
/// <summary>
/// This Method Search results based on search criteria
/// </summary>
/// <param name="Name,MgrId and Flag"></param>
/// <returns>
/// <paramref name="result"/> In case of Success
/// <paramref name="error"/> In case of Error
/// </returns>
/// <history>
/// Hari haran 27/07/2012 created
/// </history>
///
[WebMethod]
public SCT_Emp searchEmployee(string Name, string MgrId, string Flag)
{
logger.Info("Method : searchEmployee Start");
logger.DebugFormat("Input parameter Name : {0} ", Name);
logger.DebugFormat("Input parameter ManagerId : {0} ", MgrId);
try
{
SCT_Emp result = new SCT_Emp();
SCTInterface search_SI = new SCTInterface();
result = search_SI.searchEmployee_SI(Name, MgrId, Flag);
logger.Info("Method : searchEmployee Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_Emp Error = new SCT_Emp();
Error.SCT_headerDetails.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_headerDetails.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_headerDetails.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_headerDetails.StatusMsg);
logger.Error("Method : searchEmployee Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_Emp Error = new SCT_Emp();
Error.SCT_headerDetails.StatusFlag = 1;
Error.SCT_headerDetails.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_headerDetails.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_headerDetails.StatusMsg);
logger.Error("Method : searchEmployee Stop");
return Error;
}
}
[WebMethod]
public SCT_RChange getReasonForChange()
{
logger.Info("Method : getReasonForChange Start");
try
{
SCT_RChange result = new SCT_RChange();
SCTInterface PA_SI = new SCTInterface();
result = PA_SI.getReasonForChange_SI();
logger.Info("Method : getReasonForChange Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_RChange Error = new SCT_RChange();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getReasonForChange Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_RChange Error = new SCT_RChange();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getReasonForChange Stop");
return Error;
}
}
[WebMethod]
public SCT_PA getPersonnelArea()
{
logger.Info("Method : getPersonnelArea Start");
try
{
SCT_PA result = new SCT_PA();
SCTInterface PA_SI = new SCTInterface();
result = PA_SI.getPersonnelArea_SI();
logger.Info("Method : getPersonnelArea Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_PA Error = new SCT_PA();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getPersonnelArea Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_PA Error = new SCT_PA();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : searchEmployee Stop");
return Error;
}
}
[WebMethod]
public SCT_PSA getPersonnelSubArea()
{
logger.Info("Method : getPersonnelSubArea Start");
try
{
SCT_PSA result = new SCT_PSA();
SCTInterface PSA_SI = new SCTInterface();
result = PSA_SI.getPersonnelSubArea_SI();
logger.Info("Method : getPersonnelSubArea Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_PSA Error = new SCT_PSA();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getPersonnelSubArea Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_PSA Error = new SCT_PSA();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getPersonnelSubArea Stop");
return Error;
}
}
[WebMethod]
public SCT_ORGUnit getOrganizationalUnit()
{
logger.Info("Method : getOrganizationalUnit Start");
try
{
SCT_ORGUnit result = new SCT_ORGUnit();
SCTInterface ORG_SI = new SCTInterface();
result = ORG_SI.getOrganizationalUnit_SI();
logger.Info("Method : getOrganizationalUnit Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_ORGUnit Error = new SCT_ORGUnit();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getOrganizationalUnit Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_ORGUnit Error = new SCT_ORGUnit();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : searchEmployee Stop");
return Error;
}
}
[WebMethod]
public SCT_CC getCostCenter()
{
logger.Info("Method : getCostCenter Start");
try
{
SCT_CC result = new SCT_CC();
SCTInterface CC_SI = new SCTInterface();
result = CC_SI.getCostCenter_SI();
logger.Info("Method : getCostCenter Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_CC Error = new SCT_CC();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getCostCenter Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_CC Error = new SCT_CC();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getCostCenter Stop");
return Error;
}
}
[WebMethod]
public SCT_BU getBusinessUnit()
{
logger.Info("Method : getBusinessUnit Start");
try
{
SCT_BU result = new SCT_BU();
SCTInterface BU_SI = new SCTInterface();
result = BU_SI.getBusinessUnit_SI();
logger.Info("Method : getBusinessUnit Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_BU Error = new SCT_BU();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getPersonnelArea Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_BU Error = new SCT_BU();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : searchEmployee Stop");
return Error;
}
}
[WebMethod]
public SCT_SBU getStrategicBusinessUnit()
{
logger.Info("Method : getStrategicBusinessUnit Start");
try
{
SCT_SBU result = new SCT_SBU();
SCTInterface SBU_SI = new SCTInterface();
result = SBU_SI.getStrategicBusinessUnit_SI();
logger.Info("Method : getStrategicBusinessUnit Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_SBU Error = new SCT_SBU();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getStrategicBusinessUnit Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_SBU Error = new SCT_SBU();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getStrategicBusinessUnit Stop");
return Error;
}
}
[WebMethod]
public SCT_Horizontal getHorizontal()
{
logger.Info("Method : getHorizontal Start");
try
{
SCT_Horizontal result = new SCT_Horizontal();
SCTInterface get_SI = new SCTInterface();
result = get_SI.getHorizontal_SI();
logger.Info("Method : getHorizontal Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_Horizontal Error = new SCT_Horizontal();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getHorizontal Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_Horizontal Error = new SCT_Horizontal();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getHorizontal Stop");
return Error;
}
}
[WebMethod]
public SCT_BLoc getBaseLocation()
{
logger.Info("Method : getBaseLocation Start");
try
{
SCT_BLoc result = new SCT_BLoc();
SCTInterface BLoc_SI = new SCTInterface();
result = BLoc_SI.getBaseLocation_SI();
logger.Info("Method : getBaseLocation Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_BLoc Error = new SCT_BLoc();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getBaseLocation Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_BLoc Error = new SCT_BLoc();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getBaseLocation Stop");
return Error;
}
}
[WebMethod]
public SCT_CDeploy getCenterOfDeployment()
{
logger.Info("Method : getCenterOfDeployment Start");
try
{
SCT_CDeploy result = new SCT_CDeploy();
SCTInterface CDevp_SI = new SCTInterface();
result = CDevp_SI.getCenterOfDeployment_SI();
logger.Info("Method : getCenterOfDeployment Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_CDeploy Error = new SCT_CDeploy();
Error.SCT_header.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.SCT_header.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getCenterOfDeployment Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_CDeploy Error = new SCT_CDeploy();
Error.SCT_header.StatusFlag = 1;
Error.SCT_header.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.SCT_header.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.SCT_header.StatusMsg);
logger.Error("Method : getCenterOfDeployment Stop");
return Error;
}
}
/// <summary>
/// This Method fetches employee Details
/// </summary>
/// <param name="EmpId and MgrId"></param>
/// <returns>
/// <paramref name="result"/> In case of Success
/// <paramref name="error"/> In case of Error
/// </returns>
/// <history>
/// Hari haran 27/07/2012 created
/// </history>
///
[WebMethod]
public SCT_Entity getSCEmployeeDetails(string EmpId, string MgrId)
{
logger.Info("Method : getSCEmployeeDetails Start");
logger.DebugFormat("Input parameter EmployeeId : {0} ", EmpId);
logger.DebugFormat("Input parameter ManagerId : {0} ", MgrId);
try
{
SCT_Entity result = new SCT_Entity();
SCTInterface search_SI = new SCTInterface();
result = search_SI.getSCEmployeeDetails_SI(EmpId, MgrId);
logger.Info("Method : getSCEmployeeDetails Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat,System.DateTime.Now.ToString("F"),PReqNo,ex.TargetSite.ToString(),ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_Entity Error = new SCT_Entity();
Error.StatusFlag = ex.Number;
string expCode = ExpType(ex);
Error.StatusMsg = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : Status Flag = " + Error.StatusFlag.ToString());
logger.Debug("Return object Error : Status Message = " + Error.StatusMsg);
logger.Error("Method : getSCEmployeeDetails Stop");
return Error;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), PReqNo, ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
SCT_Entity Error = new SCT_Entity();
Error.StatusFlag = 1;
Error.StatusMsg = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + Error.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + Error.StatusMsg);
logger.Error("Method : getSCEmployeeDetails Stop");
return Error;
}
}
/// <summary>
/// This Method Updates the SCT Details
/// </summary>
/// <param name="SCT_Entry"></param>
/// <returns>
/// <paramref name="result"/> In case of Success
/// <paramref name="error"/> In case of Error
/// </returns>
/// <history>
/// Hari haran 27/07/2012 created
/// </history>
///
[WebMethod]
public SCT_UpdateOutputEntity updateSCEmployeeDetails([XmlElement("SCT_Input")] SCT_UpdateInputEntity SCT_Entry)
{
logger.Info("Method : updateSCEmployeeDetails Start");
logger.Debug("EmployeeID value : " + SCT_Entry.EmpNo.ToString());
SCT_UpdateOutputEntity result = new SCT_UpdateOutputEntity();
try
{
SCTInterface updateSCT_IS = new SCTInterface();
result = updateSCT_IS.updateSCEmployeeDetails_SI(SCT_Entry);
logger.Info("Method : updateSCEmployeeDetails Stop");
return result;
}
catch (SqlException ex)
{
webServiceExHandling.ExceptionLog(ex);
// string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), IS_Entry[0].PReqNo, ex.TargetSite.ToString(), ex.ToString());
// webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
result.StatusFlag = 1;
string expCode = ExpType(ex);
result.Message = SCT_Constants.cnfgErrMessages[expCode];
logger.Debug("Return object Error : ErrorCode = " + result.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + result.Message);
logger.Error("Method : updateSCEmployeeDetails Stop");
return result;
}
catch (Exception ex)
{
webServiceExHandling.ExceptionLog(ex);
//string mailBody = string.Format(SCT_Constants.mail_BodyFormat, System.DateTime.Now.ToString("F"), getPreqNo(IS_Entry), ex.TargetSite.ToString(), ex.ToString());
//webServiceExHandling.Send_Email(SCT_Constants.Email_Dic, mailBody);
result.StatusFlag = 1;
result.Message = SCT_Constants.Error;
logger.Debug("Return object Error : ErrorCode = " + result.StatusFlag.ToString());
logger.Debug("Return object Error : ErrorMessage = " + result.Message);
logger.Error("Method : updateSCEmployeeDetails Stop");
return result;
}
}
/// <summary>
/// This Method determines if exception due to conn failure/DB operation
/// </summary>
/// <param name="Ex"> Exception </param>
/// <returns>Error Code</returns>
///
private string ExpType(SqlException Ex)
{
foreach (int ErrNo in SCT_Constants.dbErrorCodes)
{
if (Ex.Number.Equals(ErrNo))
{
return "101";
}
}
return "102";
}
} |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace PathfindingVisualisation
{
public struct Point : IEquatable<Point>
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public static Point Zero { get; } = new Point(0, 0);
public int X { get; set; }
public int Y { get; set; }
public static bool operator ==(Point left, Point right)
{
if (ReferenceEquals(left, right))
{
return true;
}
if (ReferenceEquals(left, null))
{
return false;
}
if (ReferenceEquals(right, null))
{
return false;
}
return left.EqualsCore(right);
}
public static bool operator !=(Point left, Point right)
{
return !(left == right);
}
public static Point operator +(Point left, Point right)
{
return new Point(left.X + right.X, left.Y + right.Y);
}
public static Point operator -(Point left, Point right)
{
return new Point(left.X - right.X, left.Y - right.Y);
}
public static Point operator +(Point point)
{
return new Point(point.X, point.Y);
}
public static Point operator -(Point point)
{
return new Point(-point.X, -point.Y);
}
public static IEnumerable<Point> Parse(IEnumerable<string> targetStrings)
{
foreach (var targetString in targetStrings)
{
if (TryParse(targetString, out var point))
{
yield return point;
}
}
}
public static bool TryParse(string targetString, out Point point)
{
if (!string.IsNullOrWhiteSpace(targetString))
{
var match = Regex.Match(targetString, @"^\s*(?<X>[0-9]+)\s*[;,]\s*(?<Y>[0-9]+)\s*$");
if (match.Success)
{
var x = int.Parse(match.Groups["X"].Value);
var y = int.Parse(match.Groups["Y"].Value);
point = new Point(x, y);
return true;
}
}
point = Zero;
return false;
}
public bool Equals(Point other)
{
if (ReferenceEquals(other, this))
{
return true;
}
if (ReferenceEquals(other, null))
{
return false;
}
return EqualsCore(other);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, this))
{
return true;
}
if (ReferenceEquals(obj, null))
{
return false;
}
return obj is Point other && EqualsCore(other);
}
public override int GetHashCode()
{
return this.GetHashCodeFromFields(X, Y);
}
public override string ToString()
{
return $"[{X};{Y}]";
}
private bool EqualsCore(Point other)
{
return X.Equals(other.X)
&& Y.Equals(other.Y);
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace EatCleanAPI.Models
{
public partial class VegafoodBotContext : DbContext
{
public VegafoodBotContext()
{
}
public VegafoodBotContext(DbContextOptions<VegafoodBotContext> options)
: base(options)
{
}
public virtual DbSet<CustomerSentiment> CustomerSentiments { get; set; }
public virtual DbSet<Menu> Menus { get; set; }
public virtual DbSet<MenusDetail> MenusDetails { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<OrderDetail> OrderDetails { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<RefreshToken> RefreshTokens { get; set; }
public virtual DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Name=Vegafood");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerSentiment>(entity =>
{
entity.ToTable("CustomerSentiment");
entity.Property(e => e.CustomerName).HasMaxLength(30);
entity.Property(e => e.Email).HasMaxLength(50);
entity.Property(e => e.FoodComment).HasMaxLength(30);
entity.Property(e => e.FoodPredict)
.HasMaxLength(10)
.IsFixedLength();
entity.Property(e => e.NameByUser).HasMaxLength(30);
entity.Property(e => e.Phone).HasMaxLength(10);
entity.Property(e => e.ServiceComment).HasMaxLength(30);
entity.Property(e => e.ServicePredict)
.HasMaxLength(10)
.IsFixedLength();
entity.Property(e => e.VegaComment).HasMaxLength(30);
entity.Property(e => e.VegaPredict)
.HasMaxLength(10)
.IsFixedLength();
});
modelBuilder.Entity<Menu>(entity =>
{
entity.Property(e => e.MenuId).HasColumnName("menuId");
entity.Property(e => e.Description)
.HasColumnName("description")
.HasColumnType("ntext");
entity.Property(e => e.Image)
.HasColumnName("image")
.HasColumnType("ntext");
entity.Property(e => e.Name)
.HasColumnName("name")
.HasColumnType("ntext");
});
modelBuilder.Entity<MenusDetail>(entity =>
{
entity.HasKey(e => new { e.MenuId, e.ProductId })
.HasName("menusdetail_pk");
entity.ToTable("MenusDetail");
entity.Property(e => e.MenuId).HasColumnName("menuId");
entity.Property(e => e.ProductId).HasColumnName("productId");
entity.Property(e => e.Quantity).HasColumnName("quantity");
entity.HasOne(d => d.Menu)
.WithMany(p => p.MenusDetails)
.HasForeignKey(d => d.MenuId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_MenusDetail_Menus");
entity.HasOne(d => d.Product)
.WithMany(p => p.MenusDetails)
.HasForeignKey(d => d.ProductId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_MenusDetail_Products");
});
modelBuilder.Entity<Order>(entity =>
{
entity.Property(e => e.OrderId).HasColumnName("orderId");
entity.Property(e => e.Address)
.HasColumnName("address")
.HasColumnType("ntext");
entity.Property(e => e.DeliveredAt)
.HasColumnName("deliveredAt")
.HasColumnType("ntext");
entity.Property(e => e.EmailAddress)
.HasColumnName("email_address")
.HasColumnType("ntext");
entity.Property(e => e.IsDelivered).HasColumnName("isDelivered");
entity.Property(e => e.IsPaid).HasColumnName("isPaid");
entity.Property(e => e.OrderStatus).HasColumnName("orderStatus");
entity.Property(e => e.PaidAt)
.HasColumnName("paidAt")
.HasColumnType("ntext");
entity.Property(e => e.PaymentId)
.HasColumnName("paymentId")
.HasColumnType("ntext");
entity.Property(e => e.PaypalMethod)
.HasColumnName("paypalMethod")
.HasMaxLength(30);
entity.Property(e => e.ShippingPrice).HasColumnName("shippingPrice");
entity.Property(e => e.TotalPrice).HasColumnName("totalPrice");
entity.Property(e => e.UpdateTime)
.HasColumnName("update_time")
.HasColumnType("text");
entity.Property(e => e.UserId).HasColumnName("userId");
entity.HasOne(d => d.User)
.WithMany(p => p.Orders)
.HasForeignKey(d => d.UserId)
.HasConstraintName("FK_Orders_Users");
});
modelBuilder.Entity<OrderDetail>(entity =>
{
entity.HasKey(e => new { e.OrderId, e.MenuId })
.HasName("orderdetail_pk");
entity.Property(e => e.OrderId).HasColumnName("orderId");
entity.Property(e => e.MenuId).HasColumnName("menuId");
entity.HasOne(d => d.Menu)
.WithMany(p => p.OrderDetails)
.HasForeignKey(d => d.MenuId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_OrderDetails_Menus");
entity.HasOne(d => d.Order)
.WithMany(p => p.OrderDetails)
.HasForeignKey(d => d.OrderId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_OrderDetails_Orders");
});
modelBuilder.Entity<Product>(entity =>
{
entity.Property(e => e.ProductId).HasColumnName("productId");
entity.Property(e => e.Calories).HasColumnName("calories");
entity.Property(e => e.Carb).HasColumnName("carb");
entity.Property(e => e.Description)
.HasColumnName("description")
.HasColumnType("ntext");
entity.Property(e => e.Fat).HasColumnName("fat");
entity.Property(e => e.Image)
.HasColumnName("image")
.HasColumnType("ntext");
entity.Property(e => e.Name)
.HasColumnName("name")
.HasMaxLength(40);
entity.Property(e => e.Price)
.HasColumnName("price")
.HasColumnType("money");
entity.Property(e => e.Protein).HasColumnName("protein");
});
modelBuilder.Entity<RefreshToken>(entity =>
{
entity.HasKey(e => e.TokenId)
.HasName("PK__RefreshT__CB3C9E17FBB0B267");
entity.ToTable("RefreshToken");
entity.Property(e => e.TokenId).HasColumnName("token_id");
entity.Property(e => e.CustomerId).HasColumnName("customer_id");
entity.Property(e => e.ExpiryDate)
.HasColumnName("expiry_date")
.HasColumnType("datetime");
entity.Property(e => e.Token)
.HasColumnName("token")
.HasMaxLength(200)
.IsUnicode(false);
entity.HasOne(d => d.Customer)
.WithMany(p => p.RefreshTokens)
.HasForeignKey(d => d.CustomerId)
.HasConstraintName("FK_RefreshToken_Users");
});
modelBuilder.Entity<User>(entity =>
{
entity.Property(e => e.UserId).HasColumnName("userId");
entity.Property(e => e.Email)
.HasColumnName("email")
.HasMaxLength(50);
entity.Property(e => e.IsAdmin).HasColumnName("isAdmin");
entity.Property(e => e.Name)
.HasColumnName("name")
.HasMaxLength(50);
entity.Property(e => e.Password)
.HasColumnName("password")
.HasMaxLength(15);
entity.Property(e => e.PhoneNumber)
.HasColumnName("phoneNumber")
.HasMaxLength(10);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Torneio.API.Models
{
public class JogoBindingModel
{
public int Id { get; set; }
public int NumPartida { get; set; }
public DateTime DataDaPartida { get; set; }
public string Chave { get; set; }
public int TimeId1 { get; set; }
public int TimeId2 { get; set; }
public string NameTimeId1 { get; set; }
public string NameTimeId2 { get; set; }
public int GolsTimeId1 { get; set; }
public int GolsTimeId2 { get; set; }
public int TimeVencedor { get; set; }
public string NameTimeVencedor { get; set; }
public bool Terminou { get; set; }
}
} |
using MonoGame.Extended.Tiled.Serialization;
namespace MonoGame.Extended.Content.Pipeline.Tiled
{
public class TiledMapContentItem : ContentItem<TiledMapContent>
{
public TiledMapContentItem(TiledMapContent data)
: base(data)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TP_Groupe.Models;
namespace TP_Groupe.ViewModels
{
public class ArticleListViewModel
{
public IEnumerable<Article> Articles {get;set;}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Zengo.WP8.FAS.Resources;
namespace Zengo.WP8.FAS
{
public partial class HelpPage : PhoneApplicationPage
{
private ApplicationBarIconButton faqButton;
public HelpPage()
{
InitializeComponent();
PageHeaderControl.PageName = AppResources.HelpPage;
PageHeaderControl.PageTitle = AppResources.ProductTitle;
BuildApplicationBar();
}
#region Helpers
private void BuildApplicationBar()
{
ApplicationBar = new ApplicationBar();
faqButton = new ApplicationBarIconButton(new Uri("/Images/AppBar/faq.png", UriKind.RelativeOrAbsolute)) { Text = "FAQ" };
faqButton.Click += faqButton_Click;
ApplicationBar.Buttons.Add(faqButton);
}
#endregion
#region Event Handlers
void faqButton_Click(object sender, EventArgs e)
{
this.NavigationService.Navigate(new Uri("/Views/FAQPage.xaml", UriKind.RelativeOrAbsolute));
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootOnly : MonoBehaviour {
public float seconds;
public float fireRate;
public GameObject shot;
public Transform shotSpawn;
public AudioSource shootSound;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
seconds += Time.deltaTime;
if(seconds > fireRate) {
seconds = 0;
Instantiate(shot, shotSpawn.position, shot.transform.rotation);
shootSound.Play();
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Threading;
using Microsoft.Azure.WebJobs.Host.Loggers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using WebJobs.Host.Storage.Logging;
namespace Microsoft.Extensions.Hosting
{
public static class StorageServiceCollectionExtensions
{
[Obsolete("Dashboard is being deprecated. Use AppInsights.")]
public static IServiceCollection AddDashboardLogging(this IServiceCollection services)
{
services.TryAddSingleton<LoggerProviderFactory>();
services.TryAddSingleton<IFunctionOutputLoggerProvider>(p => p.GetRequiredService<LoggerProviderFactory>().GetLoggerProvider<IFunctionOutputLoggerProvider>());
services.TryAddSingleton<IFunctionOutputLogger>(p => p.GetRequiredService<IFunctionOutputLoggerProvider>().GetAsync(CancellationToken.None).GetAwaiter().GetResult());
services.TryAddSingleton<IFunctionInstanceLoggerProvider>(p => p.GetRequiredService<LoggerProviderFactory>().GetLoggerProvider<IFunctionInstanceLoggerProvider>());
services.TryAddSingleton<IFunctionInstanceLogger>(p => p.GetRequiredService<IFunctionInstanceLoggerProvider>().GetAsync(CancellationToken.None).GetAwaiter().GetResult());
services.TryAddSingleton<IHostInstanceLoggerProvider>(p => p.GetRequiredService<LoggerProviderFactory>().GetLoggerProvider<IHostInstanceLoggerProvider>());
services.TryAddSingleton<IHostInstanceLogger>(p => p.GetRequiredService<IHostInstanceLoggerProvider>().GetAsync(CancellationToken.None).GetAwaiter().GetResult());
return services;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DiagnosticsSchema.cs" company="Naos Project">
// Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Telemetry.StorageModel
{
using static System.FormattableString;
#pragma warning disable SA1203 // Constants should appear before fields
#pragma warning disable SA1600 // Elements should be documented
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class DiagnosticsSchema
{
public const string TableName = "Diagnostics";
public const string Id = "Id";
public const string SampledUtc = "SampledUtc";
public const string RowCreatedUtc = "RowCreatedUtc";
}
public static class MachineDetailsSchema
{
public const string TableName = "MachineDetails";
public const string Id = "Id";
public const string DiagnosticsId = "DiagnosticsId";
public static readonly string ForeignKeyNameDiagnosticsId = Invariant($"FK__{TableName}_{DiagnosticsId}__{DiagnosticsSchema.TableName}_{DiagnosticsSchema.Id}");
public const string MachineName = "MachineName";
public const string MachineNameMapJson = "MachineNameMapJson";
public const string ProcessorCount = "ProcessorCount";
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Gb", Justification = "Spelling/name is correct.")]
public const string PhysicalMemoryInGb = "PhysicalMemoryInGb";
public const string MemoryMapJson = "MemoryMapJson";
public const string OperatingSystemIs64Bit = "OperatingSystemIs64Bit";
public const string OperatingSystemJson = "OperatingSystemJson";
public const string ClrVersion = "ClrVersion";
public const string RowCreatedUtc = "RowCreatedUtc";
}
public static class ProcessDetailsSchema
{
public const string TableName = "ProcessDetails";
public const string Id = "Id";
public const string DiagnosticsId = "DiagnosticsId";
public static readonly string ForeignKeyNameDiagnosticsId = Invariant($"FK__{TableName}_{DiagnosticsId}__{DiagnosticsSchema.TableName}_{DiagnosticsSchema.Id}");
public const string Name = "Name";
public const string FilePath = "FilePath";
public const string FileVersion = "FileVersion";
public const string ProductVersion = "ProductVersion";
public const string RunningAsAdmin = "RunningAsAdmin";
public const string RowCreatedUtc = "RowCreatedUtc";
}
public static class AssemblyDetailsSchema
{
public const string TableName = "AssemblyDetails";
public const string Id = "Id";
public const string DiagnosticsId = "DiagnosticsId";
public static readonly string ForeignKeyNameDiagnosticsId = Invariant($"FK__{TableName}_{DiagnosticsId}__{DiagnosticsSchema.TableName}_{DiagnosticsSchema.Id}");
public const string Name = "Name";
public const string VersionJson = "VersionJson";
public const string FilePath = "FilePath";
public const string FrameworkVersion = "FrameworkVersion";
public const string RowCreatedUtc = "RowCreatedUtc";
}
#pragma warning restore SA1203 // Constants should appear before fields
#pragma warning restore SA1600 // Elements should be documented
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
|
using System.Collections.Generic;
namespace CheckMySymptoms.Forms.View.Common
{
abstract public class DetailItemView
{
abstract public DetailItemEnum DetailType { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Realtime;
namespace Lobby
{
public class RoomInfoItem : MonoBehaviour
{
public Text roomName;
public Text roomPlayerCnt;
//private Action<string> JoinRoomHandler;
private Action<RoomInfo> JoinRoomHandler;
private RoomInfo roomInfo;
public RoomInfo RoomInfo
{
get
{
return roomInfo;
}
set
{
roomInfo = value;
roomName.text = roomInfo.Name;
roomPlayerCnt.text = string.Format("{0} / {1}", roomInfo.PlayerCount, roomInfo.MaxPlayers);
}
}
public bool SetRoomInfo(RoomInfo roomInfo,Action<RoomInfo> action)
{
if (roomInfo.PlayerCount < 1)
{
return false;
//Destroy(gameObject);
}
RoomInfo = roomInfo;
JoinRoomHandler = action;
return true;
}
public void OnClicked()
{
JoinRoomHandler?.Invoke(roomInfo);
/*if (RoomInfo.PlayerCount < RoomInfo.MaxPlayers)
{
}*/
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utilities;
using System.IO;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using WebServicesFile;
namespace FinalProject
{
public partial class DeletedFile : System.Web.UI.Page
{
DBConnect objDB = new DBConnect();
SqlCommand objCommand = new SqlCommand();
FPSVC.AddFiles pxy = new FPSVC.AddFiles();
CVS.Delete proxy = new CVS.Delete();
// Delete df = new Delete();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Server.Transfer("LoginPage.aspx");
}
else
{
Label1.Text = Session["username"].ToString(); ;
}
bindGrid();
}
public void bindGrid()
{
DataSet ds = proxy.displayByUser(Label1.Text);
if (ds.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
GridView1.Visible = false;
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("Label3");
int id = Convert.ToInt32(lbl.Text);
proxy.saveDeletedFile(id);
proxy.deleteFile(id);
GridView1.EditIndex = -1;
bindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["username"] = Label1.Text;
Server.Transfer("DashBoard.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Session.Abandon();
Server.Transfer("LoginPage.aspx");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.ModelConfiguration;
using FacultyV3.Core.Models.Entities;
namespace FacultyV3.Core.Data.Mapping
{
public class ConfirguationMapping : EntityTypeConfiguration<Confirguration>
{
public ConfirguationMapping()
{
HasKey(x => x.Id);
Property(x => x.Id).IsRequired();
Property(x => x.Meta_Name).IsRequired();
Property(x => x.Meta_Value).IsOptional();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace YiXiangLibrary
{
public partial class d_bingli_caozuo : System.Web.UI.MasterPage
{
public string d_id = "";
public string str0 = "";
public string str1 = "";
public string str2 = "";
public string str3 = "";
public string str4 = "";
public string str5 = "";
protected void Page_Load(object sender, EventArgs e)
{
d_id = Request["did"];
str0 = "~/search_bingli.aspx?did=" + d_id;
str1 = "~/d_bingli_select.aspx?did=" + d_id;
str2 = "~/d_bingli_insert.aspx?did=" + d_id;
str3 = "~/d_bibgli_del.aspx?did=" + d_id;
str4 = "~/d_bingli_update.aspx?did=" + d_id;
str5 = "~/question_d.aspx?did=" + d_id;
//跳转网页的语句
NavigationMenu.Items[0].NavigateUrl = str0;
NavigationMenu.Items[1].NavigateUrl = str1;
NavigationMenu.Items[2].NavigateUrl = str2;
NavigationMenu.Items[3].NavigateUrl = str3;
NavigationMenu.Items[4].NavigateUrl = str4;
NavigationMenu.Items[5].NavigateUrl = str5;
}
}
} |
using App.Data;
using App.Entity;
using System.Collections.Generic;
using System;
namespace App.Logic
{
public class PathLC : IBasicMethods<PathBE>
{
private PathDAC DataAccessCLass = new PathDAC();
public void CreateTable()
{
DataAccessCLass.CreateTable();
}
public void Delete(string filterText)
{
DataAccessCLass.Delete(filterText);
}
public void Insert(List<PathBE> tBeClass)
{
DataAccessCLass.Insert(tBeClass);
}
public void Insert(PathBE tBeClass)
{
DataAccessCLass.Insert(tBeClass);
}
public List<PathBE> SelectAll()
{
return DataAccessCLass.SelectAll();
}
public PathBE Select(string filter)
{
return DataAccessCLass.Select(filter);
}
public List<PathBE> SelectList(string filterText)
{
return DataAccessCLass.SelectList(filterText);
}
public void Update(string setText, string filter)
{
DataAccessCLass.Update(setText, filter);
}
public void Update(PathBE tBeClass, string filter)
{
DataAccessCLass.Update(tBeClass, filter);
}
public List<PathBE> SelectList(string filterText, object[] parameters = null)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Theater
{
class PasswordChangeReciever
{
public string NewPassword { get; set; }
public string CurrentPassword { get; set; }
public string ConfimationPassword { get; set; }
public My_Account Account { get; set; }
public PasswordChangeReciever(string newp, string curp, string confirmp, My_Account acc)
{
NewPassword = newp;
CurrentPassword = curp;
ConfimationPassword = confirmp;
Account = acc;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AspNetCore.Api.TenantResolver
{
public static class Constants
{
public static string TenantKey = "tenant";
}
}
|
using Controllers.ViewModels.Account;
using Grifling.Blog.DomainModels;
using Grifling.Helpers.Helpers;
using Grifling.Service.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Controllers.Controllers
{
public class AccountController : Controller
{
private IAccountUserService _userService;
private ITransactionService _transactionService;
public AccountController(IAccountUserService userService, ITransactionService transactionService)
{
_userService = userService;
_transactionService = transactionService;
}
// GET: Account
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Create(AccountCreateViewModel model)
{
bool checkUser = _userService.EmailExist(model.Email);
if(checkUser)
{
ModelState.AddModelError("Email", "Email finns redan.");
return View("index", model);
}
AccountUser user = model.ToDomainModel(model);
_transactionService.Save(user);
_transactionService.Commit();
CookieHelper.AddUserCookie(user);
return View("index");
}
[HttpPost]
public ActionResult Login(AccountLoginViewModel model)
{
var user = _userService.User(model.Email);
if(user != null)
{
byte[] hashBytes = user.Password.PasswordText;
AccountHelper hash = new AccountHelper(hashBytes);
if(!hash.Verify(model.Password))
{
ModelState.AddModelError("", "Användarnamn eller lösenord stämmer inte.");
return View("index", model);
}
CookieHelper.AddUserCookie(user);
}
return Content("Inloggad");
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace LostAndFound.Presenters
{
public class MenuViewModel : IMenuViewModel
{
public string Username { get; set; }
public Command openFoundCommand { get; }
public Command openLostCommand { get; }
public Command userProfileCommand { get; }
public string Name { get; set; }
private MenuPage instance;
public MenuViewModel()
{
instance = MenuPage.instance;
openFoundCommand = new Command(() => OpenFound());
openLostCommand = new Command(() => OpenLost());
//userProfileCommand
}
private void OpenLost()
{
FormController.OpenLostItems(instance);
}
private void OpenFound()
{
FormController.OpenFoundPage(instance);
}
}
}
|
using System;
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;
using Newtonsoft.Json;
namespace IntentAppOne
{
public class BasketMetadata
{
public DateTime Date { get; set; }
public decimal Amount { get; set; }
public string StoreName { get; set; }
}
[Activity(Label = "Activity ONE", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += (sender, e) =>
{
var intent = new Intent("com.kimserey.action.FIND_BASKET");
intent.PutExtra("com.kimserey.extra.BASKET_METADATA_NAME", "ASDA FROM A");
intent.PutExtra("com.kimserey.extra.BASKET_METADATA_DATE", DateTime.UtcNow.ToString("dd MMMM yyyy").ToUpper());
intent.PutExtra("com.kimserey.extra.BASKET_METADATA_AMOUNT", (222.22).ToString("C2"));
intent.SetFlags(ActivityFlags.NewTask);
StartActivity(intent);
};
}
}
}
|
namespace E02_BankAccounts
{
using E02_BankAccounts.AbstractClasses;
using E02_BankAccounts.Interfaces;
public class Deposit : Account, IDepositable, IWithdrawable
{
public Deposit(Customer owner, decimal balance,
decimal monthlyInterestRate, ushort numberOfMonths)
: base(owner, balance, monthlyInterestRate, numberOfMonths)
{
}
public void Withdraw(decimal amount)
{
this.Balance -= amount;
}
public override decimal CalculateInterestAmount()
{
if (this.Balance >= 0 && this.Balance < 1000)
{
return 0;
}
return base.CalculateInterestAmount();
}
}
}
|
using Eventual.EventStore.Core;
using Eventual.EventStore.Readers.Tracking;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Eventual.EventStore.Readers.Reactive
{
public class EventStreamReactiveReader : IEventStreamReactiveReader
{
#region Attributes
private IEventStreamReader eventStreamReader;
#endregion
#region Constructors
public EventStreamReactiveReader(IEventStreamReader eventStreamReader)
{
this.EventStreamReader = eventStreamReader;
}
#endregion
#region Public methods
public async Task CatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Action<Revision> onNext)
{
// Set default cancellation token in case it is not provided (it will do nothing)
CancellationToken cancellationToken = new CancellationTokenSource().Token;
await CatchUpAllEventStreamsAsync(initialCommit, onNext, cancellationToken);
}
public async Task CatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Func<Revision, Task> onNext)
{
// Set default cancellation token in case it is not provided (it will do nothing)
CancellationToken cancellationToken = new CancellationTokenSource().Token;
await CatchUpAllEventStreamsAsync(initialCommit, onNext, cancellationToken);
}
public async Task CatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Action<Revision> onNext, CancellationToken cancellationToken)
{
await CatchUpAllEventStreams(initialCommit, async revision =>
{
// Execute onNext task specified by the client
onNext(revision);
await Task.CompletedTask;
},
cancellationToken);
}
public async Task CatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Func<Revision, Task> onNext, CancellationToken cancellationToken)
{
await CatchUpAllEventStreams(initialCommit, onNext, cancellationToken);
}
public async Task ContinuouslyCatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Action<Revision> onNext)
{
// Set default cancellation token in case it is not provided (it will do nothing)
CancellationToken cancellationToken = new CancellationTokenSource().Token;
await ContinuouslyCatchUpAllEventStreamsAsync(initialCommit, onNext, cancellationToken);
}
public async Task ContinuouslyCatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Func<Revision, Task> onNext)
{
// Set default cancellation token in case it is not provided (it will do nothing)
CancellationToken cancellationToken = new CancellationTokenSource().Token;
await ContinuouslyCatchUpAllEventStreamsAsync(initialCommit, onNext, cancellationToken);
}
public async Task ContinuouslyCatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Action<Revision> onNext, CancellationToken cancellationToken)
{
await ContinuouslyCatchUpAllEventStreams(initialCommit, async revision =>
{
// Execute onNext task specified by the client
onNext(revision);
await Task.CompletedTask;
},
cancellationToken);
}
public async Task ContinuouslyCatchUpAllEventStreamsAsync(GlobalCheckpoint initialCommit, Func<Revision, Task> onNext, CancellationToken cancellationToken)
{
await ContinuouslyCatchUpAllEventStreams(initialCommit, onNext, cancellationToken);
}
#endregion
#region Private methods
private async Task CatchUpAllEventStreams(GlobalCheckpoint initialCommit, Func<Revision, Task> handleRevision, CancellationToken cancellationToken)
{
try
{
// Subscribe to all event streams and execute onNext action and save changes for each revision received
await (EventStoreObservables.AllEventStreamsFrom(this.EventStreamReader, initialCommit)
.SelectFromAsync(handleRevision)
.RetryWithBackoffStrategy(retryCount: int.MaxValue, retryOnError: e => e is DbUpdateConcurrencyException)
.ToTask(cancellationToken));
}
catch (InvalidOperationException ex)
{
if (ex.HResult == -2146233079)
{
// TODO: Write to log instead of the console
Console.WriteLine(string.Format("An invalid operation exception has been thrown with code {0} when processing results from the server. Perhaps you are already up to date. Detailed error: {1}", ex.HResult, ex.Message));
}
else
{
throw ex;
}
}
}
private async Task ContinuouslyCatchUpAllEventStreams(GlobalCheckpoint initialCommit, Func<Revision, Task> handleRevision,
CancellationToken cancellationToken)
{
try
{
// Subscribe to all event streams and execute onNext action and save changes for each revision received
await (EventStoreObservables.ContinuousAllEventStreamsFrom(this.EventStreamReader, initialCommit)
.SelectFromAsync(handleRevision)
.RetryWithBackoffStrategy(retryCount: int.MaxValue, retryOnError: e => e is EventStreamTrackedReaderDbConcurrencyException)
.ToTask(cancellationToken));
}
catch (InvalidOperationException ex)
{
if (ex.HResult == -2146233079)
{
// TODO: Write to log instead of the console
Console.WriteLine(string.Format("An invalid operation exception has been thrown with code {0} when processing results from the server. Perhaps you are already up to date. Detailed error: {1}", ex.HResult, ex.Message));
}
else
{
throw ex;
}
}
}
#endregion
#region Properties
private IEventStreamReader EventStreamReader
{
get
{
return this.eventStreamReader;
}
set
{
//TODO: Insert validation code here
this.eventStreamReader = value;
}
}
#endregion
}
}
|
namespace Bomberman.Api
{
public class PerkState
{
public Point Location { get; }
public Element PerkType { get; }
public int ExpiresIn { get; private set; }
public bool IsExpired => ExpiresIn <= 0;
public PerkState(Point location, Element perk)
{
Location = location;
PerkType = perk;
ExpiresIn = Settings.PerkExpirationTime;
}
public PerkState Clone()
{
return new PerkState(Location, PerkType)
{
ExpiresIn = ExpiresIn
};
}
public void ProcessTurn()
{
ExpiresIn--;
}
public override string ToString()
{
return $"{Location} {(char) PerkType} exp={ExpiresIn}";
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Project.Domain.AggregatesModel;
namespace Project.Infrastructure.EntityConfigurations
{
public class ProjectPropertyConfig : IEntityTypeConfiguration<ProjectPropetry>
{
public void Configure(EntityTypeBuilder<ProjectPropetry> builder)
{
builder.ToTable("ProjectPropetries");
builder.Property(x => x.Key).IsRequired().HasMaxLength(100);
builder.Property(x => x.Value).IsRequired().HasMaxLength(100);
builder.HasKey(x => new { x.ProjectId, x.Key, x.Value });
}
}
} |
namespace OmniSharp.Extensions.JsonRpc
{
public interface IRequestContext
{
IHandlerDescriptor Descriptor { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class DialogManager : Manager {
Dialog currentlyVisibleDialog = null;
public GameObject dialogAnchor;
///////////////////// BOOTSTRAP /////////////////////
private static Manager instance;
public static DialogManager getInstance()
{
return getInstance(ref instance, "DialogManager") as DialogManager;
}
void Awake() {
}
public void ShowDialog(string dialogName, string message) {
this.DismissDialog();
GameObject prefab = Resources.Load ("Prefabs/Dialogs/"+dialogName) as GameObject;
GameObject go = GameObject.Instantiate(prefab) as GameObject;
go.transform.parent = dialogAnchor.transform;
go.transform.localPosition = Vector3.zero;
currentlyVisibleDialog = go.GetComponent<Dialog>();
currentlyVisibleDialog.SetMessage(message);
}
public void DismissDialog() {
if (currentlyVisibleDialog != null){
GameObject.Destroy(currentlyVisibleDialog.gameObject);
}
}
}
|
namespace RefactoringApp.MovingFeaturesBetweenObjects
{
public class IntroduceForeignMethod
{
/// <summary>
/// Mechanics
/// Create a method in the client class that does what you needjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjn
/// </summary>
public void LegacyService()
{
var viewModel = new DateViewmModel(2020, 01, 01)
{};
/// Do something else.
var viewModel1 = new DateViewmModel(2020, 01, 01);
}
public void Refactoring()
{
var viewModel = DateViewmModel.Create(2020, 01, 01);
// do something else.
}
}
public class DateViewmModel
{
public int Year { get; }
public int Month { get; }
public int Day { get; }
public DateViewmModel(int year, int month, int day)
{
Year = year;
Month = month;
Day = day;
}
public static DateViewmModel Create(int year, int month, int day)
{
return new DateViewmModel(year, month, day);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace WindowsServiceInstaller.InstallHelper
{
public class ArgsParser
{
private readonly string[] _args;
public ArgsParser(string[] args)
{
_args = args;
}
public string GetParamValueOrThrow(string paramName)
{
var paramValue = GetParamValueOrNull(paramName);
if (paramValue == null)
{
throw new ArgumentException($"参数{paramName}的值不能为空", paramName);
}
return paramValue;
}
public string GetParamValueOrNull(string paramName)
{
if (_args == null)
{
return null;
}
var paramNameWithSlash = paramName.StartsWith("/") ? paramName : "/" + paramName;
var paramList = _args.Where(x => x.StartsWith(paramNameWithSlash, StringComparison.InvariantCultureIgnoreCase)).ToList();
if (paramList.Count == 0)
{
return null;
}
string result = GetParamValueFromMatchingList(paramNameWithSlash, paramList);
return result;
}
private string GetParamValueFromMatchingList(string paramNameWithSlash, List<string> paramList)
{
// 参数出现次数
int paramOccurrence = 0;
string result = null;
foreach (var paramListItem in paramList)
{
var arr = paramListItem.Split(new char[] { ':', '=' }, 2);
// 通过字符串长度判断参数名称是否完全匹配, 有可能是子字符串
if (arr[0].Length != paramNameWithSlash.Length)
{
continue;
}
paramOccurrence++;
if (arr.Length == 1)
{
result = string.Empty;
}
else
{
result = arr[1];
}
}
if (paramOccurrence > 1)
{
throw new ArgumentException("参数个数大于1", paramNameWithSlash);
}
return result;
}
public bool HasParam(string paramName)
{
return GetParamValueOrNull(paramName) != null;
}
}
}
|
using ConsoleTable.Settings.Border;
namespace ConsoleTable.Settings.Symbols
{
public class TableSymbols
{
public virtual char TopRightCorner { get; set; } = '┐';
public virtual char TopLeftCorner { get; set; } = '┌';
public virtual char BottomRightCorner { get; set; } = '┘';
public virtual char BottomLeftCorner { get; set; } = '└';
public virtual char RightRowSeperator { get; set; } = '┤';
public virtual char LeftRowSeperator { get; set; } = '├';
public virtual char TopColumnSeperator { get; set; } = '┬';
public virtual char BottomColumnSeperator { get; set; } = '┴';
public virtual char TableFieldCorner { get; set; } = '┼';
public virtual char HorizontalTableFieldBorder { get; set; } = '─';
public virtual char VerticalTableFieldBorder { get; set; } = '│';
public virtual char GetBorderSymbol(HorizontalBorder horizontalBorder, VerticalBorder verticalBorder)
{
if (horizontalBorder == HorizontalBorder.Left && verticalBorder == VerticalBorder.Top)
{
return TopLeftCorner;
}
if (horizontalBorder == HorizontalBorder.Left && verticalBorder == VerticalBorder.Center)
{
return LeftRowSeperator;
}
if (horizontalBorder == HorizontalBorder.Left && verticalBorder == VerticalBorder.Bottom)
{
return BottomLeftCorner;
}
if (horizontalBorder == HorizontalBorder.Center && verticalBorder == VerticalBorder.Top)
{
return TopColumnSeperator;
}
if (horizontalBorder == HorizontalBorder.Center && verticalBorder == VerticalBorder.Center)
{
return TableFieldCorner;
}
if (horizontalBorder == HorizontalBorder.Center && verticalBorder == VerticalBorder.Bottom)
{
return BottomColumnSeperator;
}
if (horizontalBorder == HorizontalBorder.Right && verticalBorder == VerticalBorder.Top)
{
return TopRightCorner;
}
if (horizontalBorder == HorizontalBorder.Right && verticalBorder == VerticalBorder.Center)
{
return RightRowSeperator;
}
return BottomRightCorner;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using upsAPIs;
using System.Windows.Forms;
namespace LaserPrinter
{
public partial class AutoStorageConnector : Form
{
public AutoStorageConnector()
{
InitializeComponent();
}
Socket socketSend;
Boolean transEnable = true;
String currentTask = "00000000";
Boolean connectEnable = false;
Thread c_thread;
Thread task_thread;
private void AutoStorageConnector_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
txt_ip.Text = Properties.Settings.Default.serverIP;
txt_port.Text = Properties.Settings.Default.port;
comboBox1.Text = Properties.Settings.Default.storageNO;
connectServer();
}
/// <summary>
/// 连接服务端
/// </summary>
public void connectServer() {
try
{
if (txt_ip.Text.ToString().Trim().Equals("") || txt_port.Text.ToString().Trim().Equals(""))
{
MessageBox.Show("服务端IP和端口号设置不能为空!");
}
else
{
//创建客户端Socket,获得远程ip和端口号
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(txt_ip.Text.ToString());
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txt_port.Text.ToString()));
socketSend.Connect(point);
connectEnable = true;
transEnable = true;
ShowMsg("连接成功!");
//开启新的线程,不停的接收服务器发来的消息
c_thread = new Thread(Received);
c_thread.IsBackground = true;
c_thread.Start();
task_thread = new Thread(tryGetTask);
task_thread.IsBackground = true;
task_thread.Start();
btn_disconnect.Enabled = true;
btn_connect.Enabled = false;
//timer1.Enabled = true;
}
}
catch (Exception erroMsg)
{
ShowMsg("连接失败:" + erroMsg.Message.ToString());
btn_disconnect.Enabled = false;
btn_connect.Enabled = true;
}
}
public void ShowMsg(string str)
{
textBox1.AppendText(str + "\r\n");
}
public void Send(String sendMSG)
{
try
{
if (sendMSG != null && !sendMSG.Trim().Equals(""))
{
byte[] buffer = new byte[1024 * 1024 * 3];
//buffer = Encoding.UTF8.GetBytes(sendMSG);
String cmd = sendMSG.Substring(0,4);
String strx = sendMSG.Substring(4,2);
String stry = sendMSG.Substring(6,2);
int x = Convert.ToInt16(strx);
int y = Convert.ToInt16(stry);
String str_x = x.ToString("X2");
String str_y = y.ToString("X2");
String strcmd = cmd + str_x + str_y;
buffer = strToToHexByte(strcmd);
socketSend.Send(buffer);
ShowMsg("发送:" + sendMSG);
}
}
catch(Exception erro)
{
ShowMsg("发送失败:" + sendMSG+" 原因:"+erro.Message.ToString());
}
}
/// <summary>
/// 接收服务端返回的消息
/// </summary>
public void Received()
{
while (connectEnable)
{
Thread.Sleep(100);
try
{
byte[] buffer = new byte[1024 * 1024 * 3];
//实际接收到的有效字节数
int len = socketSend.Receive(buffer);
if (len == 0)
{
break;
}
//string str = Encoding.UTF8.GetString(buffer, 0, len);
string str = byteToHexStr(buffer,0,len);
if (str != null && (str.Length==10) && str.Substring(str.Length - 2, 2).Equals("01"))
{
String cmd = str.Substring(0,4);
String strx = str.Substring(4, 2);
String stry = str.Substring(6, 2);
int x = Int32.Parse(strx, System.Globalization.NumberStyles.HexNumber);
int y = Int32.Parse(stry, System.Globalization.NumberStyles.HexNumber);
String x2 = x.ToString();
String y2 = y.ToString();
if (x < 10)
x2 = "0"+x2;
if (y < 10)
y2 = "0" + y2;
String strmsg = cmd + x2 + y2;
//ShowMsg("反馈mes:" + strmsg);
Thread.Sleep(100);
bool updateResult = updateTask(strmsg);
if (updateResult)
{
ShowMsg("更新MES配送任务成功!");
transEnable = true;
}
else //如果更新失败则再重复请求3次
{
transEnable = false;
ShowMsg("更新MES配送任务失败!请检查网络连接是否正常。");
/*for (int i = 0; i < 3; i++)
{
if (!transEnable)
{
Thread.Sleep(1000);
if (updateTask(strmsg))
{
transEnable = true;
ShowMsg("更新MES配送任务成功!");
}
else
ShowMsg("更新MES配送任务失败!请检查网络连接是否正常。");
}
}*/
/*while (!transEnable)
{
Thread.Sleep(5000);
if (updateTask(strmsg))
{
transEnable = true;
ShowMsg("更新MES配送任务成功!");
}
else
ShowMsg("更新MES配送任务失败!请检查网络连接是否正常。");
}*/
}
}
ShowMsg(socketSend.RemoteEndPoint + ":" + str);
}
catch(Exception erro)
{
ShowMsg( "接收消息出错:" + erro.Message.ToString());
}
}
}
private void tryGetTask() {
bool flag = true;
while(true)
{
if (transEnable && flag)
{
flag = false;
String strTask = getTask();
if (strTask != null && !strTask.Equals("false"))
{
currentTask = strTask;
Send(strTask);
transEnable = false;
}
flag = true;
}
Thread.Sleep(2000);
}
}
private void btn_connect_Click(object sender, EventArgs e)
{
connectServer();
}
private void btn_disconnect_Click(object sender, EventArgs e)
{
if (socketSend != null)
{
socketSend.Disconnect(true);
connectEnable = false;
transEnable = false;
ShowMsg("连接断开!");
btn_connect.Enabled = true;
btn_disconnect.Enabled = false;
c_thread.Join();
task_thread.Abort();
}
}
public String getTask()
{
String new_task = "";
upsWebAPIs upsapi = new upsWebAPIs();
new_task = upsapi.getTask(comboBox1.Text.ToString());
return new_task;
}
public bool updateTask(String msg)
{
bool result = false;
if (msg != null && msg.Trim() != "")
{
upsWebAPIs upsapi = new upsWebAPIs();
String str = upsapi.updateTask(msg, comboBox1.Text.ToString());
if (str.Trim().Equals("true"))
result = true;
}
return result;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
txt_ip.Enabled = false;
txt_port.Enabled = false;
comboBox1.Enabled = false;
}
else
{
txt_ip.Enabled = true;
txt_port.Enabled = true;
comboBox1.Enabled = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
//Send("01012243");
//String cmd = getTask();
//bool cmd = updateTask("01020101");
//String task = getTask();
//textBox1.Text = task;
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Properties.Settings.Default.storageNO = comboBox1.Text.ToString();
Properties.Settings.Default.Save();
}
private void txt_ip_TextChanged(object sender, EventArgs e)
{
Properties.Settings.Default.serverIP = txt_ip.Text.ToString();
Properties.Settings.Default.Save();
}
private void txt_port_TextChanged(object sender, EventArgs e)
{
Properties.Settings.Default.port = txt_port.Text.ToString();
Properties.Settings.Default.Save();
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string byteToHexStr(byte[] bytes,int index,int len)
{
string returnStr = "";
if (bytes != null)
{
for (int i = index; i < len; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
}
}
|
using Infnet.Engesoft.SysBank.Model.Dominio;
using NUnit.Framework;
namespace Infnet.Engesoft.SysBank.Model.Teste
{
[TestFixture]
class ClientePessoaJuridicaTeste
{
public PessoaJuridica Cliente = new PessoaJuridica();// TODO: Initialize to an appropriate value
[Test]
public void Test_Nome()
{
string expected = @"Paulo Vasconcelos"; //string.Empty;
string actual;
Cliente.Nome = expected;
actual = Cliente.Nome;
Assert.AreEqual(expected, actual);
}
[Test]
public void Test_CNPJ()
{
string expected = "30.097.554/0001-10";
string actual;
Cliente.Cnpj = expected;
actual = Cliente.Cnpj;
Assert.AreEqual(expected, actual);
}
[Test]
public void Test_Receita()
{
decimal expected = 10547.99m;
decimal actual;
Cliente.Receita = expected;
actual = Cliente.Receita;
Assert.AreEqual(expected, actual);
}
}
}
|
using Liddup.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Liddup.TemplateSelectors
{
class SpotifyAuthenticationDataTemplateSelector : DataTemplateSelector
{
public DataTemplate AuthenticatedTemplate { get; set; }
public DataTemplate NotAuthenticatedTemplate { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container) => (item as User).IsSpotifyAuthenticated ? AuthenticatedTemplate : NotAuthenticatedTemplate;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Data;
namespace WindowsFormsApplication1
{
public partial class Welcome_Form : Form
{
MySqlConnection con = new MySqlConnection("Data Source=localhost;port=3306;Initial Catalog=school_management;User Id=root;password=''");
public Welcome_Form()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
this.Hide();
studntLoginForm fm2 = new studntLoginForm();
fm2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnStaff_Click(object sender, EventArgs e)
{
this.Hide();
Lecturer_Login Lec = new Lecturer_Login();
Lec.Show();
}
private void btnAdmin_Click(object sender, EventArgs e)
{
this.Hide();
Admin_Form adf = new Admin_Form();
adf.Show();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary.Model
{
public class POIDTOReceive : POIDTO
{
[ForeignKey("Local")]
public int LocalID { get; set; }
[ForeignKey("Categoria")]
public int CategoriaID { get; set; }
public POIDTOReceive()
{
}
public POIDTOReceive(POI poi)
{
this.PoiID = poi.PoiID;
this.Nome = poi.Nome;
this.Descricao = poi.Descricao;
this.LocalID = poi.LocalID;
this.CategoriaID = poi.CategoriaID;
}
}
}
|
using System;
using UnityEngine;
using SimpleJSON;
namespace ColorPalette
{
[Serializable]
public class PaletteImporterData : PaletteData
{
public PaletteImporterData (string name = null) : base(name)
{
this.paletteURL = "";
this.loadPercent = false;
}
[SerializeField]
public string
paletteURL;
[SerializeField]
public bool
loadPercent;
public override JSONClass getJsonPalette ()
{
JSONClass jClass = base.getJsonPalette ();
jClass ["paletteURL"] = this.paletteURL;
jClass ["loadPercent"].AsBool = this.loadPercent;
//Debug.Log ("getDataClass: " + jClass ["colors"].Count + " " + jClass ["percentages"].Count);
return jClass;
}
public override void setPalette (JSONClass jClass)
{
this.paletteURL = jClass ["paletteURL"];
this.loadPercent = jClass ["loadPercent"].AsBool;
base.setPalette (jClass);
}
public override string ToString ()
{
JSONClass jClass = getJsonPalette ();
string baseClass = base.ToString ();
baseClass += " paletteURL: " + jClass ["paletteURL"].ToString ()
+ " loadPercent: " + jClass ["loadPercent"].ToString ();
return baseClass;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.Threading;
using MyDuplexClient.ServiceReference1;
namespace MyDuplexClient
{
[CallbackBehavior(
ConcurrencyMode = ConcurrencyMode.Single,
UseSynchronizationContext = false)]
public class Program : DuplexServerCallback
{
private SynchronizationContext _uiSyncContext;
private DuplexServerClient _DuplexServer;
static void Main(string[] args)
{
Program pro = new Program();
pro.Call();
Console.ReadKey();
}
public void Call() {
_uiSyncContext = SynchronizationContext.Current;
_DuplexServer = new DuplexServerClient(new InstanceContext(this), "WSDualHttpBinding_DuplexServer");
_DuplexServer.Open();
_DuplexServer.MakeClientJoinNetWork("KHOIDN");
}
public void Close() {
_DuplexServer.Close();
}
public void ShowMessage(string message)
{
Console.WriteLine(message);
}
}
}
|
namespace TestApplicationDomain.DynamicQuery
{
public class DataDescriptor
{
public OrderDescriptor Order { get; set; }
public FilterDescription[] Filter { get; set; }
public PaginationDescriptor Pagination { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace Spine
{
public class AnimationStateData
{
internal SkeletonData skeletonData;
private Dictionary<KeyValuePair<Animation, Animation>, float> animationToMixTime = new Dictionary<KeyValuePair<Animation, Animation>, float>();
internal float defaultMix;
public SkeletonData SkeletonData
{
get
{
return this.skeletonData;
}
}
public float DefaultMix
{
get
{
return this.defaultMix;
}
set
{
this.defaultMix = value;
}
}
public AnimationStateData(SkeletonData skeletonData)
{
this.skeletonData = skeletonData;
}
public void SetMix(string fromName, string toName, float duration)
{
Animation animation = this.skeletonData.FindAnimation(fromName);
if (animation == null)
{
throw new ArgumentException("Animation not found: " + fromName);
}
Animation animation2 = this.skeletonData.FindAnimation(toName);
if (animation2 == null)
{
throw new ArgumentException("Animation not found: " + toName);
}
this.SetMix(animation, animation2, duration);
}
public void SetMix(Animation from, Animation to, float duration)
{
if (from == null)
{
throw new ArgumentNullException("from cannot be null.");
}
if (to == null)
{
throw new ArgumentNullException("to cannot be null.");
}
KeyValuePair<Animation, Animation> keyValuePair = new KeyValuePair<Animation, Animation>(from, to);
this.animationToMixTime.Remove(keyValuePair);
this.animationToMixTime.Add(keyValuePair, duration);
}
public float GetMix(Animation from, Animation to)
{
KeyValuePair<Animation, Animation> keyValuePair = new KeyValuePair<Animation, Animation>(from, to);
float result;
if (this.animationToMixTime.TryGetValue(keyValuePair, ref result))
{
return result;
}
return this.defaultMix;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using Ext.Net;
using Ext.Net.Utilities;
using NETDataLuma;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Aspx
{
public partial class AspxRepGuias : System.Web.UI.Page
{
private static readonly ExecStoreSql ZConexion = new ExecStoreSql(ConfigurationManager.AppSettings["SIDTUMCon"], ConfigurationManager.AppSettings["SIDTUM_Cat"], ConfigurationManager.AppSettings["RutaDatum"]);
private DataSet _zDataset = new DataSet();
//UoMetodos z_metodos = new UoMetodos();
protected void Page_Load(object sender, EventArgs e)
{
if (X.IsAjaxRequest) return;
ZdirmeLlenaCombo();
}
[DirectMethod]
public string ZdirmeCargarGuia(string jsonParams)
{
var zVarstrresultado = string.Empty;
try
{
_zDataset = ZConexion.ExecuteSpDs("SPQRY_Buscaguias", "sidtum_Buscaguias", ParametrosSp(jsonParams));
if (!_zDataset.IsNull())
{
if (_zDataset.Tables[0].Rows.Count > 0)
{
if (_zDataset.Tables[0].Columns[0].ColumnName != "CtlCod")
{
zVarstrresultado = JsonResulEjec(1, "SQL_OK", "ZdirmeCargarGuia", "");
z_Store_Resultado.DataSource = _zDataset.Tables[0];
z_Store_Resultado.DataBind();
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_ERROR", "ZdirmeCargarGuia",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_VACIO", "ZdirmeCargarGuia",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_NULL", "ZdirmeCargarGuia",
"Servidor de SQL no disponible...");
}
}
catch (Exception ex)
{
zVarstrresultado = JsonResulEjec(0, "IIS_ERROR", "ZdirmeCargarGuia", ex.Message);
}
return zVarstrresultado;
}
[DirectMethod]
public string ZdirViajeRuta()
{
var zVarstrresultado1 = string.Empty;
try
{
ZConexion.NoConexion = ConfigurationManager.AppSettings["SID_autocarga_con"];
ZConexion.RutaArchivoConexiones = ConfigurationManager.AppSettings["RutaDatum"];
// ZConexion.RutaArchivoConexiones = "D:/web/datum/Universal.xml";
ZConexion.Catalogo = ConfigurationManager.AppSettings["SID_autocarga_cat"];
ZConexion.Open();
_zDataset = ZConexion.ExecuteSpDs("SPQRY_VericaRutasConcesionarios", "sidtum_VerificaRuta");
if (!_zDataset.IsNull())
{
if (_zDataset.Tables[0].Rows.Count > 0)
{
if (_zDataset.Tables[0].Columns[0].ColumnName != "CtlCod")
{
zVarstrresultado1 = JsonResulEjec(1, "SQL_OK", "ZdirViajeRuta", "");
z_Store_ViajeRuta.DataSource = _zDataset.Tables[0];
z_Store_ViajeRuta.DataBind();
}
else
{
zVarstrresultado1 = JsonResulEjec(0, "SQL_ERROR", "ZdirViajeRuta",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado1 = JsonResulEjec(0, "SQL_VACIO", "ZdirViajeRuta",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado1 = JsonResulEjec(0, "SQL_NULL", "ZdirViajeRuta",
"Servidor de SQL no disponible...");
}
}
catch (Exception ex)
{
zVarstrresultado1 = JsonResulEjec(0, "IIS_ERROR", "ZdirViajeRuta", ex.Message);
}
return zVarstrresultado1;
}
[DirectMethod]
public string ZdirmeModificaGuia(string jsonParams)
{
var zVarstrresultado = string.Empty;
try
{
ZConexion.NoConexion = ConfigurationManager.AppSettings["SID_autocarga_con"];
ZConexion.RutaArchivoConexiones = ConfigurationManager.AppSettings["RutaDatum"];
// ZConexion.RutaArchivoConexiones = "D:/web/datum/Universal.xml";
ZConexion.Catalogo = ConfigurationManager.AppSettings["SID_autocarga_cat"];
ZConexion.Open();
// _zDataset = ZConexion.ExecuteSpDs("SPUPD_DesAisgnaGuias", "sidtum_DesAisgnaGuias", ParametrosSp(jsonParams));
_zDataset = ZConexion.ExecuteSpDs("SPUPD_DesAisgnaGuias1", "sidtum_DesAisgnaGuias", ParametrosSp(jsonParams));
if (!_zDataset.IsNull())
{
if (_zDataset.Tables[0].Rows.Count > 0)
{
if (_zDataset.Tables[0].Rows[0][1].ToString() != "SQL_ERROR")
{
zVarstrresultado = JsonResulEjec(1, "SQL_OK", "ZdirmeModificaGuia", "");
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_ERROR", "ZdirmeModificaGuia",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_VACIO", "ZdirmeModificaGuia",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_NULL", "ZdirmeModificaGuia",
"Servidor de SQL no disponible...");
}
}
catch (Exception ex)
{
zVarstrresultado = JsonResulEjec(0, "IIS_ERROR", "ZdirmeModificaGuia", ex.Message);
}
return zVarstrresultado;
}
[DirectMethod]
public string ZdirmeLlenaCombo()
{
var zVarstrresultado = string.Empty;
try
{
ZConexion.NoConexion = ConfigurationManager.AppSettings["SIDTUMCon"];
ZConexion.RutaArchivoConexiones = ConfigurationManager.AppSettings["RutaDatum"];
// ZConexion.RutaArchivoConexiones = "D:/web/datum/Universal.xml";
ZConexion.Catalogo = ConfigurationManager.AppSettings["SIDTUM_Cat"];
ZConexion.Open();
_zDataset = ZConexion.ExecuteSpDs("SPQRY_Combo_FolioViaje", "sidtum_ComboViaje");
if (_zDataset.Tables[0].Rows.Count > 0)
{
zVarstrresultado = JsonResulEjec(1, "SQL_OK", "ZdirmeLlenaCombo", "");
z_Store_Combo.DataSource = _zDataset.Tables[0];
z_Store_Combo.DataBind();
}
else
{
z_cmbViaje.Disabled = true;
z_reestablecer.Disabled = true;
zVarstrresultado = JsonResulEjec(1, "SQL_OK", "ZdirmeLlenaCombo", "");
}
}
catch (Exception ex)
{
zVarstrresultado = JsonResulEjec(0, "IIS_ERROR", "ZdirmeLlenaCombo", ex.Message);
}
return zVarstrresultado;
}
[DirectMethod]
public string ZdirmeRutaCiudad(string jsonParams)
{
var zVarstrresultado = string.Empty;
try
{
ZConexion.NoConexion = ConfigurationManager.AppSettings["SIDTUMCon"];
//ZConexion.RutaArchivoConexiones = ConfigurationManager.AppSettings["RutaDatum"];
ZConexion.RutaArchivoConexiones = "D:/web/datum/Universal.xml";
ZConexion.Catalogo = ConfigurationManager.AppSettings["SIDTUM_Cat"];
ZConexion.Open();
_zDataset = ZConexion.ExecuteSpDs( "dbo","SPQRY_FolioViajeRutaCiudad", "sidtum_Consulta", jsonParams.ToString());
if (!_zDataset.IsNull())
{
if (_zDataset.Tables["sidtum_Consulta"].Rows.Count > 0)
{
if (_zDataset.Tables["sidtum_Consulta"].Columns[0].ColumnName != "CtlCod")
{
zVarstrresultado = JsonResulEjec(1, "SQL_OK", "ZdirmeRutaCiudad", "");
z_store_InfoGral.DataSource = _zDataset.Tables["sidtum_Consulta"];
z_store_InfoGral.DataBind();
z_store_RutaCiudad.DataSource = _zDataset.Tables["sidtum_Consulta1"];
z_store_RutaCiudad.DataBind();
z_store_CiudadConcesionario.DataSource = _zDataset.Tables["sidtum_Consulta2"];
z_store_CiudadConcesionario.DataBind();
lbl_NumeroViaje.Text = _zDataset.Tables["sidtum_Consulta"].Rows[0]["FolioViaje"].ToString();
lbl_Operador.Text = _zDataset.Tables["sidtum_Consulta"].Rows[0]["Operador"].ToString();
lbl_NumUnidad.Text = _zDataset.Tables["sidtum_Consulta"].Rows[0]["Unidad"].ToString();
lbl_Ayudante.Text = _zDataset.Tables["sidtum_Consulta"].Rows[0]["Ayudante"].ToString();
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_ERROR", "ZdirmeRutaCiudad",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_VACIO", "ZdirmeRutaCiudad",
"Error en ejecución SQL...");
}
}
else
{
zVarstrresultado = JsonResulEjec(0, "SQL_NULL", "ZdirmeRutaCiudad",
"Servidor de SQL no disponible...");
}
}
catch (Exception ex)
{
zVarstrresultado = JsonResulEjec(0, "IIS_ERROR", "ZdirmeRutaCiudad", ex.Message);
}
return zVarstrresultado;
}
private static object[] ParametrosSp(string jsonParams)
{
var dynObj = (JObject)JsonConvert.DeserializeObject(jsonParams);
var lista = new List<string>();
foreach (var al in dynObj)
{
lista.Add((string)al.Value);
}
return lista.ToArray();
}
public string JsonResulEjec(short codigo, string clave, string objeto, string observaciones)
{
var sbResultado = new System.Text.StringBuilder();
try
{
sbResultado.Append("{\"Rows\":[{");
sbResultado.Append("\"CtlCod\":" + codigo.ToString() + ",");
sbResultado.Append("\"CtlCve\":\"" + clave + "\",");
sbResultado.Append("\"CtlObj\":\"" + objeto + "\",");
sbResultado.Append("\"CtlObs\":\"" + observaciones + "\"}]}");
}
catch (Exception ex)
{
X.Msg.Show(new MessageBoxConfig
{
Buttons = MessageBox.Button.OK,
Icon = MessageBox.Icon.INFO,
Title = "Error",
Message = "Error no Tipificado"
});
ResourceManager.AjaxSuccess = false;
ResourceManager.AjaxErrorMessage = ex.Message;
}
return sbResultado.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace SurveySite.Models
{
public class SurveySiteEntities: DbContext
{
public DbSet<Question> Questions { get; set; }
public DbSet<AnswerVariant> AnswerVariants { get; set; }
public DbSet<Answer> Answers { get; set; }
}
} |
using System;
using System.Globalization;
using: asdADasdASDawd
namespace TimeTest
{
class Program
{
private void WeekDay()
{
// Assume the current is en-US.
// Create a DateTime for the first of May, 2003.
DateTime dt = new DateTime(2003, 5, 1);
Console.WriteLine("Is Thursday the day of the week for {0:d}?: {1}", dt, dt.DayOfWeek == DayOfWeek.Thursday);
Console.WriteLine("The day of the week for {0:d} is {1}.", dt, dt.DayOfWeek);
}
private void fullYearsDays()
{
int[] years = { 2012, 2014, 2022 };
DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo;
Console.WriteLine("Days in the Month for the {0} culture " + "using the {1} calendar\n", CultureInfo.CurrentCulture.Name,
dtfi.Calendar.GetType().Name.Replace("Calendar", ""));
Console.WriteLine("{0, -10}{1, -15}{2,4}\n", "Year", "Month", "Days");
foreach (var year in years)
{
for (int ctr = 0; ctr <= dtfi.MonthNames.Length - 1; ctr++)
{
if (String.IsNullOrEmpty(dtfi.MonthNames[ctr]))
{
continue;
}
Console.WriteLine("{0, -10}{1,-15}{2, 4}", year, dtfi.MonthNames[ctr], DateTime.DaysInMonth(year, ctr + 1));
}
Console.WriteLine();
}
}
private int DaysInMonth()
{
int July = 7;
int Feb = 2;
int daysInJuly = DateTime.DaysInMonth(2001, July);
Console.WriteLine($"The number of days in July of 2001 was {daysInJuly}.");
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = DateTime.DaysInMonth(1998, Feb);
Console.WriteLine($"The number of days in Feb of 1998 was {daysInFeb}.");
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = DateTime.DaysInMonth(1996, Feb);
Console.WriteLine($"The number of days in Feb of 1996 was {daysInFebLeap}.");
int daysInFeb2022 = DateTime.DaysInMonth(2022, Feb);
Console.WriteLine($"The number of days in Feb of 2022 was {daysInFeb2022}.");
return daysInFeb2022;
}
private void DisplayDateWithTimeZoneName(DateTime date1, TimeZoneInfo timeZone)
{
Console.WriteLine("The time is {0:t} on {0:d} {1}", date1, timeZone.IsDaylightSavingTime(date1) ?
timeZone.DaylightName : timeZone.StandardName);
}
private DateTime GetCurrentDate()
{
DateTime localDate = DateTime.Now;
DateTime utcDate = DateTime.UtcNow;
String[] cultureNames = { "en-US", "en-GB", "fr-FR", "de-DE", "ru-RU" };
foreach (var cultureName in cultureNames)
{
var culture = new CultureInfo(cultureName);
Console.WriteLine("{0}:", culture.NativeName);
Console.WriteLine(" Local date and time: {0}, {1:G}", localDate.ToString(culture), localDate.Kind);
Console.WriteLine(" UTC date and time: {0}, {1:G}\n", utcDate.ToString(culture), utcDate.Kind);
}
return localDate;
}
private TimeZoneInfo DisplayTimeZone()
{
TimeZoneInfo localZone = TimeZoneInfo.Local;
Console.WriteLine("Local Time Zone ID: {0}", localZone.Id);
Console.WriteLine(" Display Name is: {0}.", localZone.DisplayName);
Console.WriteLine(" Standard name is: {0}.", localZone.StandardName);
Console.WriteLine(" Daylight saving name is: {0}.", localZone.DaylightName);
return localZone;
}
static void Main(string[] args)
{
Program p = new Program();
TimeZoneInfo currentTimeZone;
DateTime currentDate;
int daysOfMonth;
currentTimeZone = p.DisplayTimeZone();
currentDate = p.GetCurrentDate();
p.DisplayDateWithTimeZoneName(currentDate, currentTimeZone);
daysOfMonth = p.DaysInMonth();
p.fullYearsDays();
p.WeekDay();
}
}
}
|
using Microsoft.Xna.Framework.Input;
namespace WUIClient {
public static class WKeyboard {
public static KeyboardState prevKeyboardState;
public static KeyboardState currentKeyboardState;
public static void Update() {
prevKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
}
public static bool KeyClick(Keys key) {
return currentKeyboardState.IsKeyDown(key) && !prevKeyboardState.IsKeyDown(key);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace NekoUchi.Model
{
public class Translations
{
public Dictionary<string, string> WordFieldTranslations = new Dictionary<string, string>() {
{"Meaning", "Značenje" },
{"Kanji", "Kanji" },
{"Kana", "Kana" },
{"Image", "Slika" },
{"Audio", "Zvuk" }
};
public Dictionary<string, string> PrijevodiPoljaRijeci = new Dictionary<string, string>()
{
{"Značenje", "Meaning" },
{"Kanji", "Kanji" },
{"Kana", "Kana" },
{"Slika", "Image" },
{"Zvuk", "Audio" }
};
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WeddingPlanner.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Google.Maps;
using Google.Maps.StaticMaps;
using Google.Maps.Geocoding;
namespace WeddingPlanner.Controllers
{
public class UserWeddingViewModelController : Controller
{
private MyContext dbContext;
public UserWeddingViewModelController(MyContext context)
{
dbContext = context;
}
[Route("addrsvp/{wedid}/{userid}")]
[HttpGet]
public IActionResult AddRsvp(int wedid, int userid)
{
Wedding newWed = dbContext.Weddings.Include(c => c.WeddingtoUser).ThenInclude(b => b.User).FirstOrDefault(wed => wed.WeddingId == wedid);
User newUser = dbContext.Users.Include(c => c.UsertoWedding).ThenInclude(b => b.Wedding).FirstOrDefault(us => us.UserId == userid);
foreach (var thiswed in newUser.UsertoWedding)
{
if (thiswed.Wedding.WeddingDate.Date == newWed.WeddingDate.Date)
{
ModelState.AddModelError("WeddingDate", "You have plan to go to another wedding on that day already!!!");
ViewBag.sameDayWedding = true;
return Redirect("/User/Dashboard");
}
}
ViewBag.sameDayWedding = false;
UserWeddingViewModel a = new UserWeddingViewModel();
a.WeddingId = wedid;
a.UserId = userid;
dbContext.Add(a);
dbContext.SaveChanges();
return RedirectToAction("DetailWed", "Wedding", new { id = wedid });
}
[Route("unrsvp/{id}")]
[HttpGet]
public IActionResult UnRsvp(int id)
{
UserWeddingViewModel a = dbContext.UserWeddingViewModels.FirstOrDefault(wed => wed.UserWeddingViewModelId == id);
dbContext.Remove(a);
dbContext.SaveChanges();
return Redirect("/User/Dashboard");
}
}
} |
using UnityEngine;
using System.Collections;
public class ScreenShake : MonoBehaviour {
public float ShakeAmount = 0.25f;
public float DecreaseFactor = 1.0f;
private Camera cam;
private Vector3 cameraPos;
private float shake = 0.0f;
void Start()
{
cam = GetComponent<Camera>();
}
void Update()
{
if (this.shake > 0.0f) {
var shakeArea = Random.insideUnitSphere * ShakeAmount * shake;
cam.transform.localPosition = new Vector3(shakeArea.x, shakeArea.y, cam.transform.position.z);
shake -= Time.deltaTime * DecreaseFactor;
if (shake <= 0.0f) {
shake = 0.0f;
cam.transform.localPosition = this.cameraPos;
}
}
}
public void Shake(float amount)
{
if (shake <= 0.0f) {
cameraPos = cam.transform.position;
}
shake = amount;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace ALM.Reclutamiento.Entidades
{
[Serializable]
public class CargaArchivo
{
//HttpPostedFileBase
public HttpPostedFileBase file { get; set; }
public string Id { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.Dashboard.Model
{
/**
* Interface IWidgetRequest
*
* WidgetRequest are created by the Dashboard App and used to communicate from
* the frontend to the backend.
* The object is send to the WidgetClass using IDashboardWidget::requestWidget
*
* @see IDashboardWidget::requestWidget
*
* @since 15.0.0
*
* @package OCP\Dashboard\Model
*/
public interface IWidgetRequest {
/**
* Get the widgetId.
*
* @since 15.0.0
*
* @return string
*/
string getWidgetId();
/**
* Get the WidgetClass.
*
* @since 15.0.0
*
* @return IDashboardWidget
*/
IDashboardWidget getWidget();
/**
* Get the 'request' string sent by the request from the front-end with
* the format:
*
* net.requestWidget(
* {
* widget: widgetId,
* request: request,
* value: value
* },
* callback);
*
* @since 15.0.0
*
* @return string
*/
string getRequest();
/**
* Get the 'value' string sent by the request from the front-end.
*
* @see getRequest
*
* @since 15.0.0
*
* @return string
*/
string getValue();
/**
* Returns the result.
*
* @since 15.0.0
*
* @return array
*/
IList<string> getResult();
/**
* add a result (as string)
*
* @since 15.0.0
*
* @param string key
* @param string result
*
* @return this
*/
IWidgetRequest addResult(string key, string result);
/**
* add a result (as array)
*
* @since 15.0.0
*
* @param string key
* @param array result
*
* @return this
*/
IWidgetRequest addResultArray(string key, IList<string> result);
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace dojoBelt.Models
{
public abstract class BaseEntity{};
public class Register : BaseEntity
{
[Key]
public int UserId{get;set;}
[Required]
[MinLength(2)]
public string FirstName{get;set;}
[Required]
[MinLength(2)]
public string LastName{get;set;}
[Required]
[EmailAddress]
public string Email{get;set;}
[Required]
[MinLength(8)]
[DataType(DataType.Password)]
public string Password{get;set;}
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword{get;set;}
}
public class Login : BaseEntity
{
[Required]
[EmailAddress]
public string Email {get;set;}
[Required]
[MinLength(8, ErrorMessage="Passwords must be at least 8 characters")]
[DataType(DataType.Password)]
public string Password{get;set;}
}
public class ActivityCheck : BaseEntity
{
[Required]
[MinLength(2,ErrorMessage="Title must be at least 2 characters")]
public string Title {get;set;}
[Required]
public double? ActivityTime {get;set;}
[Required(ErrorMessage = "You must enter a Activity Date")]
[DisplayFormat(DataFormatString = @"{0:dd\/MM\/yyyy}")]
[DataType(DataType.Date)]
public DateTime ActivityDate {get;set;}
[Required]
public int? Duration {get;set;}
[Required]
[MinLength(10, ErrorMessage="Description must be more than 10 characters")]
public string Description {get;set;}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QLBH.Control;
namespace QLBH.View
{
public partial class TimKiemTheoTenNhaCC : UserControl
{
public static TimKiemTheoTenNhaCC ncc = new TimKiemTheoTenNhaCC();
public TimKiemTheoTenNhaCC()
{
InitializeComponent();
}
private void LoadNCC()
{
HangHoaCtr khctr = new HangHoaCtr();
comboBox1.DataSource = khctr.NhaSanXuat();
comboBox1.DisplayMember = "TenNSX";
comboBox1.ValueMember = "MaNSX";
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
HangHoaCtr hh = new HangHoaCtr();
dt = hh.GetData2("Where MaNSX = '" + comboBox1.SelectedValue.ToString() + "'");
if (dt.Rows.Count > 0)
{
dgvDanhSach.DataSource = dt;
}
else
{
MessageBox.Show("Không tìm thấy.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
dgvDanhSach.DataSource = dt;
dgvDanhSach.ClearSelection();
}
}
private void TimKiemTheoTenNhaCC_Load(object sender, EventArgs e)
{
LoadNCC();
}
}
}
|
using System.Text;
using GraphQL.Common.Response;
namespace Indico.Exception
{
[System.Serializable]
public class GraphQLException : System.Exception
{
public GraphQLException() { }
public GraphQLException(GraphQLError[] errors) : base(SerializeGraphQLErrors(errors)) { }
public GraphQLException(GraphQLError[] errors, System.Exception inner) : base(SerializeGraphQLErrors(errors), inner) { }
protected GraphQLException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
static string SerializeGraphQLErrors(GraphQLError[] errors)
{
StringBuilder builder = new StringBuilder();
int i = 0;
builder.AppendLine();
foreach (GraphQLError err in errors)
{
builder.AppendLine($"{++i} : {err.Message}");
}
return builder.ToString();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Keycard : MonoBehaviour
{
/// <summary>
/// The room numbers are 1 - 5
/// </summary>
public List<int> permittedRooms;
}
|
//5.You are given an array of strings. Write a method that sorts the array by the length
//of its elements (the number of characters composing them).
using System;
using System.Collections.Generic;
using System.Linq;
class SortArrayByLenght
{
static void Main()
{
List<string> listOfStrings = new List<string> { "Hey friend,", "Don't", "...be ", "lalalaa", "worry", "Have a nice day!", "happy!" };
foreach (string myArray in LenghtSort(listOfStrings))
{
Console.WriteLine(myArray); //print the values of the sorted array
}
}
static IEnumerable<string> LenghtSort(IEnumerable<string> elements)
{
var sortedString = from myString in elements
orderby myString.Length ascending
select myString;
return sortedString;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.