blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
1325696bec457fa0b52f6bdc1153b51c330da407
|
C#
|
henkla/MultiUserHeat
|
/MultiUserHeat/Heat.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace MultiUserHeat
{
public class Heat
{
private static Random _random;
public IDictionary<int, Competitor> HeatResult { get; private set; }
public IEnumerable<Competitor> Competitors { get; private set; }
public int Number { get; private set; }
public Heat(ICollection<Competitor> competitors, int number)
{
Competitors = competitors;
HeatResult = new Dictionary<int, Competitor>();
Number = number;
_random = new Random();
}
public IDictionary<int, Competitor> RunHeat()
{
ShuffleCompetitors(Competitors);
CreateHeatResult(Competitors);
return HeatResult;
}
private void CreateHeatResult(IEnumerable<Competitor> competitors)
{
var position = 1;
foreach (var competitor in competitors)
{
HeatResult.Add(position++, competitor);
}
}
private void ShuffleCompetitors(IEnumerable<Competitor> list)
{
var shuffledList = list.Select(x => new { Number = _random.Next(), Item = x }).OrderBy(x => x.Number).Select(x => x.Item);
Competitors = shuffledList;
}
}
}
|
61edf27a57c32011f97a2c8040af38d15ba34f09
|
C#
|
eaardal/MicroMonitor
|
/MicroMonitor/Engine/EventLog/EventLogPoller.cs
| 2.75
| 3
|
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MicroMonitor.Engine.MicroLog;
using MicroMonitor.Infrastructure;
using Timer = System.Timers.Timer;
namespace MicroMonitor.Engine.EventLog
{
public class EventLogPoller
{
private readonly Timer _timer = new Timer();
private readonly EventLogReader _eventLogReader = new EventLogReader();
public void StartPollingAtIntervals(string logName, double pollIntervalSeconds)
{
_timer.Interval = pollIntervalSeconds * 1000;
Logger.Debug($"Timer polling Event Log {logName} every {pollIntervalSeconds}s / {_timer.Interval}ms");
_timer.Elapsed += (sender, args) =>
{
var thread = new Thread(Poll);
thread.Start(new List<object> {logName});
Logger.Debug($"Spawned thread {thread.ManagedThreadId} for polling Event Log \"{logName}\"");
};
_timer.Start();
}
public void StopPolling()
{
_timer.Stop();
}
private void Poll(object data)
{
(var ok, var logDisplayName) = ParseArguments(data);
if (!ok)
{
Logger.Error("Could not parse arguments passed as object to EventLogPoller.Poll");
return;
}
var logEntries = _eventLogReader.ReadEventLog(logDisplayName);
MicroLogCache.Instance.InsertOrUpdate(logDisplayName, logEntries);
}
private static (bool ok, string logDisplayName) ParseArguments(object data)
{
var argsList = data as List<object>;
if (argsList != null)
{
var logDisplayName = (string)argsList.ElementAt(0);
return (true, logDisplayName);
}
return (false, null);
}
}
}
|
db9556ed8bb506cd837f4449c576b6dafea9fd62
|
C#
|
KissLog-net/KissLog.Sdk
|
/src/KissLog/Http/HttpProperties.cs
| 2.8125
| 3
|
using System;
namespace KissLog.Http
{
public class HttpProperties
{
public HttpRequest Request { get; }
public HttpResponse Response { get; private set; }
internal HttpProperties(HttpRequest httpRequest)
{
Request = httpRequest ?? throw new ArgumentNullException(nameof(httpRequest));
}
internal void SetResponse(HttpResponse response)
{
if (response == null)
throw new ArgumentNullException(nameof(response));
Response = response;
}
internal HttpProperties Clone()
{
HttpRequest request = Request.Clone();
HttpResponse response = Response == null ? null : Response.Clone();
return new HttpProperties(request)
{
Response = response
};
}
}
}
|
cb8e7244c02aa45216eda47fc6cf8abf9bdeeec0
|
C#
|
ivelin1936/SoftUni-
|
/C#/ConditionalStatementsandLoops/CountOfIntegers/StartUp.cs
| 3.28125
| 3
|
namespace CountOfIntegers
{
using System;
public class StartUp
{
public static void Main()
{
string input = Console.ReadLine();
int reminder = 0;
int count = 0;
while (int.TryParse(input, out reminder))
{
count++;
input = Console.ReadLine();
}
Console.WriteLine(count);
}
}
}
|
e47abf5126300f61af8951f61c11e25d2b7c060e
|
C#
|
K5680/Olio
|
/Labra7/Labra7/Program.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Labra7
{
class Program
{
static void Main(string[] args)
{
// Tee ohjelma, joka lukee yksinkertaisesta tekstitiedosto nimet.txt
// henkilöitten nimiä ja kertoo montako nimeä löytyy ja montako kertaa kukin nimi esiintyy.
// tallenne eri paikkaan -> file exist?
int i = 0;
//luodaan nimiä -oliolista
List<Nimet> nimiä = new List<Nimet>();
string hakemisto = "e:\\"; //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
try
{
int[] esiintymiset = new int[30];
string[] rivit = System.IO.File.ReadAllLines(hakemisto + @"\nimet.txt"); //luetaan tiedoston rivit taulukkoon
int onkojo = 0; // muuttuja, jonka arvo 1, jos nimi on jo olemassa
int a = 0;
//käydään läpi kaikki tiedoston rivit
while (i < rivit.Count()) // rivit.Count = montako riviä taulukossa
{
foreach (string rivi in rivit) // käydään läpi kaikki tiedoston rivit
{
foreach (Nimet nimet in nimiä) // Olio-listan jokaisen nimen kohdalla verrataan nimeä olio-listan nimiin
{
if (nimet.ToString().Contains(rivi)) // jos oliolistan nimi sisältää tiedosto-listan nimen
{
onkojo = 1; // Annetaan arvoksi 1 jottei sitä enää lisätä oliolistaan uudestaan
nimet.Lisää(); // mutta lisätään kyseisen nimen lukumäärää
//Console.WriteLine("Lisätty " + nimet.Nimi + nimet.Määrä);
}
}
if (onkojo == 0) // jos vertailun jälkeen nähdään että nimeä ei ole jo oliolistalla, lisätään se
{
nimiä.Add(new Nimet { Nimi = rivi }); // lisätään nimi olioksi
foreach (Nimet nimet in nimiä)
{
if (nimet.ToString().Contains(rivi)) // jos oliolistan nimi sisältää tiedosto-listan nimen, annetaan arvoksi 1 jottei sitä enää lisätä oliolistaan uudestaan
{
nimet.Lisää(); // lisätään kyseisen nimen lukumäärää
Console.WriteLine("Löydetty nimi: " + rivi);
}
}
a++;
}
onkojo = 0;
i++;
}
}
Console.WriteLine("\nRivejä yhteensä: {0} Nimiä yhteensä: {1} \n", rivit.Count(), a);
// listataan nimet
foreach (Nimet nimet in nimiä)
{
Console.WriteLine("Nimiä " + nimet.Nimi + " löydetty " + nimet.Määrä + "kpl");
}
Console.ReadKey();
}
catch (FileNotFoundException)
{
Console.WriteLine("Tiedostoa ei löydy: (FileNotFoundException)");
Console.ReadKey();
}
}
}
}
|
f68b899f454aeb3ad66f421df2c9702e045f93eb
|
C#
|
Nekoscholar/shooting
|
/FairyStar/FairyStar/Play/LoopThread(Engine)/FrameThread.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FairyStar
{
public class FrameThread //추후 서브 스레드까지 제작하여 4중 버퍼링 구현할것. 이 클래스는 패널 전체를 담당하고, 서브 스레드에서 비트맵은 플레이 영역으로 한정하여 탄, 유닛, 레이저등 요소를 TouchThread 처럼 나눠서 구현할것
{ //필요 정보 : 투명색 초기화.
PlayArea Play;
private Timer Paint_Call;
public static int Buffer_Count = 3;
public Bitmap[] Buffer = new Bitmap[Buffer_Count];
public int Buffer_Select = 0; //출력버퍼 선택, 입력버퍼는 다음버퍼를 이용
public Graphics g;
public Pen p;
public Brush b;
ThreadStart TS;
Thread TASK;
public FrameThread(PlayArea obj)
{
Play = obj;
Paint_Call = new Timer(repaint, null, 0, 15);
for(int i=0;i<Buffer_Count;i++)
Buffer[i] = new Bitmap(Config.pWidth, Config.pHeight);
g = Graphics.FromImage(Buffer[1]);
Config.DefaultMatrix = g.Transform;
g.SmoothingMode = Config.SmoothingStrategy; //그래픽 혹사.. 안되면 AntiAlias 사용.
Config.DefaultClip = g.ClipBounds;
p = new Pen(Config.color_PlayArea_Foreground);
b = new SolidBrush(Config.color_PlayArea_Background);
}
public void Init()
{
TS = new ThreadStart(BufferPaint);
TASK = new Thread(TS);
TASK.Start();
}
public void EndPaint() {
while (true)
{
Buffer_Select = (++Buffer_Select) % Buffer_Count;
try
{
g = Graphics.FromImage(Buffer[(Buffer_Select + 1) % Buffer_Count]);
g.Clear(Color.Transparent);
g.SmoothingMode = Config.SmoothingStrategy;
}
catch(Exception e) //버퍼에 동시 참조가 걸리면 잠기지 않은 다음 버퍼를 찾음.
{
continue;
}
break;
}
}
public void BufferPaint()
{
while (true)
{
DateTime start = DateTime.Now;
Play.paintDo(g, p, b);
EndPaint();
DateTime end = DateTime.Now;
double term = (end - start).TotalSeconds;
if (term < 0.015)
{
Thread.Sleep(15 - (int)(term * 1000));
}
}
}
public long Count = 0;
public void repaint(object obj)
{
Count++;
Play.window.Refresh();
}
}
}
|
506ccc5e427a7beb773a69019416a68bc8ff029e
|
C#
|
paiashwita/MerchantsOfGalaxy
|
/Common/Concrete/CreditsAssignmentStatementType.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Common.Concrete
{
public class CreditsAssignmentStatementType : IStatementTypeDecider
{
public StatementType StatementType { get => StatementType.CreditsAssignment; }
public bool isTrue(string inputStatement)
{
return inputStatement.Contains(Constants.ASSIGNMENT_STATEMENTS_IS)
&& inputStatement.Contains(Constants.ASSIGNMENT_STATEMENTS_WITHCREDITS)
&& !inputStatement.Contains(Constants.QUESTION_STATEMENTS_WITHCREDITS)
&& !inputStatement.Contains(Constants.QUESTION_STATEMENTS_WITH_IS);
}
}
}
|
7ab1f868b03b0362d2d539ac8351738915bd2bc0
|
C#
|
wcoder/CustomRecyclerViewXamarin
|
/RVItemClickExample/MainActivity.cs
| 2.953125
| 3
|
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Views;
namespace RVItemClickExample
{
// Ported from Java:
// https://github.com/Hariofspades/CustomRecyclerView/blob/master/app/src/main/java/com/hariofspades/customrecyclerview/MainActivity.java#L31
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
//Declare the Adapter, AecyclerView and our custom ArrayList
private RecyclerView _recyclerView;
private CustomAdapter _adapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
// Set toolbar
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
_recyclerView = FindViewById<RecyclerView>(Resource.Id.recycleView);
//As explained in the tutorial, LineatLayoutManager tells the RecyclerView that the view
//must be arranged in linear fashion
_recyclerView.SetLayoutManager(new LinearLayoutManager(this));
/*
* RecyclerView: Implementing single item click and long press (Part-II)
*/
_recyclerView.AddOnItemTouchListener(
new RecyclerTouchListener(this, _recyclerView, new ItemClickListener(this)));
_adapter = new CustomAdapter(this);
// Method call for populating the view
PopulateRecyclerViewValues();
}
private void PopulateRecyclerViewValues()
{
var listContentArr = new List<CustomPojo>();
/** This is where we pass the data to the adpater using POJO class.
* The for loop here is optional. I've just populated same data for 50 times.
* You can use a JSON object request to gather the required values and populate in the
* RecyclerView.
* */
for (int iter = 0; iter <= 50; iter++)
{
//Creating POJO class object
//Values are binded using set method of the POJO class
var pojoObject = new CustomPojo
{
Name = "User Name",
Content = "Hello RecyclerView! item: " + iter,
Time = "10:45PM"
};
//After setting the values, we add all the Objects to the array
//Hence, listConentArr is a collection of Array of POJO objects
listContentArr.Add(pojoObject);
}
//We set the array to the adapter
_adapter.SetListContent(listContentArr);
//We in turn set the adapter to the RecyclerView
_recyclerView.SetAdapter(_adapter);
}
}
/*
* RecyclerView: Implementing single item click and long press (Part-II)
*
* - creating an Interface for single tap and long press
* - Parameters are its respective view and its position
*/
public interface IClickListener
{
void OnClick(View view, int position);
void OnLongClick(View view, int position);
}
public class ItemClickListener : IClickListener
{
private readonly Context _context;
public ItemClickListener(Context context)
{
_context = context;
}
public void OnClick(View view, int position)
{
//Values are passing to activity & to fragment as well
Android.Widget.Toast.MakeText(_context, "Single Click on position :" + position,
Android.Widget.ToastLength.Short).Show();
}
public void OnLongClick(View view, int position)
{
Android.Widget.Toast.MakeText(_context, "Long press on position :" + position,
Android.Widget.ToastLength.Short).Show();
}
}
}
|
dabd33cd950b2801fcf288c93a07de9363cde5fe
|
C#
|
gmarino2048/senior-project-s20
|
/Main Game/Assets/Scripts/Visuals/Flicker.cs
| 2.78125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Random = System.Random;
namespace Visuals
{
public class Flicker : MonoBehaviour
{
public int randomSeed = 2000;
public int numberPrimes = 20;
public float flickerSpeed = 1.0f;
public float maxFlickerDuration = 0.5f;
private System.Random _random;
private List<Light> _campfireLights;
private List<float> _lightIntensity;
private List<int> _primes;
private List<FlickerInterval> _intervals;
private List<float> _nextFlicker;
class FlickerInterval
{
private Light light { get; }
private float interval { get; }
private float counter { get; set; }
private readonly float _maxFlickerDuration;
private readonly Random _random;
private const float rampTime = 0.05f;
public FlickerInterval(Light light, float interval, float maxFlickerDuration, Random random = null)
{
this.light = light;
this.interval = interval;
counter = 0;
_maxFlickerDuration = maxFlickerDuration;
_random = random ?? new Random();
}
public IEnumerator Increment(float deltaTime)
{
counter += deltaTime;
if (counter > interval)
{
counter = 0;
yield return DoFlicker();
}
}
private IEnumerator DoFlicker()
{
var duration = _maxFlickerDuration * (float)_random.NextDouble();
var currentIntensity = light.intensity;
var finalIntensity = currentIntensity * 0.75f;
yield return RampDown(currentIntensity, finalIntensity);
yield return new WaitForSeconds(duration);
yield return RampUp(finalIntensity, currentIntensity);
// Need to set this so because the scene just keeps getting dimmer and dimmer
light.intensity = currentIntensity;
}
private IEnumerator RampDown(float initialIntensity, float finalIntensity)
{
if (initialIntensity < finalIntensity)
{
yield return RampUp(initialIntensity, finalIntensity);
}
else
{
var currentIntensity = initialIntensity;
while (currentIntensity > finalIntensity)
{
var span = initialIntensity - finalIntensity;
var decAmount = span * (Time.deltaTime / rampTime);
light.intensity -= decAmount;
currentIntensity -= decAmount;
yield return new WaitForEndOfFrame();
}
}
}
private IEnumerator RampUp(float initialIntensity, float finalIntensity)
{
if (initialIntensity > finalIntensity)
{
yield return RampDown(initialIntensity, finalIntensity);
}
else
{
var currentIntensity = initialIntensity;
while (currentIntensity < finalIntensity)
{
var span = finalIntensity - currentIntensity;
var incAmount = span * (Time.deltaTime / rampTime);
light.intensity += incAmount;
currentIntensity += incAmount;
yield return new WaitForEndOfFrame();
}
}
}
}
// Start is called before the first frame update
void Start()
{
_random = new System.Random(randomSeed);
_campfireLights = new List<Light>(GetCampfireLights());
_lightIntensity = new List<float>();
foreach (var light in _campfireLights)
{
_lightIntensity.Add(light.intensity);
}
// Avoid light flicker overlapping
if (numberPrimes < _campfireLights.Count * 2)
numberPrimes = _campfireLights.Count * 2;
_primes = new List<int>(GetPrimes(numberPrimes));
// Select primes from the list for each light
_intervals = new List<FlickerInterval>();
foreach (var campfireLight in _campfireLights)
{
var interval = GetInterval(_primes, _random);
_intervals.Add(new FlickerInterval(
campfireLight,
interval,
maxFlickerDuration,
_random));
}
}
// Update is called once per frame
void Update()
{
foreach (var flickerInterval in _intervals)
{
StartCoroutine(flickerInterval.Increment(Time.deltaTime * flickerSpeed));
}
}
public void ResetIntensity()
{
StopAllCoroutines();
for (var i = 0; i < _campfireLights.Count; i++)
{
var light = _campfireLights[i];
light.intensity = _lightIntensity[i];
}
}
// Get the interval for each light
private float GetInterval(List<int> primes, Random random = null)
{
random = random ?? new Random();
var selected = new SortedSet<int>(RandomSelect(2, primes, random));
// List of primes should be unique so standard removal should work
foreach (var item in selected)
{
primes.Remove(item);
}
return selected.Max / (float) selected.Min;
}
// Fetch all the point lights in the object
private IEnumerable<Light> GetCampfireLights()
{
return gameObject.GetComponentsInChildren<Light>().Where(
light => light.type == LightType.Point);
}
// Get a list of all the intervals that shouldn't overlap
private IEnumerable<int> GetPrimes(int numPrimes)
{
int count;
var primeList = new List<int>();
int nextPrime = 3;
while ((count = primeList.Count) <= numPrimes)
{
switch (count)
{
case 0:
primeList.Add(2);
break;
case 1:
primeList.Add(3);
break;
default:
if (IsPrime(nextPrime, primeList))
{
primeList.Add(nextPrime);
}
break;
}
nextPrime += 2;
}
return primeList;
}
// Check to see if a number is prime given a list of other primes
private bool IsPrime(int candidate, IEnumerable<int> previousValues)
{
var sqrt = (int) Math.Sqrt(candidate);
foreach (var prime in previousValues)
{
if (prime > sqrt) return true;
if (candidate % prime == 0) return false;
}
return true;
}
// Select `count` elements randomly from list
private IEnumerable<T> RandomSelect<T>(int count, IList<T> list, System.Random random = null)
{
var retVal = new List<T>(count);
var randomImpl = random ?? new System.Random();
for (var i = 0; i < count; i++)
{
var idx = random.Next(list.Count());
retVal.Add(list[idx]);
list.RemoveAt(idx);
}
return retVal;
}
}
}
|
edd66ef84ea4a01588980595bd0201b80ecf2084
|
C#
|
schifflee/LightFramework.Net
|
/LightFramework.Web/Helper/RestHelper.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
namespace LightFramework.Web
{
public class RestHelper
{
public static string Get(Uri uri)
{
string text;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
text = new StreamReader(responseStream).ReadToEnd();
}
response.Close();
return text;
}
catch(Exception ex)
{
return ex.Message;
}
}
public static string Post<T>(Uri uri, T dto)
{
string text = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
using (Stream requestStream = request.GetRequestStream())
{
new DataContractJsonSerializer(dto.GetType()).WriteObject(requestStream, dto);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
text = new StreamReader(responseStream).ReadToEnd();
}
response.Close();
return text;
}
catch(Exception ex)
{
return ex.Message;
}
}
}
}
|
3bc1f1b1511f2fb5b045411c72245a2b413979e3
|
C#
|
arsiarola/2dcsgo
|
/Assets/Scripts/Recordable/TransformRecordable.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Recordable
{
/// <summary>
/// Inherits recordable and extends it to include the position and rotation
/// </summary>
public class TransformRecordable : Recordable
{
/// <summary>
/// Base method + adds the transform component to the param recordableState.
/// </summary>
/// <param name="state">RecordableState which needs Transform data added to it.</param>
protected override void AddProperties(RecordableState.RecordableState state)
{
base.AddProperties(state);
state.AddProperty<RecordableState.Transform>();
}
}
}
|
7afc428217e58d073fab40cff390bee917a9fefa
|
C#
|
gsenthilmca/MovieTitles
|
/MovieTitles/Program.cs
| 3.25
| 3
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MovieTitles
{
public class Movie
{
public string Title { get; set; }
public int Year { get; set; }
public string imdbID { get; set; }
}
public class MovieSearch
{
public string page { get; set; }
public int per_page { get; set; }
public int total { get; set; }
public int total_pages { get; set; }
public List<Movie> data { get; set; }
}
public class Solution
{
public static void Main(string[] args)
{
var title = Console.ReadLine();
string[] movieTtiles = getMovieTitles(title);
foreach(var name in movieTtiles)
{
Console.WriteLine(name);
}
Console.ReadLine();
}
private static string[] getMovieTitles(string title)
{
string movieSearchEndpoint = "https://jsonmock.hackerrank.com/api/movies/search/?Title={0}&page={1}";
List<string> movieTitles = new List<string>();
var data = HttpGet(string.Format(movieSearchEndpoint, title, "1"));
var searchResults = JsonConvert.DeserializeObject<MovieSearch>(data);
AddToMovieTitles(searchResults, ref movieTitles);
while (Convert.ToInt32(searchResults.page) < searchResults.total_pages)
{
data = HttpGet(string.Format(movieSearchEndpoint, title, Convert.ToInt32(searchResults.page) + 1));
searchResults = JsonConvert.DeserializeObject<MovieSearch>(data);
AddToMovieTitles(searchResults,ref movieTitles);
}
return movieTitles.OrderBy(t=>t).ToArray();
}
private static void AddToMovieTitles(MovieSearch data, ref List<string> movieTitles)
{
foreach(var movie in data.data)
{
movieTitles.Add(movie?.Title);
}
}
private static string HttpGet(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string data;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
data = reader.ReadToEnd();
}
return data;
}
}
}
|
e62218c8bafcf0b7d7cdfd1a0bcd96026a83867c
|
C#
|
cyber-secured/cyber-secured
|
/PROJ-4900---Cyber-Security-Game-master/Assets/OLD/PopupManager.cs
| 2.78125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PopupManager : MonoBehaviour
{
public GameObject text_box; //in inspector drag a panel object
public Text text_in_box; //in inspector drag the corresponding text
public TextAsset text_file; //to grab a text file
public string[] text_lines; //to put dialogue into an array
public int current_line; //current line of dialogue
public int end_at_line; //end of dialogue
float elapsed_time; //keep track of time for lerp
// Use this for initialization
void Start()
{
//import the text into the text_lines array
if(text_file != null)
{
text_lines = (text_file.text.Split('\n')); //split up the text file between new lines
}
//sets the number of lines of dialogue til the end
if(end_at_line == 0)
{
end_at_line = text_lines.Length - 1;
}
//text_box.transform.localScale = new Vector2(1.0f, 1.0f);
}
// Update is called once per frame
void Update()
{
//changes the text in the textbox to display the current line
text_in_box.text = text_lines[current_line];
//when there is no more text
if(current_line == end_at_line)
{
//move text elements out
LerpShrink(text_box);
} else {
//move text elements in
LerpExpand(text_box);
}
//input for next line
if(Input.GetKeyDown(KeyCode.Return))
{
elapsed_time = 0; //reset time for lerp
if(current_line != end_at_line)
{
current_line++; //go to the next line
}
}
}
void FixedUpdate()
{
}
//TODO: can do polymorphism better probably
//Changes the scale of a game object smoothly
void LerpScale(GameObject g, Vector2 end, float ease)
{
elapsed_time += Time.deltaTime;
Vector2 current_scale = g.transform.localScale;
g.transform.localScale = Vector2.Lerp(current_scale, end, ease * elapsed_time);
}
void LerpExpand(GameObject g)
{
Vector2 current_pos = g.transform.position;
LerpScale(g, new Vector2(1.0f, 1.0f), 0.5f);
}
void LerpShrink(GameObject g)
{
Vector2 current_pos = g.transform.position;
LerpScale(g, new Vector2(0.0f, 0.0f), 0.8f);
}
}
|
a7e9af8cede8f3019171ca028af0d15bf80237ec
|
C#
|
shendongnian/download4
|
/first_version_download2/219795-17186490-42388469-2.cs
| 2.765625
| 3
|
public async Task<IRandomAccessStream> BeepBeep(int Amplitude, int Frequency, int Duration)
{
double A = ((Amplitude * (System.Math.Pow(2, 15))) / 1000) - 1;
double DeltaFT = 2 * Math.PI * Frequency / 44100.0;
int Samples = 441 * Duration / 10;
int Bytes = Samples * 4;
int[] Hdr = { 0X46464952, 36 + Bytes, 0X45564157, 0X20746D66, 16, 0X20001, 44100, 176400, 0X100004, 0X61746164, Bytes };
using (MemoryStream MS = new MemoryStream(44 + Bytes))
{
using (BinaryWriter BW = new BinaryWriter(MS))
{
for (int I = 0; I < Hdr.Length; I++)
{
BW.Write(Hdr[I]);
}
for (int T = 0; T < Samples; T++)
{
short Sample = System.Convert.ToInt16(A * Math.Sin(DeltaFT * T));
BW.Write(Sample);
BW.Write(Sample);
}
BW.Flush();
MS.Seek(0, SeekOrigin.Begin);
var stream = await ConvertToRandomAccessStream(MS);
return stream;
}
}
}
public async Task<IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
{
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
var dw = new DataWriter(outputStream);
var task = Task.Factory.StartNew(() => dw.WriteBytes(memoryStream.ToArray()));
await task;
await dw.StoreAsync();
await outputStream.FlushAsync();
return randomAccessStream;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var beepStream = await BeepBeep(200, 3000, 250);
mediaElement1.SetSource(beepStream, string.Empty);
mediaElement1.Play();
}
|
430ea32cad306bafcdc373a923d21b42f47759cd
|
C#
|
spungemonkey/MUC
|
/Tammaro, Michele. S0908639. Mobile and Ubiquitous Computing Coursework/MappingApplication/MappingApplication/Pages/Diary.xaml.cs
| 2.6875
| 3
|
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 System.IO.IsolatedStorage;
namespace MappingApplication
{
public partial class Diary : PhoneApplicationPage
{
//need to instantiate an instance of IsolatedStorageSettings to store
//data on a WP8 app
IsolatedStorageSettings isoSettings = IsolatedStorageSettings.ApplicationSettings;
public Diary()
{
//constructor
InitializeComponent();
loadDiary();
}
private void saveDiary_Click(object sender, RoutedEventArgs e)
{
//saves the diary.
//Checks to see if an Isolated Storage file exists
//if it does not it creates a new one and inserts the
//inputted text into it.
if (!isoSettings.Contains("uDiary"))
{
isoSettings.Add("uDiary", userDiary.Text);
}
else
{
//if the file exists data is stored
isoSettings["uDiary"] = userDiary.Text;
}
//feedback shown to the user to inform them changes have been saved
MessageBox.Show("Diary Saved", "Saved", MessageBoxButton.OK);
//.Save() method called to save the data
isoSettings.Save();
}
private void deleteDiary_Click(object sender, RoutedEventArgs e)
{
//creates a message box that prompts the user for input
MessageBoxResult delIsoSto = MessageBox.Show("Are you sure you want to delete your diary?", "Warning", MessageBoxButton.OKCancel);
//if the user accepts the message box the file is deleted and
//the text inputted into the text box is deleted.
//feedback is shown
if (delIsoSto == MessageBoxResult.OK && isoSettings.Contains("uDiary"))
{
IsolatedStorageSettings.ApplicationSettings.Remove("uDiary");
userDiary.Text = "";
MessageBox.Show("Diary Successfully Deleted", "Deleted", MessageBoxButton.OK);
}
else
{
//Do nothing
}
}
private void loadDiary()
{
//method is run when diary view is open.
//if file exists the text is loaded into the user diary
if (isoSettings.Contains("uDiary"))
{
userDiary.Text += IsolatedStorageSettings.ApplicationSettings["uDiary"] as string;
}
else
{
userDiary.Text = "";
}
}
private void map_Click(object sender, EventArgs e)
{
//method to return to tge map view.
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
private void prevHosts_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Pages/hosts.xaml", UriKind.Relative));
}
}
}
|
00ec7429feab3ff782e7c3c78e00a20f6f635eca
|
C#
|
ArmanPoghosyan2001/Store
|
/Store.DAL/Category/CategoryContext.cs
| 2.796875
| 3
|
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace Store.DAL.Category
{
public class CategoryContext
{
public List<CategoryModel> GetCategories()
{
string connectionString = @"Data Source=DESKTOP-VJMA770;Initial Catalog=Market;Integrated Security=True";
string sqlExpression = "Select * from Categories";
CategoryModel category = new CategoryModel();
List<CategoryModel> categories = new List<CategoryModel>();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
category.Id = reader.GetInt32(0);
category.CategoryName = reader.GetString(1);
categories.Add(category);
}
}
reader.Close();
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
return categories;
}
}
}
|
bf40548355739031e06907400196137bae5e6414
|
C#
|
DmitryiDerepovskyi/Port
|
/ManagerPort.SupportClass/ValidateInputData.cs
| 3.203125
| 3
|
using System;
using System.Text.RegularExpressions;
namespace ManagerPort.SupportClass
{
public static class ValidateInputData
{
public static int InputId()
{
var id = 0;
var isId = false;
while (!isId)
{
isId = Int32.TryParse(Console.ReadLine(), out id);
isId = isId && (id > 0);
if (!isId)
Console.WriteLine("Incorrect data!");
}
return id;
}
public static int InputNumber()
{
var number = 0;
var isNumber = false;
while (!isNumber)
{
isNumber = Int32.TryParse(Console.ReadLine(), out number);
isNumber = isNumber && (number > 0);
if (!isNumber)
Console.WriteLine("Incorrect data!");
}
return number;
}
public static string InputName()
{
var name = String.Empty;
var pattern = @"\w";
var regex = new Regex(pattern);
var isWrongName = true;
while (isWrongName)
{
name = Console.ReadLine();
isWrongName = !regex.IsMatch(name, 0);
if (isWrongName)
Console.WriteLine("Incorrect data!");
}
return name;
}
public static DateTime InputDate()
{
var dateTime = new DateTime();
var isWrongDate = true;
while (isWrongDate)
{
var date = Console.ReadLine();
isWrongDate = !DateTime.TryParse(date, out dateTime);
if (isWrongDate)
Console.WriteLine("Incorrect data!");
}
return dateTime;
}
public static int? ConvertToNullableInt(string str)
{
if (str == String.Empty)
return null;
try
{
return int.Parse(str);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
}
|
40a0d37ae0e50d692e7fdb307e405e42b6cb5b99
|
C#
|
AntoineMer/Papyrus-master
|
/dllConnec/connection.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace dllConnec
{
public class Connection
{
public SqlConnection DBConnection;
public Connection()
{
}
public Connection(string _nameDB, string _userId, string _dataSource, string _password)
{
DBConnection = new SqlConnection();
SqlConnectionStringBuilder stringBuilder;
stringBuilder = new SqlConnectionStringBuilder();
stringBuilder.IntegratedSecurity = false;
stringBuilder.InitialCatalog = _nameDB;
stringBuilder.UserID = _userId;
stringBuilder.DataSource = _dataSource;
stringBuilder.Password = _password;
DBConnection.ConnectionString = (stringBuilder.ConnectionString);
}
public void Connect()
{
DBConnection.Open();
}
public SqlDataReader GetDataReader(string _commandText, List<string> _parameter, List<string> _value)
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = DBConnection;
command.CommandText = _commandText;
if (_value == null)
{
command.CommandType = CommandType.Text;
return command.ExecuteReader();
}
else
{
command.Parameters.Clear();
command.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < _parameter.Count; i++)
{
command.Parameters.Add(new SqlParameter(_parameter[i], _value[i]));
}
return command.ExecuteReader();
}
}
}
}
}
|
a8f439330b875d121cd28601e64f6a5a46ead654
|
C#
|
Plamen-Angelov/C-sharp-Advanced
|
/Generics/EX08Threeuple/Tuple.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace EX07Tuple
{
public class Tuple <T, V, U>
{
public T Item1 { get; set; }
public V Item2 { get; set; }
public U Item3 { get; set; }
public Tuple()
{
}
public Tuple(T item1, V item2, U item3)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
}
}
}
|
b2b4d2d5157a838f712e5c0ff633333ae1495545
|
C#
|
JZO001/Forge
|
/.Legacy/Forge.Base/Collections/IEnumeratorSpecialized.cs
| 3.03125
| 3
|
/* *********************************************************************
* Date: 18 Apr 2012
* Created by: Zoltan Juhasz
* E-Mail: forge@jzo.hu
***********************************************************************/
using System.Collections.Generic;
namespace Forge.Collections
{
/// <summary>
/// IEnumerator specialized (mutable enumerator) interface
/// </summary>
/// <typeparam name="T">Generic type</typeparam>
public interface IEnumeratorSpecialized<T> : IEnumerator<T>
{
/// <summary>
/// Removes from the underlying collection the last element returned by the
/// iterator (optional operation). This method can be called only once per
/// call to <tt>next</tt>. The behavior of an iterator is unspecified if
/// the underlying collection is modified while the iteration is in
/// progress in any way other than by calling this method.
/// </summary>
void Remove();
/// <summary>
/// Determines whether has a next item in the enumerator.
/// </summary>
/// <returns>
/// <c>true</c> if this instance has next; otherwise, <c>false</c>.
/// </returns>
bool HasNext();
}
}
|
4a10dd77acabf1361cd6fb722ecfdb52503d7b35
|
C#
|
chaseedward/2015-Winter-IT-FDN-105
|
/Chase.Hu/Homework 4/Homework 4/Program.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homework_4
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 5, -2, 100, 12, 4, -5 };
Console.WriteLine(numbers.Max());
Console.WriteLine(numbers.Min());
Console.ReadLine();
}
}
}
|
521ff36ec9388a4bfe0018917ead437e47cab833
|
C#
|
snakeddp/CookieCore
|
/Cookie.IO/BigEndian.cs
| 3.09375
| 3
|
using System.Runtime.CompilerServices;
namespace Cookie.IO
{
internal static unsafe class BigEndian
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static short ReadInt16(byte* src)
{
return (short) ((src[0] << 8) | src[1]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int ReadInt32(byte* src)
{
return (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static long ReadInt64(byte* src)
{
return (uint) ((src[4] << 24) | (src[5] << 16) | (src[6] << 8)) | src[7] |
((long) ((src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]) << 32);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void WriteInt16(byte* dst, short value)
{
dst[0] = (byte) (value >> 8);
dst[1] = (byte) value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void WriteInt32(byte* dst, int value)
{
dst[0] = (byte) (value >> 24);
dst[1] = (byte) (value >> 16);
dst[2] = (byte) (value >> 8);
dst[3] = (byte) value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void WriteInt64(byte* dst, long value)
{
dst[0] = (byte) (value >> 56);
dst[1] = (byte) (value >> 48);
dst[2] = (byte) (value >> 40);
dst[3] = (byte) (value >> 32);
dst[4] = (byte) (value >> 24);
dst[5] = (byte) (value >> 16);
dst[6] = (byte) (value >> 8);
dst[7] = (byte) value;
}
}
}
|
34c48d61cf927954a30504157b0d6848eddabe37
|
C#
|
juhatkoiv/TwinStickSurvival
|
/Assets/Scripts/General/Game.cs
| 2.796875
| 3
|
using UnityEngine;
using UnityEngine.Events;
/*
* A general class for the Game.
* - spawns player
* - keeps count of kills
* - handles Quitting and some events
*/
public class Game : MonoBehaviour
{
// TODO - find more suitable place for these
public static UnityEvent EnemyKilledEvent = new UnityEvent();
public static UnityEvent PlayerKilledEvent = new UnityEvent();
private static void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
[Header("Mandatory references")]
[SerializeField]
private GameObject playerPrototype;
[SerializeField]
private GameObject playerSpawnPointGameObject;
[Header("HUD")]
[SerializeField]
private GameObject hudGameObject;
private HUD hud;
private int totalKillCount;
private void Awake()
{
if (!playerPrototype || !playerSpawnPointGameObject)
{
Debug.LogError("Some mandatory GameObjects are not defined. Quitting...");
Quit();
}
Instantiate(playerPrototype, playerSpawnPointGameObject.transform.position, Quaternion.identity);
EnemyKilledEvent.AddListener(OnEnemyKilled);
PlayerKilledEvent.AddListener(OnPlayerKilled);
hud = hudGameObject.GetComponent<HUD>();
}
private void OnDestroy()
{
EnemyKilledEvent.RemoveListener(OnEnemyKilled);
PlayerKilledEvent.RemoveListener(OnPlayerKilled);
}
private void OnEnemyKilled()
{
if (!hud)
{
Debug.LogError("HUD misconfiger.");
return;
}
totalKillCount++;
hud.SetKillCount(totalKillCount);
}
private void OnPlayerKilled()
{
Debug.Log("YOU DIED - Score: " + totalKillCount.ToString());
Quit();
}
}
|
8f1b6d15830f067e1a1318618fd0c45652148450
|
C#
|
smartpcr/DataStructure
|
/UnitTests/HeapTest.cs
| 3.046875
| 3
|
using System.Collections.Generic;
using System.Diagnostics;
using DataStructure.Heaps;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests
{
[TestClass]
public class HeapTest
{
[TestMethod]
public void BuildMinHeap()
{
List<int> items = new List<int>()
{
11,28,314,3,156,561,401,359,271
};
var minHeap = new MinHeap<int>(items);
Assert.AreEqual(3, minHeap.GetTop());
var itemRemoved = minHeap.ExtractDominating();
Assert.AreEqual(3, itemRemoved);
Assert.AreEqual(11, minHeap.GetTop());
var maxHeap = new MaxHeap<int>(items);
Assert.AreEqual(561, maxHeap.GetTop());
itemRemoved = maxHeap.ExtractDominating();
Assert.AreEqual(561, itemRemoved);
Assert.AreEqual(401, maxHeap.GetTop());
}
}
}
|
4f20996ae1732e0cbddae90f6d776f25628a9a48
|
C#
|
maki1997/PlatformeZaObjektnoProgramiranje
|
/NOVI PROJEKAT SF 12 GUI/SF-12-2016/SF-12-2016/Model/DodatnaUsluga.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SF_12_2016.Model
{
[Serializable]
public class DodatnaUsluga : INotifyPropertyChanged
{
public enum Prikaz
{
Naziv,
Cena,
};
public enum NacinSortiranja
{
asc,
desc,
};
private int id;
public int Id
{
get { return id; }
set
{
id = value;
OnPropertyChanged("Id");
}
}
private string naziv;
public string Naziv
{
get { return naziv; }
set { naziv = value; OnPropertyChanged("Naziv"); }
}
private double cena;
public event PropertyChangedEventHandler PropertyChanged;
public double Cena
{
get { return cena; }
set { cena = value; OnPropertyChanged("Cena"); }
}
private bool obrisan;
public bool Obrisan
{
get { return obrisan; }
set { obrisan = value; OnPropertyChanged("Obrisan"); }
}
public object Clone()
{
return new DodatnaUsluga()
{
id = Id,
naziv = Naziv,
cena = Cena,
obrisan = Obrisan,
};
}
public static DodatnaUsluga GetById(int id)
{
foreach (var du in Projekat.Instance.dodaci)
{
if (du.Id == id)
{
return du;
}
}
return null;
}
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#region Database
public static ObservableCollection<DodatnaUsluga> GetAll()
{
var du = new ObservableCollection<DodatnaUsluga>();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM DodatnaUsluga WHERE Obrisan=0";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "DodatnaUsluga"); // Query se izvrsava
foreach (DataRow row in ds.Tables["DodatnaUsluga"].Rows)
{
var d = new DodatnaUsluga();
d.Id = int.Parse(row["Id"].ToString());
d.Naziv = row["Naziv"].ToString();
d.Obrisan = bool.Parse(row["Obrisan"].ToString());
d.Cena = double.Parse(row["Cena"].ToString());
du.Add(d);
}
return du;
}
}
public static DodatnaUsluga Create(DodatnaUsluga d)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString))
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = $"Insert into DodatnaUsluga (Naziv,Obrisan,Cena) Values(@Naziv,@Obrisan,@Cena);";//razmisli o ne unosenju obrisan pri dodavanju vec to u bazi
cmd.CommandText += "Select scope_identity();";
cmd.Parameters.AddWithValue("Naziv", d.Naziv);
cmd.Parameters.AddWithValue("Obrisan", d.Obrisan);
cmd.Parameters.AddWithValue("Cena", d.Cena);
int newId = int.Parse(cmd.ExecuteScalar().ToString()); //es izvrsava query
d.Id = newId;
}
Projekat.Instance.dodaci.Add(d);//obrati paznju {azurira i stanje modela}
return d;
}
public static void Update(DodatnaUsluga d)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString))
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "Update DodatnaUsluga set Naziv=@Naziv,Obrisan=@Obrisan,Cena=@Cena where Id=@Id";
cmd.Parameters.AddWithValue("Id", d.Id);
cmd.Parameters.AddWithValue("Naziv", d.Naziv);
cmd.Parameters.AddWithValue("Obrisan", d.Obrisan);
cmd.Parameters.AddWithValue("Cena", d.Cena);
cmd.ExecuteNonQuery();
foreach (var du in Projekat.Instance.dodaci)
{
if (du.Id == d.Id)
{
du.Naziv = d.Naziv;
du.Obrisan = d.Obrisan;
du.Cena = d.Cena;
break;
}
}
}
}
public static void Delete(DodatnaUsluga d)
{
d.Obrisan = true;
Update(d);
}
public static ObservableCollection<DodatnaUsluga> Sort(Prikaz p, NacinSortiranja nn)
{
var du = new ObservableCollection<DodatnaUsluga>();
switch (p)
{
case Prikaz.Naziv:
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
if (nn == NacinSortiranja.asc)
{
cmd.CommandText = "SELECT * FROM DodatnaUsluga WHERE Obrisan=0 Order by Naziv";
}
else
{
cmd.CommandText = "SELECT * FROM DodatnaUsluga WHERE Obrisan=0 Order by Naziv desc";
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "DodatnaUsluga"); // Query se izvrsava
foreach (DataRow row in ds.Tables["DodatnaUsluga"].Rows)
{
var d = new DodatnaUsluga();
d.Id = int.Parse(row["Id"].ToString());
d.Naziv = row["Naziv"].ToString();
d.Obrisan = bool.Parse(row["Obrisan"].ToString());
d.Cena = double.Parse(row["Cena"].ToString());
du.Add(d);
}
}
break;
case Prikaz.Cena:
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
if (nn == NacinSortiranja.asc)
{
cmd.CommandText = "SELECT * FROM DodatnaUsluga WHERE Obrisan=0 Order by Cena";
}
else
{
cmd.CommandText = "SELECT * FROM DodatnaUsluga WHERE Obrisan=0 Order by Cena desc";
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "DodatnaUsluga"); // Query se izvrsava
foreach (DataRow row in ds.Tables["DodatnaUsluga"].Rows)
{
var d = new DodatnaUsluga();
d.Id = int.Parse(row["Id"].ToString());
d.Naziv = row["Naziv"].ToString();
d.Obrisan = bool.Parse(row["Obrisan"].ToString());
d.Cena = double.Parse(row["Cena"].ToString());
du.Add(d);
}
}
break;
}
return du;
}
public static ObservableCollection<DodatnaUsluga> Search(Prikaz p, String s)
{
var du = new ObservableCollection<DodatnaUsluga>();
switch (p)
{
case Prikaz.Naziv:
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM DodatnaUsluga WHERE Obrisan=0 and Naziv like '%'+@s+'%'";
cmd.Parameters.AddWithValue("s", s);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "DodatnaUsluga"); // Query se izvrsava
foreach (DataRow row in ds.Tables["DodatnaUsluga"].Rows)
{
var d = new DodatnaUsluga();
d.Id = int.Parse(row["Id"].ToString());
d.Naziv = row["Naziv"].ToString();
d.Obrisan = bool.Parse(row["Obrisan"].ToString());
d.Cena = double.Parse(row["Cena"].ToString());
du.Add(d);
}
}
break;
case Prikaz.Cena:
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["POP"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM DodatnaUsluga WHERE Obrisan=0 and Cena like '%'+@s+'%'";
cmd.Parameters.AddWithValue("s", s);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "DodatnaUsluga"); // Query se izvrsava
foreach (DataRow row in ds.Tables["DodatnaUsluga"].Rows)
{
var d = new DodatnaUsluga();
d.Id = int.Parse(row["Id"].ToString());
d.Naziv = row["Naziv"].ToString();
d.Obrisan = bool.Parse(row["Obrisan"].ToString());
d.Cena = double.Parse(row["Cena"].ToString());
du.Add(d);
}
}
break;
}
return du;
}
#endregion
}
}
|
64f45284771d24ba54ac252a56f2056f2a606d17
|
C#
|
john-oluwasanmi/VTest
|
/V.Test.Web.App/Repository/EmployeeRepository.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using V.Test.Web.App.Entities;
using V.Test.Web.App.Repository.Interface;
namespace V.Test.Web.App.Repository
{
public class EmployeeRepository : RepositoryBase<Employee>,
IEmployeeRepository
{
public EmployeeRepository(IConfiguration configuration, ILogger<Employee> logger)
: base(configuration, logger)
{
}
public override async Task<Employee> GetAsync(int id)
{
try
{
using (var context = new VTestsContext(OptionsBuilder.Options))
{
var entity = await context.Set<Employee>()
.Where(x => x.Id == id && (x.IsDeleted == null || x.IsDeleted == false))
.Include(r => r.Organisation)
.SingleOrDefaultAsync();
var typeName = Entity?.GetType()?.Name;
VLogger.LogInformation($" Successfully retrieved {typeName} with the Id: '{entity?.Id} ");
return entity;
}
}
catch (Exception ex)
{
LogError(ex, null, id);
throw ex;
}
}
public async Task<List<Employee>> ListByOrganisationAsync(int organisationId, int pageNumber)
{
try
{
CurrentPageNumber = pageNumber;
using (var context = new VTestsContext(OptionsBuilder.Options))
{
List<Employee> result = await context.Set<Employee>().AsNoTracking()
.Where(e => (e.IsDeleted == false || e.IsDeleted == null)
&& e.OrganisationId == organisationId)
.Include(r=>r.Organisation)
.OrderBy(r => r.Id)
.Skip(SkippedDbRecordSize)
.Take(MaxPageSize)
.ToListAsync();
var typeName = Entity?.GetType()?.Name;
VLogger.LogInformation($" Successfully retrieved {typeName}'s List with page number {pageNumber} ");
CurrentPageNumber = 0;
return result;
}
}
catch (SqlNullValueException s)
{
LogError(s, null, pageNumber);
throw s;
}
catch (Exception ex)
{
LogError(ex, null, pageNumber);
throw ex;
}
}
}
}
|
d3556529cc6899d8d3648487913d257513d4a3de
|
C#
|
nullsquid/ANOMIA
|
/Assets/Scripts/EnemySensor.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySensor : MonoBehaviour {
public Vector3 directionToSearch = new Vector3(0f, 0f, 2f);
Node _nodeToSearch;
Board _gameBoard;
bool _foundPlayer = false;
public bool FoundPlayer
{
get
{
return _foundPlayer;
}
}
// Use this for initialization
void Awake () {
_gameBoard = Object.FindObjectOfType<Board>().GetComponent<Board>();
}
public void UpdateSensor(Node enemyNode) {
Vector3 worldSpacePositionToSearch = transform.TransformVector(directionToSearch) + transform.position;
if(_gameBoard != null) {
_nodeToSearch = _gameBoard.FindNodeAt(worldSpacePositionToSearch);
//Checks to see if the adjacent node is linked to the one the enemy is on
if(!enemyNode.LinkedNodes.Contains(_nodeToSearch)) {
_foundPlayer = false;
return;
}
if(_nodeToSearch == _gameBoard.PlayerNode) {
_foundPlayer = true;
}
}
}
}
|
62baba4a93fa9020b8f4ad0e1e564e66d558d53d
|
C#
|
PhilhouseT/PhilToDo
|
/PhilToDo/DataLoadHandler.cs
| 2.953125
| 3
|
using System;
using System.IO;
using System.Windows;
using System.Xml.Serialization;
namespace PhilToDo
{
public static class DataFileHandler
{
// Check that the target directory for the data file exists. Create it if not.
public static bool CheckDirectory()
{
try
{
DirectoryInfo di = Directory.CreateDirectory(Global.fileDirectory);
}
catch (Exception e)
{
String message = String.Format("Error creating save file directory: {0} - {1}. Application will close.",
e.ToString(),
Global.fileDirectory);
MessageBox.Show(message, "Error", MessageBoxButton.OK);
return false;
}
return true;
}
public static bool LoadTaskList(ref TaskList taskList)
{
bool success = true;
taskList = new();
if (File.Exists(Global.fileLocation))
{
XmlSerializer serializer = new XmlSerializer(taskList.GetType());
StreamReader streamReader = new(Global.fileLocation);
try
{
taskList = (TaskList)serializer.Deserialize(streamReader);
streamReader.Close();
}
catch (System.InvalidOperationException e)
{
streamReader.Close();
success = HandleLoadError(e);
}
}
return success;
}
// Handles an exception having been thrown in loading from the data file.
private static bool HandleLoadError(Exception e1)
{
string message = String.Format("Error importing existing XML data: {0}\nDelete file? This will erase all existing data.", e1.Message);
MessageBoxResult result = MessageBox.Show(message, Global.errorText, MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
try
{
File.Delete(Global.fileLocation);
}
catch (Exception e2)
{
MessageBox.Show(String.Format("Error deleting file: {0}", e2.Message), Global.errorText, MessageBoxButton.OK);
return false;
}
return true;
}
else
{
message = String.Format("You will need to attempt to repair the XML file manually: {0}", Global.fileLocation);
MessageBox.Show(message, Global.errorText, MessageBoxButton.OK);
return false;
}
}
}
}
|
2e13623c510b80f4c00c9a389279a20ed849b3d8
|
C#
|
ChipDTIS/Mitsubishi
|
/NC20.Web/JwtHelper.cs
| 2.703125
| 3
|
using Jose;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NC20.Web
{
public class JwtHelper
{
public static readonly string jwtSecretKey = "CBPTSecretKey";
public static string CreateJwtToken(string accessToken, DateTime expired)
{
var payload = new Dictionary<string, object>()
{
["token"] = accessToken,
["exp"] = string.Format("{0:yyyyMMdd", expired)
};
var secretKey = Encoding.UTF8.GetBytes(jwtSecretKey);
var token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
return token;
}
public static string Decode(string jwt)
{
var secretKey = Encoding.UTF8.GetBytes(jwtSecretKey);
var json = JWT.Decode(jwt, secretKey);
return json;
}
}
}
|
2c0a724c6f9ff0eb04fd8501003d2fef0f9cd5ca
|
C#
|
srimani75/TwitterApp
|
/StepWise/Apps/WebUW3/StepwiseWebClient/StepwiseWebClient/BLL/Common.cs
| 2.75
| 3
|
using System;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Xml; //used for xml dom parsing
using System.Xml.XPath;
using System.Reflection;
using Optum.StepWise.WebClient.BE;
using Optum.StepWise.WebClient.BE.Enums;
using Optum.StepWise.Common.Logging;
namespace Optum.StepWise.WebClient.BLL
{
/// <summary>
/// Summarize the purpose of the class here.
/// </summary>
public class Common
{
#region Constants
#endregion
#region Type Definitions
#endregion
#region Enumerations
#endregion
#region Public Properties
#endregion
#region Public Variables
#endregion
#region Protected Variables
#endregion
#region Private Variables
private static ISystemLogger _log = Logger.GetSystemLogger(new SystemLogContext { Context = LoggingContext.UnderwritingClient, LoggerName = "Common" });
#endregion
#region Event Handlers
#endregion
#region Public Methods
//Constructor
public Common()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Used to chech if a string is a Whole Number (Number >= 0). This can be used to ensure
/// a string can be cast to an integer before the cast and not raise an error.
/// </summary>
/// <param name="TestValue">The string to be tested</param>
/// <returns>True if the string contains text that is a whole number, false otherwise.</returns>
public static bool IsWholeNumber(string TestValue)
{
Regex Pattern = new Regex("[^0-9]");
return !Pattern.IsMatch(TestValue);
}
/// <summary>
/// Used to check for error messages from SW Engine.
/// If an error is encountered in the XML, the function returns true and sets the error message.
/// If an error is generated parsing the XML, the error is thrown to the caller.
/// </summary>
/// <param name="doc">True if error else false</param>
/// <returns></returns>
public static bool IsError(System.Xml.XmlDocument doc, out string ErrMsg)
{
ErrMsg = string.Empty;
//bool Err;
try
{
if (doc.GetElementsByTagName("Error").Count > 0)
{
//Error returned from the web service
//Check to see that the error string is set to true. If false ignore and do not set error
bool Err = (doc.GetElementsByTagName("Error").Item(0).InnerText.ToUpper() == "TRUE") ? true : false;
if (Err)
{
//Get the error string and set the error message in session
ErrMsg = doc.GetElementsByTagName("ErrorMessage").Item(0).InnerText;
return true;
}
else
return false;
}
else
return false;
}
catch (Exception ex)
{
if (_log.IsErrorEnabled) _log.Error("Error parsing xml from Engine.", ex);
throw ex;
}
}
/// <summary>
/// Used to check for error messages from SW Engine.
/// If an error is encountered in the XML, the function returns true and sets the error message.
/// If an error is generated parsing the XML, the error is thrown to the caller.
/// </summary>
/// <param name="doc">True if error else false</param>
/// <returns></returns>
public static bool IsError(string xml, out string errMessage)
{
System.Xml.XmlDocument doc = new XmlDocument();
errMessage = string.Empty;
if (xml == string.Empty)
return false;
try
{
doc.XmlResolver = null;
doc.LoadXml(xml);
return IsError(doc,out errMessage);
}
catch (Exception ex)
{
//Not valid xml
if (_log.IsErrorEnabled) _log.Error("InvalidXml xml=" + xml, ex);
throw ex;
}
}
/// <summary>
/// Returns the error message imbedded in the xml document
/// </summary>
/// <param name="xml">The document that contains the error message</param>
/// <returns>The error message string</returns>
public static string GetErrorMessage(string xml)
{
XmlDocument Doc = new XmlDocument();
System.Xml.XmlNode ErrNode;
string ErrorMsg = "";
try
{
Doc.XmlResolver = null;
Doc.LoadXml(xml);
if (Doc.GetElementsByTagName("ErrorMessage").Count > 0)
{
ErrNode = Doc.GetElementsByTagName("ErrorMessage")[0];
ErrorMsg = ErrNode.InnerText;
}
else
{
//No error message found.
ErrorMsg = null;
}
}
catch (Exception ex)
{
if (_log.IsErrorEnabled) _log.Error("Error getting error message from xml", ex);
throw ex;
}
return ErrorMsg;
}
/// <summary>
/// Returns the error number if an error number is specified in the xml.
/// If no error number, then 0 is returned
/// </summary>
/// <param name="xml">The document that contains the error number</param>
/// <returns>The error number</returns>
public static int GetErrorNumber(string xml)
{
XmlDocument Doc = new XmlDocument();
System.Xml.XmlNode ErrNode;
int ErrorNumber = 0;
try
{
Doc.XmlResolver = null;
Doc.LoadXml(xml);
if (Doc.GetElementsByTagName("ErrorNumber").Count > 0)
{
ErrNode = Doc.GetElementsByTagName("ErrorNumber")[0];
ErrorNumber = int.Parse(ErrNode.InnerText);
}
}
catch (Exception ex)
{
if (_log.IsErrorEnabled) _log.Error("Error getting error number from xml", ex);
throw ex;
}
return ErrorNumber;
}
/// <summary>
/// Returns the enumeration for the type of engine error thrown by the engine
/// </summary>
/// <param name="xml">The document that contains the error number</param>
/// <returns>The Enumeration for errror types</returns>
public static Optum.StepWise.WebClient.BE.Enums.EngineErrorType GetEngineErrorType(string xml)
{
try
{
int MyErrorNumber = GetErrorNumber(xml);
switch (MyErrorNumber)
{
case 0:
return BE.Enums.EngineErrorType.NoError;
case 1:
return BE.Enums.EngineErrorType.SessionExpired;
default:
return BE.Enums.EngineErrorType.NoError;
}
}
catch (Exception ex)
{
if (_log.IsErrorEnabled) _log.Error("Error setting error Type", ex);
throw ex;
}
}
//Attempts to create an instance of the quote Info object
public static void SetQuoteInfo(string quoteInfo, ref QuoteInfo Q)
{
//First try to get the QuoteInfo xml out of session
System.Xml.XmlDataDocument QuoteInfoXml = new XmlDataDocument();
System.Xml.XmlNode QuoteNode;
System.Xml.XmlAttributeCollection QuoteAtts;
string Multi;
string Frozen;
string ReadOnly;
if (quoteInfo == null || string.Empty == null)
{ throw new Exception("Quote Information does not exist. Your session has expired?!"); }
QuoteInfoXml.XmlResolver = null;
QuoteInfoXml.LoadXml(quoteInfo);
//Get the first tab/item in the menu markup
QuoteNode = QuoteInfoXml.GetElementsByTagName("QuoteInfo")[0];
//Set properties of the QuoteInfo object based on attributes
QuoteAtts = QuoteNode.Attributes;
Q.Xml = quoteInfo;
Multi = (QuoteAtts.GetNamedItem("MultiSubgroup") == null) ? "False" : (string)QuoteAtts.GetNamedItem("MultiSubgroup").Value;
Frozen = (QuoteAtts.GetNamedItem("IsFrozen") == null) ? "False" : (string)QuoteAtts.GetNamedItem("IsFrozen").Value;
ReadOnly = (QuoteAtts.GetNamedItem("IsReadOnly") == null) ? "False" : (string)QuoteAtts.GetNamedItem("IsReadOnly").Value;
//Q.SystemDescription = QuoteAtts.GetNamedItem("SystemDesc").Value;
Q.FormulaDescription = QuoteAtts.GetNamedItem("FormulaDesc").Value;
Q.FormulaId = QuoteAtts.GetNamedItem("FormulaName").Value;
Q.IsMultiSubGroup = (Multi.ToUpper() == "TRUE") ? true : false;
Q.QuoteNumber = int.Parse(QuoteAtts.GetNamedItem("QuoteNumber").Value);
Q.QuoteId = QuoteAtts.GetNamedItem("QuoteID").Value;
Q.IsFrozen = (Frozen.ToUpper() == "TRUE") ? true : false;
Q.IsReadOnly = (ReadOnly.ToUpper() == "TRUE") ? true : false;
//Set Menu/Tabs
System.Xml.XmlNodeList Tabs;
Tabs = QuoteInfoXml.GetElementsByTagName("Item");
Q.MenuItems.Clear();
for (int i = 0; i < Tabs.Count; i++)
{
//Get each item from the xml doc and create a MenuItem
MenuItem mi = new MenuItem();
mi.Id = short.Parse(Tabs[i].Attributes.GetNamedItem("Id").InnerText);
mi.Text = Tabs[i].Attributes.GetNamedItem("Text").InnerText;
mi.Url = Tabs[i].Attributes.GetNamedItem("Url").InnerText;
Q.MenuItems.Add(mi);
}
//Set the tabId initially to the first tab in the list
if (Q.MenuItems.Count > 0)
Q.TabId = Q.MenuItems[0].Text;
//Set Triggers
System.Xml.XmlNodeList TriggerNodes;
TriggerNodes = QuoteInfoXml.GetElementsByTagName("Trigger");
for (int i = 0; i < TriggerNodes.Count; i++)
{
//Get each item from the xml doc and create a MenuItem
Trigger t = new Trigger();
t.Name = TriggerNodes[i].InnerText;
Q.Triggers.Add(t);
}
//Set the Categories
System.Xml.XmlNodeList CatNodes;
CatNodes = QuoteInfoXml.GetElementsByTagName("Category");
CategoryList c = new CategoryList();
for (int i = 0; i < CatNodes.Count; i++)
{
//Get each item from the xml doc and create a MenuItem
Category ci = new Category();
ci.Id = short.Parse(CatNodes[i].Attributes.GetNamedItem("CId").InnerText);
ci.Name = CatNodes[i].InnerText;
c.Add(ci);
}
//c.Count = (short)c.CategoryItem.Count;
Q.Categorys = c;
}
#endregion
#region Protected Methods
#endregion
#region Private Methods
#endregion
}
/// <summary>
/// Singleton class which loads product settings including version information
/// </summary>
public sealed class ProductSettings
{
// public ProductSettings()
// {}
private static readonly ProductSettings _instance = new ProductSettings();
private ProductSettings() { }
public static ProductSettings Instance
{
get
{
return _instance;
}
}
//Assembly Info
private static string _appVersion = null;
private static string _appProduct = null;
private static string _appCompany = null;
private static string _appDescription = null;
private static System.Version _version = null;
private static Assembly MyAssembly = Assembly.GetExecutingAssembly();
/// <summary>
/// Public getter for the application version from the assembly
/// </summary>
public static string AppVersion
{
get
{
if (_appVersion == null)
{
Assembly MyAssembly = Assembly.GetCallingAssembly();
_appVersion = MyAssembly.GetName().Version.ToString();
}
return _appVersion;
}
}
/// <summary>
/// Public getter for the application description from the assembly
/// </summary>
public static string AppDescription
{
get
{
if (_appDescription == null)
{
AssemblyDescriptionAttribute MyDescription = (AssemblyDescriptionAttribute)AssemblyDescriptionAttribute.GetCustomAttribute(MyAssembly, typeof(AssemblyDescriptionAttribute));
_appDescription = MyDescription.Description;
}
return _appDescription;
}
}
/// <summary>
/// Returns the verson object for the calling assembly
/// </summary>
public static Version Version
{
get
{
if (_version == null)
{
Assembly MyAssembly = Assembly.GetCallingAssembly();
_version = MyAssembly.GetName().Version;
}
return _version;
}
}
/// <summary>
/// Public getter for the application Company from the assembly
/// </summary>
public static string AppCompany
{
get
{
if (_appCompany == null)
{
AssemblyCompanyAttribute MyCompany = (AssemblyCompanyAttribute)AssemblyCompanyAttribute.GetCustomAttribute(MyAssembly, typeof(AssemblyCompanyAttribute));
_appCompany = MyCompany.Company;
}
return _appCompany;
}
}
/// <summary>
/// Public getter for the application Product from the assembly
/// </summary>
public static string AppProduct
{
get
{
if (_appProduct == null)
{
AssemblyProductAttribute MyProduct = (AssemblyProductAttribute)AssemblyProductAttribute.GetCustomAttribute(MyAssembly, typeof(AssemblyProductAttribute));
_appProduct = MyProduct.Product;
}
return _appProduct;
}
}
}
}
|
33e8ecacbe5c0ea2ab6f17cbafdbd1089ade417f
|
C#
|
luismoax/Competitive-Programming---luismo
|
/COJ_ACCEPTED/1601 Sequences of Digits.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//1601 Sequences of Digits
int tc = int.Parse(Console.ReadLine());
for (int c = 0; c < tc; c++)
{
string[] p = Console.ReadLine().Split(' ');
bool[] bArr = new bool[10];
List<int> lst = new List<int>();
//Recorro la lista de numeros
for (int i = 0; i < p.Length; i++)
{
//voy tomando los numeros de atras en adelante
int ax = int.Parse(p[p.Length - 1 - i]);
//Le doy patras en el arrelgo de bool
for (int j = 9; j >= 9 - ax; j--)
{
//Si tengo alguno marcado corro el limite
if (bArr[j]) ax++;
}
bArr[9 - ax] = true;
lst.Add(9 - ax);
}
Console.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}",lst[9],lst[8],lst[7],lst[6],lst[5],lst[4],lst[3],lst[2],lst[1],lst[0]);
}
Console.ReadLine();
}
}
}
|
65207e2ddcdad43233d9c7e9b640ce69ddeb01c4
|
C#
|
akarnokd/Reactive4.NET
|
/Reactive4.NET/operators/FlowableEnumerable.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Reactive4.NET.operators
{
internal sealed class FlowableEnumerable<T> : AbstractFlowableSource<T>
{
readonly IEnumerable<T> enumerable;
internal FlowableEnumerable(IEnumerable<T> enumerable)
{
this.enumerable = enumerable;
}
public override void Subscribe(IFlowableSubscriber<T> subscriber)
{
IEnumerator<T> enumerator = null;
bool b;
try
{
enumerator = enumerable.GetEnumerator();
b = enumerator.MoveNext();
}
catch (Exception ex)
{
try
{
enumerator?.Dispose();
}
catch (ObjectDisposedException)
{
// can't do much about this
}
subscriber.OnSubscribe(EmptySubscription<T>.Instance);
subscriber.OnError(ex);
return;
}
if (!b)
{
try
{
enumerator.Dispose();
}
catch (ObjectDisposedException)
{
// can't do much about this
}
subscriber.OnSubscribe(EmptySubscription<T>.Instance);
subscriber.OnComplete();
return;
}
if (subscriber is IConditionalSubscriber<T> s)
{
subscriber.OnSubscribe(new EnumerableConditionalSubscription(s, enumerator));
}
else
{
subscriber.OnSubscribe(new EnumerableSubscription(subscriber, enumerator));
}
}
internal abstract class AbstractEnumerableSubscription : IQueueSubscription<T>
{
protected readonly IEnumerator<T> enumerator;
protected long requested;
protected int cancelled;
bool done;
internal AbstractEnumerableSubscription(IEnumerator<T> enumerator)
{
this.enumerator = enumerator;
}
public void Cancel()
{
if (Interlocked.CompareExchange(ref cancelled, 1, 0) == 0)
{
Request(1);
}
}
public void Clear()
{
done = true;
try
{
enumerator.Dispose();
}
catch (ObjectDisposedException)
{
// can't do much about this
}
}
public bool IsEmpty()
{
return done;
}
public bool Offer(T item)
{
throw new InvalidOperationException("Should not be called!");
}
public bool Poll(out T item)
{
if (!done)
{
T v = enumerator.Current;
if (v == null)
{
throw new NullReferenceException("One of the IEnumerator items is null");
}
item = v;
done = !enumerator.MoveNext();
return true;
}
item = default(T);
return false;
}
public int RequestFusion(int mode)
{
return mode & FusionSupport.SYNC;
}
public void Request(long n)
{
if (n <= 0L)
{
throw new ArgumentOutOfRangeException(nameof(n));
}
if (SubscriptionHelper.AddRequest(ref requested, n) == 0)
{
OnRequest(n);
}
}
protected abstract void OnRequest(long n);
}
internal sealed class EnumerableSubscription : AbstractEnumerableSubscription
{
readonly IFlowableSubscriber<T> actual;
internal EnumerableSubscription(IFlowableSubscriber<T> actual, IEnumerator<T> enumerator) : base(enumerator)
{
this.actual = actual;
}
protected override void OnRequest(long n)
{
IFlowableSubscriber<T> a = actual;
IEnumerator<T> en = enumerator;
long e = 0L;
for (;;)
{
while (e != n)
{
if (Volatile.Read(ref cancelled) != 0)
{
Clear();
return;
}
T v = en.Current;
if (v == null)
{
Clear();
a.OnError(new NullReferenceException("One of the IEnumerator items is null"));
return;
}
a.OnNext(v);
bool b;
try
{
b = en.MoveNext();
}
catch (Exception ex)
{
Clear();
a.OnError(ex);
return;
}
if (!b)
{
Clear();
if (Volatile.Read(ref cancelled) == 0)
{
a.OnComplete();
}
return;
}
e++;
}
n = Volatile.Read(ref requested);
if (e == n)
{
n = Interlocked.Add(ref requested, -n);
if (n == 0L)
{
break;
}
e = 0L;
}
}
}
}
internal sealed class EnumerableConditionalSubscription : AbstractEnumerableSubscription
{
readonly IConditionalSubscriber<T> actual;
internal EnumerableConditionalSubscription(IConditionalSubscriber<T> actual, IEnumerator<T> enumerator) : base(enumerator)
{
this.actual = actual;
}
protected override void OnRequest(long n)
{
IConditionalSubscriber<T> a = actual;
IEnumerator<T> en = enumerator;
long e = 0L;
for (;;)
{
while (e != n)
{
if (Volatile.Read(ref cancelled) != 0)
{
Clear();
return;
}
T v = en.Current;
if (v == null)
{
Clear();
a.OnError(new NullReferenceException("One of the IEnumerator items is null"));
return;
}
if (a.TryOnNext(v))
{
e++;
}
bool b;
try
{
b = en.MoveNext();
}
catch (Exception ex)
{
Clear();
a.OnError(ex);
return;
}
if (!b)
{
Clear();
if (Volatile.Read(ref cancelled) == 0)
{
a.OnComplete();
}
return;
}
}
n = Volatile.Read(ref requested);
if (e == n)
{
n = Interlocked.Add(ref requested, -n);
if (n == 0L)
{
break;
}
e = 0L;
}
}
}
}
}
}
|
77df1d387bfca8213a0e19ef7cc573a7f0c6ef9b
|
C#
|
omariomadureira/sistema-matricula
|
/Models/Registry.cs
| 2.515625
| 3
|
using SistemaMatricula.DAO;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using SistemaMatricula.Helpers;
namespace SistemaMatricula.Models
{
public class Registry
{
public Guid IdRegistry { get; set; }
public Grid Grid { get; set; }
public Student Student { get; set; }
public bool? Alternative { get; set; }
public DateTime RegisterDate { get; set; }
public Guid RegisterBy { get; set; }
public DateTime? DeleteDate { get; set; }
public Guid? DeleteBy { get; set; }
public static bool Add(Registry item)
{
var send = SendBill(item.Student.Name, item.Student.CPF, item.Grid.Price);
if (send == false)
return false;
return RegistryDAO.Add(item);
}
public static Registry Find(Guid id)
{
return RegistryDAO.Find(id);
}
public static List<Registry> List(Registry filters = null, bool actual = false)
{
return RegistryDAO.List(filters, actual);
}
public static bool Delete(Guid id)
{
return RegistryDAO.Delete(id);
}
public static bool DeleteByGrid(Guid id)
{
return RegistryDAO.DeleteByGrid(id);
}
public static ValidationResult Allow(Controllers.RegistryView[] list)
{
if (list == null)
return new ValidationResult("Não foi possível realizar a matrícula. Tente novamente mais tarde.");
var student = Student.FindLoggedUser();
if (student == null)
return new ValidationResult("Não foi possível realizar a matrícula. Tente novamente mais tarde.");
Registry filters = new Registry()
{
Student = student
};
var registries = List(filters, true);
if (registries == null)
return new ValidationResult("Não foi possível realizar a matrícula. Tente novamente mais tarde.");
int restForFirst = 4 - registries.FindAll(x => !x.Alternative.HasValue || !x.Alternative.Value).Count;
int restForSecond = 2 - registries.FindAll(x => x.Alternative.HasValue && x.Alternative.Value).Count;
int first = 0, second = 0;
foreach (Controllers.RegistryView item in list)
{
if (item.FirstOption == true)
first++;
else if (item.SecondOption == true)
second++;
}
if (restForFirst < 1 && restForSecond < 1)
return new ValidationResult("A quantidade máxima de matrículas foi atingida.");
if (restForFirst > 0 && first == 0)
return new ValidationResult("Escolha pelo menos 1 disciplina para primeira opção.");
if (restForFirst > 0 && first > restForFirst)
return new ValidationResult(
string.Format("Escolha no máximo {0} disciplina(s) para primeira opção.", restForFirst));
if (restForFirst == 0 && first > restForFirst)
return new ValidationResult("A quantidade máxima de matrículas para primeira opção foi atingida.");
if (restForFirst == 0 && restForSecond > 0 && second == 0)
return new ValidationResult("Escolha pelo menos 1 disciplina para segunda opção.");
if (restForSecond > 0 && second > restForSecond)
return new ValidationResult(
string.Format("Escolha no máximo {0} disciplina(s) para segunda opção.", restForSecond));
return ValidationResult.Success;
}
public static List<Registry> IsFull(List<Registry> itens)
{
try
{
if (itens == null)
return null;
List<Grid> list = new List<Grid>();
foreach (Registry item in itens)
list.Add(item.Grid);
foreach (Grid item in list)
{
if (item.Registries > 9)
{
item.Status = Grid.FINISHED;
var update = Grid.Update(item);
if (update == false)
throw new Exception("Grade não atualizada");
itens.RemoveAll(x => x.Grid.IdGrid == item.IdGrid);
}
}
return itens;
}
catch (Exception e)
{
string notes = LogHelper.Notes(itens, e.Message);
Log.Add(Log.TYPE_ERROR, "SistemaMatricula.Models.Registry.IsFull", notes);
}
return null;
}
public static List<Registry> GridList(Guid idStudent, Guid idCourse)
{
try
{
var list = RegistryDAO.GridList(idStudent, idCourse);
if (list == null)
return null;
list = IsFull(list);
if (list == null)
throw new Exception("Erro na checagem da grade com quantidade máxima de matrículas");
return list;
}
catch (Exception e)
{
object[] parameters = { idStudent, idCourse };
string notes = LogHelper.Notes(parameters, e.Message);
Log.Add(Log.TYPE_ERROR, "SistemaMatricula.Models.Registry.GridList", notes);
}
return null;
}
public static bool SendBill(string name, string cpf, double price)
{
try
{
if (string.IsNullOrWhiteSpace(name))
throw new Exception("Parâmetro name vazio");
if (string.IsNullOrWhiteSpace(cpf))
throw new Exception("Parâmetro cpf vazio");
if (price < 1)
throw new Exception("Parâmetro value vazio");
var url = string.Format("{0}/bill/post?name={1}&cpf={2}&value={3}", API.COBRANCA_API_URL, name, cpf, price);
var api = API.Call("POST", url);
if (api == false)
throw new Exception("Fatura de matrícula não enviada.");
return true;
}
catch (Exception e)
{
object[] parameters = { name, cpf, price };
string notes = LogHelper.Notes(parameters, e.Message);
Log.Add(Log.TYPE_ERROR, "SistemaMatricula.Models.Registry.SendBill", notes);
}
return false;
}
}
}
|
dc08ab17bd1683c8380ab03a5996703f51b42a72
|
C#
|
jfpsb/Algoritmos2
|
/SurplusDeficit/Program.cs
| 3.3125
| 3
|
using System;
namespace AtividadeNDamas
{
class Program
{
static int surplus = 0;
static void Main(string[] args)
{
while (true)
{
string[] input = Console.ReadLine().Split();
int s = int.Parse(input[0]);
int d = int.Parse(input[1]);
surplus = 0;
ChamaSurplusDeficit(new int[12], s, d);
if (surplus == 0)
{
Console.WriteLine("Deficit");
}
else
{
Console.WriteLine(surplus);
}
}
}
public static void ChamaSurplusDeficit(int[] vetor, int s, int d)
{
SurplusDeficit(vetor, 0, s, d, 0);
}
public static void SurplusDeficit(int[] vetor, int index, int s, int d, int soma)
{
int total = 0;
if (index == 12)
{
for (int i = 0; i < 12; i++)
{
total += vetor[i];
}
if (total > surplus)
surplus = total;
}
else
{
bool ok = true;
if (index > 4)
{
if (soma > 0)
{
ok = false;
}
else
{
soma -= vetor[index - 5];
}
}
if (ok)
{
vetor[index] = s;
SurplusDeficit(vetor, index + 1, s, d, soma + vetor[index]);
vetor[index] = -d;
SurplusDeficit(vetor, index + 1, s, d, soma + vetor[index]);
}
}
}
}
}
|
ffb5f5ffac380c976916c8be85cb02b49cb06f7f
|
C#
|
PetLahev/VBE_Modules
|
/VBEModules/Business/Utils.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Microsoft.Vbe.Interop;
using VbeComponents.Resources;
namespace VbeComponents.Business
{
public static class Utils
{
/// <summary>
/// Checks if given path exists
/// TODO: Make it faster for network paths
/// </summary>
/// <param name="path">a path to check</param>
/// <returns>True if the path exists, otherwise False</returns>
public static bool PathExists(string path)
{
return Directory.Exists(path);
}
/// <summary>
/// Check if at least one file in given path has extension of a VBA component
/// The extension can be cls, bas, frm
/// </summary>
/// <param name="path">path to a folder where to check components</param>
/// <returns>True if at least one file is valid VBA component, otherwise false</returns>
/// <exception cref="IOException">thrown if given path doesn't exists</exception>
public static bool HasComponent(string path)
{
if (!PathExists(path)) throw new IOException(string.Format(strings.FolderDoesnExists, path));
IEnumerable<string> files = Directory.EnumerateFiles(path);
return files.Any(x => x.EndsWith(".cls") || x.EndsWith(".bas") || x.EndsWith(".frm"));
}
public static string DisplayFolderDialog(bool displayNewFolderButton = true,
bool useLastSavedFolder = true)
{
FolderBrowserDialog fbd = new FolderBrowserDialog { ShowNewFolderButton = displayNewFolderButton };
if (useLastSavedFolder)
{
Configurations.ConfigurationXmlFile config = new Configurations.ConfigurationXmlFile();
fbd.SelectedPath = config.GetLastSavedProject().Path;
}
DialogResult result = fbd.ShowDialog();
return result == DialogResult.OK ? fbd.SelectedPath : null;
}
/// <summary>
/// Gets all valid VBA components from given path
/// </summary>
/// <param name="path">a path where to get components from</param>
/// <returns></returns>
public static IEnumerable<Component> GetComponents(string path )
{
IEnumerable<string> files = Directory.EnumerateFiles(path).Where(x => x.EndsWith(".cls") || x.EndsWith("frm") || x.EndsWith(".bas") );
var enumerable = files as string[] ?? files.ToArray();
if (!enumerable.Any()) return null;
List<Component> components = new List<Component>();
foreach (string file in enumerable)
{
string ext = file.Substring(file.Length - 3, 3);
string name = Path.GetFileName(file);
switch (ext)
{
case "bas":
components.Add(new Component() { Name = name, Path = path, Type = vbext_ComponentType.vbext_ct_StdModule, Content = GetContent(file) } );
break;
case "cls":
components.Add(new Component() { Name = name, Path = path, Type = vbext_ComponentType.vbext_ct_ClassModule, Content = GetContent(file) });
break;
case "frm":
components.Add(new Component() { Name = name, Path = path, Type = vbext_ComponentType.vbext_ct_MSForm, Content = GetContent(file) });
break;
}
}
return components;
}
/// <summary>
/// Gets content of given file
/// </summary>
/// <param name="fullPath">full path to a component to load content</param>
/// <returns>text of the component</returns>
private static string GetContent(string fullPath)
{
StringBuilder str = new StringBuilder();
using (StreamReader sr = File.OpenText(fullPath))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
str.AppendLine(s);
}
}
return str.ToString();
}
}
}
|
8105cb9b10c31570bc269900af5087f414ac6ce7
|
C#
|
lanicon/FlaUI.Adapter.White
|
/src/FlaUI.Adapter.White/AutomationSearchCondition.cs
| 2.65625
| 3
|
using System.Collections.Generic;
using FlaUI.Core.Conditions;
using FlaUI.Core.Definitions;
namespace FlaUI.Adapter.White
{
public class AutomationSearchCondition
{
private readonly List<ConditionBase> _conditions = new List<ConditionBase>();
public static ConditionFactory ConditionFactory => WhiteAdapter.ConditionFactory;
public virtual ConditionBase Condition
{
get
{
if (_conditions.Count == 1)
{
return _conditions[0];
}
if (_conditions.Count == 0)
{
return TrueCondition.Default;
}
return new AndCondition(_conditions);
}
}
public AutomationSearchCondition()
{
}
public AutomationSearchCondition(ConditionBase condition)
{
Add(condition);
}
public void Add(ConditionBase condition)
{
_conditions.Add(condition);
}
public AutomationSearchCondition OfName(string name)
{
_conditions.Add(ConditionFactory.ByName(name));
return this;
}
public AutomationSearchCondition OfControlType(ControlType controlType)
{
_conditions.Add(ConditionFactory.ByControlType(controlType));
return this;
}
public AutomationSearchCondition WithAutomationId(string id)
{
_conditions.Add(ConditionFactory.ByAutomationId(id));
return this;
}
public virtual AutomationSearchCondition WithProcessId(int processId)
{
_conditions.Add(ConditionFactory.ByProcessId(processId));
return this;
}
public static AutomationSearchCondition ByName(string name)
{
var automationSearchCondition = new AutomationSearchCondition();
automationSearchCondition.OfName(name);
return automationSearchCondition;
}
public static AutomationSearchCondition ByControlType(ControlType controlType)
{
var automationSearchCondition = new AutomationSearchCondition();
automationSearchCondition.OfControlType(controlType);
return automationSearchCondition;
}
public static AutomationSearchCondition ByAutomationId(string id)
{
var automationSearchCondition = new AutomationSearchCondition();
automationSearchCondition.WithAutomationId(id);
return automationSearchCondition;
}
public static AutomationSearchCondition ByClassName(string className)
{
var asc = new AutomationSearchCondition();
asc._conditions.Add(ConditionFactory.ByClassName(className));
return asc;
}
public static AutomationSearchCondition All
{
get
{
var asc = new AutomationSearchCondition();
asc._conditions.Add(TrueCondition.Default);
return asc;
}
}
}
}
|
974fcef34bb4eac3e0b6ef2f140d31f16e203d36
|
C#
|
OlegAxenow/FastGuid
|
/FastGuid.Tests/StaticDataGeneration.cs
| 3
| 3
|
using System;
using System.Text;
using NUnit.Framework;
namespace FastGuid.Tests
{
[TestFixture]
public class StaticDataGeneration
{
/// <summary>
/// Length of the "StaticData.BitsFromHex" to compare while parsing.
/// Not 256 to allocate less memory for "StaticData.BitsFromHex".
/// </summary>
private const int BitsFromHexLength = 104;
[Test, Explicit("Manual generation of HexDwords")]
public void Generate_HexDwords()
{
// arrange
var hexDwords = new uint[256];
for (int i = 0; i < hexDwords.Length; i++)
{
var tuple = HexTuples[i];
hexDwords[i] = (uint)(tuple.Item1) ^ ((uint)tuple.Item2 << 16);
}
var builder = new StringBuilder(3000);
builder.Append("{");
// act
for (int i = 0; i < hexDwords.Length; i++)
{
if (i % 8 == 0)
builder.AppendLine();
else
builder.Append(" ");
builder.Append("0x").Append(((int)hexDwords[i]).ToString("x")).Append(",");
}
builder.AppendLine().Append("};");
Console.WriteLine(builder.ToString());
}
[Test, Explicit("Manual generation of BitsFromHex")]
public void Generate_BitsFromHex()
{
// arrange
var bits = new ushort[BitsFromHexLength];
for (int i = 0; i < bits.Length; i++)
{
bits[i] = 255;
}
for (ushort i = 0; i < HexTuplesForParsing.Length; i++)
{
var tuple = HexTuplesForParsing[i];
bits[tuple.Item1] = i;
bits[tuple.Item2] = i;
}
var builder = new StringBuilder(3000);
builder.Append("{");
// act
for (int i = 0; i < bits.Length; i++)
{
if (i % 8 == 0)
builder.AppendLine();
else
builder.Append(" ");
if (bits[i] == 255)
{
builder.Append("(Bits)").Append(bits[i]);
}
else
{
builder.Append("new Bits(").Append(bits[i]).Append(")");
}
builder.Append(",");
}
builder.AppendLine().Append("};");
Console.WriteLine(builder.ToString());
}
private static readonly ValueTuple<char, char>[] HexTuplesForParsing =
{
('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'),
('A', 'a'), ('B', 'b'), ('C', 'c'), ('D', 'd'), ('E', 'e'), ('F', 'f')
};
private static readonly ValueTuple<char, char>[] HexTuples =
{
('0', '0'), ('0', '1'), ('0', '2'), ('0', '3'), ('0', '4'), ('0', '5'), ('0', '6'), ('0', '7'), ('0', '8'), ('0', '9'),
('0', 'a'), ('0', 'b'), ('0', 'c'), ('0', 'd'), ('0', 'e'), ('0', 'f'), ('1', '0'), ('1', '1'), ('1', '2'), ('1', '3'),
('1', '4'), ('1', '5'), ('1', '6'), ('1', '7'), ('1', '8'), ('1', '9'), ('1', 'a'), ('1', 'b'), ('1', 'c'), ('1', 'd'),
('1', 'e'), ('1', 'f'), ('2', '0'), ('2', '1'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('2', '6'), ('2', '7'),
('2', '8'), ('2', '9'), ('2', 'a'), ('2', 'b'), ('2', 'c'), ('2', 'd'), ('2', 'e'), ('2', 'f'), ('3', '0'), ('3', '1'),
('3', '2'), ('3', '3'), ('3', '4'), ('3', '5'), ('3', '6'), ('3', '7'), ('3', '8'), ('3', '9'), ('3', 'a'), ('3', 'b'),
('3', 'c'), ('3', 'd'), ('3', 'e'), ('3', 'f'), ('4', '0'), ('4', '1'), ('4', '2'), ('4', '3'), ('4', '4'), ('4', '5'),
('4', '6'), ('4', '7'), ('4', '8'), ('4', '9'), ('4', 'a'), ('4', 'b'), ('4', 'c'), ('4', 'd'), ('4', 'e'), ('4', 'f'),
('5', '0'), ('5', '1'), ('5', '2'), ('5', '3'), ('5', '4'), ('5', '5'), ('5', '6'), ('5', '7'), ('5', '8'), ('5', '9'),
('5', 'a'), ('5', 'b'), ('5', 'c'), ('5', 'd'), ('5', 'e'), ('5', 'f'), ('6', '0'), ('6', '1'), ('6', '2'), ('6', '3'),
('6', '4'), ('6', '5'), ('6', '6'), ('6', '7'), ('6', '8'), ('6', '9'), ('6', 'a'), ('6', 'b'), ('6', 'c'), ('6', 'd'),
('6', 'e'), ('6', 'f'), ('7', '0'), ('7', '1'), ('7', '2'), ('7', '3'), ('7', '4'), ('7', '5'), ('7', '6'), ('7', '7'),
('7', '8'), ('7', '9'), ('7', 'a'), ('7', 'b'), ('7', 'c'), ('7', 'd'), ('7', 'e'), ('7', 'f'), ('8', '0'), ('8', '1'),
('8', '2'), ('8', '3'), ('8', '4'), ('8', '5'), ('8', '6'), ('8', '7'), ('8', '8'), ('8', '9'), ('8', 'a'), ('8', 'b'),
('8', 'c'), ('8', 'd'), ('8', 'e'), ('8', 'f'), ('9', '0'), ('9', '1'), ('9', '2'), ('9', '3'), ('9', '4'), ('9', '5'),
('9', '6'), ('9', '7'), ('9', '8'), ('9', '9'), ('9', 'a'), ('9', 'b'), ('9', 'c'), ('9', 'd'), ('9', 'e'), ('9', 'f'),
('a', '0'), ('a', '1'), ('a', '2'), ('a', '3'), ('a', '4'), ('a', '5'), ('a', '6'), ('a', '7'), ('a', '8'), ('a', '9'),
('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('b', '0'), ('b', '1'), ('b', '2'), ('b', '3'),
('b', '4'), ('b', '5'), ('b', '6'), ('b', '7'), ('b', '8'), ('b', '9'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('b', 'd'),
('b', 'e'), ('b', 'f'), ('c', '0'), ('c', '1'), ('c', '2'), ('c', '3'), ('c', '4'), ('c', '5'), ('c', '6'), ('c', '7'),
('c', '8'), ('c', '9'), ('c', 'a'), ('c', 'b'), ('c', 'c'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('d', '0'), ('d', '1'),
('d', '2'), ('d', '3'), ('d', '4'), ('d', '5'), ('d', '6'), ('d', '7'), ('d', '8'), ('d', '9'), ('d', 'a'), ('d', 'b'),
('d', 'c'), ('d', 'd'), ('d', 'e'), ('d', 'f'), ('e', '0'), ('e', '1'), ('e', '2'), ('e', '3'), ('e', '4'), ('e', '5'),
('e', '6'), ('e', '7'), ('e', '8'), ('e', '9'), ('e', 'a'), ('e', 'b'), ('e', 'c'), ('e', 'd'), ('e', 'e'), ('e', 'f'),
('f', '0'), ('f', '1'), ('f', '2'), ('f', '3'), ('f', '4'), ('f', '5'), ('f', '6'), ('f', '7'), ('f', '8'), ('f', '9'),
('f', 'a'), ('f', 'b'), ('f', 'c'), ('f', 'd'), ('f', 'e'), ('f', 'f')
};
}
}
|
33dbf3a9325eae52808ed7ae3eabe8cc4940091f
|
C#
|
Krishnendu1995/employee-management-system
|
/employee management system/Program.cs
| 3.5
| 4
|
using System;
namespace employee_management_system
{
class Program
{
static void Main(string[] args)
{
employee obj = new employee();
Console.WriteLine("Enter Employee Name");
obj.setName(Console.ReadLine());
Console.WriteLine("Enter Employee Address");
obj.setAddress(Console.ReadLine());
Console.WriteLine("Enter Employee Age");
obj.setAge(Convert.ToInt32(Console.ReadLine()));
Console.WriteLine("Enter Employee salary");
obj.setSalary(Convert.ToInt32(Console.ReadLine()));
Console.WriteLine(obj.getName());
Console.WriteLine(obj.getAddress());
Console.WriteLine(obj.getAge());
Console.WriteLine(obj.getSalary());
}
}
}
|
400d078870a2777b35d209226e6d452099e874d3
|
C#
|
ShiranuiNui/CGSS_EventBorder_To_Discord
|
/StarlightDeck_To_Discord/Program.cs
| 2.6875
| 3
|
using System;
using System.Net;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Threading.Tasks;
using DSharpPlus;
using System.Reactive;
using NCrontab;
namespace StarlightDeck_To_Discord
{
class Program
{
//args[0] = API Key
//args[1] = Target Channel Number
static async Task Main(string[] args)
{
var schedule = CrontabSchedule.Parse("30 0 */3 * * *", new CrontabSchedule.ParseOptions() { IncludingSeconds = true });
var discordClient = new DiscordClient(args[0]);
await discordClient.Connect(ulong.Parse(args[1]));
System.Reactive.Linq.Observable.Generate(0, d => true, d => d + 1, d => d, d => new DateTimeOffset(schedule.GetNextOccurrence(DateTime.Now)))
.Subscribe(async x =>
{
string target = await StarlightAPIController.GetAPI();
await discordClient.SendMessageToTarget(target);
});
Console.ReadLine();
await discordClient.Disconnect();
}
}
public class StarlightAPIController
{
public static async Task<string> GetAPI()
{
using (var webClient = new WebClient())
{
string str = await webClient.DownloadStringTaskAsync("https://api.tachibana.cool/v1/starlight/event/1024/ranking_list.json");
var ReceivedAPIData = JsonConvert.DeserializeObject<List<StartlightAPI_EventResponse>>(str);
return ReceivedAPIData.Last().ToString();
}
}
public class StartlightAPI_EventResponse
{
public DateTime Date { get; set; }
public long Rank1 { get; set; }
public long Rank2 { get; set; }
public long Rank3 { get; set; }
public long Reward1 { get; set; }
public long Reward2 { get; set; }
public long Reward3 { get; set; }
public long Reward4 { get; set; }
public long Reward5 { get; set; }
public override string ToString()
{
return
$"{this.Date.ToString("yyyy/MM/dd H:mm:ss")}現在{Environment.NewLine}" +
$"1位:{this.Rank1}{Environment.NewLine}" +
$"2000位:{this.Reward1}{Environment.NewLine}" +
$"10000位:{this.Reward2}{Environment.NewLine}" +
$"20000位:{this.Reward3}{Environment.NewLine}" +
$"60000位:{this.Reward4}{Environment.NewLine}" +
$"120000位:{this.Reward5}{Environment.NewLine}";
}
}
}
class DiscordClient
{
private DSharpPlus.DiscordClient Client { get; set; }
private DSharpPlus.DiscordChannel TargetChannel { get; set; }
public DiscordClient(string token)
{
var cfg = new DiscordConfig
{
Token = token,
TokenType = TokenType.Bot,
AutoReconnect = true,
LogLevel = LogLevel.Debug,
UseInternalLogHandler = true
};
this.Client = new DSharpPlus.DiscordClient(cfg);
}
public async Task Connect(ulong targetChannelId)
{
this.Client.Ready += async e =>
{
await Task.Yield();
this.Client.DebugLogger.LogMessage(LogLevel.Info, "DiscordClient", "Ready! Setting status message..", DateTime.Now);
var game = new Game()
{
Name = "魔王降誕の儀式を幻視中",
StreamType = 0
};
await this.Client.UpdateStatusAsync(game, UserStatus.Online);
this.Client.DebugLogger.LogMessage(LogLevel.Info, "DiscordClient", "Discord Ready", DateTime.Now);
};
this.Client.DebugLogger.LogMessage(LogLevel.Info, "DiscordClient", "Connecting", DateTime.Now);
await this.Client.ConnectAsync();
this.TargetChannel = await this.Client.GetChannelAsync(targetChannelId);
}
public async Task Disconnect()
{
await this.Client.DisconnectAsync();
}
public async Task SendMessageToTarget(string content)
{
this.Client.DebugLogger.LogMessage(LogLevel.Info, "DiscordClient", "Sending Data", DateTime.Now);
await this.TargetChannel.SendMessageAsync(content);
}
}
}
|
f737687c4d31cea3d4e7f6fbfa730edbd2e95944
|
C#
|
kishonadiaz/CsharpClasswork
|
/FileAccess/FileAccess/Program.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace FileAccess
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/*Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());*/
Console.WriteLine("Current Directory:");
// Directory.SetCurrentDirectory(@"c:\");
Console.WriteLine(Directory.GetCurrentDirectory());
Console.WriteLine();
DirectoryInfo dir = new DirectoryInfo(".");
foreach (FileInfo file in dir.GetFiles())
{
string fileName = file.Name;
DateTime fileCreationDate = file.CreationTime;
long fileSize = file.Length;
Console.WriteLine(fileName.PadRight(40) + fileSize + "\t" + fileCreationDate);
}
Console.WriteLine();
StreamWriter outfile = new StreamWriter("data.txt");
string strData = "The quick brown fox jumps over the lazy dog.";
outfile.WriteLine(strData);
strData = "Hello World";
outfile.WriteLine(strData);
outfile.Close();
StreamReader infile = new StreamReader("data.txt");
string strReadData = infile.ReadToEnd();
Console.WriteLine(strReadData);
Console.ReadLine();
}
}
}
|
3cac62bf826330923107a2a4ad4f5068510562c1
|
C#
|
A000917542/FirstASPNetCoreWebsite
|
/FirstASPNetCoreWebsite/Models/Product.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Mvc;
namespace FirstASPNetCoreWebsite.Models
{
public class Product
{
[Key]
[HiddenInput]
[Required]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
[Range(0, double.PositiveInfinity, ErrorMessage = "This value is out of range.")]
public decimal Price { get; set; }
}
}
|
e67cbe6970643a451f32e6398171b679b65e7a38
|
C#
|
DotNetFrameWork/Tracy.Frameworks
|
/DEV/Tracy.Frameworks/Tracy.Frameworks.RedisConfig/HostCollection.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace Tracy.Frameworks.RedisConfig
{
public class HostCollection : ConfigurationElementCollection
{
public HostCollection()
{
HostConfig details = (HostConfig)CreateNewElement();
if (details.IP != "" && details.Port != "")
{
Add(details);
}
}
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
protected override ConfigurationElement CreateNewElement()
{
return new HostConfig();
}
protected override Object GetElementKey(ConfigurationElement element)
{
HostConfig config = ((HostConfig)element);
return string.Format("{0}:{1}:{2}", config.IP, config.Port,config.ReadOnly);
}
public HostConfig this[int index]
{
get
{
return (HostConfig)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
new public HostConfig this[string name]
{
get
{
return (HostConfig)BaseGet(name);
}
}
public int IndexOf(HostConfig details)
{
return BaseIndexOf(details);
}
public void Add(HostConfig details)
{
BaseAdd(details);
}
protected override void BaseAdd(ConfigurationElement element)
{
BaseAdd(element, false);
}
public void Remove(HostConfig details)
{
if (BaseIndexOf(details) >= 0)
BaseRemove(string.Format("{0}:{1}",details.IP , details.Port));
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
BaseRemove(name);
}
public void Clear()
{
BaseClear();
}
protected override string ElementName
{
get { return "host"; }
}
}
}
|
1cbc3f9edbd6a8e4a1da2f17dab12121e5cb68bb
|
C#
|
sami-lab/Software-House-Web
|
/SoftwareHouseWeb/Data/Repositories/EmployeeRepository.cs
| 2.640625
| 3
|
using SoftwareHouseWeb.Data.Interfaces;
using SoftwareHouseWeb.Data.Models.Employee;
using SoftwareHouseWeb.ViewModel.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SoftwareHouseWeb.Data.Repositories
{
public class EmployeeRepository : IEmployeeRepository
{
public ApplicationDbContext context;
public EmployeeRepository(ApplicationDbContext _context)
{
context = _context;
}
public int AddEmployee(RegisterEmployeeViewModel model)
{
var user = new Employee()
{
Name = model.Name,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
Position = model.Position,
Time = model.Time,
StartDate = model.StartDate,
EndDate = model.EndDate,
Skills = model.Skill1 + "," + model.Skill2 + "," + model.Skill3 + "," + model.Skill4,
Salary = model.Salary,
age = model.age,
is_active = true,
};
context.Employees.Add(user);
context.SaveChanges();
return user.Employee_id;
}
public List<RegisterEmployeeViewModel> ListEmployees()
{
var employees = context.Employees.Where(x => x.is_active == true).Select(x => new RegisterEmployeeViewModel()
{
Employee_id = x.Employee_id,
Email = x.Email,
age = x.age,
Name = x.Name,
EndDate = x.EndDate,
PhoneNumber = x.PhoneNumber,
Position = x.Position,
Skills = x.Skills,
StartDate = x.StartDate,
Salary = x.Salary,
Time = x.Time
}).ToList();
return employees;
}
public List<RegisterEmployeeViewModel> ListInterns()
{
var employees = context.Employees.Where(x => x.is_active == true).Select(x => new RegisterEmployeeViewModel()
{
Employee_id = x.Employee_id,
Email = x.Email,
age = x.age,
Name = x.Name,
EndDate = x.EndDate,
PhoneNumber = x.PhoneNumber,
Position = x.Position,
Skills = x.Skills,
StartDate = x.StartDate,
Salary = x.Salary,
Time = x.Time
}).Where(x => x.Time == Time.Intern).ToList();
return employees;
}
public RegisterEmployeeViewModel Employee(int Employee_id)
{
var employees = context.Employees.Where(x=> x.is_active ==true).Select(x => new RegisterEmployeeViewModel()
{
Employee_id = x.Employee_id,
Email = x.Email,
age = x.age,
Name = x.Name,
EndDate = x.EndDate,
PhoneNumber = x.PhoneNumber,
Position = x.Position,
Skills = x.Skills,
StartDate = x.StartDate,
Salary = x.Salary,
Time = x.Time
}).FirstOrDefault(x => x.Employee_id == Employee_id);
return employees;
}
public bool delete(int Employee_id)
{
var result = context.Employees.FirstOrDefault(u => u.Employee_id == Employee_id);
if (result != null)
{
result.is_active = false;
result.EndDate = DateTime.Now;
context.Entry(result).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
context.SaveChanges();
return true;
}
return false;
}
}
}
|
71bb8f94068a6459483ffef76f84283bb551ff84
|
C#
|
peterGeorgeAlfred/Scholarship-Application
|
/Scholarship Application/Helper/IntializerData.cs
| 2.75
| 3
|
using Microsoft.AspNetCore.Identity;
using Scholarship_Application.Data;
using Scholarship_Application.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Scholarship_Application.Helper
{
public static class IntializerData
{
public static async Task Initialize(ApplicationDbContext context, SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
if (!roleManager.Roles.Any())
{
List<IdentityRole> roles = new List<IdentityRole>
{
new IdentityRole { Name ="Admin"} ,
new IdentityRole { Name ="Student"} ,
};
foreach (var item in roles)
{
await roleManager.CreateAsync(item);
}
}
if (!userManager.Users.Any())
{
var user = new ApplicationUser
{
Email = "pgalfred2014@hotmail.com",
UserName = "PeterGeorege",
EmailConfirmed = true
};
await userManager.CreateAsync(user, "Peter123*");
await userManager.AddToRoleAsync(user, "Admin");
if (user.PasswordHash == null)
await signInManager.SignInAsync(user, true);
else
{
var result = await signInManager.PasswordSignInAsync(user.Email, "Peter123*", true, false);
if (result.Succeeded)
Console.WriteLine("Ok");
}
} // if There not any User in DB Create Default
}
}
}
|
f42e24cfdf224ff3b05c11affe568b6bd6ecf9fc
|
C#
|
Pyotr23/Algorithm
|
/Codewars/RailFenceCipher/Program.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Codewars.Three.RailFenceCipher
{
internal static class Program
{
static void Main()
{
Console.WriteLine(Encode("WEAREDISCOVEREDFLEEATONCE", 3));
Console.WriteLine(Decode("WECRLTEERDSOEEFEAOCAIVDEN", 3));
}
public static string Encode(string s, int n)
{
var lists = new List<List<char>>();
for (var i = 0; i < n; i++)
{
lists.Add(new List<char>());
}
var listIndex = 0;
var isForward = true;
foreach (var letter in s)
{
lists[listIndex].Add(letter);
if (listIndex == 0 && !isForward || listIndex == n - 1 && isForward)
isForward = !isForward;
listIndex = isForward
? listIndex + 1
: listIndex - 1;
}
return string.Concat(lists.SelectMany(x => x));
}
public static string Decode(string s, int n)
{
var dictionary = new Dictionary<int, List<int>>();
for (var i = 0; i < n; i++)
{
dictionary.Add(i, new List<int>());
}
var listIndex = 0;
var isForward = true;
for (var i = 0; i < s.Length; i++)
{
dictionary[listIndex].Add(i);
if (listIndex == 0 && !isForward || listIndex == n - 1 && isForward)
isForward = !isForward;
listIndex = isForward
? listIndex + 1
: listIndex - 1;
}
var letters = dictionary
.SelectMany(pair => pair.Value)
.ToArray();
var decodedArray = new char[s.Length];
for (var i = 0; i < s.Length; i++)
{
decodedArray[letters[i]] = s[i];
}
return new string(decodedArray);
}
}
}
|
83757ac0866b61a3151824690a9be264bc13e422
|
C#
|
Bogidaev/GzipTest
|
/Test/Extension/StreamEextension.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace Test.Extension
{
public static class StreamExtensions
{
/// <summary>
/// Копирование стрима
/// </summary>
/// <param name="src">Текущий стрим</param>
/// <param name="dest">В копируемый стрим</param>
public static void CopyTo(this Stream src, Stream dest)
{
byte[] buffer = new byte[1024 * 1024];
int read;
while ((read = src.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, read);
}
}
}
}
|
eb889cbadfe0cfd99a2a292f0de1e10d23176c08
|
C#
|
TheJP/stebs
|
/ProcessorSimulation/MpmParser/IMpmFileParser.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProcessorSimulation.MpmParser
{
/// <summary>
/// Parser, which takes raw configuration strings or configuration files and extract information for the mpm (micro program memory) and the opcode decoder.
/// </summary>
public interface IMpmFileParser : IMpmParser
{
/// <summary>
/// Decodes the given instructions file.
/// </summary>
/// <param name="instructions">Instructions file in a csv format. The csv format should not contain headers.</param>
/// <returns>Parsed instructions.</returns>
IDictionary<byte, IInstruction> ParseInstructionsFile(string filename);
/// <summary>
/// Decodes the given micro instructions files.
/// </summary>
/// <param name="filename1">
/// Logisim ram export file 1 containing the micro instructions.
/// (This format has to be used beacause of compatibility reasons.)
/// </param>
/// <param name="filename2">
/// Logisim ram export file 2 containing the micro instructions.
/// (This format has to be used beacause of compatibility reasons.)
/// </param>
/// <returns>Parsed micro instructions in a dictionary. The key is the micro instructions address.</returns>
IDictionary<int, IMicroInstruction> ParseMicroInstructionsFile(string filename1, string filename2);
}
}
|
a184883298f4f9ba560bb02fc2fa688f155ff6cd
|
C#
|
shendongnian/download4
|
/code6/1112952-29176306-86318829-2.cs
| 2.75
| 3
|
private bool IsTaskItemExists(Outlook.TaskItem oTaskItem)
{
Outlook.NameSpace ns = null;
Outlook.MAPIFolder tasksFolder = null;
Outlook.Items taskFolderItems = null;
Outlook.TaskItem task = null;
Outlook.Application outlookApp = new Application();
bool foundItem = false;
try
{
ns = outlookApp.Session;
tasksFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks);
taskFolderItems = tasksFolder.Items;
for (int i = 1; i <= taskFolderItems.Count; i++)
{
task = taskFolderItems[i] as Outlook.TaskItem;
if (task != null && task.Subject.ToLower() == oTaskItem.Subject.ToLower())
{
foundItem = true;
break;
}
}
return foundItem;
}
finally
{
if (taskFolderItems != null)
Marshal.ReleaseComObject(taskFolderItems);
if (tasksFolder != null)
Marshal.ReleaseComObject(tasksFolder);
if (ns != null)
Marshal.ReleaseComObject(ns);
}
}
|
f22507933064824037d0693d39f2424dc91a712c
|
C#
|
angelroma/House_PM
|
/House_PM_WCF/Service1.svc.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace House_PM_WCF
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IProduct
{
public List<Product> GetAll()
{
//List<Product> lista = new List<Product>();
//lista.Add(new Product() { Id = 1, Name = "Javier" });
//lista.Add(new Product() { Id = 2, Name = "Angel" });
//lista.Add(new Product() { Id = 3, Name = "Octavio" });
//lista.Add(new Product() { Id = 4, Name = "Ciro" });
//return lista;
List<Product> lista = new List<Product>
{
new Product() { Id = 1, Name = "Javier" },
new Product() { Id = 2, Name = "Angel" },
new Product() { Id = 3, Name = "Octavio" },
new Product() { Id = 4, Name = "Ciro" }
};
return lista;
}
public Product GetById(int id)
{
if(id == 1)
{
return new Product() { Id = 1, Name = "Javier" };
}
if (id == 2)
{
return new Product() { Id = 2, Name = "Angel" };
}
if (id == 3)
{
return new Product() { Id = 3, Name = "Octavio" };
}
else
{
return new Product() { Id = 4, Name = "Ciro" };
}
}
}
}
|
3faf637f3cb3bb8b48197b6203943bfe8d6ea79b
|
C#
|
agracio/edge-js
|
/performance/BookService/Program.cs
| 2.609375
| 3
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.ServiceModel;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace BookService
{
public class Book
{
public string title = "Run .NET and node.js in-process with edge.js";
public object author = new { first = "Tomasz", last = "Janczuk" };
public int year = 2013;
public double price = 24.99;
public bool available = true;
public string description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus posuere tincidunt felis, et mattis mauris ultrices quis. Cras molestie, quam varius tincidunt tincidunt, mi magna imperdiet lacus, quis elementum ante nibh quis orci. In posuere erat sed tellus lacinia luctus. Praesent sodales tellus mauris, et egestas justo. In blandit, metus non congue adipiscing, est orci luctus odio, non sagittis erat orci ac sapien. Proin ut est id enim mattis volutpat. Vivamus ultrices dapibus feugiat. In dictum tincidunt eros, non pretium nisi rhoncus in. Duis a lacus et elit feugiat ullamcorper. Mauris tempor turpis nulla. Nullam nec facilisis elit.";
public byte[] picture = new byte[16000];
public object[] tags = new object[] { ".NET", "node.js", "CLR", "V8", "interop" };
}
public class BookController : ApiController
{
static readonly Uri baseAddress = new Uri("http://localhost:31415/");
public Book Get()
{
return new Book();
}
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
config.HostNameComparisonMode = HostNameComparisonMode.Exact;
// Register default route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + baseAddress);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
finally
{
if (server != null)
{
server.CloseAsync().Wait();
}
}
}
}
}
|
6164c9eb575052e065e2341846cb76a04ae6d87d
|
C#
|
nasascience/Pixbind3D
|
/BBWT.Web/UploadHandler.ashx.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace BBWT.Web
{
/// <summary>
/// Summary description for UploadHandler
/// </summary>
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
string path = context.Request["path"];
FileInfo fn = new FileInfo(path);
fn.CopyTo(context.Server.MapPath("~/Content/images/Uploads" + fn.Name));
//context.Response.ContentType = "text/plain";
context.Response.Write(fn.Name);
}
catch
{
context.Response.Write("Error");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
|
5d3a2d6ae1b5d84584b71de34e4e1307674e8105
|
C#
|
war-man/Ecommerce-1
|
/Library/Models/LayoutMeta.cs
| 2.65625
| 3
|
using System.ComponentModel.DataAnnotations;
namespace Library.Models
{
public class LayoutMeta
{
public int Id { get; set; } // Id (Primary key)
[Required(ErrorMessage = "Please select the layout container")]
///<summary>
/// Id kho chứa layout
///</summary>
public int WarehouseId { get; set; } // WarehouseId
///<summary>
/// Tên kho chứa layout
///</summary>
public string WarehouseName { get; set; } // WarehouseName (length: 300)
[Required(ErrorMessage = "Please enter a layout name")]
///<summary>
/// Tên layout
///</summary>
public string Name { get; set; } // Name (length: 300)
///<summary>
/// Loại của layout: 0: Khu vực, 1: Layout, 2: Giá kệ, 3: Hàng trong giá kệ, 4: Bin trong giá kệ
///</summary>
public byte Mode { get; set; } // Mode
[Required(ErrorMessage = "Layout code can not be empty.")]
///<summary>
/// Mã của layout
///</summary>
public string Code { get; set; } // Code (length: 50)
///<summary>
/// Id Layout cha
///</summary>
public int? ParentLayoutId { get; set; } // ParentLayoutId
///<summary>
/// Tên Layout cha
///</summary>
public string ParentLayoutName { get; set; } // ParentLayoutName (length: 300)
///<summary>
/// Mô tả về layout
///</summary>
public string Description { get; set; } // Description (length: 500)
///<summary>
/// 0: Mới, 1: Đang sử dụng, 2: Cũ
///</summary>
public byte Status { get; set; } // Status
///<summary>
/// Chiều dài
///</summary>
public int? Length { get; set; } // Length
///<summary>
/// Chiều rộng
///</summary>
public int? Width { get; set; } // Width
///<summary>
/// Chiều cao
///</summary>
public int? Height { get; set; } // Height
///<summary>
/// Cân nặng tối đa
///</summary>
public int? MaxWeight { get; set; } // MaxWeight
}
}
|
0d987497b8689cde8975024178c70e4cb2b8e1d0
|
C#
|
meet1993shah/azure-sdk-for-net
|
/sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample_AnalyzeOperation.cs
| 2.53125
| 3
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Azure.AI.TextAnalytics.Tests;
using Azure.Core.TestFramework;
using NUnit.Framework;
namespace Azure.AI.TextAnalytics.Samples
{
[LiveOnly]
public partial class TextAnalyticsSamples: SamplesBase<TextAnalyticsTestEnvironment>
{
[Test]
public void AnalyzeOperation()
{
string endpoint = TestEnvironment.Endpoint;
string apiKey = TestEnvironment.ApiKey;
var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
#region Snippet:TextAnalyticsAnalyzeOperation
string documentA = @"We love this trail and make the trip every year. The views are breathtaking and well
worth the hike! Yesterday was foggy though, so we missed the spectacular views.
We tried again today and it was amazing. Everyone in my family liked the trail although
it was too challenging for the less athletic among us.
Not necessarily recommended for small children.
A hotel close to the trail offers services for childcare in case you want that.";
string documentB = @"Last week we stayed at Hotel Foo to celebrate our anniversary. The staff knew about
our anniversary so they helped me organize a little surprise for my partner.
The room was clean and with the decoration I requested. It was perfect!";
string documentC = @"That was the best day of my life! We went on a 4 day trip where we stayed at Hotel Foo.
They had great amenities that included an indoor pool, a spa, and a bar.
The spa offered couples massages which were really good.
The spa was clean and felt very peaceful. Overall the whole experience was great.
We will definitely come back.";
var batchDocuments = new List<TextDocumentInput>
{
new TextDocumentInput("1", documentA)
{
Language = "en",
},
new TextDocumentInput("2", documentB)
{
Language = "en",
},
new TextDocumentInput("3", documentC)
{
Language = "en",
}
};
TextAnalyticsActions batchActions = new TextAnalyticsActions()
{
ExtractKeyPhrasesOptions = new List<ExtractKeyPhrasesOptions>() { new ExtractKeyPhrasesOptions() },
RecognizeEntitiesOptions = new List<RecognizeEntitiesOptions>() { new RecognizeEntitiesOptions() },
RecognizePiiEntitiesOptions = new List<RecognizePiiEntitiesOptions>() { new RecognizePiiEntitiesOptions() },
DisplayName = "AnalyzeOperationSample"
};
AnalyzeBatchActionsOperation operation = client.StartAnalyzeBatchActions(batchDocuments, batchActions);
TimeSpan pollingInterval = new TimeSpan(1000);
while (!operation.HasCompleted)
{
Thread.Sleep(pollingInterval);
operation.UpdateStatus();
}
foreach (AnalyzeBatchActionsResult documentsInPage in operation.GetValues())
{
RecognizeEntitiesResultCollection entitiesResult = documentsInPage.RecognizeEntitiesActionsResults.FirstOrDefault().Result;
ExtractKeyPhrasesResultCollection keyPhrasesResult = documentsInPage.ExtractKeyPhrasesActionsResults.FirstOrDefault().Result;
RecognizePiiEntitiesResultCollection piiResult = documentsInPage.RecognizePiiEntitiesActionsResults.FirstOrDefault().Result;
Console.WriteLine("Recognized Entities");
foreach (RecognizeEntitiesResult result in entitiesResult)
{
Console.WriteLine($" Recognized the following {result.Entities.Count} entities:");
foreach (CategorizedEntity entity in result.Entities)
{
Console.WriteLine($" Entity: {entity.Text}");
Console.WriteLine($" Category: {entity.Category}");
Console.WriteLine($" Offset: {entity.Offset}");
Console.WriteLine($" ConfidenceScore: {entity.ConfidenceScore}");
Console.WriteLine($" SubCategory: {entity.SubCategory}");
}
Console.WriteLine("");
}
Console.WriteLine("Recognized PII Entities");
foreach (RecognizePiiEntitiesResult result in piiResult)
{
Console.WriteLine($" Recognized the following {result.Entities.Count} PII entities:");
foreach (PiiEntity entity in result.Entities)
{
Console.WriteLine($" Entity: {entity.Text}");
Console.WriteLine($" Category: {entity.Category}");
Console.WriteLine($" Offset: {entity.Offset}");
Console.WriteLine($" ConfidenceScore: {entity.ConfidenceScore}");
Console.WriteLine($" SubCategory: {entity.SubCategory}");
}
Console.WriteLine("");
}
Console.WriteLine("Key Phrases");
foreach (ExtractKeyPhrasesResult result in keyPhrasesResult)
{
Console.WriteLine($" Recognized the following {result.KeyPhrases.Count} Keyphrases:");
foreach (string keyphrase in result.KeyPhrases)
{
Console.WriteLine($" {keyphrase}");
}
Console.WriteLine("");
}
}
}
#endregion
}
}
|
3f21f4a0a15275f19b0aa2ed064539d56e1a233a
|
C#
|
xabre/xamarin-forms-tab-badge
|
/Source/Plugin.Badge.UWP/Extensions.cs
| 2.71875
| 3
|
using Windows.UI.Xaml.Media;
using Xamarin.Forms;
namespace Plugin.Badge.UWP
{
public static class Extensions
{
public static Windows.UI.Color ToWindowsColor(this Color color)
{
return Windows.UI.Color.FromArgb((byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255));
}
public static Brush ToBrush(this Color color)
{
return new SolidColorBrush(color.ToWindowsColor());
}
}
}
|
bad04f2a71e7bbfc750b792e01af284182b21383
|
C#
|
janssener/AdventOfCode
|
/AdventOfCode/Day12.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdventOfCode
{
public class ProgramCommInfo
{
public List<string> CommPrograms;
public string CurrentProgName { get; set; }
public ProgramCommInfo(string currProg, List<string> commProgs)
{
CurrentProgName = currProg;
CommPrograms = new List<string>(commProgs);
}
}
public static class Day12
{
public static List<ProgramCommInfo> ProgramsReadIn;
public static List<string> GroupedPrograms;
public static int Run()
{
return RunLogic(false);
}
public static int Run2()
{
return RunLogic(true);
}
private static int RunLogic(bool part2)
{
GroupedPrograms = new List<string>();
ProgramsReadIn = new List<ProgramCommInfo>();
int groups = 0;
using (StreamReader sr = new StreamReader(@""))
{
while (!sr.EndOfStream)
{
var lineRead = sr.ReadLine().Split(new string[] { " <-> " }, StringSplitOptions.None);
var dirProgName = lineRead[0];
var connectedProgs = lineRead[1].Split(new string[] { ", " }, StringSplitOptions.None).ToList();
ProgramsReadIn.Add(new ProgramCommInfo(dirProgName, connectedProgs));
}
}
if (part2)
{
int lastLoopProgCount = 0;
foreach (var prog in ProgramsReadIn)
{
lastLoopProgCount = GroupedPrograms.Count;
ProcessProgram(prog);
if (lastLoopProgCount != GroupedPrograms.Count) groups++;
}
}
else ProcessProgram(ProgramsReadIn.First());
return part2 ? groups : GroupedPrograms.Count;
}
private static void ProcessProgram(ProgramCommInfo currentProg)
{
if (!GroupedPrograms.Contains(currentProg.CurrentProgName))
{
GroupedPrograms.Add(currentProg.CurrentProgName);
foreach (var prog in currentProg.CommPrograms)
{
ProcessProgram(ProgramsReadIn.Find(t => t.CurrentProgName == prog));
}
}
}
}
}
|
414766593c4ac4bffc6273ceed3f96e360e4f634
|
C#
|
rkoning/UnityNetworking
|
/Assets/Scripts/Spells/SpellEffects/DealDamage.cs
| 2.71875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DealDamage : SpellEffect
{
public float damage;
public bool hitOnce = true;
private List<GameObject> hits;
public override void Cast() {
hits = new List<GameObject>();
}
public override void HitHealth(Health health)
{
if (hitOnce) {
if (!hits.Contains(health.gameObject))
spell.owner.DealDamage(health, damage);
} else {
spell.owner.DealDamage(health, damage);
}
hits.Add(health.gameObject);
}
}
|
8f8b7fd981b2cb2364ee500060b27e2893de6f81
|
C#
|
akkadotnet/Alpakka
|
/src/SignalIR/Akka.Streams.SignalR/Events.cs
| 2.71875
| 3
|
using Microsoft.AspNet.SignalR;
namespace Akka.Streams.SignalR
{
/// <summary>
/// A common interface for all events incoming from SignalR socket.
///
/// Available event types are:
/// - <see cref="Received"/>
/// - <see cref="Connected"/>
/// - <see cref="Disconnected"/>
/// - <see cref="Reconnected"/>
/// </summary>
public interface ISignalREvent
{
/// <summary>
/// SignalR request attached to current event.
/// </summary>
IRequest Request { get; }
/// <summary>
/// Identifier of a connection, which has sent the event.
/// </summary>
string ConnectionId { get; }
}
/// <summary>
/// A standard message send explicitly from the client with data attached.
/// </summary>
public sealed class Received : ISignalREvent
{
/// <inheritdoc cref="ISignalREvent"/>
public IRequest Request { get; }
/// <inheritdoc cref="ISignalREvent"/>
public string ConnectionId { get; }
/// <summary>
/// Payload send by the client.
/// </summary>
public string Data { get; }
public Received(IRequest request, string connectionId, string data)
{
Request = request;
ConnectionId = connectionId;
Data = data;
}
public override string ToString()
=> $"Received(connectionId: {ConnectionId}, data: {Data}, request: {Request})";
}
/// <summary>
/// An event send, when a new connection has been established.
/// </summary>
public sealed class Connected : ISignalREvent
{
/// <inheritdoc cref="ISignalREvent"/>
public IRequest Request { get; }
/// <inheritdoc cref="ISignalREvent"/>
public string ConnectionId { get; }
public Connected(IRequest request, string connectionId)
{
Request = request;
ConnectionId = connectionId;
}
public override string ToString()
=> $"Connected(connectionId: {ConnectionId}, request: {Request})";
}
/// <summary>
/// An event send, when an existing connection has been lost.
/// </summary>
public sealed class Disconnected : ISignalREvent
{
/// <inheritdoc cref="ISignalREvent"/>
public IRequest Request { get; }
/// <inheritdoc cref="ISignalREvent"/>
public string ConnectionId { get; }
public bool StopCalled { get; }
public Disconnected(IRequest request, string connectionId, bool stopCalled)
{
Request = request;
ConnectionId = connectionId;
StopCalled = stopCalled;
}
public override string ToString()
=> $"Disconnected(connectionId: {ConnectionId}, stopCalled: {StopCalled}, request: {Request})";
}
/// <summary>
/// An event send, when disconnected client has been reconnected again.
/// </summary>
public sealed class Reconnected : ISignalREvent
{
/// <inheritdoc cref="ISignalREvent"/>
public IRequest Request { get; }
/// <inheritdoc cref="ISignalREvent"/>
public string ConnectionId { get; }
public Reconnected(IRequest request, string connectionId)
{
Request = request;
ConnectionId = connectionId;
}
public override string ToString()
=> $"Reconnected(connectionId: {ConnectionId}, request: {Request})";
}
}
|
aa4a630f0d1e276697f69c09c1843c6fc9a0b5e2
|
C#
|
tzm1119/Positron
|
/src/Positron.UI/Builder/PositronUiBuilderExtensions.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Positron.UI.Builder
{
/// <summary>
/// Extensions for <see cref="IPositronUiBuilder"/>.
/// </summary>
public static class PositronUiBuilderExtensions
{
/// <summary>
/// Sets the <see cref="IConsoleLogger"/> used to handle Chromium console messages.
/// </summary>
/// <param name="builder">The <see cref="IPositronUiBuilder"/>.</param>
/// <param name="consoleLogger"><see cref="IConsoleLogger"/> used to handle Chromium console messages.</param>
/// <returns>The <see cref="IPositronUiBuilder"/>.</returns>
public static IPositronUiBuilder UseConsoleLogger(this IPositronUiBuilder builder, IConsoleLogger consoleLogger)
{
return builder.ConfigureServices(services =>
{
services.AddSingleton(consoleLogger);
});
}
/// <summary>
/// Configures the debug port used to support Chromium developer tools.
/// </summary>
/// <param name="builder">The <see cref="IPositronUiBuilder"/>.</param>
/// <param name="debugPort">Debug port used to support Chromium developer tools.</param>
/// <returns>The <see cref="IPositronUiBuilder"/>.</returns>
/// <remarks>Access developer tools using http://localhost:xxxx from Chrome.</remarks>
public static IPositronUiBuilder UseDebugPort(this IPositronUiBuilder builder, int debugPort)
{
return builder.ConfigureSettings(settings =>
{
settings.RemoteDebuggingPort = debugPort;
});
}
}
}
|
cf50270dc4978dc7b4801ba78e9a41fab39ad585
|
C#
|
caneq/Warehouse
|
/Warehouse.BusinessLogicLayer/Models/ClientRequestFilterParams.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using Warehouse.DataAccessLayer.Models;
namespace Warehouse.BusinessLogicLayer.Models
{
public class ClientRequestFilterParams
{
public int? Id { get; set; }
public string ApplicationUserId { get; set; }
public string Title { get; set; }
public bool? Completed { get; set; }
public DateTime? DateTimeMin { get; set; }
public DateTime? DateTimeMax { get; set; }
public int? ClientUnreadMessagesCountMin { get; set; }
public int? ClientUnreadMessagesCountMax { get; set; }
public int? ManagersUnreadMessagesCountMin { get; set; }
public int? ManagersUnreadMessagesCountMax { get; set; }
internal Expression<Func<ClientRequest, bool>> GetLinqExpression()
{
return (ClientRequest c) =>
(Id != null ? c.Id == Id : true) &&
(ApplicationUserId != null ? c.ApplicationUserId == ApplicationUserId : true) &&
(Title != null ? c.Title == Title : true) &&
(Completed != null ? c.Completed == Completed : true) &&
(ClientUnreadMessagesCountMin != null ? c.ClientUnreadMessagesCount >= ClientUnreadMessagesCountMin : true) &&
(ClientUnreadMessagesCountMax != null ? c.ClientUnreadMessagesCount <= ClientUnreadMessagesCountMax : true) &&
(ManagersUnreadMessagesCountMin != null ? c.ManagersUnreadMessagesCount >= ManagersUnreadMessagesCountMin : true) &&
(ManagersUnreadMessagesCountMax != null ? c.ManagersUnreadMessagesCount <= ManagersUnreadMessagesCountMax : true) &&
(DateTimeMin != null ? c.DateTime > DateTimeMin : true) &&
(DateTimeMax != null ? c.DateTime < DateTimeMax : true);
}
internal Func<ClientRequest, bool> GetFuncPredicate()
{
return GetLinqExpression().Compile();
}
}
}
|
776d056015ba133616290897d8c829bb5703ab99
|
C#
|
G1ANT-Robot/G1ANT.Addon.Appium
|
/G1ANT.Addon.Appium/Commands/AppiumButtonCommand.cs
| 2.515625
| 3
|
using System;
using G1ANT.Language;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Remote;
namespace G1ANT.Addon.Appium
{
[Command(Name = "appium.button", Tooltip = "This command clicks choden element.")]
public class ButtonCommand : Language.Command
{
public class Arguments : CommandArguments
{
[Argument(Required = true, Tooltip = "Keycode of the button to be pressed")]
public TextStructure KeyCode { get; set; } = new TextStructure("");
}
public ButtonCommand(AbstractScripter scripter) : base(scripter)
{
}
public void Execute(Arguments arguments)
{
var driver = OpenCommand.GetDriver();
string keycode = arguments.KeyCode.Value.ToLower();
switch (keycode)
{
case "back":
driver.PressKeyCode(AndroidKeyCode.Back);
break;
default:
throw new ArgumentException($"Provided button name is invalid.");
}
}
}
}
|
fa985d3add536d34bd12eb6c82e92347512d4872
|
C#
|
BronzeRonze/AdventOfCode2019
|
/AdventCode19/Day 2/ProgramAlarm.cs
| 3.109375
| 3
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.IO;
namespace AdventCode19
{
class ProgramAlarm
{
public static void StartProgramSequence()
{
using (StreamReader reader = new StreamReader("F:\\Programming\\CodeAdvent\\2019\\Day2Input.txt"))
{
string line = null;
int[] numbers = { };
int input1Fix = 12;
int input2Fix = 2;
int resultIndex = 0;
line = reader.ReadLine();
string[] values = line.Split(',');
numbers = new int[values.Length];
ProcessInputFile(reader, numbers);
ProcessProgramSequence(numbers, input1Fix, input2Fix, resultIndex);
// We need this output in order to completegravity assist.
int gravityResultReq = 19690720;
int gravitySeqResult = 0;
int answer = 0;
for(int inputAddr1 = 0; inputAddr1 < 100; inputAddr1++)
{
for(int inputAddr2 = 0; inputAddr2 < 100; inputAddr2++)
{
ProcessInputFile(reader, numbers);
gravitySeqResult = ProcessProgramSequence(numbers, inputAddr1, inputAddr2, resultIndex);
if(gravityResultReq == gravitySeqResult)
{
answer = 100 * inputAddr1 + inputAddr2;
Console.WriteLine(answer);
return;
}
}
}
}
}
static int ProcessProgramSequence(int[] program, int ManualInputPos1, int ManualInputPos2, int desiredIndex)
{
int opCode = 0;
int programIndex = 0;
int index1 = 0;
int index2 = 0;
int index3 = 0;
int result = 0;
program[1] = ManualInputPos1;
program[2] = ManualInputPos2;
while (opCode != 99 || (programIndex > program.Length))
{
opCode = program[programIndex++];
// Process message based on opCode
switch (opCode)
{
// 1 = Addition. Take the next two indexes, add them together and save result to the index following these two. [1, 5, 6, 3] Add 5 and 6, save to 3.
case 1:
index1 = program[programIndex++];
index2 = program[programIndex++];
index3 = program[programIndex++];
result = program[index1] + program[index2];
program[index3] = result;
break;
// 2 = Multiplication Take the next two indexes, multiply them together and save result to the index following these two. [1, 5, 6, 3] Multiply 5 and 6, save to 3.
case 2:
index1 = program[programIndex++];
index2 = program[programIndex++];
index3 = program[programIndex++];
result = program[index1] * program[index2];
program[index3] = result;
break;
// End of program!
case 99:
Console.WriteLine(program[desiredIndex]);
break;
default:
// Error! non-valid opcode!
Console.WriteLine("Error! Non-Valid Op-Code!");
return -1;
}
}
return program[desiredIndex];
}
static void ProcessInputFile(StreamReader reader, int[] numbers)
{
string line = null;
reader.DiscardBufferedData();
reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
while (!reader.EndOfStream)
{
line = reader.ReadLine();
string[] values = line.Split(',');
for (int i = 0; i < values.Length; i++)
{
numbers[i] = int.Parse(values[i]);
}
}
}
}
}
|
950cdd81156993bc791bee03229eede78edb0ec0
|
C#
|
chelotron/PhoneBook
|
/MVCPhone/appPhone/appPhone/ViewModels/PhoneBookViewModel.cs
| 2.671875
| 3
|
namespace appPhone.ViewModels
{
using appPhone.Models;
using appPhone.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xamarin.Forms;
public class PhoneBookViewModel:BaseViewModel
{
#region Attributes
private ObservableCollection<Phone> phones;
private ApiService apiService;
#endregion
#region Properties
public ObservableCollection<Phone> Phones
{
get { return this.phones; }
set { SetValue(ref this.phones, value); }
}
#endregion
#region Constructor
public PhoneBookViewModel()
{
this.apiService = new ApiService();
this.LoadPhones();
}
#endregion
#region Methods
private async void LoadPhones()
{
var connection = await this.apiService.CheckConnection();
if(!connection.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert(
"Connection Error",
connection.Message,
"Accept");
return;
}
var response = await this.apiService.GetList<Phone>(
"http://localhost:51071/",
"api/",
"Phones");
if (!response.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert(
"Phone GET Error",
response.Message,
"Accept");
return;
}
MainViewModel mainViewModel = MainViewModel.GetInstance();
mainViewModel.ListPhone = (List<Phone>)response.Result;
this.Phones = new ObservableCollection<Phone>(this.ToPhoneView());
}
private IEnumerable<Phone> ToPhoneView()
{
ObservableCollection<Phone> collection = new ObservableCollection<Phone>();
MainViewModel main = MainViewModel.GetInstance();
foreach (var lista in main.ListPhone)
{
Phone numero = new Phone();
numero.PhoneID = lista.PhoneID;
numero.Name = lista.Name;
numero.Type = lista.Type;
numero.Contact = lista.Contact;
collection.Add(numero);
}
return collection;
}
#endregion
}
}
|
b094b4b56e05d3c9eb2d60b5877afa52cd841176
|
C#
|
arnold191997/SampleMVC
|
/SampleMVC/Services/Method/CustomerService.cs
| 2.6875
| 3
|
using SampleMVC.Models;
using SampleMVC.Services.Interface;
using SampleMVC.Utilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace SampleMVC.Services.Method
{
public class CustomerService : ICustomerService
{
private string connectionstring { get; set; }
public CustomerService()
{
connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["Sqlconnection"].ToString();
}
public List<Customer> GetCustomers()
{
List<Customer> customerlist = new List<Customer>();
try
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("GetCustomers", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var customer = new Customer();
customer.id = int.Parse(reader["CustomerCode"].ToString());
customer.address = reader["Address"].ToString();
customer.addservices = reader["AddService"].ToString();
customer.area = reader["Area"].ToString();
customer.customername = reader["CustName"].ToString();
customer.email = reader["Email"].ToString();
customer.phonenumber = reader["PhoneNumber"].ToString();
customer.status = reader["Status"].ToString();
customerlist.Add(customer);
}
}
}
}
}
}
catch (Exception ex)
{
}
return customerlist;
}
public Customer GetCustomerid(int customerid)
{
var customer = new Customer();
try
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("GetCustomersById", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Id", SqlDbType.Int).Value = customerid;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
customer = new Customer();
customer.id = int.Parse(reader["CustomerCode"].ToString());
customer.address = reader["Address"].ToString();
customer.addservices = reader["AddService"].ToString();
customer.area = reader["Area"].ToString();
customer.customername = reader["CustName"].ToString();
customer.email = reader["Email"].ToString();
customer.phonenumber = reader["PhoneNumber"].ToString();
customer.status = reader["Status"].ToString();
}
}
}
}
}
}
catch (Exception)
{
}
return customer;
}
public List<Service> getservices()
{
List<Service> servicelist = new List<Service>();
try
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("GetServices", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var Service = new Service();
Service.servicecode = int.Parse(reader["ServiceCode"].ToString());
Service.servicename = reader["ServiceName"].ToString();
servicelist.Add(Service);
}
}
}
}
}
}
catch (Exception ex)
{
}
return servicelist;
}
public void insertcustomer(Customer customer)
{
try
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("InsertCustomer", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@customername", SqlDbType.NVarChar).Value = customer.customername;
cmd.Parameters.AddWithValue("@email", SqlDbType.NVarChar).Value = customer.email;
cmd.Parameters.AddWithValue("@phonenumber", SqlDbType.NVarChar).Value = customer.phonenumber;
cmd.Parameters.AddWithValue("@status", SqlDbType.NVarChar).Value = customer.status;
cmd.Parameters.AddWithValue("@area", SqlDbType.NVarChar).Value = customer.area;
cmd.Parameters.AddWithValue("@address", SqlDbType.NVarChar).Value = customer.address;
cmd.Parameters.AddWithValue("@services", SqlDbType.NVarChar).Value = customer.addservices;
cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
}
}
public void updatecustomer(Customer customer)
{
try
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("UpdateCustomer", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@custid", SqlDbType.BigInt).Value = customer.id;
cmd.Parameters.AddWithValue("@customername", SqlDbType.NVarChar).Value = customer.customername;
cmd.Parameters.AddWithValue("@email", SqlDbType.NVarChar).Value = customer.email;
cmd.Parameters.AddWithValue("@phonenumber", SqlDbType.NVarChar).Value = customer.phonenumber;
cmd.Parameters.AddWithValue("@status", SqlDbType.NVarChar).Value = customer.status;
cmd.Parameters.AddWithValue("@area", SqlDbType.NVarChar).Value = customer.area;
cmd.Parameters.AddWithValue("@address", SqlDbType.NVarChar).Value = customer.address;
cmd.Parameters.AddWithValue("@services", SqlDbType.NVarChar).Value = customer.addservices;
cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
}
}
public void deletecustomer(int customerid)
{
try
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("deleteCustomer", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@custid", SqlDbType.BigInt).Value = customerid;
cmd.ExecuteNonQuery();
}
}
}
catch (Exception)
{
}
}
}
}
|
6f2ac7364e2f799027e282e9791dc7ef12c7cb93
|
C#
|
Saladinas/SquaresCounting
|
/src/DevbridgeSquares/Models/PointsListForUpdate.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace DevbridgeSquares.Models
{
public class PointsListForUpdate
{
public PointsListForUpdate(int id, string name, List<Point> points)
{
Name = name;
Points = points;
}
[Required(ErrorMessage = "You should provide a name value.")]
[MaxLength(50, ErrorMessage = "Name cannot be longer than 50 symbols.")]
public string Name { get; set; }
public int NumberOfPoints
{
get
{
return Points.Count;
}
}
[MaxLength(10000)]
public List<Point> Points { get; set; } = new List<Point>();
}
}
|
2c79789287014f1374124cc5c699114542117440
|
C#
|
shendongnian/download4
|
/first_version_download2/482567-43501349-143500933-4.cs
| 2.6875
| 3
|
static void Main(string[] args)
{
AlwaysCreateNewDatabase();
CarBrand hondaDb = null;
using (var context = new MyContext())
{
hondaDb = context.CarBrands.Add(new CarBrand {Name = "Honda"}).Entity;
context.SaveChanges();
}
using (var context = new MyContext())
{
var car2 = new Car() { CarBrandId = hondaDb.CarBrandId };
context.Cars.Add(car2);
context.SaveChanges();
}
}
|
f18b729c9a46e41ad318bff0560d9e2b20073806
|
C#
|
Igonzalezz/PDT
|
/BE-PDT/BE-PDT/Controllers/UserController.cs
| 2.640625
| 3
|
using BE_PDT.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BE_PDT.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly ApplicationDbContext _context;
public UserController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/<UserController>
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> Get()
{
try
{
var listUsers = await _context.User.ToListAsync();
return Ok(listUsers);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// POST api/<UserController>/SingleUser
[HttpPost("SingleUser")]
public async Task<IActionResult> Post([FromBody] User user)
{
try
{
user.FechaReg = DateTime.Now.ToString("d");
_context.Add(user);
await _context.SaveChangesAsync();
return Ok(user);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// POST api/<UserController>/MultiUser
[HttpPost("MultiUser")]
public async Task<IActionResult> PostList([FromBody] IEnumerable<User> userList)
{
try
{
foreach (var user in userList)
{
user.FechaReg = DateTime.Now.ToString("d");
_context.Add(user);
}
await _context.SaveChangesAsync();
return Ok(userList);
}
catch (Exception ex)
{
//this code is to handle the error for fields that have more data than the allowed in the database.
Array error = ex.InnerException.Message.Contains("truncated") ? ex.InnerException.Message.Split("'") : null;
if (error.Length == 7)
{
return Conflict(error.GetValue(3) + ": " + error.GetValue(5));
}
return BadRequest(ex.Message);
}
}
// put api/<UserController>/5
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, [FromBody] User user)
{
try
{
if(id != user.Id)
{
return NotFound();
}
user.FechaReg = _context.User.AsNoTracking().FirstOrDefault(x => x.Id == user.Id).FechaReg;
_context.Update(user);
await _context.SaveChangesAsync();
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// DELETE api/<UserController>/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
try
{
var user = await _context.User.FindAsync(id);
if(user == null)
{
return NotFound();
}
_context.User.Remove(user);
await _context.SaveChangesAsync();
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
|
9ee0f47f7ccdff443785ec90b175206508635ca4
|
C#
|
AlexandrTolstov/ProcessProgramm
|
/ProcessProgramm/Program.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProcessProgramm
{
class Program
{
static void Main(string[] args)
{
foreach (Process process in Process.GetProcesses())
{
Console.WriteLine("ID: {0} Name: {1}", process.Id, process.ProcessName);
}
Process proc = Process.GetProcessesByName("devenv")[0];
Console.WriteLine("ID: {0}", proc.Id);
Console.WriteLine("___________________________________");
ProcessThreadCollection processThread = proc.Threads;
foreach (ProcessThread thread in processThread)
{
Console.WriteLine("Thread: {0} StartTime: {1}", thread.Id, thread.StartTime);
}
Console.WriteLine("___________________________________");
ProcessModuleCollection modules = proc.Modules;
foreach (ProcessModule module in modules)
{
Console.WriteLine("Name: {0} MemorySize: {1}", module.ModuleName, module.ModuleMemorySize);
}
//Process.Start("http://google.com");
//Process.Start("G://Price.php");
//Process.Start(@"C:\Program Files\Adobe\Adobe Photoshop CC 2017\Photoshop.exe");
}
}
}
|
1e2470f7c0ee54b2339ccec9b38aeece3a03715c
|
C#
|
magnus80/at
|
/USSS/Helpers/ReaderMail.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AT;
using AT.WebDriver;
namespace USSS.Helpers
{
class ReaderMail
{
public void ReadLastMail()
{
Yandex y = new Yandex();
y.GoToMailList();
y.GoToLastMail();
y.DownloadFile();
Console.WriteLine(y.GetText());
}
}
internal class Yandex : PageBase
{
public void GoToMailList()
{
Browser.Navigate("https://mail.yandex.ru/");
WebElement login = new WebElement().ByXPath("//input[@name='login']");
login.SendKeys("usss.pnz");
WebElement password = new WebElement().ByXPath("//input[@name='passwd']");
password.SendKeys("Qwerty4$");
WebElement submit =
new WebElement().ByXPath("//button[@class=' nb-button _nb-action-button nb-group-start']");
submit.Click();
Thread.Sleep(10000);
}
public void GoToLastMail()
{
WebElement lastMail =
new WebElement().ByXPath(
"//div[@class='b-messages b-messages_threaded']//a[@class='b-messages__message__link daria-action'][1]");
lastMail.Click();
Thread.Sleep(10000);
}
public void DownloadFile()
{
WebElement a =
new WebElement().ByXPath(
"//a[@class='b-link b-link_w b-link_js b-file__download js-attachments-get-btn daria-action']");
a.Click();
Thread.Sleep(5000);
SendKeys.SendWait("{ENTER}");
Thread.Sleep(10000);
}
public string GetText()
{
WebElement div = new WebElement().ByXPath("//div[@class='b-message-body__content']");
return div.Text;
}
}
}
|
29f3a817f5d8aba5d6d0f19429024728cfbf700d
|
C#
|
nesmeyanov/C-begining
|
/HomeWork7/HomeWork7/Car.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeWork7
{
abstract class Car
{
public event EventHandler<string> Finish;
public int MaxSpeed { get; set; }
public int CurrentSpeed { get; set; }
public int Acceleration { get; set; }
public int Distance { get; set; }
public string Name { get; set; }
private int _totalMoves;
public void Start(int totalDistance)
{
CurrentSpeed = Acceleration;
Distance = 0;
TotalDistance = totalDistance;
_totalMoves = 0;
}
public int TotalDistance { get; set; }
public int Stop()
{
Acceleration = 0;
CurrentSpeed = 0;
Finish.Invoke(this, $"{Name} drivig: {Distance} miles by {_totalMoves} moves");
return Distance;
}
public int SpeedUp()
{
CurrentSpeed += Acceleration;
return CurrentSpeed;
}
public int SpeedDown()
{
CurrentSpeed -= Acceleration;
return CurrentSpeed;
}
public int Move()
{
_totalMoves++;
Distance += CurrentSpeed;
if (TotalDistance <= Distance)
{
Stop();
}
return Distance;
}
}
}
|
717e5e044d50b2983a98c3ce9fa3469f48c0255f
|
C#
|
GrishinM/PO
|
/Circle.cs
| 3.875
| 4
|
using System;
namespace Lab1
{
/// <summary>
/// A circle is a shape consisting of all points in a plane that are a given distance from a given point, the centre
/// </summary>
public class Circle : Figure
{
private double r;
public Circle(Vector a, double r) : base(a)
{
R = r;
}
public double R
{
get => r;
set
{
if (value <= 0)
throw new Exception();
r = value;
}
}
public override double S()
{
return Math.PI * Math.Pow(r, 2);
}
public override double P()
{
return 2 * Math.PI * r;
}
protected override void LocalInfo()
{
Console.WriteLine($"Радиус: {r}{Environment.NewLine}");
}
public override string ToString()
{
return "Круг";
}
}
}
|
deb8fb8ab0ca5b0cb9a716dcf17806097bed595c
|
C#
|
gertjvr/ModernWPF
|
/ModernWPF.Client/Features/Converters/HorizontalAlignmentToTextAlignmentConverter.cs
| 2.75
| 3
|
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace ModernWPF.Client.Features.Converters
{
public class HorizontalAlignmentToTextAlignmentConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var a = value as HorizontalAlignment?;
if (!a.HasValue) return value;
switch (a.Value)
{
case HorizontalAlignment.Left:
return TextAlignment.Left;
case HorizontalAlignment.Right:
return TextAlignment.Right;
default:
return TextAlignment.Center;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
f585e699793e63591e0bab97236e5c6dc27ea67f
|
C#
|
dezlorator/ElementaryTasks
|
/NumericalSequence/Controler.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClientUI;
using ArgumentsValidator;
namespace NumericalSequence
{
class Controler
{
#region private
IArgumentsValidator argumentsValidator;
private const int SIZE_OF_THE_ARGUMENTS_ARRAY = 1;
#endregion
public void Run(string[] args)
{
UI.ConsoleOutPut(StringConstants.WELCOME_STRING);
int number = 0;
if(!CheckArguments(args, ref number))
{
return;
}
NumericalSequenceCreator numericalSequence = GetSequance(number);
RunWithSequence(numericalSequence);
}
private NumericalSequenceCreator GetSequance(int number)
{
return new NumericalSequenceCreator(number);
}
private void RunWithSequence(NumericalSequenceCreator sequence)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var i in sequence)
{
stringBuilder.Append(i);
stringBuilder.Append(", ");
}
stringBuilder.Length -= 2;
UI.ConsoleOutPut(stringBuilder.ToString());
}
private void Intialize()
{
argumentsValidator = new ArgsValidator();
}
private bool CheckArguments(string[] args, ref int number)
{
bool IsCorrect = true;
Intialize();
if (!argumentsValidator.CheckArgsArrayLength(args, SIZE_OF_THE_ARGUMENTS_ARRAY))
{
UI.ConsoleOutPut(StringConstants.WRONG_NUMBER_OF_ARGUMENTS);
IsCorrect = false;
}
else if(!argumentsValidator.TryParseInteger(args[0], ref number))
{
UI.ConsoleOutPut(StringConstants.INFO_ABOUT_INPUT);
IsCorrect = false;
}
return IsCorrect;
}
}
}
|
eb7f42532b196c2af37241a1fdc42ec8b2eaff54
|
C#
|
stevensrf11/Droplet
|
/src/DropletSln/WpfAppCore/Helpers/ColumnBindingHelper.cs
| 2.875
| 3
|
using System.Windows;
using System.Windows.Data;
namespace WpfAppCore.Helpers {
/// <summary>
/// ColumnBindingHelper object
/// Used in xaml binding of grid column
/// </summary>
public class ColumnBindingHelper {
#region Fields
/// <summary>
/// BindingPath Attached DependencyProperty
/// Used in binding columns value from source
/// </summary>
/// <value>DependencyProperty</value>
public static readonly DependencyProperty BindingPathProperty =
DependencyProperty.RegisterAttached("BindingPath",
typeof(string),
typeof(ColumnBindingHelper),
new PropertyMetadata(null, OnBindingPathChanged));
#endregion
#region Property Accessors
#region BindingPath Get/Set Property Accessors
/// <summary>
/// GetBindingPath Get Property Accessor
/// BindingPathProperty Get Accessory
/// </summary>
/// <param name="obj">Source of accessor property</param>
/// <returns>string</returns>
public static string GetBindingPath(DependencyObject obj)
{
return (string)obj.GetValue(BindingPathProperty);
}
/// <summary>
/// SetBindingPath Set Property Accessor
/// BindingPathProperty Set Accessory
/// </summary>
/// <param name="obj">Source of accessor property</param>
/// <param name="value">Value to set property to</param>
public static void SetBindingPath(DependencyObject obj, string value)
{
obj.SetValue(BindingPathProperty, value);
}
#endregion
#endregion
#region Utility Methods
/// <summary>
/// OnBindingPathChanged event change handler
/// Called when the BindingPathProperty changed value
/// </summary>
/// <param name="d">Source of even property change</param>
/// <param name="e">Event property change event information</param>
private static void OnBindingPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var column = d as DevExpress.Xpf.Grid.GridColumn;
if (column == null || e.NewValue == null)
return;
column.Binding = new Binding(e.NewValue.ToString());
}
#endregion
}
}
|
c8e130afb697d641d56101b6f603ff8fb3007c0f
|
C#
|
jeffijoe/messageformat.net
|
/src/Jeffijoe.MessageFormat/Parsing/Literal.cs
| 3.234375
| 3
|
// MessageFormat for .NET
// - Literal.cs
// Author: Jeff Hansen <jeff@jeffijoe.com>
// Copyright (C) Jeff Hansen 2014. All rights reserved.
namespace Jeffijoe.MessageFormat.Parsing
{
/// <summary>
/// Represents a position in the source text where we should look for format patterns.
/// </summary>
public class Literal
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="Literal" /> class.
/// </summary>
/// <param name="startIndex">
/// The start index.
/// </param>
/// <param name="endIndex">
/// The end index.
/// </param>
/// <param name="sourceLineNumber">
/// The source line number.
/// </param>
/// <param name="sourceColumnNumber">
/// The source column number.
/// </param>
/// <param name="innerText">
/// The inner text.
/// </param>
public Literal(
int startIndex,
int endIndex,
int sourceLineNumber,
int sourceColumnNumber,
string innerText)
{
this.StartIndex = startIndex;
this.EndIndex = endIndex;
this.SourceLineNumber = sourceLineNumber;
this.SourceColumnNumber = sourceColumnNumber;
this.InnerText = innerText;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the end index in the source string.
/// </summary>
/// <value>
/// The end index.
/// </value>
public int EndIndex { get; private set; }
/// <summary>
/// Gets the inner text (the content between the braces).
/// </summary>
/// <value>
/// The inner text.
/// </value>
public string InnerText { get; private set; }
/// <summary>
/// Gets the source column number.
/// </summary>
/// <value>
/// The source column number.
/// </value>
public int SourceColumnNumber { get; private set; }
/// <summary>
/// Gets the source line number in the original input string.
/// </summary>
/// <value>
/// The source line number.
/// </value>
public int SourceLineNumber { get; private set; }
/// <summary>
/// Gets the start index in the source string.
/// </summary>
/// <value>
/// The start index.
/// </value>
public int StartIndex { get; private set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns>
/// The <see cref="Literal" />.
/// </returns>
public Literal Clone()
{
// Assuming that InnerText will never be tampered with.
return new Literal(
this.StartIndex,
this.EndIndex,
this.SourceLineNumber,
this.SourceColumnNumber,
this.InnerText);
}
/// <summary>
/// Updates the start and end index.
/// </summary>
/// <param name="resultLength">
/// Length of the result.
/// </param>
/// <param name="literal">
/// The literal that was just formatted.
/// </param>
public void ShiftIndices(int resultLength, Literal literal)
{
int offset = (literal.EndIndex - literal.StartIndex) - 1;
this.StartIndex = (this.StartIndex - offset) + resultLength;
this.EndIndex = (this.EndIndex - offset) + resultLength;
}
#endregion
}
}
|
14ffeb5fe9a8281f593e32263b0e0d2aadfa1823
|
C#
|
mykeels/ScrapR
|
/ScrapR.Models/TrvStart/Query.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScrapR.Models.TrvStart
{
public class Query
{
public Locale locale { get; set; }
public Travellers travellers { get; set; }
public string tripType { get; set; }
public List<Itinerary> itineraries { get; set; }
public class TripType
{
public const string oneWay = "oneway";
public const string returnTrip = "return";
public const string multiTrip = "multiTrip";
public static string GetTripType(int type)
{
if (type == 1) return oneWay;
else if (type == 2) return returnTrip;
else return multiTrip;
}
}
public class Locale
{
public string country { get; set; }
public string currentLocale { get; set; }
}
public class Travellers
{
public int adults { get; set; }
public int children { get; set; }
public int infants { get; set; }
}
public class Itinerary
{
public string departDate { get; set; }
public string id { get; set; }
public string returnDate { get; set; }
public Location destination { get; set; }
public Location origin { get; set; }
public class Location
{
public string display { get; set; }
public Detail value { get; set; }
public class Detail
{
public string airport { get; set; }
public string city { get; set; }
public string code { get; set; }
public string country { get; set; }
public string countryIata { get; set; }
public string iata { get; set; }
public string locationId { get; set; }
public string type { get; set; }
}
}
}
public string GetHomeUrl()
{
return "https://travelstart.com.ng";
}
public static Query GetSampleQuery(string tripType = TripType.oneWay)
{
Query query = new Query();
query = Newtonsoft.Json.JsonConvert.DeserializeObject<Query>(Resources.trvStart_SampleData);
query.tripType = tripType;
int dayAdd = 3;
query.itineraries.ForEach((itinerary) =>
{
itinerary.departDate = DateTime.Now.AddDays(dayAdd).ToString("yyyy-MM-dd");
itinerary.returnDate = DateTime.Now.AddDays(dayAdd + 2).ToString("yyyy-MM-dd");
dayAdd += 3;
});
return query;
}
}
}
|
878247ee6cfaf14ad4e9d82e2bd35a55b90437b7
|
C#
|
matteocontrini/Textify
|
/Textify.Tests/ListsTests.cs
| 2.734375
| 3
|
using Xunit;
namespace Textify.Tests
{
public class ListsTests : BaseTest
{
[Theory]
[InlineData("<ul></ul>", "")]
[InlineData("<ul><li>Test 1</li></ul>", "* Test 1")]
[InlineData("<ul><li>Test 1</li><li>Test 2</li><li>Test 3</li></ul>", "* Test 1\n* Test 2\n* Test 3")]
[InlineData("<ul><li>Test 1: <a href=\"link1\">Link1</a></li><li>Test 2: <a href=\"link2\">Link2</a></li><li>Test 3: <a href=\"link1\">Link1</a></li></ul>", "* Test 1: Link1 [1]\n* Test 2: Link2 [2]\n* Test 3: Link1 [1]\n\n[1] link1\n[2] link2")]
[InlineData("<ul><li>Test 1: <a href=\"link1\">Link1</a></li><li>Test 2: <a href=\"link2\">Link2</a></li><li>Nesting: <ul><li>Test 1: <a href=\"link1\">Link1</a></li><li>Test 2: <a href=\"link2\">Link2</a></li></ul></li><li>Test 3: <a href=\"link1\">Link1</a></li></ul>", "* Test 1: Link1 [1]\n* Test 2: Link2 [2]\n* Nesting:\n\n\t* Test 1: Link1 [1]\n\t* Test 2: Link2 [2]\n\n* Test 3: Link1 [1]\n\n[1] link1\n[2] link2")]
public void ShouldConvertLists(string input, string expected)
{
RunConversion(input, expected);
}
[Theory]
[InlineData("<ul><li>Test 1<ul><li>Nested</li></ul></li</ul>", "* Test 1\n\n\t* Nested")]
[InlineData("<ul><li>Test 1<ul><li>Nested 1</li><li>Nested 2</li><li>Nested 3</li></ul></li><li>Test 2</li></ul>", "* Test 1\n\n\t* Nested 1\n\t* Nested 2\n\t* Nested 3\n\n* Test 2")]
[InlineData("<ul><li>Test 1<ul><li>Nested 1 <ul><li>Nested 1a</li><li>Nested 1b</li></ul></li></ul></li><li>Test 2<ul><li>Nested 2 <ul><li>Nested 2a</li><li>Nested 2b</li></ul></li><li>Nested 3 <ul><li>Nested 3a</li><li>Nested 3b</li></ul></li></ul></li><li>Test 3</li></ul>", "* Test 1\n\n\t* Nested 1\n\n\t\t* Nested 1a\n\t\t* Nested 1b\n\n* Test 2\n\n\t* Nested 2\n\n\t\t* Nested 2a\n\t\t* Nested 2b\n\n\t* Nested 3\n\n\t\t* Nested 3a\n\t\t* Nested 3b\n\n* Test 3")]
public void ShouldRenderNestedLists(string input, string expected)
{
RunConversion(input, expected);
}
}
}
|
fc9f2a8db2f0903f0607e19744da2050d36a8202
|
C#
|
olcan123/Apskaita5vNext
|
/Source/Apskaita5.DAL.Common/MicroOrm/EntityContextNotFoundException.cs
| 2.6875
| 3
|
using System;
namespace Apskaita5.DAL.Common.MicroOrm
{
public class EntityContextNotFoundException : Exception
{
public EntityContextNotFoundException(Type entityType, string query, SqlParam[] parameters)
: base (string.Format(Properties.Resources.DbEntityContextNotFoundException, entityType.Name,
query, parameters.GetDescription()))
{
EntityType = entityType;
Query = query;
Parameters = parameters.GetDescription();
}
/// <summary>
/// Gets a type of the business object for which the initialization context failed to fetch
/// </summary>
public Type EntityType { get; }
/// <summary>
/// Gets an SQL query that was used to fetch initialization context.
/// </summary>
public string Query { get; }
/// <summary>
/// Gets a description of the SQL query parameters that was used to fetch initialization context.
/// </summary>
public string Parameters { get; }
}
}
|
819cdb468685c36aef517ae5183adaa64d92fa39
|
C#
|
CristianBarragan/Shop
|
/Service/Mappers/CategoryMapper.cs
| 2.84375
| 3
|
using DataModelEntities;
using DtoEntities;
using Service.IMappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Service.Mappers
{
public class CategoryMapper : ICategoryMapper
{
public CategoryMapper() {}
public CategoryDTO getDTO(Category entity)
{
CategoryDTO category = new CategoryDTO();
category.CategoryId = entity.CategoryId;
category.Name = entity.Name;
category.Timestamp = entity.Timestamp;
return category;
}
public List<CategoryDTO> getDTOs(List<Category> entities)
{
List<CategoryDTO> category = new List<CategoryDTO>();
entities.ForEach(c => category.Add(getDTO(c)));
return category;
}
public Category getEntity(CategoryDTO dto)
{
Category category = new Category();
category.CategoryId = dto.CategoryId;
category.Name = dto.Name;
category.Timestamp = dto.Timestamp;
return category;
}
public List<Category> getEntities(List<CategoryDTO> dtos)
{
throw new NotImplementedException();
}
}
}
|
1901df3fb35218fd078e5d25a6a7fe600b1dfd40
|
C#
|
mff-uk/exolutio
|
/Model/OCL/Types/CollectionType.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Exolutio.Model.OCL.Types {
/// <summary>
/// CollectionType describes a list of elements of a particular given type. CollectionType is a concrete metaclass whose
/// instances are the family of abstract Collection(T) data types.
/// </summary>
public class CollectionType : DataType, ICompositeType {
public CollectionKind CollectionKind {
private set;
get;
}
public Classifier ElementType {
get;
protected set;
}
public CollectionType(TypesTable.TypesTable tt, Classifier elemetnType, Classifier superClassifier)
: this(tt, CollectionKind.Collection, elemetnType, superClassifier) {
}
protected CollectionType(TypesTable.TypesTable tt, CollectionKind collectionKind, Classifier elemetnType, Classifier superClassifier)
: base(tt,new Namespace("isolatedNS"), GetName(collectionKind, elemetnType), superClassifier) {
this.CollectionKind = collectionKind;
this.ElementType = elemetnType;
}
private static string GetName(CollectionKind kind, Classifier elemetnType) {
return String.Format("{0}({1})", kind.ToString(), elemetnType.QualifiedName);
}
public override bool ConformsToRegister(Classifier other) {
return (other == TypeTable.Library.Any);
}
public override bool Equals(object obj) {
//resi i Equals pro potomky(bag,set,sequence,ordetset)
CollectionType other = obj as CollectionType;
if (other == null)
return false;
return this.CollectionKind == other.CollectionKind
&& this.ElementType == other.ElementType;
}
public override string ToString() {
return Name;
}
public override int GetHashCode() {
return CollectionKind.GetHashCode() + this.ElementType.GetHashCode();
}
public static bool operator ==(CollectionType left, CollectionType right) {
if (object.ReferenceEquals(left, null) && object.ReferenceEquals(right, null))
return true;
if (object.ReferenceEquals(left, null) || object.ReferenceEquals(right, null))
return false;
return left.Equals(right);
}
public static bool operator !=(CollectionType left, CollectionType right) {
return !(left == right);
}
public virtual IteratorOperation LookupIteratorOperation(string name) {
return CollectionIteratorOperation.Lookup(name);
}
#region IConformsToComposite Members
public virtual bool ConformsToComposite(Classifier other) {
//resi i potomky (bag,set,sequence,ordetset)
CollectionType otherColl = other as CollectionType;
if (otherColl != null && (otherColl.GetType().IsSubclassOf(this.GetType()) || otherColl.GetType() == typeof(CollectionType) || otherColl.GetType() == this.GetType())) {
return ElementType.ConformsTo(otherColl.ElementType);
}
else
return false;
}
#endregion
public override Classifier CommonSuperType(Classifier other) {
Classifier common = CommonSuperType<CollectionType>((tt, el) => tt.Library.CreateCollection(CollectionKind.Collection, el), other);
if (common == null) {
if (other is IConformsToComposite && other is ICompositeType == false) {
return other.CommonSuperType(this);// commonSuperType is symetric
}
return base.CommonSuperType(other);
}
return common;
}
public Classifier CommonSuperType<T>(Func<TypesTable.TypesTable, Classifier, T> creator, Classifier other) where T : CollectionType {
if (other is T) {
Classifier commonElementType = this.ElementType.CommonSuperType(((T)other).ElementType);
if (commonElementType != null) {
CollectionType commenType = creator(TypeTable, commonElementType);
TypeTable.RegisterType(commenType);
return commenType;
}
}
return null;
}
#region ICompositeType Members
public bool ConformsToSimple(Classifier other) {
return TypeTable.ConformsTo(this, other, true);
}
#endregion
/// <summary>
///
/// </summary>
static class CollectionIteratorOperation {
static Dictionary<string, IteratorOperation> operation = new Dictionary<string, IteratorOperation>();
public static IteratorOperation Lookup(string name) {
IteratorOperation op;
if (operation.TryGetValue(name, out op)) {
return op;
}
else {
return null;
}
}
private static void RegistredOperation(string name, Func<int, bool> iteratorCount, Func<CollectionType, Classifier, TypesTable.TypesTable, Classifier> expressionType,
Func<CollectionType, Classifier, TypesTable.TypesTable, Classifier> bodyType) {
operation.Add(name, new IteratorOperation(name, iteratorCount, expressionType, bodyType));
}
static CollectionIteratorOperation() {
RegistredOperation("any", c => c == 1, (s, b, t) => s.ElementType, (s, b, t) => t.Library.Boolean);
RegistredOperation("closure", c => c == 1,
(s, b, t) => {
if (s.CollectionKind == CollectionKind.Sequence || s.CollectionKind == CollectionKind.OrderedSet) {
OrderedSetType ordSet = (OrderedSetType)t.Library.CreateCollection(CollectionKind.OrderedSet, s.ElementType);
return ordSet;
}
else {
SetType set = (SetType)t.Library.CreateCollection(CollectionKind.Set, s.ElementType);
t.RegisterType(set);
return set;
}
}
, (s, b, t) => { // TODO revise
if (b is CollectionType && ((CollectionType)b).ElementType.ConformsTo(s.ElementType)) {
return (CollectionType)b;
}
else {
return s.ElementType;
}
});
RegistredOperation("collect", c => c == 1,
(s, b, t) => {
if (s.CollectionKind == CollectionKind.Sequence || s.CollectionKind == CollectionKind.OrderedSet) {
SequenceType seq = (SequenceType)t.Library.CreateCollection(CollectionKind.Sequence, b);
t.RegisterType(seq);
return seq;
}
else {
BagType bag = (BagType)t.Library.CreateCollection(CollectionKind.Bag, b);
t.RegisterType(bag);
return bag;
}
}
, (s, b, t) => b);
RegistredOperation("collectNested", c => c == 1,
(s, b, t) => {
return t.Library.Boolean;
}
, (s, b, t) => b);
RegistredOperation("exists", c => c == 1,
(s, b, t) => {
return t.Library.Boolean;
}
, (s, b, t) => t.Library.Boolean);
RegistredOperation("forAll", c => c == 1,
(s, b, t) => {
return t.Library.Boolean;
}
, (s, b, t) => t.Library.Boolean);
RegistredOperation("isUnique", c => c == 1,
(s, b, t) => {
return t.Library.Boolean;
}
, (s, b, t) => b);
RegistredOperation("one", c => c == 1,
(s, b, t) => t.Library.Boolean
, (s, b, t) => t.Library.Boolean);
RegistredOperation("select", c => c == 1,
(s, b, t) => s
, (s, b, t) => t.Library.Boolean);
//RegistredOperation("isUnique", c => c == 1,
// (s, b, t) =>
// {
// return t.Library.Boolean;
// }
// , (s, b, t) => b);
//RegistredOperation("select", c => c == 1,
// (s, b, t) => s
// , (s, b, t) => t.Library.Boolean);
RegistredOperation("selectUnique", c => c == 1,
(s, b, t) => (SetType)t.Library.CreateCollection(CollectionKind.Set, s.ElementType)
, (s, b, t) => b);
RegistredOperation("reject", c => c == 1,
(s, b, t) => s
, (s, b, t) => t.Library.Boolean);
RegistredOperation("sortedBy", c => c == 1,
(s, b, t) => {
if (s.CollectionKind == CollectionKind.Sequence || s.CollectionKind == CollectionKind.Bag) {
SequenceType seq = (SequenceType)t.Library.CreateCollection(CollectionKind.Sequence, b);
t.RegisterType(seq);
return seq;
}
else {
OrderedSetType ordSet = (OrderedSetType)t.Library.CreateCollection(CollectionKind.OrderedSet, b);
t.RegisterType(ordSet);
return ordSet;
}
}
, (s, b, t) => t.Library.Boolean);
}
}
public bool DeferredFullInitialization { get; set; }
}
}
|
eefc8c72ed70d5d365e24656bf13cab39eba01ae
|
C#
|
Innos/Soft-Uni-Homework
|
/CSharp Basics Homework/06HomeworkConditionalStatements/HomeworkConditionalStatements/06TheBiggestOfFiveNumbers/TheBiggestOfFiveNumbers.cs
| 3.984375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class TheBiggestOfFiveNumbers
{
static void Main(string[] args)
{
Console.WriteLine("Input 5 numbers each at a seperate line:");
double[] num = new double[5];
for (int i = 0; i < num.Length; i++)
{
num[i] = double.Parse(Console.ReadLine());
}
//Console.WriteLine(num.Max()); //Solution with one line, but oh well have your ifs
if(num[0]>num[1] && num[0] > num[2] && num[0] > num[3] && num[0] > num[4])
{
Console.WriteLine(num[0]);
}
else if (num[1] > num[0] && num[1] > num[2] && num[1] > num[3] && num[1] > num[4])
{
Console.WriteLine(num[1]);
}
else if (num[2] > num[0] && num[2] > num[1] && num[2] > num[3] && num[2] > num[4])
{
Console.WriteLine(num[2]);
}
else if (num[3] > num[0] && num[3] > num[1] && num[3] > num[2] && num[3] > num[4])
{
Console.WriteLine(num[3]);
}
else if (num[4] > num[0] && num[4] > num[1] && num[4] > num[2] && num[4] > num[3])
{
Console.WriteLine(num[4]);
}
}
}
|
cc587b5ad03c2b56892a0e9f1e757e26d9db6062
|
C#
|
thiagoguardado/autoshot
|
/Assets/scripts/Weapons/WeaponCrateFactory.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponBoxFactory : MonoBehaviour
{
public static WeaponBoxFactory Instance { get; private set; }
public WeaponBox WeaponBoxPrefab;
public void Awake()
{
Instance = this;
}
public WeaponBox CreateWeaponBox()
{
GameObject weaponBoxObject = Instantiate(WeaponBoxPrefab.gameObject);
WeaponBox weaponBox = weaponBoxObject.GetComponent<WeaponBox>();
return weaponBox;
}
}
|
cb8df347bb989fb1f43833bfc243611d08e4ab1d
|
C#
|
EstebanGuru/Obl-ProgDeRedes
|
/ServerLogHost/Program.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Configuration;
namespace ServerLogHost
{
class Program
{
static void Main(string[] args)
{
ServiceHost studentServiceHost = null;
try
{
Uri httpBaseAddress = new Uri(ConfigurationManager.AppSettings["httpBaseAddress"]);
//Instantiate ServiceHost
studentServiceHost = new ServiceHost(typeof(WcfLogServices.LogService),
httpBaseAddress);
//Add Endpoint to Host
studentServiceHost.AddServiceEndpoint(typeof(WcfLogServices.ILogService),
new WSHttpBinding(), "");
//Metadata Exchange
ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
serviceBehavior.HttpGetEnabled = true;
studentServiceHost.Description.Behaviors.Add(serviceBehavior);
//Open
studentServiceHost.Open();
Console.WriteLine("Service is live now at: {0}", httpBaseAddress);
Console.ReadKey();
}
catch (Exception ex)
{
studentServiceHost = null;
Console.WriteLine("There is an issue with StudentService" + ex.Message);
Console.ReadKey();
}
}
}
}
|
93c25bf2228ecdacff9c5470dbe9740fa222c7ba
|
C#
|
PlumpMath/DesignPatterns-404
|
/DesignPatterns/Creational/Abstract Factory/ProductA1.cs
| 2.578125
| 3
|
using System;
namespace DesignPatterns.Creational.Abstract_Factory
{
class ProductA1 : IAbstractProductA
{
public void PrintProductName()
{
Console.WriteLine("ProductA1");
}
}
}
|
35bb087795c7274898fe6526a0bfbc4dcbac483e
|
C#
|
Alireza1044/AP96972
|
/Assignment13/Assignment13Tests/PrivacyScrubberTest.cs
| 2.796875
| 3
|
using System;
using Logger;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LoggerTest
{
[TestClass]
public class PrivacyScrubberTest
{
[TestMethod]
public void SinglePhoneNumberTest()
{
string piiNum = "(517)303-5279";
string scrubbedPII = "(XXX)XXX-XXXX";
string testString = $"My phone number is {piiNum}";
string scrubbedString = $"My phone number is {scrubbedPII}";
string replacedPIINum = PhoneNumberScrubber.Instance.Scrub(testString);
Assert.AreEqual(replacedPIINum, scrubbedString);
}
[TestMethod]
public void MultiplePhoneNumbersTest()
{
string pii1 = "(517)303-5279";
string pii2 = "206-323-1212";
string scrubbedPII1 = "(XXX)XXX-XXXX";
string scrubbedPII2 = "XXX-XXX-XXXX";
string testString = $"My phone number was {pii1} but it is {pii2} now";
string scrubbedString = $"My phone number was {scrubbedPII1} but it is {scrubbedPII2} now";
string replacedPIINum = PhoneNumberScrubber.Instance.Scrub(testString);
Assert.AreEqual(replacedPIINum, scrubbedString);
}
[TestMethod]
public void IDTest()
{
string testString = "Ali's KodMelli is 108-0492704";
string expectedString = "Ali's KodMelli is XXX-XXXXXXX";
string scrubbedString = IDScrubber.Instance.Scrub(testString);
Assert.AreEqual(scrubbedString, expectedString);
}
[TestMethod]
public void EmailTest()
{
string testString = "Ali's Email is Ali@gmail.com";
string expectedString = "Ali's Email is Xxx@xxxxx.xxx";
string scrubbedString = EmailScrubber.Instance.Scrub(testString);
Assert.AreEqual(scrubbedString, expectedString);
}
[TestMethod]
public void CCTest()
{
string testString = "Ali's CC is 6037-4324-5432-7547";
string expectedString = "Ali's CC is XXXX-XXXX-XXXX-XXXX";
string scrubbedString = CCScrubber.Instance.Scrub(testString);
Assert.AreEqual(scrubbedString, expectedString);
}
[TestMethod]
public void FullNameTest()
{
string testString = "Mr. Bill Gates failed the exam.";
string expectedString = "Xx. Xxxx Xxxxx failed the exam.";
string maskedString = FullNameScrubber.Instance.Scrub(testString);
Assert.AreEqual(expectedString, maskedString);
}
}
}
|
49138f3ec313be2b744a0ae562ffa34a35a9b9a0
|
C#
|
balackLT/adventOfCode
|
/src/AdventOfCode.Solutions2020/Day09/Solution.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using AdventOfCode.Executor;
namespace AdventOfCode.Solutions2020.Day09;
public class Solution : ISolution
{
public int Day { get; } = 9;
public string SolveFirstPart(Input input)
{
var codes = input
.GetLinesAsList()
.Select(long.Parse)
.ToList();
Debug.Assert(HasSum(40, new List<long>{35, 20, 15, 25, 47}));
Debug.Assert(!HasSum(127, new List<long>{95, 102, 117, 150, 182}));
var result = FindInvalidCode(25, codes);
return result.ToString();
}
public string SolveSecondPart(Input input)
{
var codes = input
.GetLinesAsList()
.Select(long.Parse)
.ToList();
var invalidCode = FindInvalidCode(25, codes);
for (int i = 0; i < codes.Count - 1; i++)
{
long sum = 0;
long min = long.MaxValue;
long max = 0;
for (int j = i; j < codes.Count; j++)
{
min = Math.Min(codes[j], min);
max = Math.Max(codes[j], max);
sum += codes[j];
if (sum == invalidCode)
return (max + min).ToString();
}
}
return 0.ToString();
}
private long FindInvalidCode(int preambleLength, List<long> codes)
{
for (int i = preambleLength; i < codes.Count; i++)
{
var subList = codes
.Skip(i - preambleLength)
.Take(preambleLength)
.ToList();
if (!HasSum(codes[i], subList))
{
return codes[i];
}
}
return 0;
}
private bool HasSum(long target, IList<long> list)
{
for (var i = 0; i < list.Count; i++)
{
for (var j = 0; j < list.Count; j++)
{
if (i != j && list[i] + list[j] == target)
return true;
}
}
return false;
}
}
|
b75f21366b20990f131ce69e720ffe4839f14f0a
|
C#
|
umhr/FullScreenWebBrowser
|
/FullScreenWebBrowser/FullScreenWebBrowser/MultiScreen.cs
| 2.953125
| 3
|
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FullScreenWebBrowser
{
class MultiScreen
{
public Rectangle rectangle()
{
Rectangle result = new Rectangle(0, 0, 0, 0);
Rectangle temp = new Rectangle(0, 0, 0, 0);
// ディスプレイの解像度を取得するには?
// http://www.atmarkit.co.jp/fdotnet/dotnettips/003screen/screen.html
foreach (Screen s in Screen.AllScreens)
{
//Console.WriteLine(s.Bounds);
temp.X = Math.Min(temp.X, s.Bounds.X);
temp.Y = Math.Min(temp.Y, s.Bounds.Y);
temp.Width = Math.Max(temp.Width, s.Bounds.Right);
temp.Height = Math.Max(temp.Height, s.Bounds.Bottom);
}
//Console.WriteLine(screenRectangle);
// ウィンドウの位置やサイズを指定
result.X = temp.X;
result.Y = temp.Y;
result.Width = temp.Width - temp.X;
result.Height = temp.Height - temp.Y;
if (Properties.Settings.Default.Width > -1)
{
result.Width = Properties.Settings.Default.Width;
}
if (Properties.Settings.Default.Height > -1)
{
result.Height = Properties.Settings.Default.Height;
}
if (Properties.Settings.Default.Left > -1)
{
result.X = Properties.Settings.Default.Left;
}
if (Properties.Settings.Default.Top > -1)
{
result.Y = Properties.Settings.Default.Top;
}
return result;
}
}
}
|
984093c6d4911a4ab0743471a42ec6a0081aeb5d
|
C#
|
SachaVanleene/WonderCrash
|
/Assets/Scripts/UI/Personalities.cs
| 2.765625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Personality {
public string titre, nom, profession, age, description, atout, handicap, bouton;
}
public static class Personalities {
private static Dictionary<int, Personality> _conv = new Dictionary<int, Personality> {
//Personalité 1 (par défaut) : Ernest -> rôle patient
{1, new Personality { titre = "Personnalité N°1",
nom = "Ernest Fringuant",
profession = "Boucher",
age = "32 ans",
description = "Père de famille et vie ordinaire était votre quotidien. Mais tout a basculé le jour où vous avez accidentellement confondu un gigot avec la main d’une cliente. Vous étiez pourtant sûr d’avoir vu ce gigot flotter dans les airs mais rien à faire, personne ne vous croit… Ainsi, vous finissez en asile persuadé d’être sain d’esprit.",
atout = "Aimé des autres patients, ils se confient toujours à vous.",
handicap = "Vous n’êtes pas censé vous échapper, ce n'est pas bien !",
bouton = "Touche 1 pour accéder au personnage" }
},
//Personalité 2 : Jean-Eude -> rôle médecin
{2, new Personality { titre = "Personnalité N°2",
nom = "Jean-Eude Marseault",
profession = "Médecin",
age = "47 ans",
description = "Après de longues années d’études en médecine, vous avez décidé de vous spécialiser dans la chirurgie esthétique. Votre rêve ? Rendre le monde plus beau. Suite à une erreur fatale sur une patiente, vous vous êtes retrouvé sans travail mais vous continuez de côtoyer vos semblables dans la vie de tous les jours en attente de votre retour à l’heure de gloire.",
atout = "Vous êtes un maître du dialogue avec le personnel de l’asile.",
handicap = "Vos talents incomparables sont souvents sollicités par les autres médecins.",
bouton = "Touche 2 pour accéder au personnage" }
},
//Personalité 3 : Jack -> rôle garde
{3, new Personality { titre = "Personnalité N°3 ",
nom = "Jack Boxer",
profession = "Gardien d’asile",
age = "22 ans",
description = "Seul sain d’esprit parmi une famille de fous, vous avez pris l’habitude de vous occuper de votre famille dès le plus jeune âge.Courses, factures, repassage, vous étiez sur tous les fronts. Mais un beau jour, l’assistante sociale a jugé que vous ne pouviez pas, du haut de vos 10 ans, continuer de faire tout cela. 12 ans plus tard, vous devenez gardien d’asile et êtes de retour auprès de votre famille.",
atout = "Vous pouvez circuler tranquillement en présence des gardiens à votre poursuite.",
handicap = "Vous prenez les patients pour votre famille du coup votre taux de folie augmente plus vite que la normale.",
bouton = "Touche 3 pour accéder au personnage" }
},
};
public static Personality GetPerso(int id) {
Personality text;
_conv.TryGetValue(id, out text);
return text;
}
}
|
32f30acb97940f854866a7e15525860c39da1b08
|
C#
|
Cinchoo/ChoETL
|
/src/Test/ChoManifoldWriterTest/Program.cs
| 2.578125
| 3
|
using ChoETL;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace ChoManifoldWriterTest
{
[TestFixture]
[SetCulture("en-US")] // TODO: Check if correct culture is used
class Program
{
static void Main(string[] args)
{
ToTextTest();
}
[SetUp]
public void Setup()
{
Environment.CurrentDirectory = TestContext.CurrentContext.TestDirectory;
// Needs to be reset because of some tests changes these settings
ChoTypeConverterFormatSpec.Instance.Reset();
ChoXmlSettings.Reset();
}
//[Test]
public static void ToTextTest()
{
string expected = @"Raj Mar212
1|123124|65657657|05122019|DateText||0|0
10,Mark,2/2/2001 12:00:00 AM,True,$100.00";
string actual = null;
List<object> objs = new List<object>();
SampleType s = new SampleType() { Field1 = "Raj", Field2 = "Mark", Field3 = 1212 };
objs.Add(s);
var o = new Orders { CustomerID = "123124", OrderID = 1, EmployeeID = 65657657, OrderDate = DateTime.Today, RequiredDate = "DateText" };
objs.Add(o);
dynamic rec1 = new ExpandoObject();
rec1.Id = 10;
rec1.Name = "Mark";
rec1.JoinedDate = new DateTime(2001, 2, 2);
rec1.IsActive = true;
rec1.Salary = new ChoCurrency(100);
objs.Add(rec1);
actual = ChoManifoldWriter.ToText(objs);
Assert.AreEqual(expected, actual);
}
//[Test]
public static void QuickTest()
{
string expected = @"Raj Mar212
1|123124|65657657|05122019|DateText||0|0
10,Mark,2/2/2001 12:00:00 AM,True,$100.00";
string actual = null;
List<object> objs = new List<object>();
SampleType s = new SampleType() { Field1 = "Raj", Field2 = "Mark", Field3 = 1212 };
objs.Add(s);
var o = new Orders { CustomerID = "123124", OrderID = 1, EmployeeID = 65657657, OrderDate = new DateTime(2019,12,5), RequiredDate = "DateText" };
objs.Add(o);
dynamic rec1 = new ExpandoObject();
rec1.Id = 10;
rec1.Name = "Mark";
rec1.JoinedDate = new DateTime(2001, 2, 2);
rec1.IsActive = true;
rec1.Salary = new ChoCurrency(100);
objs.Add(rec1);
using (var stream = new MemoryStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
using (var parser = new ChoManifoldWriter(writer))
{
parser.Write(objs);
writer.Flush();
stream.Position = 0;
actual = reader.ReadToEnd();
}
Assert.AreEqual(expected, actual);
}
}
[ChoFixedLengthRecordObject]
public class SampleType
{
[ChoFixedLengthRecordField(0, 8)]
[ChoDefaultValue("() => DateTime.Now")]
public string Field1 { get; set; }
[ChoFixedLengthRecordField(8, 3)]
public string Field2 { get; set; }
[ChoFixedLengthRecordField(11, 3)]
public int Field3 { get; set; }
public override string ToString()
{
return "SampleType: " + Field2 + " - " + Field3;
}
}
[ChoCSVRecordObject("|")]
public class Orders
{
public int OrderID { get; set; }
public string CustomerID { get; set; }
public int EmployeeID { get; set; }
[ChoTypeConverter(typeof(ChoDateTimeConverter), Parameters = "ddMMyyyy")]
public DateTime OrderDate { get; set; }
public string RequiredDate { get; set; }
public string ShippedDate { get; set; }
public int ShipVia { get; set; }
public decimal Freight { get; set; }
public override string ToString()
{
return "Orders: " + OrderID + " - " + CustomerID + " - " + Freight;
}
}
[ChoCSVRecordObject(";")]
public class Customer
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Country { get; set; }
public override string ToString()
{
return "Customer: " + CustomerID + " - " + CompanyName + ", " + ContactName;
}
}
[ChoCSVRecordObject]
public class EmployeeRecWithCurrency
{
public int? Id { get; set; }
public string Name { get; set; }
public ChoCurrency Salary { get; set; }
}
}
|
2867530f95cc361fd169951fc1ad0321d82afb72
|
C#
|
AnthonyMoscoso/WalletProyect-.net-core
|
/Core.Entities/Utilities/EntityGenerator/Abstracts/IRandomValueGenerator.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Core.Entities.Utilities.EntityGenerator.Abstracts
{
public interface IRandomValueGenerator
{
/// <summary>
/// Generate a random char
/// </summary>
/// <returns>a random char</returns>
char GetRandomChar(char init = 'a',char end='z');
/// <summary>
/// Generate a random char from a collection of char
/// </summary>
/// <param name="values"></param>
/// <returns>random char</returns>
char GetRandomChar(List<char> values);
/// <summary>
/// Generate a random Datetime
/// </summary>
/// <param name="startDate">min date for generate</param>
/// <param name="finishDate">max date for generate</param>
/// <returns>a random Date/returns>
DateTime GetRandomDate(DateTime? startDate = null, DateTime? finishDate = null);
/// <summary>
/// Generate a random Datetime from a list
/// </summary>
/// <param name="values">list of datetime</param>
/// <returns>random datetime</returns>
DateTime GetRandomDate(List<DateTime> values);
/// <summary>
/// Genetare a random int from max or minValue
/// </summary>
/// <param name="maxValue">max value</param>
/// <param name="minValue">min value</param>
/// <returns>random int</returns>
int GetRandomInt(int maxValue = 10, int minValue = 0);
/// <summary>
/// Take a random int fron a list of values
/// </summary>
/// <param name="values">list of int</param>
/// <returns>one of list entities</returns>
int GetRandomInt(List<int> values);
/// <summary>
/// Generate a random double
/// </summary>
/// <param name="maxValue">max value</param>
/// <param name="minValue">min value</param>
/// <returns>a random double</returns>
double GetRandomDouble(double maxValue = 10, double minValue = 0);
/// <summary>
/// Generate a random double
/// </summary>
/// <param name="values">list to get a double</param>
/// <returns>double from list</returns>
double GetRandomDouble(List<double> values);
/// <summary>
/// Generate a random string
/// </summary>
/// <param name="textFormats">format of text</param>
/// <returns>random string</returns>
string GetRandomString(TextFormats textFormats = TextFormats.Mixed);
/// <summary>
/// Generate a random string from a list
/// </summary>
/// <param name="values">list of string</param>
/// <returns>random string from list</returns>
string GetRandomString(string[] values);
/// <summary>
/// Generate a random string
/// </summary>
/// <param name="maxLength">max lenght to string</param>
/// <param name="minLength">min lenght to string </param>
/// <param name="textFormats">text format</param>
/// <returns>random string</returns>
string GetRandomString(int maxLength, int minLength = 0, TextFormats textFormats = TextFormats.Mixed);
/// <summary>
/// Generate a random bool
/// </summary>
/// <returns>random bool</returns>
bool GetRandomBool();
/// <summary>
/// Generate a random Phone number
/// </summary>
/// <returns>phone number</returns>
string GetRandomNumberPhone();
/// <summary>
/// Generate a random string of numbers
/// </summary>
/// <param name="n">string only with numbers</param>
/// <returns></returns>
string GetStringOfNumber(int n);
/// <summary>
/// Generate a random email
/// </summary>
/// <param name="textFormats">type of text</param>
/// <returns>email</returns>
string GetRandomEmail(TextFormats textFormats = TextFormats.Mixed);
#region From parameters
/// <summary>
/// Generate a random date from parameters in a dictionary
/// </summary>
/// <param name="parameters">keys and value for rules to generate a random date</param>
/// <returns>the random date generate</returns>
DateTime GetRandomDateFromParameters(IDictionary<string, string> parameters);
/// <summary>
/// Generate a random Double from parameters in a dictionary
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
double GetRandomDoubleFromParameters(IDictionary<string, string> parameters);
/// <summary>
/// Generate a random Int from parameters in a dictionary
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
int GetRandomIntFromParameters(IDictionary<string, string> parameters);
/// <summary>
/// Generate a random Char from parameters in a dictionary
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
char GetRandomCharFromParameters(IDictionary<string, string> parameters);
/// <summary>
/// Generate a random string from parameters in a dictionary
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
string GetRandomStringFromParameters(IDictionary<string, string> parameters);
#endregion;
}
}
|
a58e30a6e694ea8daae17de9827ca384cb6e8886
|
C#
|
starshayayord/crack
|
/src/Yord.Crack.Begin/LeetCode/Task1470.cs
| 3.484375
| 3
|
namespace Yord.Crack.Begin.LeetCode
{
// дан массив [x1,x2,x3....,y1,y2,y3..] вернуть [x1,y1,x2,y2...]. 2N - длина массива. Все числа - неотрицательные.
public class Task1470
{
public static int[] Shuffle(int[] nums, int n)
{
var r = new int[nums.Length];
for (int i = 0; i < n; i++)
{
r[2 * i] = nums[i]; // четные равны Хам, т.е. просто по порядку
r[2 * i + 1] = nums[i + n]; // нечетные равны n+1 по порядку
}
return r;
}
public static int[] Shuffle_NoSpace(int[] nums, int n)
{
int i = 0;
while (i < 2 * n) // до конца массива
{
int j = i; //ищем хелаемый индекс начиная от текущего
while (nums[i] >= 0) //пока на iом индексе не на встало число, которое должно там стоять
{
// положенный индекс текущего числа равен для левой части 2j для правой части (j-n)*2+1
j = j < n ? 2 * j : (j - n) * 2 + 1;
// для номеров, которые встали на нужный индекс ставим -, чтоб не перебирать их снова
int t = nums[i]; // для этого числа нашли положенный индекс
nums[i] = nums[j]; //ставим число с желаемого индекса на место переставляемого
nums[j] = -t; //ставим текущее помеченное "-" число на желаемый индекс
}
i++; // на iом месте стоит верное число, переходим к следующему
}
for (i = 0; i < 2 * n; i++)
{
nums[i] = -nums[i];
}
return nums;
}
}
}
|
94bdd04fc7cef9011af9f58a9a5c87b78c215a89
|
C#
|
944414275/WPF-FunctionTest
|
/WpfChartTest1/MainWindow.xaml.cs
| 2.625
| 3
|
using Microsoft.Research.DynamicDataDisplay.DataSources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DynamicDataDisplay;
namespace WpfChartTest1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public ObservableDataSource<Point> source1 = null;
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Environment.Exit(0);
e.Cancel = false;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
source1 = new ObservableDataSource<Point>();
// Set identity mapping of point in collection to point on plot
source1.SetXYMapping(p => p);
// Add the graph. Colors are not specified and chosen random
//plotter.AddLineGraph(source1, 2, "Data row");
// Force everyting to fit in view
plotter.Viewport.FitToView();
// Start computation process in second thread
Thread simThread = new Thread(new ThreadStart(Simulation));
simThread.IsBackground = true;
simThread.Start();
}
private void Simulation()
{
int i = 0;
while (true)
{
Point p1 = new Point(i, 0.3 * Math.Sin(i));
source1.AppendAsync(Dispatcher, p1);
i++;
Thread.Sleep(10);
}
}
}
}
|
d087556aa214e27bd9b5aad2679b7947564291a8
|
C#
|
dp433/CodewarsTasks
|
/Tests/NextBiggerNumberTest.cs
| 2.96875
| 3
|
using System;
using NUnit.Framework;
using NextBiggerNumber;
namespace Tests
{
[TestFixture]
class NextBiggerNumberTest
{
[Test]
public void Test1()
{
Console.WriteLine("****** Small Number");
Assert.AreEqual(21, Kata.NextBiggerNumber(12));
Assert.AreEqual(531, Kata.NextBiggerNumber(513));
Assert.AreEqual(2071, Kata.NextBiggerNumber(2017));
Assert.AreEqual(441, Kata.NextBiggerNumber(414));
Assert.AreEqual(414, Kata.NextBiggerNumber(144));
}
}
}
|
65127b618c9793ed92a811e5e29b5ad34ab3f162
|
C#
|
LambertW/DesignPattern
|
/DesignPattern.Visitor/Demo2/Goods.cs
| 2.5625
| 3
|
namespace DesignPattern.Visitor.Demo2
{
public abstract class Goods
{
public abstract void Operate(Visitor visitor);
public int Size { get; set; }
public int State { get; set; }
}
}
|
db1637a7c7fddd56ebee41f06a1039ab85785068
|
C#
|
Svichkaryov/CA
|
/Matrix.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Matrix
{
[Serializable()]
public class Matrix : ISerializable
{
public Matrix(SerializationInfo info, StreamingContext ctxt)
{
rows = (int)info.GetValue("rows", typeof(int));
cols = (int)info.GetValue("cols", typeof(int));
element = (int[,])info.GetValue("element", typeof(int[,]));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("rows", rows);
info.AddValue("cols", cols);
info.AddValue("element", element);
}
/// <summary>
/// Class attributes/members
/// </summary>
private int rows, cols;
private int[,] element;
/// <summary>
/// Contructor
/// </summary>
public Matrix(int rows, int cols)
{
this.rows = rows;
this.cols = cols;
element = new int[rows, cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
element[i, j] = 0;
}
/// <summary>
/// Properites
/// </summary>
public int Rows
{
get { return rows; }
}
public int Cols
{
get { return cols; }
}
/// <summary>
/// Indexer
/// </summary>
public int this[int row, int col]
{
get { return GetElement(row, col); }
set { SetElement(row, col, value); }
}
/// <summary>
/// Internal functions for getting/setting values
/// </summary>
public int GetElement(int row, int col)
{
if (row < 0 || row > rows - 1 || col < 0 || col > Cols - 1)
throw new MatrixVectorException("Invalid index specified");
return element[row, col];
}
public void SetElement(int row, int col, int value)
{
if (row < 0 || row > Rows - 1 || col < 0 || col > Cols - 1)
throw new MatrixVectorException("Invalid index specified");
element[row, col] = value;
}
/// <summary>
/// Returns the transpose of the current matrix
/// </summary>
public Matrix Transpose()
{
Matrix transposeMatrix = new Matrix(this.Cols, this.Rows);
for (int i = 0; i < transposeMatrix.Rows; i++)
for (int j = 0; j < transposeMatrix.Cols; j++)
transposeMatrix[i, j] = this[j, i];
return transposeMatrix;
}
/// <summary>
/// Return the minor of a matrix element[Row,Col]
/// </summary>
public static Matrix Minor(Matrix matrix, int row, int col)
{
Matrix minor = new Matrix(matrix.Rows - 1, matrix.Cols - 1);
int m = 0, n = 0;
for (int i = 0; i < matrix.Rows; i++)
{
if (i == row)
continue;
n = 0;
for (int j = 0; j < matrix.Cols; j++)
{
if (j == col)
continue;
minor[m, n] = matrix[i, j];
n++;
}
m++;
}
return minor;
}
/// <summary>
/// Returns the determinent of the current Matrix
/// It computes the determinent in the traditional way (i.e. using minors)
/// </summary>
public int Determinent()
{
return Determinent(this);
}
/// <summary>
/// Helper function for the above Determinent() method
/// it calls itself recursively and computes determinent using minors
/// </summary>
private int Determinent(Matrix matrix)
{
int det = 0;
if (matrix.Rows == 1)
return matrix[0, 0];
for (int j = 0; j < matrix.Cols; j++)
det += (matrix[0, j] * Determinent(Matrix.Minor(matrix, 0, j)) * (int)System.Math.Pow(-1, 0 + j));
return det;
}
/// <summary>
/// Returns the adjoint of the current matrix
/// </summary>
public Matrix Adjoint()
{
Matrix adjointMatrix = new Matrix(this.Rows, this.Cols);
for (int i = 0; i < this.Rows; i++)
for (int j = 0; j < this.Cols; j++)
adjointMatrix[i, j] = (int)Math.Pow(-1, i + j) * (Minor(this, i, j).Determinent());
adjointMatrix = adjointMatrix.Transpose();
return adjointMatrix;
}
/// <summary>
/// Returns the inverse of a square matrix over GF(2) (by adjoint method)
/// </summary>
public Matrix Inverse()
{
if (this.Determinent() == 0)
throw new MatrixVectorException("Matrix is non-regular !");
Matrix m = (this.Adjoint() / this.Determinent());
for (int i = 0; i < this.Rows; i++)
for (int j = 0; j < this.Cols; j++)
if (m[i, j] < 0)
m[i, j] = -1 * m[i, j];
return m;
}
/// <summary>
/// Operator for the matrix object
/// includes binary operator /
/// </summary>
public static Matrix operator /(Matrix matrix, int iNo)
{ return Matrix.Multiply(matrix, iNo); }
/// <summary>
/// Internal function for the above operator
/// </summary>
private static Matrix Multiply(Matrix matrix, int iNo)
{
Matrix result = new Matrix(matrix.Rows, matrix.Cols);
for (int i = 0; i < matrix.Rows; i++)
for (int j = 0; j < matrix.Cols; j++)
result[i, j] = matrix[i, j] * iNo;
return result;
}
/// <summary>
/// The function adds one superpoly for the current matrix
/// </summary>
public Matrix AddRow(List<int> superpoly)
{
Matrix m = new Matrix(this.Rows + 1, this.Cols);
for (int i = 0; i < this.Rows; i++)
for (int j = 0; j < this.Cols; j++)
m[i, j] = this[i, j];
for (int j = 0; j < this.Cols; j++)
m[m.Rows - 1, j] = superpoly[j];
return m;
}
/// <summary>
/// The function deletes the last row of the current matrix
/// </summary>
public Matrix DeleteLastRow()
{
Matrix m = new Matrix(this.Rows - 1, this.Cols);
for (int i = 0; i < this.Rows - 1; i++)
for (int j = 0; j < this.Cols; j++)
m[i, j] = this[i, j];
return m;
}
/// <summary>
/// The function deletes the first columnm of the current matrix
/// </summary>
public Matrix DeleteFirstColumn()
{
Matrix m = new Matrix(this.Rows, this.Cols - 1);
for (int i = 0; i < m.Rows; i++)
for (int j = 1; j <= m.Cols; j++)
m[i, j - 1] = this[i, j];
return m;
}
}
/// <summary>
/// Exception class for Matrix and Vector, derived from System.Exception
/// </summary>
public class MatrixVectorException : Exception
{
public MatrixVectorException()
: base()
{ }
public MatrixVectorException(string Message)
: base(Message)
{ }
public MatrixVectorException(string Message, Exception InnerException)
: base(Message, InnerException)
{ }
}
}
|
2bd7849f0cca20ea8c450eb30e834e7f0db5c4cd
|
C#
|
ProyectoL4/Recurso
|
/RRHHPlanilla/RRHH.BL/BusquedaBL.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RRHH.BL
{
public class BusquedaBL
{
private SqlConnection conexion = new SqlConnection("Data Source = (localdb)\\MSSQLLocalDB; Initial Catalog = RRHHDB; Integrated Security = true");
private DataSet ds;
public DataTable MostrarDatos()
{
conexion.Open();
SqlCommand cmd = new SqlCommand("select * from Trabajador", conexion);
//SqlCommand cmd2 = new SqlCommand("SELECT dbo.Cargo.Id, dbo.Cargo.Descripcion FROM dbo.Cargo INNER JOIN dbo.Trabajador ON dbo.Cargo.Id = dbo.Trabajador.CargoId", conexion);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
//SqlDataAdapter ad2 = new SqlDataAdapter(cmd2);
ds = new DataSet();
ad.Fill(ds, "tabla");
//ad2.Fill(ds, "tabla");
conexion.Close();
return ds.Tables["tabla"];
}
public DataTable Buscar(string nombre, string apellido)
{
conexion.Open();
SqlCommand cmd = new SqlCommand(string.Format("select * from Trabajador where Nombre like '%{0}%'", nombre), conexion);
SqlCommand cmd2 = new SqlCommand(string.Format("select * from Trabajador where Apellido like '%{0}%'", apellido), conexion);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
SqlDataAdapter ad2 = new SqlDataAdapter(cmd2);
ds = new DataSet();
ad.Fill(ds, "tabla");
ad2.Fill(ds, "tabla");
conexion.Close();
return ds.Tables["tabla"];
}
}
}
|
bd9b663b38d56d14e1f1263fc76bda3c4bd152af
|
C#
|
IgnorantCoder/AutomaticDifferentiation
|
/sample/csharp/Sample/CallOptionPricerBottomup.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample
{
class CallOptionPricerBottomup
{
private Dictionary<String, Double> Result { get; }
public Double Price
{
get
{
return this.Result[@"Price"];
}
}
public double Delta
{
get
{
return this.Result[@"Delta"];
}
}
public double Theta
{
get
{
return this.Result[@"Theta"];
}
}
public double Vega
{
get
{
return this.Result[@"Vega"];
}
}
private static Adcs.Bu.Variable N(Adcs.Bu.Variable x)
{
return 0.5 * (1.0 + Adcs.Bu.Math.Erf(x / Math.Sqrt(2.0)));
}
private static Adcs.Bu.Variable Ndash(Adcs.Bu.Variable x)
{
return Adcs.Bu.Math.Exp(-(x * x) / 2.0) / Math.Sqrt(2.0 * Math.PI);
}
private static Adcs.Bu.Variable CalcD1(
Adcs.Bu.Variable x,
Adcs.Bu.Variable t,
Adcs.Bu.Variable k,
Adcs.Bu.Variable s,
Adcs.Bu.Variable r)
{
return (Adcs.Bu.Math.Log(x / k) + (r + s * s * 0.5) * t) / (s * Adcs.Bu.Math.Sqrt(t));
}
private static Adcs.Bu.Variable CalcD2(
Adcs.Bu.Variable x,
Adcs.Bu.Variable t,
Adcs.Bu.Variable k,
Adcs.Bu.Variable s,
Adcs.Bu.Variable r)
{
return (Adcs.Bu.Math.Log(x / k) + (r - s * s * 0.5) * t) / (s * Adcs.Bu.Math.Sqrt(t));
}
public static Adcs.Bu.Variable CalcPrice(
Adcs.Bu.Variable x,
Adcs.Bu.Variable t,
Adcs.Bu.Variable k,
Adcs.Bu.Variable s,
Adcs.Bu.Variable r)
{
var d1 = CalcD1(x, t, k, s, r);
var d2 = CalcD2(x, t, k, s, r);
var df = Adcs.Bu.Math.Exp(-r * t);
return x * N(d1) - df * k * N(d2);
}
static public CallOptionPricerBottomup Calculate(
Double x,
Double t,
Double k,
Double s,
Double r)
{
var mgr = Adcs.Bu.VariableManager.Create();
var v_x = mgr.ToVariable(x);
var v_t = mgr.ToVariable(t);
var v_k = mgr.ToVariable(k);
var v_s = mgr.ToVariable(s);
var v_r = mgr.ToVariable(r);
var ret = CalcPrice(
x: v_x,
t: v_t,
k: v_k,
s: v_s,
r: v_r);
var dy = Adcs.Bu.Derivative.Create(ret);
var data = new Dictionary<String, Double>
{
{ @"Price", ret.ToDouble() },
{ @"Delta", dy.D(v_x) },
{ @"Vega", dy.D(v_s) },
{ @"Theta", dy.D(v_t) }
};
return new CallOptionPricerBottomup(data);
}
private CallOptionPricerBottomup(Dictionary<String, Double> result)
{
this.Result = result;
}
}
}
|
1c44a9ff4714df5f503544c721a3f8974b1eff8b
|
C#
|
pcbender/AxosoftAPI.NET
|
/AxosoftAPI.NET/Helpers/CustomerConverter.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using AxosoftAPI.NET.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AxosoftAPI.NET.Helpers
{
public class CustomerConverter : JsonConverter
{
public override bool CanWrite
{
get
{
// This forces Json.NET to use the default Json serializer
return false;
}
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Customer));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load JObject from stream
var jObject = JObject.Load(reader);
// Create "emtpy" object
var target = new Customer();
// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);
// Find any "custom_" fields
var customFields = ((IEnumerable<KeyValuePair<string, JToken>>)jObject).Where(x =>
x.Key.ToLower().StartsWith("custom_") &&
x.Key.ToLower() != "custom_fields");
// If we got any
if (customFields != null && customFields.Any())
{
// If we need to initiate the custom fields property
if (target.CustomFields == null)
{
target.CustomFields = new Dictionary<string, object>();
}
// Add all custom fields
foreach (var token in customFields)
{
target.CustomFields.Add(token.Key, ((JValue)token.Value).Value);
}
}
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// No implementation needed since CanWrite is hardcoded to return 'false'
throw new NotImplementedException();
}
}
}
|
1248bf66ec56ce94c030ca9d1e03debc0dd77a06
|
C#
|
UniversityOfAppliedSciencesFrankfurt/LearningApi
|
/LearningApi/src/MLAlgorithms/GaussianMeanFilter/GaussianFilter.cs
| 3.140625
| 3
|
using LearningFoundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GaussianAndMeanFilter
{
public class GaussianFilter : IPipelineModule<double[,,], double[,,]>
{
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="ctx"></param>
/// <returns></returns>
public double[,,] Run(double[,,] data, IContext ctx)
{
return filter(data);
}
/// <summary>
/// Implementing a Gaussian filter matrix of (3x3) dimention
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private double[,,] filter(double[,,] data)
{
double[,,] result = data;
for (int x = 1; x < data.GetLength(0) - 1; x++)
{
for (int y = 1; y < data.GetLength(1) - 1; y++)
{
//Red value first column
var prev11R = data[x - 1, y - 1, 0];
var prev12R = data[x, y - 1, 0];
var prev13R = data[x + 1, y - 1, 0];
//Red value sencond column
var prev21R = data[x - 1, y, 0];
var prev22R = data[x, y, 0];
var prev23R = data[x + 1, y, 0];
//Red value third column
var prev31R = data[x - 1, y + 1, 0];
var prev32R = data[x, y + 1, 0];
var prev33R = data[x + 1, y + 1, 0];
//Green value first column
var prev11G = data[x - 1, y - 1, 1];
var prev12G = data[x, y - 1, 1];
var prev13G = data[x + 1, y - 1, 1];
//Green value sencond column
var prev21G = data[x - 1, y, 1];
var prev22G = data[x, y, 1];
var prev23G = data[x + 1, y, 1];
//Green value third column
var prev31G = data[x - 1, y + 1, 1];
var prev32G = data[x, y + 1, 1];
var prev33G = data[x + 1, y + 1, 1];
//Blue value first column
var prev11B = data[x - 1, y - 1, 2];
var prev12B = data[x, y - 1, 2];
var prev13B = data[x + 1, y - 1, 2];
//Blue value sencond column
var prev21B = data[x - 1, y, 2];
var prev22B = data[x, y, 2];
var prev23B = data[x + 1, y, 2];
//Blue value third column
var prev31B = data[x - 1, y + 1, 2];
var prev32B = data[x, y + 1, 2];
var prev33B = data[x + 1, y + 1, 2];
//Calculating new pixel value
double avgR = (prev11R * 1 + prev12R * 2 + prev13R * 1 + prev21R * 2 + prev22R * 4 + prev23R * 2 + prev31R * 1 + prev32R * 2 + prev33R * 1) / 16;
double avgG = (prev11G * 1 + prev12G * 2 + prev13G * 1 + prev21G * 2 + prev22G * 4 + prev23G * 2 + prev31G * 1 + prev32G * 2 + prev33G * 1) / 16;
double avgB = (prev11B * 1 + prev12B * 2 + prev13B * 1 + prev21B * 2 + prev22B * 4 + prev23B * 2 + prev31B * 1 + prev32B * 2 + prev33B * 1) / 16;
//Replacing the original pixel value by the calculated value
result[x, y, 0] = avgR;
result[x, y, 1] = avgG;
result[x, y, 2] = avgB;
}
}
return result;
}
}
}
|
3480be903a6aa41757aa9fa12bcdecc872fee8af
|
C#
|
singhsugga/dating-api
|
/Extensions/Extensions.cs
| 2.859375
| 3
|
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using DatingAPI.Helpers;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace DatingAPI.Extensions
{
public static class Extensions
{
public static void AddApplicationError(this HttpResponse response, string message)
{
response.Headers.Add("Application-Error", message);
response.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
response.Headers.Add("Access-Control-Allow-Origin", "*");
}
public static void AddPagination(this HttpResponse response, int currentPage, int itemsPerPage, int totalItems,
int totalPages)
{
var paginationHeader = new PaginationHeader(currentPage, itemsPerPage, totalItems, totalPages);
var camelCaseFormatter = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
response.Headers.Add("Pagination", JsonConvert.SerializeObject(paginationHeader, camelCaseFormatter));
response.Headers.Add("Access-Control-Expose-Headers", "Pagination");
}
public static int CalculateAge(this DateTime date)
{
var age = DateTime.Today.Year - date.Year;
if (date.AddYears(age) > DateTime.Today)
age--;
return age;
}
public static string GetUserIpAddress(this HttpContext context)
{
// https://stackoverflow.com/a/61479085/7220620
var ipAddress = context.Connection.RemoteIpAddress;
if (ipAddress == null)
return "";
// If we got an IPV6 address, then we need to ask the network for the IPV4 address
// This usually only happens when the browser is on the same machine as the server.
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
ipAddress = Dns.GetHostEntry(ipAddress).AddressList
.First(x => x.AddressFamily == AddressFamily.InterNetwork);
return ipAddress.ToString();
}
}
}
|
7f1a8a38175b7ea807873219306f7608c57a15cf
|
C#
|
shendongnian/download4
|
/code1/183094-3485658-7265743-2.cs
| 2.953125
| 3
|
public class Car
{
public Car(float gravity, float speed)
{
Gravity = gravity;
Speed = speed;
}
protected float Gravity { get; private set; }
...
|