commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
fb6a8ef5ca6a03ae4513d643acf24bae5c40de22
Add AssemblyInfo.cs
HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite,lanyudhy/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,yangle/HaliteIO,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,HaliteChallenge/Halite-II
airesources/CSharp/AssemblyInfo.cs
airesources/CSharp/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Halite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Halite")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1460a17a-7e8b-4643-b0a9-06a1b86f07e9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
a6f80e8b877a54e354fd440a277fcedadb4f3816
Create 2.cs
rikkus/adventofcode2016,rikkus/adventofcode2016
2.cs
2.cs
struct Vector { public int X; public int Y; }; Vector Move(Vector position, char move) { switch (move) { case 'U': return new Vector { X = position.X, Y = Math.Max(0, position.Y - 1) }; case 'D': return new Vector { X = position.X, Y = Math.Min(keypad[0].Length - 1, position.Y + 1) }; case 'L': return new Vector { X = Math.Max(0, position.X - 1), Y = position.Y }; case 'R': return new Vector { X = Math.Min(keypad[0].Length - 1, position.X + 1), Y = position.Y }; default: throw new ArgumentOutOfRangeException(nameof(move), move, "Must be one of: U, D, L, R"); } } static int[][] keypad = new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9 } }; const string testInput = @"ULL RRDDD LURDL UUUUD"; const string realInput = @"DLUUULUDLRDDLLLUDULLULLRUURURLUULDUUUDLDDRUDLUULLRLDDURURDDRDRDLDURRURDLDUURULDDULDRDDLDLDLRDRUURLDLUDDDURULRLLLLRLULLUDRDLDUURDURULULULRLULLLULURLRDRDDDDDDDLRLULUULLULURLLDLRLUDULLDLLURUDDLDULDLULDDRLRLRDDLRURLLLURRLDURRDLLUUUUDRURUULRLDRRULLRUDLDRLUDRDRDRRDDURURRDRDRUDURDLUDRUDLRRULDLRDDRURDDUUDLDRDULDDRRURLLULRDRURLRLDLLLUULUUDLUDLDRRRRDUURULDUDUDRLDLLULLLRDDDDDLRDDLLUULLRRRDURLRURDURURLUDRRLRURDRDRRRRULUDLDRDULULRUDULLLUDRRLRLURDDURULDUUDULLURUULRDRDULRUUUDURURDDRRUDURRLRDRULRUUU LDRURRUUUULDRDDDLLULDRUDDRLLDLDRDLRUDDDLDDULULULLRULDUDRRDLRUURURDRURURDLLRUURDUUDRLDURDRDLRRURURDUUUURUURRLLLDRDUURRRRURULUUUDLUDDRUURRLDULRDULRRRRUDURRLURULRURRDRDLLDRRDUDRDURLDDRURULDRURUDDURDLLLUURRLDRULLURDRDRLDRRURRLRRRDDDDLUDLUDLLDURDURRDUDDLUDLRULRRRDRDDLUDRDURDRDDUURDULRRULDLDLLUDRDDUDUULUDURDRLDURLRRDLDDLURUDRLDUURLLRLUDLLRLDDUDLLLRRRLDLUULLUDRUUDRLDUUUDUURLRDDDDRRDRLDDRDLUDRULDDDRDUULLUUUUULDULRLLLRLLDULRDUDDRDDLRRLRDDULLDURRRURDDUDUDDRLURRLUUUULLDRDULUUDRDULDLLUDLURDLLURRDLUULURRULRLURRRRRUURDDURLRLLDDLRRDUUURDRDUDRDDDLLDDRDRRRLURRDUULULULULRRURDDLDDLLLRUDDDDDDLLLRDULURULLRLRDRR DDRLLLDLRRURRDLDDRUURRURRLRRRRUURUURDLURRRDDLRUDRURLUURLLRRLRLURLURURDULLLLDLRURULUUDURRLULRDRDRRDDLLULRLUDLUUUDRLLRRURRLDULDDLRRLUUUUDDLRLDRLRRDRDLDDURDDRDDLDLURLRRRDDUDLLRLRLURRRRULLULLLLDRLDULDLLDULRLDRDLDDRRDDDDRUDRLLURULRLDDLLRRURURDDRLLLULLULDDRDLDDDLRLLDRLDRUURRULURDDRLULLDUURRULURUUDULLRUDDRRLLDLLRDRUDDDDLLLDDDLLUUUULLDUUURULRUUDUUUDDLDURLDRDRRLLUDULDLUDRLLLDRRRULUUDDURUDRLUDDRRLLDUDUURDDRURLUURDURURURRUUDUDDLLLDRRRURURRURDLRULLDUDRLRLLRUDRUDLR RRRDRLRURLRRLUURDRLDUURURLRDRRUDLLUUDURULLUURDLLDRRLURRUDUUDRRURLRRDULLDDLRRRUDUUDUUDLDDDLUUDLDULDDULLDUUUUDDUUDUDULLDDURRDLRRUDUDLRDUULDULRURRRLDLLURUDLDDDRRLRDURDLRRLLLRUDLUDRLLLRLLRRURUDLUDURLDRLRUDLRUULDRULLRLDRDRRLDDDURRRUDDDUDRRDRLDDRDRLLRLLRDLRDUDURURRLLULRDRLRDDRUULRDDRLULDLULURDLRUDRRDDDLDULULRDDRUDRLRDDRLDRDDRRRDUURDRLLDDUULRLLLULLDRDUDRRLUUURLDULUUURULLRLUDLDDLRRDLLRDDLRDRUUDURDDLLLDUUULUUDLULDUDULDRLRUDDURLDDRRRDLURRLLRRRUDDLDDRURDUULRUURDRRURURRRUUDUDULUDLUDLLLUUUULRLLRRRRDUDRRDRUDURLUDDLDRDLDDRULLRRULDURUL DLLLRDDURDULRRLULURRDULDLUDLURDDURRLLRRLLULRDLDRDULRLLRDRUUULURRRLLRLDDDRDRRULDRRLLLLDLUULRRRURDDRULLULDDDLULRLRRRUDRURULUDDRULDUDRLDRRLURULRUULLLRUURDURLLULUURUULUUDLUDLRRULLLRRLRURDRRURDRULRURRUDUDDDRDDULDLURUDRDURLDLDLUDURLLRUULLURLDDDURDULRLUUUDLLRRLLUURRDUUDUUDUURURDRRRRRRRRRUDULDLULURUDUURDDULDUDDRDDRDRLRUUUUDLDLRDUURRLRUUDDDDURLRRULURDUUDLUUDUUURUUDRURDRDDDDULRLLRURLRLRDDLRUULLULULRRURURDDUULRDRRDRDLRDRRLDUDDULLDRUDDRRRD"; static string[] moveLists = realInput.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); void Main() { string.Join ( "", moveLists.Aggregate ( new[] { new Vector { X = 1, Y = 1 } }, (positions, moveList) => positions.Concat ( new[] { moveList.Aggregate ( positions.Last(), (position, move) => Move(position, move) ) } ) .ToArray() ) .Skip(1) .Select(position => keypad[position.Y][position.X]) ) .Dump(); // 36629? }
mit
C#
83c8ec2ecb68c3d0f0e61eb70b451c4a050290b9
fix head offset for teleport position
vazor222/PartPacifist
Assets/Scripts/SingleLinkTeleporter.cs
Assets/Scripts/SingleLinkTeleporter.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SingleLinkTeleporter : MonoBehaviour { public float POSITION_CHECK_TIME_LENGTH_IN_SECONDS = 3; public GameObject myDestination; public GameObject headCannon; public GameObject preTeleportPosistion; private float positionCheckStartTime; // Use this for initialization void Start() { positionCheckStartTime = 0; Debug.Log("Current preTeleportPosistion:" +preTeleportPosistion.transform.position ); Debug.Log("Current myDestination:" +myDestination.transform.position ); } // Update is called once per frame void Update() { //Debug.Log("Current playerRig:" +playerRig.transform.position ); //Debug.Log("Current targetLocation:" +targetLocation.transform.position ); } void OnTriggerEnter(Collider other) { teleportCheck(other); } void OnTriggerStay(Collider other) { teleportCheck(other); } private void teleportCheck(Collider other) { if (positionCheckStartTime == 0) { if (other.gameObject == headCannon && facingMostlyForward(other.gameObject.transform.forward)) { // start timer positionCheckStartTime = Time.time; Debug.Log ("TimerStarted:" + positionCheckStartTime); } } else { if( Time.time - positionCheckStartTime >= POSITION_CHECK_TIME_LENGTH_IN_SECONDS ) { Debug.Log ("Teleport time? other.gameObject:"+other.gameObject+" headCannon:"+headCannon); if (other.gameObject == headCannon && facingMostlyForward (other.gameObject.transform.forward)) { // teleport now! Debug.Log ("Teleported! ....hopefully"); Debug.Log ("preTeleportPosistion when teleporting:" + preTeleportPosistion.transform.position); Debug.Log ("myDestination when teleporting:" + myDestination.transform.position); Vector3 offset = headCannon.transform.position - preTeleportPosistion.transform.position; preTeleportPosistion.transform.position = myDestination.transform.position + offset; //OriginTransform.position = Pointer.SelectedPoint + offset; Debug.Log ("myDestination after teleporting:" + myDestination.transform.position); Debug.Log("preTeleportPosistion after teleporting:" +preTeleportPosistion.transform.position ); } else Debug.Log ("was not other or matching forward"); positionCheckStartTime = 0; } } } private bool facingMostlyForward(Vector3 playerCurrentForward) { bool dotResult = Vector3.Dot(playerCurrentForward, gameObject.transform.forward) > 0; Debug.Log ("checking facing: " + playerCurrentForward + " gameObject.transform.forward:"+gameObject.transform.forward+" result:"+dotResult); return dotResult; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SingleLinkTeleporter : MonoBehaviour { public float POSITION_CHECK_TIME_LENGTH_IN_SECONDS = 3; public GameObject myDestination; public GameObject headCannon; public GameObject preTeleportPosistion; private float positionCheckStartTime; // Use this for initialization void Start() { positionCheckStartTime = 0; Debug.Log("Current preTeleportPosistion:" +preTeleportPosistion.transform.position ); Debug.Log("Current myDestination:" +myDestination.transform.position ); } // Update is called once per frame void Update() { //Debug.Log("Current playerRig:" +playerRig.transform.position ); //Debug.Log("Current targetLocation:" +targetLocation.transform.position ); } void OnTriggerEnter(Collider other) { teleportCheck(other); } void OnTriggerStay(Collider other) { teleportCheck(other); } private void teleportCheck(Collider other) { if (positionCheckStartTime == 0) { if (other.gameObject == headCannon && facingMostlyForward(other.gameObject.transform.forward)) { // start timer positionCheckStartTime = Time.time; Debug.Log ("TimerStarted:" + positionCheckStartTime); } } else { if( Time.time - positionCheckStartTime >= POSITION_CHECK_TIME_LENGTH_IN_SECONDS ) { Debug.Log ("Teleport time? other.gameObject:"+other.gameObject+" headCannon:"+headCannon); if (other.gameObject == headCannon && facingMostlyForward (other.gameObject.transform.forward)) { // teleport now! Debug.Log ("Teleported! ....hopefully"); Debug.Log ("preTeleportPosistion when teleporting:" + preTeleportPosistion.transform.position); Debug.Log ("myDestination when teleporting:" + myDestination.transform.position); preTeleportPosistion.transform.position = myDestination.transform.position; //OriginTransform.position = Pointer.SelectedPoint + offset; Debug.Log ("myDestination after teleporting:" + myDestination.transform.position); Debug.Log("preTeleportPosistion after teleporting:" +preTeleportPosistion.transform.position ); } else Debug.Log ("was not other or matching forward"); positionCheckStartTime = 0; } } } private bool facingMostlyForward(Vector3 playerCurrentForward) { bool dotResult = Vector3.Dot(playerCurrentForward, gameObject.transform.forward) > 0; Debug.Log ("checking facing: " + playerCurrentForward + " gameObject.transform.forward:"+gameObject.transform.forward+" result:"+dotResult); return dotResult; } }
mpl-2.0
C#
aa7e60756a440973d09ab5ec364f00d0b8bbb135
Create GTV.cs
etormadiv/njRAT_0.7d_Stub_ReverseEngineering
j_csharp/OK/GTV.cs
j_csharp/OK/GTV.cs
//Reversed by Etor Madiv public static object GTV(string n, object ret) { try { return F.Registry.CurrentUser.OpenSubKey( System.String.Concat("Software\\", RG) ).GetValue( n, System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(ret) ); } catch(Exception) { } return ret; }
unlicense
C#
7bba2cb5524690ed6f88fb21b49b4b81d14f7ef1
Add AeroListView
stefan-baumann/AeroSuite
AeroSuite/Controls/AeroListView.cs
AeroSuite/Controls/AeroListView.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AeroSuite.Controls { /// <summary> /// An aero-styled ListView. /// </summary> /// <remarks> /// A ListView with the "Explorer"-WindowTheme applied and. /// If the operating system is Windows XP or older, nothing will be changed. /// </remarks> [DesignerCategory("Code")] [DisplayName("Aero ListView")] [Description("An aero-styled ListView.")] [ToolboxItem(true)] [ToolboxBitmap(typeof(ListView))] public class AeroListView : ListView, ITestControl { private const int LVS_EX_DOUBLEBUFFER = 0x10000; private const int LVM_SETEXTENDEDLISTVIEWSTYLE = 4150; /// <summary> /// Initializes a new instance of the <see cref="AeroListView"/> class. /// </summary> public AeroListView() : base() { this.FullRowSelect = true; } /// <summary> /// Raises the <see cref="E:HandleCreated" /> event. /// </summary> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); if (PlatformHelper.VistaOrHigher) { NativeMethods.SetWindowTheme(this.Handle, "explorer", null); NativeMethods.SendMessage(this.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, new IntPtr(LVS_EX_DOUBLEBUFFER), new IntPtr(LVS_EX_DOUBLEBUFFER)); } } /// <summary> /// Prepares the control for tests (setting properties etc.). /// </summary> void ITestControl.PrepareForTests() { this.SmallImageList = TestDataProvider.SmallImageList; this.LargeImageList = TestDataProvider.LargeImageList; this.Items.AddRange(new string[] { "First Item", "Second Item", "Third Item", "Fourth Item", "Fifth Item" }.Select((s, i) => new ListViewItem(s, i)).ToArray()); this.Size = new Size(400, 300); } } }
mit
C#
5cf2db9f666021410bb0b486d1cc7f1c678e9386
Read and write a Trie
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
VariousArtists/print_a_trie.cs
VariousArtists/print_a_trie.cs
// Print a trie using System; using System.Collections.Generic; using System.Linq; using System.IO; class Node { private Dictionary<char, Node> Next = new Dictionary<char, Node>(); private bool IsWord; public static Node Read(List<String> items) { return items .Aggregate( new Node(), (acc, x) => { var root = acc; for (var i = 0 ; i < x.Length; i++) { if (!root.Next.ContainsKey(x[i])) { root.Next[x[i]] = new Node { IsWord = i == x.Length - 1 }; } root = root.Next[x[i]]; } return acc; }); } public static List<String> Write(Node node) { return node.Next.Keys.Count == 0 ? new [] { String.Empty }.ToList() : node.Next.Keys.SelectMany(x => Write(node.Next[x]).Select(y => String.Format("{0}{1}", x, y)).ToList()) .OrderBy(x => x) .ToList(); } } class Solution { static IEnumerable<String> GetWords(int n) { var r = new Random(); var lines = File.ReadAllLines("/usr/share/dict/words"); return Enumerable .Range(0, n) .Select(x => lines[r.Next(lines.Length)]); } static void Main() { var words = GetWords(100).OrderBy(x => x).ToList(); Console.WriteLine(String.Join(", ", words)); Console.WriteLine(String.Join(", ", Node.Write(Node.Read(words)))); if (!words.SequenceEqual(Node.Write(Node.Read(words)))) { Console.WriteLine("HAHAHA IDOIT!!!"); } } }
mit
C#
0f16a5dea5d6f002ad54522b238db9560a12c31e
Create C#.cs
TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets
Backend/CreateUACGroup/C#.cs
Backend/CreateUACGroup/C#.cs
import RestSharp; public string Server = "https://api.chayns.net/v2.0"; private const string Secret = "Your Tapp Secret"; public const int MangerUacGroup = 1; [HttpPost] [Route("CreateUac")] public IHttpActionResult CreateUac(int locationId, int tappId, string name, string showName) { try { //Create the UAC-group dynamic group = CreateUacGroup(locationId, tappId, name, showName); //null means creation failed if (group == null) { return InternalServerError(); } else { //Build group-model object groupModel = new { userGroupId=group.userGroupId, tappId=group.tappId, countMember = group.countMember, showName =group.showName, name =group.name }; return Ok(groupModel); } } catch (Exception exception) { return InternalServerError(exception); } } public dynamic CreateUacGroup(int locationId, int tappId, string name, string showName) { //Set up RestSharp RestClient restClient = new RestClient(Server); //Build the request RestRequest req = new RestRequest("/" + locationId + "/Uac"); req.Method = Method.POST; req.AddHeader("Content-Type", "application/json"); req.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToString(tappId) + ':' + Secret))); req.RequestFormat = DataFormat.Json; req.AddBody(new { showname = showName, name = name }); //Run the request IRestResponse resp = restClient.Execute(req); //Test response health if (resp.StatusCode == HttpStatusCode.Created) { //Parse data dynamic data = JObject.Parse(resp.Content); //Just return the group-model return data.data[0]; } //Return null if the request went wrong return null; }
mit
C#
76ce34d28963e759f98ea4c515a781462c265dd2
Create StringExtensions.cs
keith-hall/Extensions,keith-hall/Extensions
src/StringExtensions.cs
src/StringExtensions.cs
public static class StringExtensions { public static int IndexOfEnd (this string value, string find, int? start = null) { var pos = value.IndexOf(find, start.HasValue ? start.Value : 0); if (pos > -1) pos += find.Length; return pos; } public static IEnumerable<KeyValuePair<string, int>> AllIndexesOf (this string value, IEnumerable<string> find) { foreach (var search in find) { var pos = 0; while ((pos = value.IndexOf(search, pos)) > -1) { yield return new KeyValuePair<string, int>(search, pos); pos += search.Length; } } } public static IEnumerable<KeyValuePair<string, int>> AllSortedIndexesOf (this string value, IEnumerable<string> find) { var indexes = AllIndexesOf(value, find); return indexes.OrderBy(i => i.Value); } public static int CountOccurrences (this string value, IEnumerable<string> find) { return value.AllIndexesOf(find).Count(); } public static string TextBefore (this string value, string find) { var pos = value.IndexOf(find); if (pos == -1) pos = 0; return value.Substring(0, pos); } public static string TextAfter (this string value, string find) { var pos = value.IndexOfEnd(find); if (pos == -1) pos = value.Length; return value.Substring(pos); } public static string TextBetween (this string value, string start, string end) { return value.TextAfter(start).TextBefore(end); } public static IEnumerable<string> AllTextBetween (this string value, string start, string end) { // get all indexes of the start and end tokens, sorted in order var results = value.AllSortedIndexesOf(new [] { start, end }); var nextIsStart = true; // first we want a start token var startpos = -1; // for each occurrence foreach (var v in results) { // ignore the result if it isn't what we need next, or if it occurs before the previous token ends if (v.Key == (nextIsStart ? start : end) && v.Value >= startpos) { if (nextIsStart) { startpos = v.Value + start.Length; nextIsStart = false; } else { yield return value.Substring(startpos, v.Value - startpos); nextIsStart = true; startpos = v.Value + end.Length; } } } } }
apache-2.0
C#
e7be131b8990e5397e13c5049caaafde4c0c447c
Add the ISnmpModule interface definition to Careminster release
TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC
OpenSim/Region/Framework/Interfaces/ISnmpModule.cs
OpenSim/Region/Framework/Interfaces/ISnmpModule.cs
/////////////////////////////////////////////////////////////////// // // (c) Careminster LImited, Melanie Thielker and the Meta7 Team // // This file is not open source. All rights reserved // public interface ISnmpModule { void Alert(string message); void Trap(string message); }
bsd-3-clause
C#
55b5bafbe6bd03c94308a9163179e9eca13b883e
Create selenium-hello-world-002.cs
TheSeleniumGuys/Code-Drills
selenium-hello-world-002.cs
selenium-hello-world-002.cs
//See the blog post at: using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpendQA.Selenium.IE; IWebdriver.driver = new InternetExplorerDriver(); driver.Navigate().GoToURL("http://www.google.com"); IWebElement element = driver.FindElement(By.name("q")); element.SendKeys("Hello, World!"); driver.FindElement(By.Name("btnG")).Click(); driver.Quit();
mit
C#
af7277a9e8dcc9ae6d6ba4bce72eb67522c15c48
Add HexString
carbon/Amazon
src/Amazon.S3/Helpers/HexString.cs
src/Amazon.S3/Helpers/HexString.cs
using System; using System.Runtime.CompilerServices; namespace Amazon.Helpers { internal static class HexString { // Based on: http://stackoverflow.com/questions/623104/byte-to-hex-string/3974535#3974535 public static string FromBytes(this byte[] bytes) { var buffer = new char[bytes.Length * 2]; byte b; for (int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx) { b = ((byte)(bytes[bx] >> 4)); buffer[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30); b = ((byte)(bytes[bx] & 0x0F)); buffer[++cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30); } return new string(buffer); } // COPYRIGHT: https://stackoverflow.com/a/17923942 public static byte[] ToBytes(ReadOnlySpan<char> hexString) { byte[] bytes = new byte[hexString.Length / 2]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = ToByte(hexString[i * 2], hexString[i * 2 + 1]); } return bytes; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte ToByte(char a, char b) { int hi = a - 65; hi = hi + 10 + ((hi >> 31) & 7); int lo = b - 65; lo = lo + 10 + ((lo >> 31) & 7) & 0x0f; return (byte)(lo | hi << 4); } } }
mit
C#
5876512d5774704f6228e04a380c4e2a3b32e4e7
Add DescribeInstanceTypesResponse
carbon/Amazon
src/Amazon.Ec2/Responses/DescribeInstanceTypesResponse.cs
src/Amazon.Ec2/Responses/DescribeInstanceTypesResponse.cs
#nullable disable using System.Xml.Serialization; namespace Amazon.Ec2 { [XmlRoot("DescribeInstanceTypesResponse", Namespace = Ec2Client.Namespace)] public sealed class DescribeInstanceTypesResponse { [XmlElement("requestId")] public string RequestId { get; set; } [XmlElement("nextToken")] public string NextToken { get; set; } [XmlArray("instanceTypeSet")] [XmlArrayItem("item")] public InstanceTypeInfo[] InstanceTypes { get; set; } public static DescribeInstanceTypesResponse Deserialize(string text) { return Ec2Serializer<DescribeInstanceTypesResponse>.Deserialize(text); } } }
mit
C#
17f56ccbdc5e2fa9493f2ccf7597b6cd1f26a72d
Add sendgeneric command to TestClient to allow one to send arbitrary GenericMessagePackets to the simulator for testing purposes
radegastdev/libopenmetaverse,radegastdev/libopenmetaverse,radegastdev/libopenmetaverse,radegastdev/libopenmetaverse
Programs/examples/TestClient/Commands/Agent/GenericMessageCommand.cs
Programs/examples/TestClient/Commands/Agent/GenericMessageCommand.cs
using System; using System.Collections.Generic; using System.Text; using OpenMetaverse; using OpenMetaverse.Packets; namespace OpenMetaverse.TestClient { /// <summary> /// Sends a packet of type GenericMessage to the simulator. /// </summary> public class GenericMessageCommand : Command { public GenericMessageCommand(TestClient testClient) { Name = "sendgeneric"; Description = "send a generic UDP message to the simulator."; Category = CommandCategory.Other; } public override string Execute(string[] args, UUID fromAgentID) { UUID target; if (args.Length < 1) return "Usage: sendgeneric method_name [value1 value2 ...]"; string methodName = args[0]; GenericMessagePacket gmp = new GenericMessagePacket(); gmp.AgentData.AgentID = Client.Self.AgentID; gmp.AgentData.SessionID = Client.Self.SessionID; gmp.AgentData.TransactionID = UUID.Zero; gmp.MethodData.Method = Utils.StringToBytes(methodName); gmp.MethodData.Invoice = UUID.Zero; gmp.ParamList = new GenericMessagePacket.ParamListBlock[args.Length - 1]; StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.Length; i++) { GenericMessagePacket.ParamListBlock paramBlock = new GenericMessagePacket.ParamListBlock(); paramBlock.Parameter = Utils.StringToBytes(args[i]); gmp.ParamList[i - 1] = paramBlock; sb.AppendFormat(" {0}", args[i]); } Client.Network.SendPacket(gmp); return string.Format("Sent generic message with method {0}, params{1}", methodName, sb); } } }
bsd-3-clause
C#
573ef5d9b4285a92e3ad12df17ed25e43dc7b3f1
Add missing file
BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop
src/BloomExe/web/I18NHandler.cs
src/BloomExe/web/I18NHandler.cs
using System.Collections.Generic; using Bloom.Collection; using L10NSharp; using Newtonsoft.Json; namespace Bloom.web { static class I18NHandler { public static bool HandleRequest(string localPath, IRequestInfo info, CollectionSettings currentCollectionSettings) { var lastSep = localPath.IndexOf("/", System.StringComparison.Ordinal); var lastSegment = (lastSep > -1) ? localPath.Substring(lastSep + 1) : localPath; switch (lastSegment) { case "loadStrings": var d = new Dictionary<string, string>(); var post = info.GetPostData(); foreach (string key in post.Keys) { var translation = LocalizationManager.GetDynamicString("Bloom", key, post[key]); if (!d.ContainsKey(key)) d.Add(key, translation); } info.ContentType = "application/json"; info.WriteCompleteOutput(JsonConvert.SerializeObject(d)); return true; } return false; } } }
mit
C#
04dee67ead33728a2728623c3cef8c388864ea4d
Include GetListProductsResponse in project
buyoolabs/clean-architecture-demo,buyoolabs/clean-architecture-demo,buyoolabs/clean-architecture-demo
CleanArchitectureDemo/CleanArchitectureDemo.Entities/UseCases/GetListProducts/GetListProductsResponse.cs
CleanArchitectureDemo/CleanArchitectureDemo.Entities/UseCases/GetListProducts/GetListProductsResponse.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CleanArchitectureDemo.Domain.UseCases.GetListProducts { public class GetListProductsResponse { public List<ProductsItem> Products; public GetListProductsResponse() { Products = new List<ProductsItem>(); } } public class ProductsItem { public int ProductId { get; set; } public string Title { get; set; } public decimal Price { get; set; } } }
mit
C#
4c6a8c63fc81fc187e6581d4b89c56e34ffcff30
Create Settings.Designer.cs
RocketSoftware/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,RocketSoftware/multivalue-lab,nkesic/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,codedecay/multivalue-lab,nkesic/multivalue-lab,RocketSoftware/multivalue-lab,nkesic/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,codedecay/multivalue-lab,nkesic/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,codedecay/multivalue-lab,codedecay/multivalue-lab,codedecay/multivalue-lab,RocketSoftware/multivalue-lab,nkesic/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab
U2-Toolkit/DataAdapter/Properties/Settings.Designer.cs
U2-Toolkit/DataAdapter/Properties/Settings.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18052 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DataAdapter.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
mit
C#
b79fbeb06cde95b72b1579a84048a57f6cf23937
Fix IDE0044
wvdd007/roslyn,AmadeusW/roslyn,wvdd007/roslyn,sharwell/roslyn,bartdesmet/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,tannergooding/roslyn,diryboy/roslyn,sharwell/roslyn,eriawan/roslyn,weltkante/roslyn,bartdesmet/roslyn,tmat/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,mavasani/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,panopticoncentral/roslyn,diryboy/roslyn,tannergooding/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,mavasani/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,gafter/roslyn,dotnet/roslyn,physhi/roslyn,panopticoncentral/roslyn,tmat/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,gafter/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,weltkante/roslyn,physhi/roslyn,AlekseyTs/roslyn,dotnet/roslyn,tmat/roslyn,weltkante/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,sharwell/roslyn,panopticoncentral/roslyn
src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/MockDesktopSpinLock.cs
src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/MockDesktopSpinLock.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="SpinLock"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(SpinLockDebugView))] [DebuggerDisplay("IsHeld = {IsHeld}")] internal struct MockDesktopSpinLock { private readonly int m_owner; public MockDesktopSpinLock(bool enableThreadOwnerTracking) { m_owner = enableThreadOwnerTracking ? 0 : int.MinValue; } public bool IsHeld => false; public bool IsHeldByCurrentThread => IsThreadOwnerTrackingEnabled ? true : throw new InvalidOperationException("Error"); public bool IsThreadOwnerTrackingEnabled => (m_owner & int.MinValue) == 0; internal class SpinLockDebugView { private readonly MockDesktopSpinLock m_spinLock; public bool? IsHeldByCurrentThread => m_spinLock.IsHeldByCurrentThread; public int? OwnerThreadID => m_spinLock.IsThreadOwnerTrackingEnabled ? m_spinLock.m_owner : (int?)null; public bool IsHeld => m_spinLock.IsHeld; public SpinLockDebugView(MockDesktopSpinLock spinLock) { m_spinLock = spinLock; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="SpinLock"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(SpinLockDebugView))] [DebuggerDisplay("IsHeld = {IsHeld}")] internal struct MockDesktopSpinLock { private readonly int m_owner; public MockDesktopSpinLock(bool enableThreadOwnerTracking) { m_owner = enableThreadOwnerTracking ? 0 : int.MinValue; } public bool IsHeld => false; public bool IsHeldByCurrentThread => IsThreadOwnerTrackingEnabled ? true : throw new InvalidOperationException("Error"); public bool IsThreadOwnerTrackingEnabled => (m_owner & int.MinValue) == 0; internal class SpinLockDebugView { private MockDesktopSpinLock m_spinLock; public bool? IsHeldByCurrentThread => m_spinLock.IsHeldByCurrentThread; public int? OwnerThreadID => m_spinLock.IsThreadOwnerTrackingEnabled ? m_spinLock.m_owner : (int?)null; public bool IsHeld => m_spinLock.IsHeld; public SpinLockDebugView(MockDesktopSpinLock spinLock) { m_spinLock = spinLock; } } } }
mit
C#
a1d4a7a6f3a12065dc8184c54695ad19b397f4a6
Add ReflectionTypeLoadException tests
Jiayili1/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ravimeda/corefx,mmitche/corefx,axelheer/corefx,ViktorHofer/corefx,Ermiar/corefx,ravimeda/corefx,shimingsg/corefx,zhenlan/corefx,Ermiar/corefx,mmitche/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,wtgodbe/corefx,ericstj/corefx,mmitche/corefx,ptoonen/corefx,zhenlan/corefx,Ermiar/corefx,zhenlan/corefx,ViktorHofer/corefx,shimingsg/corefx,ravimeda/corefx,Jiayili1/corefx,zhenlan/corefx,ravimeda/corefx,ViktorHofer/corefx,mmitche/corefx,shimingsg/corefx,mmitche/corefx,wtgodbe/corefx,BrennanConroy/corefx,Jiayili1/corefx,ericstj/corefx,ravimeda/corefx,wtgodbe/corefx,ptoonen/corefx,ptoonen/corefx,Ermiar/corefx,Ermiar/corefx,ptoonen/corefx,ptoonen/corefx,mmitche/corefx,Ermiar/corefx,Jiayili1/corefx,Jiayili1/corefx,Jiayili1/corefx,zhenlan/corefx,ptoonen/corefx,BrennanConroy/corefx,axelheer/corefx,zhenlan/corefx,axelheer/corefx,Ermiar/corefx,Jiayili1/corefx,axelheer/corefx,mmitche/corefx,BrennanConroy/corefx,axelheer/corefx,wtgodbe/corefx,wtgodbe/corefx,ViktorHofer/corefx,ravimeda/corefx,axelheer/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,zhenlan/corefx,ravimeda/corefx,ViktorHofer/corefx,ericstj/corefx,ericstj/corefx
src/System.Runtime/tests/System/Reflection/ReflectionTypeLoadExceptionTests.cs
src/System.Runtime/tests/System/Reflection/ReflectionTypeLoadExceptionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; [assembly: TypeForwardedTo(typeof(string))] [assembly: TypeForwardedTo(typeof(TypeInForwardedAssembly))] namespace System.Reflection.Tests { public static class ReflectionTypeLoadExceptionTests { [Fact] public static void NullExceptionsNoNullPointerException() { bool foundRtleException = false; try { Type[] Typo = new Type[1]; Exception[] Excepto = new Exception[1]; throw new ReflectionTypeLoadException(Typo, Excepto, "Null elements in Exceptions array"); } catch (ReflectionTypeLoadException e) { foundRtleException = true; } Assert.True(foundRtleException); } [Fact] public static void NullArgumentsNoNullPointerException() { bool foundRtleException = false; try { throw new ReflectionTypeLoadException(null, null, "Null arguments"); } catch (ReflectionTypeLoadException e) { foundRtleException = true; } Assert.True(foundRtleException); } } }
mit
C#
0f32a0ff076c57bf89ef90bad96ed171f11b9b23
Create MonitorSample.cs
alchemz/ARL_Training
CSharpDotNet_Programming/Thread/MonitorSample.cs
CSharpDotNet_Programming/Thread/MonitorSample.cs
using System; using System.Threading; namespace ThreadTutorial { public class MonitorSample { public static void Main(String[] args) { int result = 0; Cell cell = new Cell (); CellProd prod= new CellProd(cell,20); CellCons cons= new CellCons(cell,20); Thread producer = new Thread( new ThreadStart(prod.ThreadRun)); Thread consumer = new Thread(new ThreadStart(cons.ThreadRun)); try{ producer.Start(); consumer.Start(); producer.Join(); consumer.Join(); } catch(ThreadStateException e) { Console.WriteLine (e); result = 1; } catch(ThreadInterruptedException e) { Console.WriteLine (e); result = 1; } Environment.ExitCode = result; } } public class CellProd { Cell cell; int quantity=1; public CellProd(Cell box, int request) { cell = box; quantity = request; } public void ThreadRun() { for (int looper = 1; looper <= quantity; looper++) { cell.WriteToCell (looper);//"producing } } } public class CellCons { Cell cell; int quantity=1; public CellCons(Cell box, int request) { cell = box; quantity = request; } public void ThreadRun() { int valReturned; for(int looper=1; looper<=quantity; looper++) //consume the result by placing it in valReturned valReturned=cell.ReadFromCell(); } } public class Cell { int cellContents; bool readerFlag= false; public int ReadFromCell() { lock (this) { if (!readerFlag) { try{ //waits for the Monitor.Pulse in WriteCell Monitor.Wait(this); } catch(SynchronizationLockException e) { Console.WriteLine (e); } catch(ThreadInterruptedException e) { Console.WriteLine (e); } } Console.WriteLine ("Consume :{0}", cellContents); readerFlag = false; //reset the stat flag to say consuming Monitor.Pulse(this); } return cellContents; } public void WriteToCell(int n) { lock (this) { if (readerFlag) { try { Monitor.Wait(this); } catch (SynchronizationLockException e) { Console.WriteLine (e); } catch(ThreadInterruptedException e) { Console.WriteLine (e); } } cellContents = n; Console.WriteLine ("Produce:{0}", cellContents); readerFlag = true; Monitor.Pulse (this); } //exit synchronization block } } }
mit
C#
1be7939cfc65a0bdbee38f704fc3e991e77e81d3
Add SHA3-512
ektrah/nsec
src/Cryptography/Sha3_512.cs
src/Cryptography/Sha3_512.cs
using System; using static Interop.KeccakTiny; namespace NSec.Cryptography { public sealed class Sha3_512 : HashAlgorithm { public Sha3_512() : base( minHashSize: 32, defaultHashSize: 64, maxHashSize: 64) { } internal override void HashCore( ReadOnlySpan<byte> data, Span<byte> hash) { sha3_512( ref hash.DangerousGetPinnableReference(), (ulong)hash.Length, ref data.DangerousGetPinnableReference(), (ulong)data.Length); } } }
mit
C#
5aaa0477540a8fff6ebf394d0192c8ac07fcf0b3
Add SizeEx class.
Si13n7/SilDev.CSharpLib
src/SilDev/Drawing/SizeEx.cs
src/SilDev/Drawing/SizeEx.cs
#region auto-generated FILE INFORMATION // ============================================== // This file is distributed under the MIT License // ============================================== // // Filename: SizeEx.cs // Version: 2019-12-11 13:26 // // Copyright (c) 2019, Si13n7 Developments (r) // All rights reserved. // ______________________________________________ #endregion namespace SilDev.Drawing { using System; using System.Drawing; /// <summary> /// Expands the functionality for the <see cref="Size"/> class. /// </summary> public static class SizeEx { /// <summary> /// Scales the specified width or height dimension based on the specified DPI values. /// </summary> /// <param name="value"> /// The width or height dimension. /// </param> /// <param name="oldDpi"> /// The old resolution. /// </param> /// <param name="newDpi"> /// The new resolution. /// </param> public static int ScaleDimension(int value, float oldDpi, float newDpi) { var a = Math.Floor(oldDpi); var b = Math.Floor(newDpi); if (Math.Abs(a - b) < 1d) return value; return (int)Math.Floor(b / a * value); } /// <summary> /// Scales the specified width and height dimensions based on the specified DPI values. /// </summary> /// <param name="width"> /// The width dimension. /// </param> /// <param name="height"> /// The height dimension. /// </param> /// <param name="oldDpi"> /// The old resolution. /// </param> /// <param name="newDpi"> /// The new resolution. /// </param> public static Size ScaleDimensions(int width, int height, float oldDpi, float newDpi) { var size = Size.Empty; if (width > 0) size.Width = ScaleDimension(width, oldDpi, newDpi); if (height > 0) size.Height = ScaleDimension(height, oldDpi, newDpi); return size; } /// <summary> /// Scales the specified width and height dimensions based on the specified handle to a window. /// </summary> /// <param name="width"> /// The width dimension. /// </param> /// <param name="height"> /// The height dimension. /// </param> /// <param name="hWnd"> /// Handle to a window. /// <para> /// If this value is set to default, the handle of the current desktop will be used. /// </para> /// </param> public static Size ScaleDimensions(int width, int height, IntPtr hWnd = default) { var handle = hWnd == default ? WinApi.NativeMethods.GetDesktopWindow() : hWnd; using (var graphics = Graphics.FromHwnd(handle)) return ScaleDimensions(width, height, 96f, Math.Max(graphics.DpiX, graphics.DpiY)); } /// <summary> /// Scales the width and height dimensions of this <see cref="Size"/> object based on the specified DPI values. /// </summary> /// <param name="size"> /// This <see cref="Size"/> object. /// </param> /// <param name="oldDpi"> /// The old resolution. /// </param> /// <param name="newDpi"> /// The new resolution. /// </param> public static Size ScaleDimensions(this Size size, float oldDpi, float newDpi) => ScaleDimensions(size.Width, size.Height, oldDpi, newDpi); /// <summary> /// Scales the width and height dimensions of this <see cref="Size"/> object based on the specified handle to a window. /// </summary> /// <param name="size"> /// This <see cref="Size"/> object. /// </param> /// <param name="hWnd"> /// Handle to a window. /// <para> /// If this value is set to default, the handle of the current desktop will be used. /// </para> /// </param> public static Size ScaleDimensions(this Size size, IntPtr hWnd = default) => ScaleDimensions(size.Width, size.Height, hWnd); } }
mit
C#
82f8d567ce6e0cf854bc645edfb16801786278a5
Create CertificateWSTrustBinding.cs
phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core
Core/OfficeDevPnP.Core/IdentityModel/WSTrustBindings/CertificateWSTrustBinding.cs
Core/OfficeDevPnP.Core/IdentityModel/WSTrustBindings/CertificateWSTrustBinding.cs
mit
C#
6ee4a0a8661a9efd88e95e1ed247cd8deb4379b0
Add forgotten file to DefaultMono branch
gtryus/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,hatton/libpalaso,ddaspit/libpalaso,hatton/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,hatton/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,darcywong00/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,JohnThomson/libpalaso,marksvc/libpalaso,sillsdev/libpalaso,chrisvire/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,sillsdev/libpalaso,marksvc/libpalaso,marksvc/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,darcywong00/libpalaso,darcywong00/libpalaso
Palaso.MSBuildTasks/DownloadFile.cs
Palaso.MSBuildTasks/DownloadFile.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Palaso.BuildTasks { /// <summary> /// Downloads a file from a web address. Params specify the web address, the local path for the file, /// and optionally a user and password. The user/password feature has not been tested. /// If using an important password, make sure the address is https, since I think otherwise the password /// may be sent in clear. /// Adapted from http://stackoverflow.com/questions/1089452/how-can-i-use-msbuild-to-download-a-file /// </summary> public class DownloadFile : Task { [Required] public String Address // HTTP address to download from { get; set; } [Required] public String LocalFilename // Local file to which the downloaded file will be saved { get; set; } public String Username // Credential for HTTP authentication { get; set; } public String Password // Credential for HTTP authentication { get; set; } public override bool Execute() { // This doesn't seem to work reliably..can return true even when only network cable is unplugged. // Left in in case it works in some cases. But the main way of dealing with disconnect is the // same algorithm in the WebException handler. if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { if (File.Exists(LocalFilename)) { Log.LogWarning("Could not retrieve latest {0}. No network connection. Keeping existing file.", LocalFilename); return true; // don't stop the build } else { Log.LogError("Could not retrieve latest {0}. No network connection.", Address); return false; // Presumably can't continue } } bool success; int read = DoDownloadFile(Address, LocalFilename, Username, Password, out success); if (success) Log.LogMessage(MessageImportance.Low, "{0} bytes written", read); else Log.LogError("Could not download {0}", Address); return success; } public int DoDownloadFile(String remoteFilename, String localFilename, String httpUsername, String httpPassword, out bool success) { // Function will return the number of bytes processed // to the caller. Initialize to 0 here. int bytesProcessed = 0; success = true; // Assign values to these objects here so that they can // be referenced in the finally block Stream remoteStream = null; Stream localStream = null; WebResponse response = null; // Use a try/catch/finally block as both the WebRequest and Stream // classes throw exceptions upon error try { // Create a request for the specified remote file name WebRequest request = WebRequest.Create(remoteFilename); // If a username or password have been given, use them if (!string.IsNullOrEmpty(httpUsername) || !string.IsNullOrEmpty(httpPassword)) { string username = httpUsername; string password = httpPassword; request.Credentials = new NetworkCredential(username, password); } // Send the request to the server and retrieve the // WebResponse object response = request.GetResponse(); // Once the WebResponse object has been retrieved, // get the stream object associated with the response's data remoteStream = response.GetResponseStream(); // Create the local file localStream = File.Create(localFilename); // Allocate a 1k buffer var buffer = new byte[1024]; int bytesRead; // Simple do/while loop to read from stream until // no bytes are returned do { // Read data (up to 1k) from the stream bytesRead = remoteStream.Read(buffer, 0, buffer.Length); // Write the data to the local file localStream.Write(buffer, 0, bytesRead); // Increment total bytes processed bytesProcessed += bytesRead; } while (bytesRead > 0); } catch (WebException wex) { if (wex.Status == WebExceptionStatus.ConnectFailure || wex.Status == WebExceptionStatus.NameResolutionFailure) { // We probably don't have a network connection (despite the check in the caller). if (File.Exists(localFilename)) { Log.LogWarning("Could not retrieve latest {0}. No network connection. Keeping existing file.", localFilename); } else { Log.LogError("Could not retrieve latest {0}. No network connection.", remoteFilename); success = false; // Presumably can't continue } return 0; } string html = ""; if (wex.Response != null) { using (var sr = new StreamReader(wex.Response.GetResponseStream())) html = sr.ReadToEnd(); Log.LogError("Could not download from {0}. Server responds {1}", remoteFilename, html); } else { Log.LogError("Could not download from {0}. no server response. Exception {1}. Status {2}", remoteFilename, wex.Message, wex.Status); } success = false; return 0; } catch (Exception e) { Log.LogError(e.Message); Log.LogMessage(MessageImportance.Normal, e.StackTrace); success = false; } finally { // Close the response and streams objects here // to make sure they're closed even if an exception // is thrown at some point if (response != null) response.Close(); if (remoteStream != null) remoteStream.Close(); if (localStream != null) localStream.Close(); } // Return total bytes processed to caller. return bytesProcessed; } } }
mit
C#
186333f3c18a3a33217f6869bb22e89d70570248
Support symbol rename action
aelij/roslynpad
src/RoslynPad.Roslyn/WorkspaceServices/SymbolRenamedCodeActionOperationFactory.cs
src/RoslynPad.Roslyn/WorkspaceServices/SymbolRenamedCodeActionOperationFactory.cs
using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; namespace RoslynPad.Roslyn.WorkspaceServices { [ExportWorkspaceService(typeof(ISymbolRenamedCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared] internal sealed class SymbolRenamedCodeActionOperationFactory : ISymbolRenamedCodeActionOperationFactoryWorkspaceService { public CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution) { // this action does nothing - but Roslyn requires it for some Code Fixes return new RenameSymbolOperation( symbol ?? throw new ArgumentNullException(nameof(symbol)), newName ?? throw new ArgumentNullException(nameof(newName))); } private class RenameSymbolOperation : CodeActionOperation { private readonly ISymbol _symbol; private readonly string _newName; public RenameSymbolOperation( ISymbol symbol, string newName) { _symbol = symbol; _newName = newName; } public override string Title => $"Rename {_symbol.Name} to {_newName}"; } } }
apache-2.0
C#
cb4972f9002cd5875214b12ce5de0b509e4b7456
Add test for obtaining unique items with custom comparer.
sitofabi/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,sitofabi/duplicati,sitofabi/duplicati,duplicati/duplicati,sitofabi/duplicati,duplicati/duplicati,duplicati/duplicati,sitofabi/duplicati,mnaiman/duplicati,duplicati/duplicati
Duplicati/UnitTest/UtilityTests.cs
Duplicati/UnitTest/UtilityTests.cs
// Copyright (C) 2017, The Duplicati Team // http://www.duplicati.com, info@duplicati.com // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using Duplicati.Library.Utility; using NUnit.Framework; using System; using System.Collections.Generic; namespace Duplicati.UnitTest { [TestFixture] public class UtilityTests { [Test] [Category("Utility")] public void GetUniqueItems() { string[] collection = { "A", "a", "A", "b", "c", "c" }; string[] uniqueItems = { "A", "a", "b", "c" }; string[] duplicateItems = { "A", "c" }; ISet<string> actualDuplicateItems; ISet<string> actualUniqueItems = Utility.GetUniqueItems(collection, out actualDuplicateItems); CollectionAssert.AreEquivalent(uniqueItems, actualUniqueItems); CollectionAssert.AreEquivalent(duplicateItems, actualDuplicateItems); IEqualityComparer<string> comparer = StringComparer.OrdinalIgnoreCase; uniqueItems = new string[] {"a", "b", "c"}; duplicateItems = new string[] { "a", "c" }; actualDuplicateItems = null; actualUniqueItems = Utility.GetUniqueItems(collection, comparer, out actualDuplicateItems); Assert.That(actualUniqueItems, Is.EquivalentTo(uniqueItems).Using(comparer)); Assert.That(actualDuplicateItems, Is.EquivalentTo(duplicateItems).Using(comparer)); } } }
// Copyright (C) 2017, The Duplicati Team // http://www.duplicati.com, info@duplicati.com // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using Duplicati.Library.Utility; using NUnit.Framework; using System; using System.Collections.Generic; namespace Duplicati.UnitTest { [TestFixture] public class UtilityTests { [Test] [Category("Utility")] public void GetUniqueItems() { string[] collection = { "A", "a", "A", "b", "c", "c" }; string[] uniqueItems = { "A", "a", "b", "c" }; string[] duplicateItems = { "A", "c" }; ISet<string> actualDuplicateItems; ISet<string> actualUniqueItems = Utility.GetUniqueItems(collection, out actualDuplicateItems); CollectionAssert.AreEquivalent(uniqueItems, actualUniqueItems); CollectionAssert.AreEquivalent(duplicateItems, actualDuplicateItems); } } }
lgpl-2.1
C#
a1c2112320c8f4f489c78034b78103ff533589da
Add viewstart page
IliaAnastassov/OdeToFood,IliaAnastassov/OdeToFood
OdeToFood/VIews/_ViewStart.cshtml
OdeToFood/VIews/_ViewStart.cshtml
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
mit
C#
4f04916cc7dc1bf6703348cc735abb346f243879
Add F.ReduceWhile
farity/farity
Farity/ReduceWhile.cs
Farity/ReduceWhile.cs
using System; using System.Collections.Generic; namespace Farity { public static partial class F { /// <summary> /// Like <seealso cref="Reduce"/>, this returns a single item by iterating through /// the list, successively calling the iterator function. It also takes a predicate /// that is evaluated before each step. If the predicate returns <seealso cref="false"/>, /// it "short-circuits" the iteration and returns the current value of the accumulator. /// </summary> /// <typeparam name="T">The type of the reduced value.</typeparam> /// <typeparam name="TSource">The type of items over which to reduce.</typeparam> /// <param name="predicate">The predicate function which is passed the reduced value and the current item.</param> /// <param name="reducer">The iterator function which is applied to every item in the list.</param> /// <param name="seed">The initial reduced value for the reduce operation.</param> /// <param name="items">The list of items over which to reduce.</param> /// <returns>The reduced value of the list using the provided seed and reducer function.</returns> public static T ReduceWhile<T, TSource>(Func<T, TSource, bool> predicate, Func<T, TSource, T> reducer, T seed, IEnumerable<TSource> items) { var reduced = seed; foreach (var item in items) { if (!predicate(reduced, item)) return reduced; reduced = reducer(reduced, item); } return reduced; } } }
mit
C#
e4987386f5ca694498a8a215e1c4b53975a16f99
Add ExceptionHandler.cs
qqbuby/Alyio.AspNetCore.ApiMessages
src/Alyio.AspNetCore.ApiMessages/ExceptionHandler.cs
src/Alyio.AspNetCore.ApiMessages/ExceptionHandler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; namespace Alyio.AspNetCore.ApiMessages { /// <summary> /// <see cref="Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware"/>. /// </summary> public static class ExceptionHandler { /// <summary> /// <see cref="Microsoft.AspNetCore.Builder.ExceptionHandlerOptions.ExceptionHandler"/> /// </summary> /// <param name="context">The <see cref="HttpContext"/></param> /// <returns></returns> public static Task WriteUnhandledMessageAsync(HttpContext context) { var error = context.Features.Get<IExceptionHandlerFeature>().Error; context.Response.StatusCode = 500; var message = new ApiMessage { Message = error.Message, ExceptionType = error.GetType().Name, TraceIdentifier = context.TraceIdentifier, Errors = new List<string>() }; var aggregateException = error as AggregateException; if (aggregateException != null) { aggregateException.Flatten().Handle(e => { message.Errors.Add(e.Message); return true; }); message.Errors = message.Errors.Distinct().ToList(); } if (context.RequestServices.GetService<IHostingEnvironment>().IsDevelopment()) { message.Detail = error.ToString(); } string errorText = JsonConvert.SerializeObject(message); context.Response.Headers[HeaderNames.ContentType] = "application/json;charset=utf-8"; return context.Response.WriteAsync(errorText); } } }
mit
C#
89de3529702b260d8e9724fe09fcfad4297b1f28
Range sum with segment tree - pre submit
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
LeetCode/remote/range_sum_query.cs
LeetCode/remote/range_sum_query.cs
// https://leetcode.com/problems/range-sum-query-mutable/ // // Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. // The update(i, val) function modifies nums by updating the element at index i to val. // // Example: // // Given nums = [1, 3, 5] // // sumRange(0, 2) -> 9 // update(1, 2) // sumRange(0, 2) -> 8 // // Note: // // The array is only modifiable by the update function. // You may assume the number of calls to update and sumRange function is distributed evenly. // using System; public class NumArray { class TreeNode { public TreeNode Left { get; set; } public TreeNode Right { get; set; } public int Sum { get; set; } public int Start { get; set; } public int End { get; set; } public static TreeNode Construct(int[] a, int low, int high) { if (low > high) { return null; } var result = new TreeNode { Start = low, End = high }; if (low == high) { result.Sum = a[low]; return result; } var mid = low + (high - low) / 2; result.Left = Construct(a, low, mid); result.Right = Construct(a, mid + 1, high); result.Sum = result.Left.Sum + result.Right.Sum; return result; } } TreeNode root; public NumArray(int[] nums) { root = TreeNode.Construct(nums, 0, nums.Length - 1); } public void Update(int i, int val) { Update(root, i, val); } public int SumRange(int i, int j) { return SumRange(root, i, j); } private void Update(TreeNode root, int i, int j) { if (root.Start == root.End) { root.Sum = j; return; } var mid = root.Start + (root.End - root.Start) / 2; if (i <= mid) { Update(root.Left, i, j); } else { Update(root.Right, i, j); } root.Sum = root.Left.Sum + root.Right.Sum; } private int SumRange(TreeNode root, int i, int j) { if (root.Start == i && root.End == j) { return root.Sum; } var mid = root.Start + (root.End - root.Start) / 2; if (j <= mid) { return SumRange(root.Left, i, j); } if (i >= mid + 1) { return SumRange(root.Right, i, j); } return SumRange(root.Left, mid + 1, j) + SumRange(root.Right, i, mid); } static void Main() { var a = new NumArray(new [] { 1, 3, 5}); Console.WriteLine("sumRange(0, 2) = {0}", a.SumRange(0, 2)); a.Update(1, 2); Console.WriteLine("sumRange(0, 2) = {0}", a.SumRange(0, 2)); } }
mit
C#
19671325681d93fa283bdda5688ad0005473a499
Add assembly info file
DMagic1/DMModuleScienceAnimateGeneric
Source/Properties/AssemblyInfo.cs
Source/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DMModuleScienceAnimateGeneric")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DMModuleScienceAnimateGeneric")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("148cb195-6345-4253-809b-f3d61338b45b")] [assembly: AssemblyVersion("0.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")] [assembly: KSPAssembly("DMModuleScienceAnimateGeneric", 0, 6)]
bsd-2-clause
C#
295e5a7e5f7f2645b67092384be76cf551c5b9fb
Add move message module. First iteration before refactor
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
Modix/Modules/MoveMessageModule.cs
Modix/Modules/MoveMessageModule.cs
using System; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Modix.Services.CommandHelp; namespace Modix.Modules { [Name("Move Message"), RequireUserPermission(GuildPermission.ManageMessages), HiddenFromHelp] public class MoveMessageModule : ModuleBase { [Command("move")] public async Task Run([Remainder] string command) { if (Context.User.IsBot) return; var commandSplit = command.Split(' '); (ulong messageID, string channel, string reason) = (ulong.Parse(commandSplit[0]), commandSplit[1], commandSplit.ElementAtOrDefault(2)); var message = await Context.Channel.GetMessageAsync(messageID, CacheMode.AllowDownload); var channels = await Context.Guild.GetTextChannelsAsync(); var targetChannel = channels.SingleOrDefault(c => c.Mention.Equals(channel, StringComparison.OrdinalIgnoreCase)); var builder = new EmbedBuilder() .WithColor(new Color(95, 186, 125)) .WithDescription(message.Content) .WithFooter($"Message copied from #{message.Channel.Name} by @{Context.User.Username}"); builder.Build(); await targetChannel.SendMessageAsync("", embed: builder); await message.DeleteAsync(); await Context.Message.DeleteAsync(); } } }
mit
C#
036ebc4518d09861c843b21c5904ced091abaae5
Add Base file
tertis/OGL
OGL/Network/TCP/Base.cs
OGL/Network/TCP/Base.cs
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace OGL.Network.TCP { public abstract class Base { #region Send protected void SendToRemote(Socket socket, byte[] data) { // Begin sending the data to the remote device. socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), socket); } private void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket socket = (Socket)ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = socket.EndSend(ar); Console.WriteLine("Sent {0} bytes to server.", bytesSent); } catch (Exception e) { Console.WriteLine(e.ToString()); } } #endregion protected bool Disconnect(Socket socket) { try { socket.Shutdown(SocketShutdown.Both); socket.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } return true; } } }
mit
C#
10ce424026cec801736a28dc63dd1e95cea88284
Add proxydrawable lifetime tests
ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework
osu.Framework.Tests/Visual/Drawables/TestSceneProxyDrawableLifetime.cs
osu.Framework.Tests/Visual/Drawables/TestSceneProxyDrawableLifetime.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneProxyDrawableLifetime : FrameworkTestScene { [SetUp] public void Setup() => Schedule(Clear); [Test] public void TestProxyAliveWhenOriginalAlive() { Box box = null; Drawable proxy = null; AddStep("add proxy", () => { Add(box = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(100) }); Add(proxy = box.CreateProxy()); }); AddAssert("proxy should be alive", () => proxy.ShouldBeAlive); AddAssert("proxy is alive", () => proxy.IsAlive); AddStep("expire box", () => box.Expire()); AddAssert("proxy should not be alive", () => !proxy.ShouldBeAlive); AddAssert("proxy is not alive", () => !proxy.IsAlive); } [Test] public void TestLifetimeTransferred() { Box box = null; Drawable proxy = null; AddStep("add proxy", () => { Add(box = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(100) }); Add(proxy = box.CreateProxy()); }); AddStep("set lifetimes", () => { box.LifetimeStart = Time.Current - 5000; box.LifetimeEnd = Time.Current + 5000; }); AddAssert("lifetime transferred from box", () => proxy.LifetimeStart == box.LifetimeStart && proxy.LifetimeEnd == box.LifetimeEnd); } [Test] public void TestRemovedWhenOriginalRemoved() { Container container = null; Box box = null; Drawable proxy = null; AddStep("add proxy", () => { Add(container = new Container { RelativeSizeAxes = Axes.Both }); container.Add(box = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(100) }); container.Add(proxy = box.CreateProxy()); }); AddStep("expire box", () => box.Expire(true)); AddAssert("box removed", () => !container.Contains(box)); AddAssert("proxy removed", () => !container.Contains(proxy)); } } }
mit
C#
71a54ffcd7f390623491ca19d3921811a7074984
Add Formatter class to provide code formatting capability
dlwyatt/PSScriptAnalyzer,PowerShell/PSScriptAnalyzer,daviwil/PSScriptAnalyzer
Engine/Formatter.cs
Engine/Formatter.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer { public class Formatter { private Settings settings; private Formatter(Settings settings) { this.settings = settings; } public static string Format(string scriptDefinition, Settings settings) { throw new NotImplementedException(); } public static string Format( string scriptDefinition, Hashtable settingsHashtable, Runspace runspace, IOutputWriter outputWriter) { var inputSettings = new Settings(settingsHashtable); var ruleOrder = new string[] { "PSPlaceCloseBrace", "PSPlaceOpenBrace", "PSUseConsistentWhitespace", "PSUseConsistentIndentation", "PSAlignAssignmentStatement" }; var text = new EditableText(scriptDefinition); foreach (var rule in ruleOrder) { if (!inputSettings.RuleArguments.ContainsKey(rule)) { continue; } outputWriter.WriteVerbose("Running " + rule); var currentSettingsHashtable = new Hashtable(); currentSettingsHashtable.Add("IncludeRules", new string[] { rule }); var ruleSettings = new Hashtable(); ruleSettings.Add(rule, new Hashtable(inputSettings.RuleArguments[rule])); currentSettingsHashtable.Add("Rules", ruleSettings); var currentSettings = new Settings(currentSettingsHashtable); ScriptAnalyzer.Instance.UpdateSettings(inputSettings); ScriptAnalyzer.Instance.Initialize(runspace, outputWriter); var corrections = new List<CorrectionExtent>(); var records = Enumerable.Empty<DiagnosticRecord>(); var numPreviousCorrections = corrections.Count; do { var correctionApplied = new HashSet<int>(); foreach (var correction in corrections) { // apply only one edit per line if (correctionApplied.Contains(correction.StartLineNumber)) { continue; } correctionApplied.Add(correction.StartLineNumber); text.ApplyEdit(correction); } records = ScriptAnalyzer.Instance.AnalyzeScriptDefinition(text.ToString()); corrections = records.Select(r => r.SuggestedCorrections.ElementAt(0)).ToList(); if (numPreviousCorrections > 0 && numPreviousCorrections == corrections.Count) { outputWriter.ThrowTerminatingError(new ErrorRecord( new InvalidOperationException(), "FORMATTER_ERROR", ErrorCategory.InvalidOperation, corrections)); } numPreviousCorrections = corrections.Count; // get unique correction instances // sort them by line numbers corrections.Sort((x, y) => { return x.StartLineNumber < x.StartLineNumber ? 1 : (x.StartLineNumber == x.StartLineNumber ? 0 : -1); }); } while (numPreviousCorrections > 0); } return text.ToString(); } } }
mit
C#
e970bf6ba6c107bd1b9ff5169ae5fca32a4cfcd3
add dbcontext
coe-google-apps-support/Mailman,coe-google-apps-support/Mailman,coe-google-apps-support/Mailman
src/Mailman.Services/Data/MergeTemplateContext.cs
src/Mailman.Services/Data/MergeTemplateContext.cs
using Microsoft.EntityFrameworkCore; namespace Mailman.Services.Data { public class MergeTemplateContext: DbContext { public MergeTemplateContext(DbContextOptions<MergeTemplateContext> options) : base(options) { } public DbSet<MergeTemplate> MergeTemplates {get;set;} protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=mergetemplate.db"); } } }
mit
C#
7ad5b737e368763120efb8ce2a5048a5e6b80b93
Create CountWords.cs
michaeljwebb/Algorithm-Practice
Other/CountWords.cs
Other/CountWords.cs
//Count number of words in a string. //Not Complete using System; public class Test { public static void Main() { string test = "Hello there how are you?"; Console.WriteLine(CountWords(test)); } public static int CountWords(string x){ int result = 0; x = x.Trim(); if(x == ""){ return 0; } while(x.Contains(" ")){ x = x.Replace(" ", ""); } foreach(string y in x.Split(' ')){ result++; } return result; } }
mit
C#
b81e3004f28daac0909a520916d612997d5fc1bf
Add comment.
AArnott/roslyn,abock/roslyn,reaction1989/roslyn,TyOverby/roslyn,mattwar/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,srivatsn/roslyn,srivatsn/roslyn,agocke/roslyn,jeffanders/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,Giftednewt/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,bartdesmet/roslyn,diryboy/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,dpoeschl/roslyn,robinsedlaczek/roslyn,tvand7093/roslyn,nguerrera/roslyn,tmat/roslyn,akrisiun/roslyn,VSadov/roslyn,MattWindsor91/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,vslsnap/roslyn,bbarry/roslyn,davkean/roslyn,eriawan/roslyn,orthoxerox/roslyn,heejaechang/roslyn,MichalStrehovsky/roslyn,AArnott/roslyn,xoofx/roslyn,jkotas/roslyn,jmarolf/roslyn,davkean/roslyn,jcouv/roslyn,ErikSchierboom/roslyn,jamesqo/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,MattWindsor91/roslyn,brettfo/roslyn,jkotas/roslyn,jmarolf/roslyn,lorcanmooney/roslyn,bartdesmet/roslyn,abock/roslyn,brettfo/roslyn,gafter/roslyn,weltkante/roslyn,akrisiun/roslyn,a-ctor/roslyn,TyOverby/roslyn,shyamnamboodiripad/roslyn,zooba/roslyn,xasx/roslyn,MichalStrehovsky/roslyn,akrisiun/roslyn,mattscheffer/roslyn,wvdd007/roslyn,diryboy/roslyn,cston/roslyn,physhi/roslyn,pdelvo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,MattWindsor91/roslyn,mmitche/roslyn,tannergooding/roslyn,KevinH-MS/roslyn,sharwell/roslyn,zooba/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,mattscheffer/roslyn,jeffanders/roslyn,jmarolf/roslyn,MattWindsor91/roslyn,drognanar/roslyn,OmarTawfik/roslyn,jasonmalinowski/roslyn,a-ctor/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,weltkante/roslyn,zooba/roslyn,orthoxerox/roslyn,eriawan/roslyn,kelltrick/roslyn,Hosch250/roslyn,physhi/roslyn,drognanar/roslyn,tmeschter/roslyn,abock/roslyn,khyperia/roslyn,CyrusNajmabadi/roslyn,OmarTawfik/roslyn,lorcanmooney/roslyn,tannergooding/roslyn,jcouv/roslyn,OmarTawfik/roslyn,vslsnap/roslyn,kelltrick/roslyn,robinsedlaczek/roslyn,tvand7093/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,orthoxerox/roslyn,jkotas/roslyn,KevinH-MS/roslyn,mgoertz-msft/roslyn,robinsedlaczek/roslyn,KevinRansom/roslyn,khyperia/roslyn,paulvanbrenk/roslyn,srivatsn/roslyn,bkoelman/roslyn,bbarry/roslyn,physhi/roslyn,Giftednewt/roslyn,TyOverby/roslyn,aelij/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,wvdd007/roslyn,swaroop-sridhar/roslyn,tannergooding/roslyn,stephentoub/roslyn,amcasey/roslyn,AlekseyTs/roslyn,mattwar/roslyn,mmitche/roslyn,pdelvo/roslyn,KirillOsenkov/roslyn,paulvanbrenk/roslyn,nguerrera/roslyn,gafter/roslyn,Hosch250/roslyn,AArnott/roslyn,Giftednewt/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,AnthonyDGreen/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,jamesqo/roslyn,DustinCampbell/roslyn,Hosch250/roslyn,genlu/roslyn,aelij/roslyn,ErikSchierboom/roslyn,cston/roslyn,sharwell/roslyn,VSadov/roslyn,tmeschter/roslyn,amcasey/roslyn,AnthonyDGreen/roslyn,VSadov/roslyn,a-ctor/roslyn,diryboy/roslyn,amcasey/roslyn,tmat/roslyn,DustinCampbell/roslyn,khyperia/roslyn,paulvanbrenk/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KevinH-MS/roslyn,tmeschter/roslyn,xoofx/roslyn,xasx/roslyn,CaptainHayashi/roslyn,dotnet/roslyn,AnthonyDGreen/roslyn,yeaicc/roslyn,dpoeschl/roslyn,vslsnap/roslyn,xasx/roslyn,AlekseyTs/roslyn,yeaicc/roslyn,reaction1989/roslyn,mavasani/roslyn,panopticoncentral/roslyn,aelij/roslyn,kelltrick/roslyn,tmat/roslyn,pdelvo/roslyn,CaptainHayashi/roslyn,jcouv/roslyn,drognanar/roslyn,AmadeusW/roslyn,reaction1989/roslyn,mattscheffer/roslyn,nguerrera/roslyn,bbarry/roslyn,tvand7093/roslyn,brettfo/roslyn,panopticoncentral/roslyn,dotnet/roslyn,cston/roslyn,jamesqo/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,davkean/roslyn,genlu/roslyn,xoofx/roslyn,bkoelman/roslyn,eriawan/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,stephentoub/roslyn,weltkante/roslyn,lorcanmooney/roslyn,dotnet/roslyn,dpoeschl/roslyn,yeaicc/roslyn,mmitche/roslyn,mattwar/roslyn,jeffanders/roslyn,KevinRansom/roslyn,heejaechang/roslyn
src/Workspaces/Core/Desktop/SymbolSearch/SymbolSearchUpdateEngine.RemoteControlService.cs
src/Workspaces/Core/Desktop/SymbolSearch/SymbolSearchUpdateEngine.RemoteControlService.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.RemoteControl; namespace Microsoft.CodeAnalysis.SymbolSearch { internal partial class SymbolSearchUpdateEngine { private class RemoteControlService : IRemoteControlService { public IRemoteControlClient CreateClient(string hostId, string serverPath, int pollingMinutes) { // BaseUrl provided by the VS RemoteControl client team. This is URL we are supposed // to use to publish and access data from. const string BaseUrl = "https://az700632.vo.msecnd.net/pub"; return new RemoteControlClient(hostId, BaseUrl, serverPath, pollingMinutes); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.RemoteControl; namespace Microsoft.CodeAnalysis.SymbolSearch { internal partial class SymbolSearchUpdateEngine { private class RemoteControlService : IRemoteControlService { public IRemoteControlClient CreateClient(string hostId, string serverPath, int pollingMinutes) { const string BaseUrl = "https://az700632.vo.msecnd.net/pub"; return new RemoteControlClient(hostId, BaseUrl, serverPath, pollingMinutes); } } } }
mit
C#
ac88584b52db9225a01e56f931918fd24f4771cf
Fix #2
uheerme/core,uheerme/core,uheerme/core
Samesound.Services/ChannelService.cs
Samesound.Services/ChannelService.cs
using Samesound.Core; using Samesound.Data; using Samesound.Services.Infrastructure; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace Samesound.Services { public class ChannelService : Service<Channel> { public ChannelService(SamesoundContext db) : base(db) { } public virtual async Task<ICollection<Channel>> Paginate(int skip, int take) { return await Db.Channels .OrderBy(c => c.Id) .Skip(skip) .Take(take) .ToListAsync(); } public virtual async Task<int> Play(Channel channel, Music music) { if (!channel.Musics.Any(m => m.Id == music.Id)) { throw new ApplicationException(); } channel.Playing = music; return await Update(channel); } } }
mit
C#
8f9beaedb179eccfc66a6a726c9143f2d316b57d
Add discount code entity
jontansey/.Net-Core-Ecommerce-Base,jontansey/.Net-Core-Ecommerce-Base
src/Shop.Core/Entites/DiscountCode.cs
src/Shop.Core/Entites/DiscountCode.cs
using System.ComponentModel.DataAnnotations; using Shop.Core.BaseObjects; using Shop.Core.Enums; using Shop.Core.Interfaces; namespace Shop.Core.Entites { public class DiscountCode : LifetimeBase, IReferenceable<DiscountCode> { private string _code; private DiscountCodeType _discountCodeType; private decimal _discountAmount; private int _claimLimit; private int _numberClaimed; [Key] public int DiscountCodeId { get; set; } public string DiscountCodeReference { get; set; } public string Code { get => _code; set { if (_code == value) return; IsDirty = true; _code = value; } } public DiscountCodeType DiscountCodeType { get => _discountCodeType; set { if (_discountCodeType == value) return; IsDirty = true; _discountCodeType = value; } } public decimal DiscountAmount { get => _discountAmount; set { if (_discountAmount == value) return; IsDirty = true; _discountAmount = value; } } public int ClaimLimit { get => _claimLimit; set { if (_claimLimit == value) return; IsDirty = true; _claimLimit = value; } } public int NumberClaimed { get => _numberClaimed; set { if (_numberClaimed == value) return; IsDirty = true; _numberClaimed = value; } } public DiscountCode CreateReference(IReferenceGenerator referenceGenerator) { DiscountCodeReference = referenceGenerator.CreateReference("D-", Constants.Constants.ReferenceLength); return this; } } }
mit
C#
fa908d95f18a386a482a0d34cca31ee5213a0049
add MercurialClient - Hg.Net wrap
svedm/monodevelop-hg-addin
MonoDevelop.VersionControl.Mercurial/MonoDevelop.VersionControl.Mercurial/MercurialClient.cs
MonoDevelop.VersionControl.Mercurial/MonoDevelop.VersionControl.Mercurial/MercurialClient.cs
using System; using Hg.Net; using System.Collections.Generic; namespace MonoDevelop.VersionControl.Mercurial { public class MercurialClient { private readonly Hg.Net.HgClient _hgClient; public MercurialClient(string repoPath, string mercurialPath) { _hgClient = new HgClient(mercurialPath); _hgClient.Connect(repoPath); } public string Cat(string path, string revision) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException("Path cannot be empty"); } var args = new List<string> { "cat", path }; if (!string.IsNullOrEmpty(revision)) { args.Add("--rev"); args.Add(revision); } return _hgClient.ExecuteCommand(args).Response; } } }
mit
C#
ea9344173b40f060d3b6472c2640c262891f32b3
Add IWalletProvider (#2223)
AntShares/AntShares
src/neo/Plugins/IWalletProvider.cs
src/neo/Plugins/IWalletProvider.cs
using Neo.Wallets; using System; namespace Neo.Plugins { public interface IWalletProvider { event EventHandler<Wallet> WalletOpened; Wallet GetWallet(); } }
mit
C#
74e49ca5ddfb377d72629142247e6ced0385bded
add ChocolateFeast.cs
regeldso/hrank
Algorithms/Implementation/ChocolateFeast.cs
Algorithms/Implementation/ChocolateFeast.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { public static void getAnswer(int n, int c, int m) { int current = n; int total = 0; while (current >= c) { current = current - c; if (current >= 0) { total = total + 1; if (total % m == 0) { total = total + 1; } } } Console.WriteLine(total); } static void Main(String[] args) { int t = Convert.ToInt32(Console.ReadLine()); for(int a0 = 0; a0 < t; a0++){ string[] tokens_n = Console.ReadLine().Split(' '); int n = Convert.ToInt32(tokens_n[0]); int c = Convert.ToInt32(tokens_n[1]); int m = Convert.ToInt32(tokens_n[2]); getAnswer(n, c, m); } } }
mit
C#
5fc8185b2a2973171feda2fb259127bb759c79dc
Create QApp.cs
QetriX/CS
QetriX/libs/QApp.cs
QetriX/libs/QApp.cs
namespace com.qetrix.libs { /* Copyright (c) QetriX.com. Licensed under MIT License, see /LICENSE.txt file. * 2016-01-09 | QApp */ using System; using System.Collections.Generic; using System.Text; public class QApp { } }
mit
C#
86906080011567d6751e62be29b83205d3e5afd6
Add failing tests for mapping of enum values
Nick-Lucas/EntryPoint,Nick-Lucas/EntryPoint,Nick-Lucas/EntryPoint
test/EntryPointTests/EnumArguments.cs
test/EntryPointTests/EnumArguments.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EntryPoint; using Xunit; namespace EntryPointTests { public class EnumArguments { [Fact] public void Enums_Int() { string[] args = new string[] { "--opt-1", "3" }; var options = EntryPointApi.Parse<EnumAppOptions>(args); Assert.StrictEqual(Enum1.item3, options.OptEnum1); } [Fact] public void Enums_Named() { string[] args = new string[] { "--opt-1", "item3" }; var options = EntryPointApi.Parse<EnumAppOptions>(args); Assert.StrictEqual(Enum1.item3, options.OptEnum1); } [Fact] public void Enums_Defaults() { string[] args = new string[] { }; var options = EntryPointApi.Parse<EnumAppOptions>(args); Assert.StrictEqual(default(Enum1), options.OptEnum1); Assert.StrictEqual(Enum1.item2, options.OptEnum2); } } class EnumAppOptions : BaseApplicationOptions { [OptionParameter( DoubleDashName = "opt-1")] public Enum1 OptEnum1 { get; set; } [OptionParameter( DoubleDashName = "opt-2", ParameterDefaultBehaviour = ParameterDefaultEnum.CustomValue, ParameterDefaultValue = Enum1.item2)] public Enum1 OptEnum2 { get; set; } } enum Enum1 { item1 = 1, item2 = 2, item3 = 3 } }
mit
C#
3f05f67ca199de7510ec2b930a6eada2a9b203f3
Add Logger class
iceslab/OrienteeringToolWPF
OrienteeringToolWPF/Utils/Logger.cs
OrienteeringToolWPF/Utils/Logger.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace OrienteeringToolWPF.Utils { public sealed class Logger { enum VerbosityLevel { NONE, ERROR, WARN, INFO, DEBUG } private static Logger instance = null; private static readonly object padlock = new object(); private readonly StreamWriter sw; Logger() { var fileName = Directory.GetCurrentDirectory() + DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss") + ".log"; File.WriteAllText(fileName, ""); // Truncate file sw = new StreamWriter(new FileStream(fileName, FileMode.Append, FileAccess.Write)) { AutoFlush = true }; Verbosity = VerbosityLevel.DEBUG; } public static Logger Instance { get { lock (padlock) { if (instance == null) { instance = new Logger(); } return instance; } } } private static VerbosityLevel Verbosity { get { return Verbosity; } set { Verbosity = value; } } private static void WriteMessage(string severity, string message) { Instance.sw.WriteLine(string.Format("{0} [{1}]: {2}", severity, GetTimestamp(), message)); } public static void Debug(string message) { if (Verbosity >= VerbosityLevel.DEBUG) { WriteMessage("DEBUG", message); } } public static void Info(string message) { if (Verbosity >= VerbosityLevel.INFO) { WriteMessage("INFO ", message); } } public static void Warn(string message) { if (Verbosity >= VerbosityLevel.WARN) { WriteMessage("WARN ", message); } } public static void Error(string message) { if (Verbosity >= VerbosityLevel.ERROR) { WriteMessage("ERROR", message); } } private static string GetTimestamp() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.tt"); } } }
mit
C#
c4a727d7e4fa9ff948c932523a5f2115345b98c2
Remove duplicate exception clear similar link
jeddytier4/Opserver,a9261/Opserver,GABeech/Opserver,mqbk/Opserver,IDisposable/Opserver,wuanunet/Opserver,baflynn/Opserver,manesiotise/Opserver,maurobennici/Opserver,michaelholzheimer/Opserver,jeddytier4/Opserver,VictoriaD/Opserver,18098924759/Opserver,manesiotise/Opserver,volkd/Opserver,vebin/Opserver,baflynn/Opserver,huoxudong125/Opserver,rducom/Opserver,hotrannam/Opserver,a9261/Opserver,opserver/Opserver,VictoriaD/Opserver,manesiotise/Opserver,huoxudong125/Opserver,wuanunet/Opserver,agrath/Opserver,opserver/Opserver,Janiels/Opserver,geffzhang/Opserver,geffzhang/Opserver,vbfox/Opserver,volkd/Opserver,hotrannam/Opserver,mqbk/Opserver,Janiels/Opserver,agrath/Opserver,rducom/Opserver,GABeech/Opserver,michaelholzheimer/Opserver,18098924759/Opserver,IDisposable/Opserver,dteg/Opserver,vbfox/Opserver,vebin/Opserver,opserver/Opserver,maurobennici/Opserver,dteg/Opserver
Opserver/Views/Exceptions/Exceptions.Similar.cshtml
Opserver/Views/Exceptions/Exceptions.Similar.cshtml
@model StackExchange.Opserver.Views.Exceptions.ExceptionsModel @{ var e = Model.Exception; var log = Model.SelectedLog; var exceptions = Model.Errors; this.SetPageTitle(Model.Title); } @section head { <script> $(function () { Status.Exceptions.init({ log: '@log', id: '@e.GUID', enablePreviews: @(Current.Settings.Exceptions.EnablePreviews ? "true" : "false"), showingDeleted: true }); }); </script> } <div class="top-section error-bread-top"> <div class="error-header"> <a href="/exceptions">Exceptions</a> > <a href="/exceptions?log=@log.UrlEncode()">@e.ApplicationName</a> > <span class="error-title">@e.Message</span> </div> </div> <div class="bottom-section"> @Html.Partial("Exceptions.Table", Model) <div class="no-content@(exceptions.Any() ? " hidden" : "")">No similar exceptions in @Model.SelectedLog</div> </div>
@model StackExchange.Opserver.Views.Exceptions.ExceptionsModel @{ var e = Model.Exception; var log = Model.SelectedLog; var exceptions = Model.Errors; this.SetPageTitle(Model.Title); } @section head { <script> $(function () { Status.Exceptions.init({ log: '@log', id: '@e.GUID', enablePreviews: @(Current.Settings.Exceptions.EnablePreviews ? "true" : "false"), showingDeleted: true }); }); </script> } <div class="top-section error-bread-top"> <div class="error-header"> <a href="/exceptions">Exceptions</a> > <a href="/exceptions?log=@log.UrlEncode()">@e.ApplicationName</a> > <span class="error-title">@e.Message</span> @if (log.HasValue() && exceptions.Any(er => !er.IsProtected && !er.DeletionDate.HasValue) && Current.User.IsExceptionAdmin) { <span class="top-delete-link">(<a class="delete-link clear-all-link" href="/exceptions/delete-similar">Clear all visible</a>)</span> } </div> </div> <div class="bottom-section"> @Html.Partial("Exceptions.Table", Model) <div class="no-content@(exceptions.Any() ? " hidden" : "")">No similar exceptions in @Model.SelectedLog</div> </div>
mit
C#
f4b5077467669324393d5c3875e02a03af5d1718
Add missing source file
jcracknell/emd,jcracknell/emd
cs/src/pegleg.cs/Parsing/Expressions/AheadParsingExpression.cs
cs/src/pegleg.cs/Parsing/Expressions/AheadParsingExpression.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace pegleg.cs.Parsing.Expressions { public abstract class AheadParsingExpression<TBody, TProduct> : BaseParsingExpression<TProduct> { protected readonly IParsingExpression<TBody> _body; public AheadParsingExpression(IParsingExpression<TBody> body) : base(ParsingExpressionKind.Lookahead) { CodeContract.ArgumentIsNotNull(() => body, body); _body = body; } public IParsingExpression<TBody> Body { get { return _body; } } public override T HandleWith<T>(IParsingExpressionHandler<T> handler) { return handler.Handle(this); } } public class NonCapturingAheadParsingExpression<TBody> : AheadParsingExpression<TBody, TBody> { public NonCapturingAheadParsingExpression(IParsingExpression<TBody> body) : base(body) { } protected override IMatchingResult<TBody> MatchesCore(IMatchingContext context) { return _body.Matches(context.Clone()); } } public class CapturingAheadParsingExpression<TBody, TProduct> : AheadParsingExpression<TBody, TProduct> { private readonly Func<IMatch<TBody>, TProduct> _matchAction; public CapturingAheadParsingExpression(IParsingExpression<TBody> body, Func<IMatch<TBody>, TProduct> matchAction) : base(body) { CodeContract.ArgumentIsNotNull(() => matchAction, matchAction); _matchAction = matchAction; } protected override IMatchingResult<TProduct> MatchesCore(IMatchingContext context) { var bodyMatchingContext = context.Clone(); var bodyMatchingResult = _body.Matches(bodyMatchingContext); if(bodyMatchingResult.Succeeded) { var product = _matchAction(context.StartMatch().CompleteMatch(this, bodyMatchingResult.Product)); return SuccessfulMatchingResult.Create(product); } return UnsuccessfulMatchingResult.Create(this); } } }
mit
C#
62434234987e0862016a02128ece9578e4f89873
add empty renderer. (#1864)
superyyrrzz/docfx,superyyrrzz/docfx,DuncanmaMSFT/docfx,hellosnow/docfx,pascalberger/docfx,dotnet/docfx,928PJY/docfx,dotnet/docfx,hellosnow/docfx,928PJY/docfx,pascalberger/docfx,928PJY/docfx,superyyrrzz/docfx,hellosnow/docfx,dotnet/docfx,DuncanmaMSFT/docfx,pascalberger/docfx
src/Microsoft.DocAsCode.MarkdownLite/EmptyRenderer.cs
src/Microsoft.DocAsCode.MarkdownLite/EmptyRenderer.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdownLite { public class EmptyRenderer { public virtual StringBuffer Render(IMarkdownRenderer renderer, IMarkdownToken token, IMarkdownContext context) { return StringBuffer.Empty; } } }
mit
C#
b5f934b7c1cb598a895db3e38ac4dfde6a833582
Create Sounds.cs
Tech-Curriculums/101-GameDesign-2D-GameDesign-With-Unity
AngryHipsters/Sounds.cs
AngryHipsters/Sounds.cs
using System.Collections; [RequireComponent(typeof(AudioSource))] public class Sounds : MonoBehaviour { public AudioClip ScreechClip, stayGlassy; //stay glassy san francisco public void sayGlassy() { audio.clip = stayGlassy; audio.Play(); } public void screech() { audio.clip = ScreechClip; audio.Play(); } }
mit
C#
6f45c3c2937495083254474d924816f7c87a73ff
Remove C#7 syntax
ppy/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,peppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,RedNesto/osu-framework,ppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,paparony03/osu-framework,default0/osu-framework,ppy/osu-framework,RedNesto/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,default0/osu-framework
osu.Framework/Graphics/UserInterface/Tab/TabDropDownMenu.cs
osu.Framework/Graphics/UserInterface/Tab/TabDropDownMenu.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Input; // TODO: Hide header when no items in dropdown namespace osu.Framework.Graphics.UserInterface.Tab { // Keep abstract for now, until a generic styled header can be determined public abstract class TabDropDownMenu<T> : DropDownMenu<T> { // These need to be set manually until there is a dynamic way to determine public abstract float HeaderWidth { get; } public abstract float HeaderHeight { get; } protected TabDropDownMenu() { RelativeSizeAxes = Axes.X; Header.Anchor = Anchor.TopRight; Header.Origin = Anchor.TopRight; ContentContainer.Anchor = Anchor.TopRight; ContentContainer.Origin = Anchor.TopRight; } internal void HideItem(T val) { int index; if (ItemDictionary.TryGetValue(val, out index)) ItemList[index]?.Hide(); } internal void ShowItem(T val) { int index; if (ItemDictionary.TryGetValue(val, out index)) ItemList[index]?.Show(); } // Don't give focus or it will cover tabs protected override bool OnFocus(InputState state) => false; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Input; // TODO: Hide header when no items in dropdown namespace osu.Framework.Graphics.UserInterface.Tab { // Keep abstract for now, until a generic styled header can be determined public abstract class TabDropDownMenu<T> : DropDownMenu<T> { // These need to be set manually until there is a dynamic way to determine public abstract float HeaderWidth { get; } public abstract float HeaderHeight { get; } protected TabDropDownMenu() { RelativeSizeAxes = Axes.X; Header.Anchor = Anchor.TopRight; Header.Origin = Anchor.TopRight; ContentContainer.Anchor = Anchor.TopRight; ContentContainer.Origin = Anchor.TopRight; } internal void HideItem(T val) { if (ItemDictionary.TryGetValue(val, out int index)) ItemList[index]?.Hide(); } internal void ShowItem(T val) { if (ItemDictionary.TryGetValue(val, out int index)) ItemList[index]?.Show(); } // Don't give focus or it will cover tabs protected override bool OnFocus(InputState state) => false; } }
mit
C#
01afc7e74bac2aea4ecc1df4a6278f88e2c47ac0
Add class to hold snippets for the Period type
jskeet/nodatime,nodatime/nodatime,nodatime/nodatime,malcolmr/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,malcolmr/nodatime,jskeet/nodatime
src/NodaTime.Demo/PeriodDemo.cs
src/NodaTime.Demo/PeriodDemo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NodaTime.Demo { class PeriodDemo { } }
apache-2.0
C#
3925bca6f3177edf6740385c3feb4d0797aba97d
Add Ship Model ie. Models/ShipModel.cs
vnads/Fight-Fleet,vnads/Fight-Fleet,vnads/Fight-Fleet
Flight-Fleet/trunk/FightFleetApi/FightFleet/Models/ShipModel.cs
Flight-Fleet/trunk/FightFleetApi/FightFleet/Models/ShipModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FightFleet.Models { public enum ShipStatus { Live = 1, Sunk = 2 } internal abstract class ShipModel { protected ShipModel() { NumberOfLives = Size; } public abstract string Name { get; } public abstract int Size { get; } public int NumberOfLives { get; set; } public ShipStatus Status { get { return Size <= 0 ? ShipStatus.Sunk : ShipStatus.Live; } } public ShipStatus Hit() { NumberOfLives--; return Status; } } internal class AircraftCarrier : ShipModel { public override string Name { get { return "AircraftCarrier"; } } public override int Size { get { return 5; } } } internal class BattleShip : ShipModel { public override string Name { get { return "BattleShip"; } } public override int Size { get { return 4; } } } internal class Submarine : ShipModel { public override string Name { get { return "Submarine"; } } public override int Size { get { return 3; } } } internal class Cruiser : ShipModel { public override string Name { get { return "Destroyer"; } } public override int Size { get { return 3; } } } internal class Destroyer : ShipModel { public override string Name { get { return "Destroyer"; } } public override int Size { get { return 2; } } } }
mit
C#
5c4ba161576d950c80cdf4b2c6bcf6500d83191e
Add Page Location Expander
wangkanai/Detection
src/Hosting/PageLocationExpander.cs
src/Hosting/PageLocationExpander.cs
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Razor; namespace Wangkanai.Detection.Hosting { public class ResponsivePageLocationExpander : IViewLocationExpander{ public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { throw new NotImplementedException(); } public void PopulateValues(ViewLocationExpanderContext context) { throw new NotImplementedException(); } } }
apache-2.0
C#
05c198513018d5444ed82ccaa456508b1f52d549
Create StringNumConversionChallenge.cs
Zephyr-Koo/sololearn-challenge
StringNumConversionChallenge.cs
StringNumConversionChallenge.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // https://www.sololearn.com/Discuss/625282/?ref=app namespace SoloLearn { class Program { const int NUMBER_BASE = 256; static void Main(string[] zephyr_koo) { //var input = Console.ReadLine(); Console.WriteLine(GetBaseNRepresentation(NUMBER_BASE, "hi")); Console.WriteLine(GetReverseBaseNRepresentation(NUMBER_BASE, 1701013870)); Console.WriteLine(GetReverseRepresentation(1701013870)); // inspired by VcC } static double GetBaseNRepresentation(int baseNum, string input) { return Enumerable.Range(1, input.Length).Sum(n => input[n - 1] * Math.Pow(baseNum, n - 1)); } static string GetReverseBaseNRepresentation(int baseNum, int input) { var sb = new StringBuilder(); while(input > 0) { int quotient = input / baseNum; sb.Append((char)(input - (quotient * baseNum))); input = quotient; } return sb.ToString(); } static string GetReverseRepresentation(int input) { var sb = new StringBuilder(); while (input > 0) { sb.Append((char)(input & 255)); input >>= 8; } return sb.ToString(); } } }
apache-2.0
C#
9af2f7f60ffed1001d2544b71af4d9c55b0553b4
Create WorkingWithPDF.cs
asposewords/Aspose_Words_NET,asposewords/Aspose_Words_NET,asposewords/Aspose_Words_NET,aspose-words/Aspose.Words-for-.NET,aspose-words/Aspose.Words-for-.NET,aspose-words/Aspose.Words-for-.NET,asposewords/Aspose_Words_NET,aspose-words/Aspose.Words-for-.NET
Examples/CSharp/Loading-and-Saving/WorkingWithPDF.cs
Examples/CSharp/Loading-and-Saving/WorkingWithPDF.cs
using Aspose.Words.Saving; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aspose.Words.Examples.CSharp.Loading_and_Saving { class WorkingWithPDF { public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); LoadPDF(dataDir); } public static void LoadPDF(string dataDir) { //ExStart:LoadPDF Document doc = new Document(dataDir + "Document.pdf"); dataDir = dataDir + "Document_out.pdf"; doc.Save(dataDir); //ExEnd:LoadPDF Console.WriteLine("\nDocument saved.\nFile saved at " + dataDir); } } }
mit
C#
066f89ef19c76b7424663671c2c73ed47f52afa0
Add LuceneStatisticsService.
ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton
src/CK.Glouton.Service/LuceneStatisticsService.cs
src/CK.Glouton.Service/LuceneStatisticsService.cs
using CK.Glouton.Lucene; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Text; namespace CK.Glouton.Service { public class LuceneStatisticsService { private readonly LuceneConfiguration _configuration; private readonly LuceneStatistics _stats; public LuceneStatisticsService(IOptions<LuceneConfiguration> configuration) { _configuration = configuration.Value; _stats = new LuceneStatistics(_configuration); } public int AllLogCount() => _stats.AllLogCount; public int AllExceptionCount => _stats.AllExceptionCount; public int AppNameCount => _stats.AppNameCount; public IEnumerable<string> GetAppNames => _stats.GetAppNames; public Dictionary<string, int> GetLogByAppName () { Dictionary<string, int> result = new Dictionary<string, int>(); foreach (var appName in _stats.GetAppNames) { result.Add(appName, _stats.LogInAppNameCount(appName)); } return result; } public Dictionary<string, int> GetExceptionByAppName () { Dictionary<string, int> result = new Dictionary<string, int>(); foreach (var appName in _stats.GetAppNames) { result.Add(appName, _stats.ExceptionInAppNameCount(appName)); } return result; } } }
mit
C#
2bb079ea1403479e1bf513eb63fdc3f1d98bceb3
Add audio quality check tests
smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,peppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu
osu.Game.Tests/Editing/Checks/CheckAudioQualityTest.cs
osu.Game.Tests/Editing/Checks/CheckAudioQualityTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using Moq; using NUnit.Framework; using osu.Framework.Audio.Track; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit.Checks; using osu.Game.Rulesets.Objects; namespace osu.Game.Tests.Editing.Checks { [TestFixture] public class CheckAudioQualityTest { private CheckAudioQuality check; private IBeatmap beatmap; [SetUp] public void Setup() { check = new CheckAudioQuality(); beatmap = new Beatmap<HitObject> { BeatmapInfo = new BeatmapInfo { Metadata = new BeatmapMetadata { AudioFile = "abc123.jpg" } } }; } [Test] public void TestMissing() { // While this is a problem, it is out of scope for this check and is caught by a different one. beatmap.Metadata.AudioFile = null; var mock = new Mock<IWorkingBeatmap>(); mock.SetupGet(_ => _.Beatmap).Returns(beatmap); mock.SetupGet(_ => _.Track).Returns((Track)null); Assert.That(check.Run(beatmap, mock.Object), Is.Empty); } [Test] public void TestAcceptable() { var mock = getMockWorkingBeatmap(192); Assert.That(check.Run(beatmap, mock.Object), Is.Empty); } [Test] public void TestNullBitrate() { var mock = getMockWorkingBeatmap(null); var issues = check.Run(beatmap, mock.Object).ToList(); Assert.That(issues, Has.Count.EqualTo(1)); Assert.That(issues.Single().Template is CheckAudioQuality.IssueTemplateNoBitrate); } [Test] public void TestZeroBitrate() { var mock = getMockWorkingBeatmap(0); var issues = check.Run(beatmap, mock.Object).ToList(); Assert.That(issues, Has.Count.EqualTo(1)); Assert.That(issues.Single().Template is CheckAudioQuality.IssueTemplateNoBitrate); } [Test] public void TestTooHighBitrate() { var mock = getMockWorkingBeatmap(320); var issues = check.Run(beatmap, mock.Object).ToList(); Assert.That(issues, Has.Count.EqualTo(1)); Assert.That(issues.Single().Template is CheckAudioQuality.IssueTemplateTooHighBitrate); } [Test] public void TestTooLowBitrate() { var mock = getMockWorkingBeatmap(64); var issues = check.Run(beatmap, mock.Object).ToList(); Assert.That(issues, Has.Count.EqualTo(1)); Assert.That(issues.Single().Template is CheckAudioQuality.IssueTemplateTooLowBitrate); } /// <summary> /// Returns the mock of the working beatmap with the given audio properties. /// </summary> /// <param name="audioBitrate">The bitrate of the audio file the beatmap uses.</param> private Mock<IWorkingBeatmap> getMockWorkingBeatmap(int? audioBitrate) { var mockTrack = new Mock<Track>(); mockTrack.SetupGet(_ => _.Bitrate).Returns(audioBitrate); var mockWorkingBeatmap = new Mock<IWorkingBeatmap>(); mockWorkingBeatmap.SetupGet(_ => _.Beatmap).Returns(beatmap); mockWorkingBeatmap.SetupGet(_ => _.Track).Returns(mockTrack.Object); return mockWorkingBeatmap; } } }
mit
C#
3554c7af030b8c58943e8f392309bf56c59750b4
Add 'WebClientForTest.cs' which I forgot to commit.
ipponshimeji/MAPE
Source/Core/Utils/WebClientForTest.cs
Source/Core/Utils/WebClientForTest.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Cache; namespace MAPE.Utils { public class WebClientForTest: WebClient { #region constants public int Timeout { get; set; } = 100 * 1000; #endregion #region creation and disposal public WebClientForTest(): base() { // customize members this.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); return; } #endregion #region overrides protected override WebRequest GetWebRequest(Uri address) { WebRequest webRequest = base.GetWebRequest(address); webRequest.Timeout = this.Timeout; return webRequest; } #endregion } }
mit
C#
de7d7605045765616787101224dba1192fbea2f5
Revert "Revert "Missing DbContextExtensions""
mehrandvd/Tralus,mehrandvd/Tralus
Framework/Source/Tralus.Framework.BusinessModel/Entities/DbContextExtensions.cs
Framework/Source/Tralus.Framework.BusinessModel/Entities/DbContextExtensions.cs
using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace Tralus.Framework.BusinessModel.Entities { public static class DbContextExtensions { public static void AddIfNotExists<T>(this DbSet<T> dbSet, T entity) where T : EntityBase { if (!dbSet.Any(e => e.Id == entity.Id)) { dbSet.Add(entity); } } public static void AddRangeIfNotExists<T>(this DbSet<T> dbSet, IEnumerable<T> entities) where T : EntityBase { foreach (var entity in entities) { AddIfNotExists(dbSet, entity); } } } }
apache-2.0
C#
ffbd9a50a78b6d73432cfc39becd164544fae019
Add files via upload
irtezasyed007/CSC523-Game-Project
Algorithms/Term.cs
Algorithms/Term.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication19 { class Term { private string expression; private bool value; public Term(string expression, bool value) { this.expression = expression; this.value = value; } public string getExpression() { return this.expression; } public bool getValue() { return this.value; } } }
mit
C#
87265fbd86202362e99e7612000033af8f1766ae
Bump version
james-andrewsmith/Streamstone,jkonecki/Streamstone,attilah/Streamstone
Source/Streamstone.Version.cs
Source/Streamstone.Version.cs
using System; using System.Linq; using System.Reflection; [assembly: AssemblyVersion("0.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")]
using System; using System.Linq; using System.Reflection; [assembly: AssemblyVersion("0.5.0.0")] [assembly: AssemblyFileVersion("0.5.0.0")]
apache-2.0
C#
cc13e8283117dd3332d51c46d0dc28390447f789
Add LocalExecutableAttribute
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Tooling/LocalExecutableAttribute.cs
source/Nuke.Common/Tooling/LocalExecutableAttribute.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.IO; using System.Linq; using System.Reflection; using Nuke.Common.Execution; namespace Nuke.Common.Tooling { /// <summary> /// Injects a delegate for process execution. The path relative to the root directory is passed as constructor argument. /// </summary> /// <example> /// <code> /// [LocalExecutable("./tools/custom.exe")] readonly Tool Custom; /// Target FooBar => _ => _ /// .Executes(() => /// { /// var output = Custom("test"); /// }); /// </code> /// </example> public class LocalExecutableAttribute : InjectionAttributeBase { private readonly string _path; public LocalExecutableAttribute(string path) { _path = path; } public override object GetValue(MemberInfo member, object instance) { var toolPath = Path.Combine(NukeBuild.RootDirectory, _path); ControlFlow.Assert(File.Exists(toolPath), $"File.Exists({toolPath})"); return new Tool(new ToolExecutor(toolPath).Execute); } } }
mit
C#
444436abb519514fa8a8f480eb3525d68b102bb8
Create GameOver.cs
zelbo/Number-Guessing
GameOver.cs
GameOver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace NumberGuessing { partial class Program { // takes an argument that tells whether player won or lost // returns whether the player wants to play again public static bool GameOver(bool isWinner) { //while (Console.KeyAvailable) Console.ReadKey(); string message; bool playAgain = false; if (isWinner) message = "You won!"; else message = "Someone has to loose. This time that someone is you."; Console.Clear(); Console.WriteLine(message); Console.WriteLine("Press the spacebar to play again, any other key to quit."); while (!Console.KeyAvailable) { if (Console.ReadKey(true).Key == ConsoleKey.Spacebar) playAgain = true; else playAgain = false; break; } return playAgain; } } }
mit
C#
6f9f7e887f4dbcd6c70eea6bbfc5e22eaf1006d5
add assemblyinfo
Zenasoft/JellyFish.Configuration
src/Jellyfish.Configuration/Properties/AssemblyInfo.cs
src/Jellyfish.Configuration/Properties/AssemblyInfo.cs
using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo("Jellyfish.Configuration.Test")]
apache-2.0
C#
0f8738027f77d34161555a6a7c61eb595ab4cfa2
Implement MergeSort
cschen1205/cs-algorithms,cschen1205/cs-algorithms
Algorithms/Sorting/MergeSort.cs
Algorithms/Sorting/MergeSort.cs
using System; using Algorithms.Utils; namespace Algorithms.Sorting { public class MergeSort { public static void Sort<T>(T[] a) where T : IComparable<T> { Sort(a, 0, a.Length-1, (a1, a2) => a1.CompareTo(a2)); } public static void Sort<T>(T[] a, int lo, int hi, Comparison<T> compare) { var aux = new T[a.Length]; Sort(a, aux, lo, hi, compare); } private static void Sort<T>(T[] a, T[] aux, int lo, int hi, Comparison<T> compare) { if (lo >= hi) return; if (hi - lo <= 7) { InsertionSort.Sort(a, lo, hi, compare); return; } var mid = (hi - lo) / 2 + lo; Sort(a, aux, lo, mid, compare); Sort(a, aux, mid, hi, compare); Merge(a, aux, lo, mid, hi, compare); } private static void Merge<T>(T[] a, T[] aux, int lo, int mid, int hi, Comparison<T> compare) { int i, j; for (i = lo; i <= hi; ++i) { aux[i] = a[i]; } i = lo; j = mid; for(var k=lo; k <= hi; ++k) { if (i >= mid) a[k] = aux[j++]; if (j >= hi) a[k] = aux[i++]; if (SortUtil.IsLessThan(a[i], a[j], compare)) { a[k] = aux[i++]; } else { a[k] = aux[j++]; } } } } }
mit
C#
619be80ba034b0949f452451e05edafad6ff9260
Add SSD extension for now
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/SSD.cs
Battery-Commander.Web/Models/SSD.cs
using BatteryCommander.Web.Models.Data; using BatteryCommander.Web.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; namespace BatteryCommander.Web.Models { public enum SSD : byte { SSD_1, SSD_2, SSD_3, SSD_4, SSD_5 } public partial class Soldier { public virtual ICollection<SSDSnapshot> SSDSnapshots { get; set; } public virtual SSDStatusModel SSDStatus { get { return new SSDStatusModel { AsOf = SSDSnapshots .Select(snapshot => snapshot.AsOf) .Max(), SSD_1 = SSDSnapshots .OrderByDescending(snapshot => snapshot.AsOf) .Where(snapshot => snapshot.SSD == SSD.SSD_1) .Select(snapshot => (decimal?)snapshot.PerecentComplete) .FirstOrDefault(), SSD_2 = SSDSnapshots .OrderByDescending(snapshot => snapshot.AsOf) .Where(snapshot => snapshot.SSD == SSD.SSD_2) .Select(snapshot => (decimal?)snapshot.PerecentComplete) .FirstOrDefault(), SSD_3 = SSDSnapshots .OrderByDescending(snapshot => snapshot.AsOf) .Where(snapshot => snapshot.SSD == SSD.SSD_3) .Select(snapshot => (decimal?)snapshot.PerecentComplete) .FirstOrDefault(), SSD_4 = SSDSnapshots .OrderByDescending(snapshot => snapshot.AsOf) .Where(snapshot => snapshot.SSD == SSD.SSD_4) .Select(snapshot => (decimal?)snapshot.PerecentComplete) .FirstOrDefault(), SSD_5 = SSDSnapshots .OrderByDescending(snapshot => snapshot.AsOf) .Where(snapshot => snapshot.SSD == SSD.SSD_5) .Select(snapshot => (decimal?)snapshot.PerecentComplete) .FirstOrDefault() }; } } public class SSDSnapshot { public DateTimeOffset AsOf { get; set;} = DateTimeOffset.UtcNow; public SSD SSD { get; set; } = SSD.SSD_1; public decimal PerecentComplete { get; set; } } public class SSDStatusModel { public DateTimeOffset AsOf { get; set; } // Humanized time since public decimal? SSD_1 { get; set; } public decimal? SSD_2 { get; set; } public decimal? SSD_3 { get; set; } public decimal? SSD_4 { get; set; } public decimal? SSD_5 { get; set; } } } }
mit
C#
eb09bfc94e59f246875f50e69c0c894c37051129
Add UnrecognizedResponseException
Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server
src/Tgstation.Server.Client/UnrecognizedResponseException.cs
src/Tgstation.Server.Client/UnrecognizedResponseException.cs
using System; using System.Globalization; using System.Net; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Client { sealed class UnrecognizedResponseException : ClientException { /// <summary> /// Construct an <see cref="UnrecognizedResponseException"/> with the <paramref name="data"/> of a response body and the <paramref name="statusCode"/> /// </summary> /// <param name="data">The body of the response</param> /// <param name="statusCode">The <see cref="HttpStatusCode"/> for the <see cref="ClientException"/></param> public UnrecognizedResponseException(string data, HttpStatusCode statusCode) : base(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "Unrecognized response body: {0}", data), SeverApiVersion = null }, statusCode) { } /// <summary> /// Construct a <see cref="UnrecognizedResponseException"/> /// </summary> public UnrecognizedResponseException() { } /// <summary> /// Construct an <see cref="UnrecognizedResponseException"/> with a <paramref name="message"/> /// </summary> /// <param name="message">The message for the <see cref="Exception"/></param> public UnrecognizedResponseException(string message) : base(message) { } /// <summary> /// Construct an <see cref="UnrecognizedResponseException"/> with a <paramref name="message"/> and <paramref name="innerException"/> /// </summary> /// <param name="message">The message for the <see cref="Exception"/></param> /// <param name="innerException">The inner <see cref="Exception"/> for the base <see cref="Exception"/></param> public UnrecognizedResponseException(string message, Exception innerException) : base(message, innerException) { } } }
agpl-3.0
C#
748576df59a721213ac13fead62908892e97120d
Write and Read
abnaki/windows,abnaki/windows,abnaki/windows
Library/Commonality/Xml/AbnakiXml.cs
Library/Commonality/Xml/AbnakiXml.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Serialization; namespace Abnaki.Windows.Xml { public class AbnakiXml { public static void Write(string filename, object value, Type[] subtypes) { using (FileStream fs = File.Open(filename, FileMode.Create, FileAccess.Write)) { XmlWriterSettings xset = new XmlWriterSettings(); xset.Indent = true; using (XmlWriter writer = XmlWriter.Create(fs, xset)) { XmlSerializer srlz = new XmlSerializer(value.GetType(), subtypes); srlz.Serialize(writer, value); writer.Close(); } } } public static T Read<T>(FileInfo fi, Type[] subtypes) { if (false == fi.Exists) throw new FileNotFoundException("Cannot read " + fi.FullName); using (FileStream fs = File.Open(fi.FullName, FileMode.Open, FileAccess.Read) ) { using (XmlReader reader = XmlReader.Create(fs) ) { XmlSerializer srlz = new XmlSerializer(typeof(T), subtypes); T tret = (T)srlz.Deserialize(reader); reader.Close(); return tret; } } } } }
mit
C#
bfbc4bf3a704fbc003615b04d43b7a67f8e70175
Add missing file
larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl
MatterControlLib/PrinterControls/ControlWidgets/FanControlsRow.cs
MatterControlLib/PrinterControls/ControlWidgets/FanControlsRow.cs
/* Copyright (c) 2017, Kevin Pope, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Diagnostics; using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; namespace MatterHackers.MatterControl.PrinterControls { public class FanControlsRow : SettingsRow { private MHNumberEdit fanSpeedDisplay; private RoundedToggleSwitch toggleSwitch; private PrinterConfig printer; public FanControlsRow(PrinterConfig printer, ThemeConfig theme) : base ("Part Cooling Fan".Localize(), null, theme, fullRowSelect: true) { this.printer = printer; var timeSinceLastManualSend = new Stopwatch(); var container = new FlowLayoutWidget(); this.AddChild(container); this.BorderColor = Color.Transparent; fanSpeedDisplay = new MHNumberEdit(0, theme, minValue: 0, maxValue: 100, pixelWidth: 30) { Value = printer.Connection.FanSpeed0To255 * 100 / 255, VAnchor = VAnchor.Center | VAnchor.Fit, Margin = new BorderDouble(right: 2), }; fanSpeedDisplay.ActuallNumberEdit.EditComplete += (sender, e) => { // limit the rate we can send this message to 2 per second so we don't get in a crazy toggle state. if (!timeSinceLastManualSend.IsRunning || timeSinceLastManualSend.ElapsedMilliseconds > 500) { timeSinceLastManualSend.Restart(); printer.Connection.FanSpeed0To255 = (int)(fanSpeedDisplay.Value * 255 / 100 + .5); } }; container.AddChild(fanSpeedDisplay); container.Selectable = true; // put in % container.AddChild(new TextWidget("%", pointSize: 10, textColor: theme.TextColor) { VAnchor = VAnchor.Center }); toggleSwitch = new RoundedToggleSwitch(theme) { Margin = new BorderDouble(5, 0), VAnchor = VAnchor.Center }; toggleSwitch.CheckedStateChanged += (s, e) => { if (!timeSinceLastManualSend.IsRunning || timeSinceLastManualSend.ElapsedMilliseconds > 500) { timeSinceLastManualSend.Restart(); if (toggleSwitch.Checked) { printer.Connection.FanSpeed0To255 = 255; } else { printer.Connection.FanSpeed0To255 = 0; } } }; container.AddChild(toggleSwitch); this.ActionWidget = toggleSwitch; // Register listeners printer.Connection.FanSpeedSet += Connection_FanSpeedSet; } public override void OnClosed(EventArgs e) { // Unregister listeners printer.Connection.FanSpeedSet -= Connection_FanSpeedSet; base.OnClosed(e); } private void Connection_FanSpeedSet(object s, EventArgs e) { if ((int)printer.Connection.FanSpeed0To255 > 0) { toggleSwitch.Checked = true; } else { toggleSwitch.Checked = false; } fanSpeedDisplay.Value = printer.Connection.FanSpeed0To255 * 100 / 255; } } }
bsd-2-clause
C#
2938bcb627203e795c22eb7c5fe5788449ff921c
Add static method for creating KeyValuePiar object.
cube-soft/Cube.Core,cube-soft/Cube.Core
Libraries/Collections/KeyValue.cs
Libraries/Collections/KeyValue.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Collections.Generic; namespace Cube { /* --------------------------------------------------------------------- */ /// /// KeyValue /// /// <summary> /// KeyValuePair(T, U) の拡張用クラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ public static class KeyValue { #region Methods /* ----------------------------------------------------------------- */ /// /// Create /// /// <summary> /// KeyValuePair(T, U) オブジェクトを生成します。 /// </summary> /// /// <param name="key">キー</param> /// <param name="value">値</param> /// /// <returns>KeyValuePair(T, U) オブジェクト</returns> /// /* ----------------------------------------------------------------- */ public static KeyValuePair<T, U> Create<T, U>(T key, U value) => new KeyValuePair<T, U>(key, value); #endregion } }
apache-2.0
C#
728fa0b8f13bc3a23f576e1f866ea0c0d6b88be4
Create AtEnumeration.cs
HerrLoesch/ObjectFiller.NET,blmeyers/ObjectFiller.NET,DoubleLinePartners/ObjectFiller.NET,Tynamix/ObjectFiller.NET
ObjectFiller/Setup/AtEnumeration.cs
ObjectFiller/Setup/AtEnumeration.cs
namespace Tynamix.ObjectFiller { public enum At { TheBegin, TheEnd } }
mit
C#
120c9a0165d2aaaf8b0d5c5d20783f75902f06f4
Add missing source file
mike-ward/Nancy.Pile,mike-ward/Nancy.Pile,mike-ward/Nancy.Pile,mike-ward/Nancy.Pile
Nancy.PIle.Sample.Owin/Startup.cs
Nancy.PIle.Sample.Owin/Startup.cs
using Microsoft.Owin.Extensions; using Owin; namespace Nancy.PIle.Sample.Owin { public class Startup { public void Configuration(IAppBuilder app) { app.UseNancy(); app.UseStageMarker(PipelineStage.MapHandler); } } }
mit
C#
4198153f0174c6406e2cdc6773940e8b7bd9ceac
Add integration tests for Activity.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
tests/SideBySide/ActivityTests.cs
tests/SideBySide/ActivityTests.cs
#if !BASELINE #if NET5_0_OR_GREATER using System.Diagnostics; using System.Globalization; namespace SideBySide; public class ActivityTests : IClassFixture<DatabaseFixture> { public ActivityTests(DatabaseFixture database) { } [Fact] public void OpenTags() { using var parentActivity = new Activity(nameof(OpenTags)); parentActivity.Start(); Activity activity = null; using var listener = new ActivityListener { ShouldListenTo = x => x.Name == "MySqlConnector", Sample = (ref ActivityCreationOptions<ActivityContext> options) => options.TraceId == parentActivity.TraceId ? ActivitySamplingResult.AllData : ActivitySamplingResult.None, ActivityStopped = x => activity = x, }; ActivitySource.AddActivityListener(listener); string connectionString; using (var connection = new MySqlConnection(AppConfig.ConnectionString)) { connection.Open(); connectionString = connection.ConnectionString; } var csb = new MySqlConnectionStringBuilder(connectionString); Assert.NotNull(activity); Assert.Equal(ActivityKind.Client, activity.Kind); Assert.Equal("Open", activity.OperationName); #if NET6_0_OR_GREATER Assert.Equal(ActivityStatusCode.Ok, activity.Status); #endif AssertTags(activity.Tags, csb); AssertTag(activity.Tags, "otel.status_code", "OK"); } [Fact] public void SelectTags() { using var connection = new MySqlConnection(AppConfig.ConnectionString); connection.Open(); var csb = new MySqlConnectionStringBuilder(connection.ConnectionString); using var parentActivity = new Activity(nameof(OpenTags)); parentActivity.Start(); Activity activity = null; using var listener = new ActivityListener { ShouldListenTo = x => x.Name == "MySqlConnector", Sample = (ref ActivityCreationOptions<ActivityContext> options) => options.TraceId == parentActivity.TraceId ? ActivitySamplingResult.AllData : ActivitySamplingResult.None, ActivityStopped = x => activity = x, }; ActivitySource.AddActivityListener(listener); using (var command = new MySqlCommand("SELECT 1;", connection)) { command.ExecuteScalar(); } Assert.NotNull(activity); Assert.Equal(ActivityKind.Client, activity.Kind); Assert.Equal("Execute", activity.OperationName); #if NET6_0_OR_GREATER Assert.Equal(ActivityStatusCode.Ok, activity.Status); #endif AssertTags(activity.Tags, csb); AssertTag(activity.Tags, "db.connection_id", connection.ServerThread.ToString(CultureInfo.InvariantCulture)); AssertTag(activity.Tags, "db.statement", "SELECT 1;"); AssertTag(activity.Tags, "otel.status_code", "OK"); } private void AssertTags(IEnumerable<KeyValuePair<string, string>> tags, MySqlConnectionStringBuilder csb) { AssertTag(tags, "db.system", "mysql"); AssertTag(tags, "db.connection_string", csb.ConnectionString); AssertTag(tags, "db.user", csb.UserID); if (csb.Server[0] is >= 'a' and <= 'z' or >= 'A' and <= 'Z') AssertTag(tags, "net.peer.name", csb.Server); AssertTag(tags, "net.transport", "ip_tcp"); AssertTag(tags, "db.name", csb.Database); } private void AssertTag(IEnumerable<KeyValuePair<string, string>> tags, string expectedTag, string expectedValue) { var tag = tags.SingleOrDefault(x => x.Key == expectedTag); if (tag.Key is null) Assert.True(false, $"tags did not contain '{expectedTag}'"); Assert.Equal(expectedValue, tag.Value); } } #endif #endif
mit
C#
bb095b7dc017b4661c8ca703f54c48d99cd32375
Migrate Execution Quickstart
googleworkspace/dotnet-samples,gsuitedevs/dotnet-samples
appsScript/Execute/Execute.cs
appsScript/Execute/Execute.cs
// @license // Copyright Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START apps_script_execute] // Create Google Apps Script API service. string scriptId = "ENTER_YOUR_SCRIPT_ID_HERE"; var service = new ScriptService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Create an execution request object. ExecutionRequest request = new ExecutionRequest(); request.Function = "getFoldersUnderRoot"; ScriptsResource.RunRequest runReq = service.Scripts.Run(request, scriptId); try { // Make the API request. Operation op = runReq.Execute(); if (op.Error != null) { // The API executed, but the script returned an error. // Extract the first (and only) set of error details // as a IDictionary. The values of this dictionary are // the script's 'errorMessage' and 'errorType', and an // array of stack trace elements. Casting the array as // a JSON JArray allows the trace elements to be accessed // directly. IDictionary<string, object> error = op.Error.Details[0]; Console.WriteLine( "Script error message: {0}", error["errorMessage"]); if (error["scriptStackTraceElements"] != null) { // There may not be a stacktrace if the script didn't // start executing. Console.WriteLine("Script error stacktrace:"); Newtonsoft.Json.Linq.JArray st = (Newtonsoft.Json.Linq.JArray)error["scriptStackTraceElements"]; foreach (var trace in st) { Console.WriteLine( "\t{0}: {1}", trace["function"], trace["lineNumber"]); } } } else { // The result provided by the API needs to be cast into // the correct type, based upon what types the Apps // Script function returns. Here, the function returns // an Apps Script Object with String keys and values. // It is most convenient to cast the return value as a JSON // JObject (folderSet). Newtonsoft.Json.Linq.JObject folderSet = (Newtonsoft.Json.Linq.JObject)op.Response["result"]; if (folderSet.Count == 0) { Console.WriteLine("No folders returned!"); } else { Console.WriteLine("Folders under your root folder:"); foreach (var folder in folderSet) { Console.WriteLine( "\t{0} ({1})", folder.Value, folder.Key); } } } } catch (Google.GoogleApiException e) { // The API encountered a problem before the script // started executing. Console.WriteLine("Error calling API:\n{0}", e); } Console.Read(); // [END apps_script_execute]
apache-2.0
C#
e5a87d25b9f0ab331d1b07c18b96ef2786b27059
Add Index.cshtml to Atata.WebDriverExtras.TestApp project
atata-framework/atata-webdriverextras,atata-framework/atata-webdriverextras
src/Atata.WebDriverExtras.TestApp/Pages/Index.cshtml
src/Atata.WebDriverExtras.TestApp/Pages/Index.cshtml
@page @{ ViewBag.Title = "Home"; }
apache-2.0
C#
e5370bb0b8f987e67a57c1cbf26784681905333e
Create ScienceRedefined.cs
Rhidian/ScienceRedefined
ScienceRedefined.cs
ScienceRedefined.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; /* * ScienceRedefined v. 0.1 [WIP] * Author: Rhidian * All Rights Reserved */ namespace ScienceRedefined { public class ModuleResearchExperiment : ModuleScienceExperiment { [KSPField(isPersistant = true)] public bool beenBoosted = false; protected ScienceExperiment boostExperiment = null; public void initializeExperiment() { boostExperiment = new ScienceExperiment(); ConfigNode sNode = new ConfigNode(); ResearchAndDevelopment.GetExperiment(this.experimentID).Save(sNode); //Copies values from original experiment to the internal experiment boostExperiment.Load(sNode); this.experiment = boostExperiment; beenBoosted = false; } new public void DeployExperiment() { //Resets Data Decay List<ScienceSubject> ssList = ResearchAndDevelopment.GetSubjects(); foreach (ScienceSubject sub in ssList) { sub.scientificValue = 1.0f; } initializeExperiment(); base.DeployExperiment(); } } }
mit
C#
e1fff753c3354643a055efb7032bde853d55bc43
Add new login6 provider.
WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website
src/WWT.Providers/OtherProviders/Login6Provider.cs
src/WWT.Providers/OtherProviders/Login6Provider.cs
#nullable disable using Microsoft.Extensions.Logging; using System.Threading; using System.Threading.Tasks; using WWT.Catalog; using WWT.PlateFiles; namespace WWT.Providers { [RequestEndpoint("/wwtweb/login6.aspx")] public class Login6Provider : LoginUser { private readonly ICatalogAccessor _catalog; private readonly ILogger<CatalogProvider> _logger; public override string ContentType => ContentTypes.Text; public override bool IsCacheable => false; public Login6Provider(ICatalogAccessor catalogAccessor, ILogger<CatalogProvider> logger) { _catalog = catalogAccessor; _logger = logger; } public override async Task RunAsync(IWwtContext context, CancellationToken token) { var catalog_file = "wwt6_login.txt"; context.Response.AddHeader("Expires", "0"); var catalogEntry = await _catalog.GetCatalogEntryAsync(catalog_file, token); if (catalogEntry is null) { _logger.LogError(string.Format("wwt6::{0} file missing from backing storage", catalog_file)); context.Response.StatusCode = 500; return; } using (var c = catalogEntry.Contents) { await c.CopyToAsync(context.Response.OutputStream, token); context.Response.Flush(); context.Response.End(); } } } }
mit
C#
5292eacf372256becb16e8e30e93a217111eb41b
Create Problem173.cs
fireheadmx/ProjectEuler,fireheadmx/ProjectEuler
Problem173.cs
Problem173.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEuler.Problems { class Problem173 { public static void Run() { int upper = 1000000; List<int> perimeter = new List<int>(); perimeter.Add(0); // 0 perimeter.Add(0); // 1 perimeter.Add(0); // 2 int side = 3; int perim = 2 * side + 2 * (side - 1); while (perim <= upper) { perimeter.Add(perim); side++; perim = 2 * side + 2 * (side - 2); } long count = 0; int total_tiles; for (int i = 3; i < perimeter.Count; i++) { total_tiles = perimeter[i]; if (total_tiles <= upper) { count++; } for (int j = i - 2; j >= 3; j-= 2) { total_tiles += perimeter[j]; if (total_tiles <= upper) { count++; } else { break; } } } Console.WriteLine(count); Console.ReadLine(); } } }
mit
C#
92c08cc211604bb2ea6f1b8dca8625ad45d3b3da
Add network performance test
progaudi/progaudi.tarantool,aensidhe/tarantool-csharp,aensidhe/tarantool-dnx
tests/progaudi.tarantool.tests/NetworkPerformance.cs
tests/progaudi.tarantool.tests/NetworkPerformance.cs
using System; using System.Text; using ProGaudi.MsgPack.Light; using Xunit; using Shouldly; using ProGaudi.Tarantool.Client.Model.Requests; using ProGaudi.Tarantool.Client.Model.Responses; using System.Threading.Tasks; using ProGaudi.Tarantool.Client; using ProGaudi.Tarantool.Client.Tests; using ProGaudi.Tarantool.Client.Model; using System.Linq; public class NetworkPerformance : IAsyncLifetime { Box tarantoolClient; [Fact] public async Task Test() { for(int i=0;i<100;i++) { var result = await tarantoolClient.Call_1_6<TarantoolTuple<double>, TarantoolTuple<double>>( "math.sqrt", TarantoolTuple.Create(1.3)); var diff = Math.Abs(result.Data.Single().Item1 - Math.Sqrt(1.3)); diff.ShouldBeLessThan(double.Epsilon); } } Task IAsyncLifetime.DisposeAsync() { tarantoolClient?.Dispose(); return Task.CompletedTask; } async Task IAsyncLifetime.InitializeAsync() { tarantoolClient = await ProGaudi.Tarantool.Client.Box.Connect(ReplicationSourceFactory.GetReplicationSource()); } }
mit
C#
9e4a6956ab907fe32ea1752e89a38c7fc4aad8e3
Create StudentRepository
stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity
C#Development/BashSoft/BashSoft/Repositories/StudentsRepository.cs
C#Development/BashSoft/BashSoft/Repositories/StudentsRepository.cs
namespace BashSoft.Repositories { using BashSoft.Exceptions; using BashSoft.IO; using System; using System.Collections.Generic; using System.Linq; public static class StudentsRepository { public static bool isDataInitialized = false; private static Dictionary<string, Dictionary<string, List<int>>> studentsByCourse; public static void InitializeData() { if (!isDataInitialized) { OutputWriter.WriteMessageOnNewLine("Reading data..."); studentsByCourse = new Dictionary<string, Dictionary<string, List<int>>>(); ReadData(); } else { OutputWriter.WriteMessageOnNewLine(ExceptionMessages.DataAlreadyInitialisedException); } } private static void ReadData() { var input = Console.ReadLine(); while (!string.IsNullOrEmpty(input)) { //TODO: Split input and initilize variables var inputTokens = input .Split(' ') .ToArray(); var course = inputTokens[0]; var student = inputTokens[1]; var mark = int.Parse(inputTokens[2]); //TODO: Add the cource and the student if they don't exist if (!studentsByCourse.ContainsKey(course)) { studentsByCourse.Add(course, new Dictionary<string, List<int>>()); } if (!studentsByCourse[course].ContainsKey(student)) { studentsByCourse[course].Add(student, new List<int>()); } //TODO: Add mark studentsByCourse[course][student].Add(mark); input = Console.ReadLine(); } isDataInitialized = true; OutputWriter.WriteMessageOnNewLine("Data read!"); } private static bool IsQueryForCoursePossible(string courseName) { if (isDataInitialized) { if (studentsByCourse.ContainsKey(courseName)) { return true; } OutputWriter.DisplayException(ExceptionMessages.InexistingCourseInDataBase); } else { OutputWriter.DisplayException(ExceptionMessages.DataNotInitializedExceptionMessage); } return false; } private static bool IsQueryForStudentPossiblе(string courseName, string studentUserName) { if (IsQueryForCoursePossible(courseName) && studentsByCourse[courseName].ContainsKey(studentUserName)) { return true; } else { OutputWriter.DisplayException(ExceptionMessages.InexistingStudentInDataBase); } return false; } public static void GetStudentFromCourse(string courseName, string username) { if (IsQueryForStudentPossiblе(courseName, username)) { OutputWriter.PrintStudent(new KeyValuePair<string, List<int>>(username, studentsByCourse[courseName][username])); } } public static void GetAllStudentFromCourse(string courseName) { if (IsQueryForCoursePossible(courseName)) { OutputWriter.WriteMessageOnNewLine($"{courseName}:"); foreach (var studentMarkEntry in studentsByCourse[courseName]) { OutputWriter.PrintStudent(studentMarkEntry); } } } } }
mit
C#
fcf2e28921f79891083888c19d647dede2915ffc
Add - Attività Utente per la gestrione degli stati "InLavorazione" e "Prenotato"
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
src/backend/SO115App.Models/Classi/Soccorso/AttivitaUtente.cs
src/backend/SO115App.Models/Classi/Soccorso/AttivitaUtente.cs
using System; using System.Collections.Generic; using System.Text; namespace SO115App.Models.Classi.Soccorso { public class AttivitaUtente { public string Nominativo { get; set; } public DateTime DataInizioAttivita { get; set; } } }
agpl-3.0
C#
669a940cecc30a2af18f8abae5f288d458e9530c
Add simple ping controller to check functionality.
marcuson/A2BBServer,marcuson/A2BBServer,marcuson/A2BBServer
A2BBAPI/Controllers/PingController.cs
A2BBAPI/Controllers/PingController.cs
using A2BBAPI.Data; using A2BBAPI.Models; using A2BBCommon; using A2BBCommon.DTO; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Linq; using static A2BBAPI.Models.InOut; namespace A2BBAPI.Controllers { /// <summary> /// Controller user by HW granters to record in/out actions. /// </summary> [Produces("application/json")] [Route("api/ping")] [AllowAnonymous] public class PingController : Controller { #region Private fields /// <summary> /// The DB context. /// </summary> private readonly A2BBApiDbContext _dbContext; /// <summary> /// The logger. /// </summary> private readonly ILogger _logger; #endregion #region Public methods /// <summary> /// Create a new instance of this class. /// </summary> /// <param name="dbContext">The DI DB context.</param> /// <param name="loggerFactory">The DI logger factory.</param> public PingController(A2BBApiDbContext dbContext, ILoggerFactory loggerFactory) { _dbContext = dbContext; _logger = loggerFactory.CreateLogger<MeController>(); } /// <summary> /// Register in action. /// </summary> /// <param name="deviceId">The id of the device which performs this action.</param> /// <param name="subId">The subject id linked to the granter.</param> /// <returns><c>True</c> if ok, <c>false</c> otherwise.</returns> [HttpGet] public ResponseWrapper<bool> Ping() { return new ResponseWrapper<bool>(true, Constants.RestReturn.OK); } #endregion } }
apache-2.0
C#
6237258c973e23b98d5cb7a8f60ef05e4d136ee9
Create Knob.cs
Onastick/SightByte
Knob.cs
Knob.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SightByte { public partial class Knob : Form { Form1 baseForm; public Knob(Form1 baseForm) { this.baseForm = baseForm; InitializeComponent(); } private void Knob_Load(object sender, EventArgs e) { Location = new Point(Control.MousePosition.X, Control.MousePosition.Y - (this.Size.Height + (Screen.PrimaryScreen.Bounds.Height - Screen.PrimaryScreen.WorkingArea.Height))); trackBar1.Value = baseForm.trackBar1.Value; } private void trackBar1_Scroll(object sender, EventArgs e) { baseForm.trackBar1.Value = trackBar1.Value; baseForm.setGammaValue(trackBar1.Value); toolTip1.SetToolTip(trackBar1, trackBar1.Value.ToString()); } private void Knob_Deactivate(object sender, EventArgs e) { this.Dispose(); } } }
cc0-1.0
C#
c71be64dc67112e000f389e3607fd4d350a68f0c
Update BacktestReport.cs
jameschch/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,QuantConnect/Lean,StefanoRaggi/Lean,JKarathiya/Lean,kaffeebrauer/Lean,kaffeebrauer/Lean,JKarathiya/Lean,AnshulYADAV007/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,AnshulYADAV007/Lean,AnshulYADAV007/Lean,AnshulYADAV007/Lean,kaffeebrauer/Lean,AlexCatarino/Lean,Jay-Jay-D/LeanSTP,kaffeebrauer/Lean,Jay-Jay-D/LeanSTP,AlexCatarino/Lean,AnshulYADAV007/Lean,jameschch/Lean,kaffeebrauer/Lean,QuantConnect/Lean,AlexCatarino/Lean,Jay-Jay-D/LeanSTP,jameschch/Lean,StefanoRaggi/Lean,QuantConnect/Lean,StefanoRaggi/Lean,QuantConnect/Lean,JKarathiya/Lean,JKarathiya/Lean,Jay-Jay-D/LeanSTP,jameschch/Lean
Common/API/BacktestReport.cs
Common/API/BacktestReport.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Newtonsoft.Json; namespace QuantConnect.Api { /// <summary> /// Backtest Report Response wrapper /// </summary> public class BacktestReport : RestResponse { /// <summary> /// HTML data of the report with embedded base64 images /// </summary> [JsonProperty(PropertyName = "report")] public string Report { get; set; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Newtonsoft.Json; namespace QuantConnect.Api { /// <summary> /// Response from reading purchased data /// </summary> public class BacktestReport : RestResponse { /// <summary> /// HTML data of the report with embedded base64 images /// </summary> [JsonProperty(PropertyName = "report")] public string Report { get; set; } } }
apache-2.0
C#
31b56add15dcb56477f4fe66b2d761f11381773d
Add utilities
ektrah/nsec
src/Cryptography/Utilities.cs
src/Cryptography/Utilities.cs
using System; using System.Runtime.CompilerServices; namespace NSec.Cryptography { internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ToBigEndian(uint value) { if (BitConverter.IsLittleEndian) { return unchecked( (value << 24) | ((value & 0xFF00) << 8) | ((value & 0xFF0000) >> 8) | (value >> 24)); } else { return value; } } } }
mit
C#
7cce789975fdb6e5cfa28e045c549d7eff328779
Add script RtoRestart.cs
felladrin/unity-scripts,felladrin/unity3d-scripts
RtoRestart.cs
RtoRestart.cs
using UnityEngine; using UnityEngine.SceneManagement; public class RtoRestart : MonoBehaviour { private void Update() { if (Input.GetKeyDown(KeyCode.R)) { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } }
mit
C#
373395e21fbb9a0ed9f4e1d61322632b93bead6f
Add enumeration of supported SqlClient versions.
sharpjs/PSql,sharpjs/PSql
PSql/_Data/SqlClientVersion.cs
PSql/_Data/SqlClientVersion.cs
/* Copyright 2021 Jeffrey Sharp Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ namespace PSql; /// <summary> /// Supported SqlClient versions. /// </summary> public enum SqlClientVersion { /* Connection string history: MDS 1.0 - Authentication: AadPassword (all) - Authentication: AadIntegrated, AadInteractive (netfx) MDS 1.1 - Attestation Protocol - Enclave Attestation Url MDS 2.0: - Authentication: AadIntegrated, AadInteractive, AadServicePrincipal - Application Intent (was: ApplicationIntent) - Connect Retry Count (was: ConnectRetryCount) - Connect Retry Interval (was: ConnectRetryInterval) - Pool Blocking Period (was: PoolBlockingPeriod) - Multiple Active Result Sets (was: MultipleActiveResultSets) - Multi Subnet Failover (was: MultiSubnetFailover) - Transparent Network IP Resolution (was: TransparentNetworkIPResolution) - Trust Server Certificate (was: TrustServerCertificate) MDS 2.1 - Authentication: AadDeviceCodeFlow, AadManagedIdentity - Command Timeout MDS 3.0 - Authentication: AadDefault - The User ID connection property now requires a client id instead of an object id for user-assigned managed identity. MDS 4.0 - Encrypt: true by default - Authentication: AadIntegrated (allows User ID) - [REMOVED] Asynchronous Processing */ /// <summary> /// System.Data.SqlClient /// </summary> Legacy, /// <summary> /// Microsoft.Data.SqlClient 1.0.x /// </summary> Mds1, /// <summary> /// Microsoft.Data.SqlClient 1.1.x /// </summary> Mds1_1, /// <summary> /// Microsoft.Data.SqlClient 2.0.x /// </summary> Mds2, /// <summary> /// Microsoft.Data.SqlClient 2.1.x /// </summary> Mds2_1, /// <summary> /// Microsoft.Data.SqlClient 3.0.x /// </summary> Mds3, /// <summary> /// Microsoft.Data.SqlClient 4.0.x /// </summary> Mds4, }
isc
C#
0a7cc9d4140c9d924ef97aafe04dbe7474261413
Introduce a new ReleaseManager tool (populate-api-catalog)
googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet
tools/Google.Cloud.Tools.ReleaseManager/PopulateApiCatalogCommand.cs
tools/Google.Cloud.Tools.ReleaseManager/PopulateApiCatalogCommand.cs
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Cloud.Tools.Common; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Linq; namespace Google.Cloud.Tools.ReleaseManager { /// <summary> /// Tool to populate the API catalog (in google-cloud-dotnet) with values from the API index (in googleapis). /// This is only generally run when we add a new field to the API catalog, at which /// point this tool will need to change as well... but at least with it here, /// we don't need to rewrite the code every time. /// </summary> internal class PopulateApiCatalogCommand : CommandBase { public PopulateApiCatalogCommand() : base("populate-api-catalog", "Populates API catalog information from the API index. (You probably don't want this.)") { } protected override void ExecuteImpl(string[] args) { var catalog = ApiCatalog.Load(); var root = DirectoryLayout.DetermineRootDirectory(); var googleapis = Path.Combine(root, "googleapis"); var apiIndex = ApiIndex.V1.Index.LoadFromGoogleApis(googleapis); int modifiedCount = 0; foreach (var api in catalog.Apis) { var indexEntry = apiIndex.Apis.FirstOrDefault(x => x.DeriveCSharpNamespace() == api.Id); if (indexEntry is null) { continue; } // Change this line when introducing a new field... api.Json.Last.AddAfterSelf(new JProperty("serviceConfigFile", indexEntry.ConfigFile)); modifiedCount++; } Console.WriteLine($"Modified APIs: {modifiedCount}"); string json = catalog.FormatJson(); // Validate that we can still load it, before saving it to disk... ApiCatalog.FromJson(json); File.WriteAllText(ApiCatalog.CatalogPath, json); } } }
apache-2.0
C#
a0321786110ac18236c3c0d6973bd8991b537759
add user model
tsolarin/Csharp-jwt-authentication-sample
Api/Models/User.cs
Api/Models/User.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Api.Models { public class User { public int Id { get; set; } [Required] public string Username { get; set; } [Required] public string Password { get; set; } public string Filename { get; set; } public string Middlename { get; set; } public string Lastname { get; set; } public int Age { get; set; } } }
mit
C#
9b09361cc9a5b3ef1fb9cecf34e28f6401ae9def
Add testable spectator streaming client
peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu-new,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game/Tests/Visual/Spectator/TestSpectatorStreamingClient.cs
osu.Game/Tests/Visual/Spectator/TestSpectatorStreamingClient.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Bindables; using osu.Framework.Utils; using osu.Game.Online; using osu.Game.Online.Spectator; using osu.Game.Replays.Legacy; using osu.Game.Scoring; namespace osu.Game.Tests.Visual.Spectator { public class TestSpectatorStreamingClient : SpectatorStreamingClient { public new BindableList<int> PlayingUsers => (BindableList<int>)base.PlayingUsers; private readonly HashSet<int> watchingUsers = new HashSet<int>(); private readonly Dictionary<int, int> userBeatmapDictionary = new Dictionary<int, int>(); private readonly Dictionary<int, bool> userSentStateDictionary = new Dictionary<int, bool>(); public TestSpectatorStreamingClient() : base(new DevelopmentEndpointConfiguration()) { } public void StartPlay(int userId, int beatmapId) { userBeatmapDictionary[userId] = beatmapId; sendState(userId, beatmapId); } public void EndPlay(int userId, int beatmapId) { ((ISpectatorClient)this).UserFinishedPlaying(userId, new SpectatorState { BeatmapID = beatmapId, RulesetID = 0, }); userSentStateDictionary[userId] = false; } public void SendFrames(int userId, int index, int count) { var frames = new List<LegacyReplayFrame>(); for (int i = index; i < index + count; i++) { var buttonState = i == index + count - 1 ? ReplayButtonState.None : ReplayButtonState.Left1; frames.Add(new LegacyReplayFrame(i * 100, RNG.Next(0, 512), RNG.Next(0, 512), buttonState)); } var bundle = new FrameDataBundle(new ScoreInfo(), frames); ((ISpectatorClient)this).UserSentFrames(userId, bundle); if (!userSentStateDictionary[userId]) sendState(userId, userBeatmapDictionary[userId]); } public override void WatchUser(int userId) { // When newly watching a user, the server sends the playing state immediately. if (!watchingUsers.Contains(userId) && PlayingUsers.Contains(userId)) sendState(userId, userBeatmapDictionary[userId]); base.WatchUser(userId); watchingUsers.Add(userId); } private void sendState(int userId, int beatmapId) { ((ISpectatorClient)this).UserBeganPlaying(userId, new SpectatorState { BeatmapID = beatmapId, RulesetID = 0, }); userSentStateDictionary[userId] = true; } } }
mit
C#
367aacc3e110a3cee8bc35b0e9d12575aaa54cdf
Create String-Reversal.cs
DeanCabral/Code-Snippets
String-Reversal.cs
String-Reversal.cs
class StringReversal { static void Main(string[] args) { GetUserInput(); } static void GetUserInput() { string input = ""; Console.Write("Enter a word: "); input = Console.ReadLine(); Console.WriteLine("The reverse word of the string '{0}' is: {1}", input, ReverseString(input)); GetUserInput(); } static string ReverseString(string input) { string reversed = ""; for (int i = input.Length - 1; i >= 0; i--) { reversed += input[i]; } return reversed; } }
mit
C#
6b8cfe2978e2e96aa0d8ab5158559ecb4198abb8
Create UseRandomSprite.cs
felladrin/unity-scripts,felladrin/unity3d-scripts
UseRandomSprite.cs
UseRandomSprite.cs
using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] public class UseRandomSprite : MonoBehaviour { public List<Sprite> spriteList = new List<Sprite>(); void Awake () { if (spriteList.Count > 0) { GetComponent<SpriteRenderer> ().sprite = spriteList [Random.Range (0, spriteList.Count)]; } } }
mit
C#
12676aafb3cd7c78de491328289c087c930017cf
Move ExRegistry.cs
AonaSuzutsuki/ExRegistryHive
ExRegistry.cs
ExRegistry.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace ExRegistryHive { class ExRegistry { [DllImport("advapi32.dll")] private static extern int RegLoadKey(uint hKey, string lpSubKey, string lpFile); [DllImport("advapi32.dll")] private static extern int RegUnLoadKey(uint hKey, string lpSubKey); [DllImport("advapi32.dll")] private static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, ref int tokenhandle); [DllImport("kernel32.dll")] private static extern int GetCurrentProcess(); [DllImport("kernel32.dll")] private static extern bool CloseHandle(int handle); [DllImport("advapi32.dll")] private static extern int AdjustTokenPrivileges(int tokenhandle, bool disableprivs, [MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreivousState, int Returnlength); [DllImport("advapi32.dll")] private static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid); [StructLayout(LayoutKind.Sequential)] private struct LUID { public int LowPart; public int HighPart; } [StructLayout(LayoutKind.Sequential)] private struct TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; public LUID Luid; public UInt32 Attributes; } static int TOKEN_ADJUST_PRIVILEGES = 0x00000020; static uint SE_PRIVILEGE_ENABLED = 0x00000002; static int TOKEN_QUERY = 0x00000008; public enum ExRegistryKey : uint { HKEY_CLASSES_ROOT = 0x80000000, HKEY_CURRENT_USER = 0x80000001, HKEY_LOCAL_MACHINE = 0x80000002, HKEY_USERS = 0x80000003, HKEY_CURRENT_CONFIG = 0x80000005 } /// <summary> /// Load RegistryHive from file. /// </summary> /// <param name="hivename">RegistryHive name</param> /// <param name="filepath">RegistyHive filepath</param> /// <param name="rkey">Registrykey</param> /// <returns>When loading is failed, return false. When loading is succeeded, return true.</returns> public static bool LoadHive(string hivename, string filepath, ExRegistryKey rkey) { int tokenHandle = 0; LUID serLuid = new LUID(); LUID sebLuid = new LUID(); OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle); TOKEN_PRIVILEGES tokenp = new TOKEN_PRIVILEGES(); tokenp.PrivilegeCount = 1; LookupPrivilegeValue(null, "SeBackupPrivilege", ref sebLuid); tokenp.Luid = sebLuid; tokenp.Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(tokenHandle, false, ref tokenp, 0, 0, 0); tokenp.PrivilegeCount = 1; LookupPrivilegeValue(null, "SeRestorePrivilege", ref serLuid); tokenp.Luid = serLuid; tokenp.Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(tokenHandle, false, ref tokenp, 0, 0, 0); CloseHandle(tokenHandle); int rtn = RegLoadKey((uint)rkey, hivename + "\\", filepath); if (rtn == 0) { return true; } else { return false; } } /// <summary> /// Unload RegistryHive. /// </summary> /// <param name="hivename">RegistryHive name</param> /// <param name="rkey">Registrykey</param> /// <returns>When unloading is failed, return false. When unloading is succeeded, return true.</returns> public static bool UnloadHive(string hivename, ExRegistryKey rkey) { int rtn = RegUnLoadKey((uint)rkey, hivename + "\\"); if (rtn == 0) { return true; } else { return false; } } } }
mit
C#
2cb6a2a5ea628d4d9481aca1ebbb02b69f4e6a45
Create Client.cs
hprose/hprose-dotnet
src/Hprose.RPC/Client.cs
src/Hprose.RPC/Client.cs
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | Client.cs | | | | Client class for C#. | | | | LastModified: Jan 20, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using Hprose.IO; using Hprose.RPC.Codec; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Hprose.RPC { public abstract class Client { public ConcurrentDictionary<string, Settings> Settings { get; } = new ConcurrentDictionary<string, Settings>(); public ExpandoObject RequestHeaders { get; set; } = new ExpandoObject(); public int Timeout { get; set; } = 30000; public bool Simple { get; set; } = false; public Mode Mode { get; set; } = Mode.MemberMode; public LongType LongType { get; set; } = LongType.Int64; public RealType RealType { get; set; } = RealType.Double; public CharType CharType { get; set; } = CharType.String; public ListType ListType { get; set; } = ListType.List; public DictType DictType { get; set; } = DictType.NullableKeyDictionary; public IClientCodec Codec { get; set; } = ClientCodec.Instance; private List<string> urilist = new List<string>(); public List<string> Uris { get => urilist; set { if (value.Count > 0) { var random = new Random(Guid.NewGuid().GetHashCode()); urilist = value.OrderBy(x => random.Next()).ToList(); } } } private readonly HandlerManager handlerManager; Client() => handlerManager = new HandlerManager(Call, Transport); Client(string uri) : this() => urilist.Add(uri); Client(string[] uris) : this() => urilist.AddRange(uris); public Client Use(params InvokeHandler[] handlers) { handlerManager.Use(handlers); return this; } public Client Use(params IOHandler[] handlers) { handlerManager.Use(handlers); return this; } public Client Unuse(params InvokeHandler[] handlers) { handlerManager.Unuse(handlers); return this; } public Client Unuse(params IOHandler[] handlers) { handlerManager.Unuse(handlers); return this; } public async Task<T> Invoke<T>(string fullname, object[] args = null, Settings settings = null) { var context = new ClientContext(this, fullname, typeof(T), settings); return (T)(await handlerManager.InvokeHandler(fullname, args, context)); } public async Task<object> Call(string fullname, object[] args, Context context) { var request = Codec.Encode(fullname, args, context as ClientContext); var response = await handlerManager.IOHandler(request, context); return Codec.Decode(response, context as ClientContext); } public abstract Task<Stream> Transport(Stream request, Context context); } }
mit
C#
128329ea90644c7d6a50b913a546e4084b088ffb
Add sGame.cs to communicate with IDL in future
NightmareX1337/LF2.IDE
LF2.IDE/sGame.cs
LF2.IDE/sGame.cs
using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct sOpoint { int kind; int x; int y; int action; int dvx; int dvy; int oid; int facing; } [StructLayout(LayoutKind.Sequential)] struct sBpoint { int x; int y; } [StructLayout(LayoutKind.Sequential)] struct sCpoint { int kind; int x; int y; /// <summary> /// if its kind 2 this is fronthurtact /// </summary> int injury; /// <summary> /// if its kind 2 this is backhurtact /// </summary> int cover; int vaction; int aaction; int jaction; int daction; int throwvx; int throwvy; int hurtable; int decrease; int dircontrol; int taction; int throwinjury; int throwvz; } [StructLayout(LayoutKind.Sequential)] struct sWpoint { int kind; int x; int y; int weaponact; int attacking; int cover; int dvx; int dvy; int dvz; } [StructLayout(LayoutKind.Sequential)] struct sItr { int kind; int x; int y; int w; int h; int dvx; int dvy; int fall; int arest; int vrest; int effect; int catchingact; int caughtact; int bdefend; int injury; int zwidth; } [StructLayout(LayoutKind.Sequential)] struct sBdy { int kind; int x; int y; int w; int h; } [StructLayout(LayoutKind.Sequential)] struct sFrame { char exists; int pic; int state; int wait; int next; int dvx; int dvy; int dvz; int hit_a; int hit_d; int hit_j; int hit_Fa; int hit_Ua; int hit_Da; int hit_Fj; int hit_Uj; int hit_Dj; int hit_ja; int mp; int centerx; int centery; sOpoint opoint; sBpoint bpoint; sCpoint cpoint; sWpoint wpoint; int itr_count; int bdy_count; [MarshalAs(UnmanagedType.LPArray)] sItr[] itrs; [MarshalAs(UnmanagedType.LPArray)] sBdy[] bdys; // these values form a rectangle that holds all itrs/bdys within it int itr_x; int itr_y; int itr_w; int itr_h; int bdy_x; int bdy_y; int bdy_w; int bdy_h; string fname; string sound; } [StructLayout(LayoutKind.Sequential)] struct sDataFile { int walking_frame_rate; double walking_speed; double walking_speedz; int running_frame_rate; double running_speed; double running_speedz; double heavy_walking_speed; double heavy_walking_speedz; double heavy_running_speed; double heavy_running_speedz; double jump_height; double jump_distance; double jump_distancez; double dash_height; double dash_distance; double dash_distancez; double rowing_height; double rowing_distance; int weapon_hp; int weapon_drop_hurt; int pic_count; [MarshalAs(UnmanagedType.LPArray)] string[] pic_bmps; [MarshalAs(UnmanagedType.LPArray)] int[] pic_index; [MarshalAs(UnmanagedType.LPArray)] int[] pic_width; [MarshalAs(UnmanagedType.LPArray)] int[] pic_height; [MarshalAs(UnmanagedType.LPArray)] int[] pic_row; [MarshalAs(UnmanagedType.LPArray)] int[] pic_col; int id; int type; string small_bmp; //I believe at least some of this has to do with small image [MarshalAs(UnmanagedType.LPArray)] string face_bmp; //I believe at least some of this has to do with small image [MarshalAs(UnmanagedType.LPArray)] sFrame[] frames; string name; //not actually certain that the length is 12, seems like voodoo magic } [StructLayout(LayoutKind.Sequential)] struct sSpawn { int id; int x; int hp; int times; int reserve; int join; int join_reserve; int act; double ratio; int role; } [StructLayout(LayoutKind.Sequential)] struct sPhase { int bound; string music; int spawn_count; [MarshalAs(UnmanagedType.LPArray)] sSpawn[] spawns; int when_clear_goto_phase; } [StructLayout(LayoutKind.Sequential)] struct sStage { int phase_count; sPhase[] phases; } [StructLayout(LayoutKind.Sequential)] struct sBackground { int bg_width; int bg_zwidth1; int bg_zwidth2; int perspective1; int perspective2; int shadow; int layer_count; string[] layer_bmps; string shadow_bmp; string name; int[] transparency; int[] layer_width; int[] layer_x; int[] layer_y; int[] layer_height; } [StructLayout(LayoutKind.Sequential)] struct sFileManager { sDataFile[] datas; sStage[] stages; sBackground[] backgrounds; }
mit
C#
2d11bfad57aa232de0333795111692780735df62
Create CrowdSSOUser.cs
ryanmcdonough/CrowdSSO
CrowdSSOUser.cs
CrowdSSOUser.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; public class CrowdSSOUser { public string Name { get; set; } }
mit
C#
7390bb0acdd331eacbbe6c3aab1208fc289ca2c6
fix veigar add tristana
imsosharp/LeagueSharp,srjojo/leaguesharp,srjojo/leaguesharp,srjojo/leaguesharp,imsosharp/LeagueSharp,j8f7/mirrored,imsosharp/LeagueSharp,j8f7/mirrored
AutoSharpporting/Plugins/Tristana.cs
AutoSharpporting/Plugins/Tristana.cs
#region LICENSE // Copyright 2014 Support // Morgana.cs is part of Support. // // Support is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Support is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Support. If not, see <http://www.gnu.org/licenses/>. // // Filename: Support/Support/Morgana.cs // Created: 01/10/2014 // Date: 26/12/2014/16:23 // Author: h3h3 #endregion using System; using System.Collections.Generic; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using SharpDX; using Support.Evade; using Support.Util; using ActiveGapcloser = Support.Util.ActiveGapcloser; using SpellData = LeagueSharp.SpellData; namespace Support.Plugins { public class Tristana : PluginBase { public Tristana() { Q = new Spell(SpellSlot.Q, 703); E = new Spell(SpellSlot.E, 703); R = new Spell(SpellSlot.R, 703); } public override void OnUpdate(EventArgs args) { if (ComboMode) { if (Q.CastCheck(Target, "ComboQ")) { Q.Cast(); } if (W.CastCheck(Target, "ComboW") && W.IsKillable(Target)) { W.Cast(Target, true); } if (E.CastCheck(Target, "ComboE")) { E.Cast(Target, true); } if (R.CastCheck(Target, "ComboR") && R.IsKillable(Target)) { R.Cast(Target, true); } } if (HarassMode) { if (E.CastCheck(Target, "HarassE")) { E.Cast(Target, true); } } } public override void OnPossibleToInterrupt(Obj_AI_Base unit, InterruptableSpell spell) { if (spell.DangerLevel < InterruptableDangerLevel.High || unit.IsAlly) { return; } if (R.CastCheck(unit, "Interrupt.R")) { R.Cast(unit, UsePackets); return; } } public override void ComboMenu(Menu config) { config.AddBool("ComboQ", "Use Q", true); config.AddBool("ComboW", "Use W", true); config.AddBool("ComboE", "Use E", true); config.AddBool("ComboR", "Use R", true); } public override void HarassMenu(Menu config) { config.AddBool("HarassE", "Use E", true); } public override void InterruptMenu(Menu config) { config.AddBool("Interrupt.R", "Use R to Interrupt Spells", true); } } }
mit
C#
fc2d487ac7fdd6bb459cb2f2be8b9f39e71fb4f6
Add visual test for EdgeSnappingContainer
EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework
osu.Framework.Tests/Visual/Containers/TestSceneEdgeSnappingContainer.cs
osu.Framework.Tests/Visual/Containers/TestSceneEdgeSnappingContainer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Containers { public class TestSceneEdgeSnappingContainer : FrameworkTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(EdgeSnappingContainer), typeof(SnapTargetContainer) }; public TestSceneEdgeSnappingContainer() { FillFlowContainer<SnapTestContainer> container; Child = container = new FillFlowContainer<SnapTestContainer> { Direction = FillDirection.Horizontal, Margin = new MarginPadding(20), Spacing = new Vector2(20), Children = new[] { new SnapTestContainer(Edges.Left), new SnapTestContainer(Edges.Left | Edges.Top), new SnapTestContainer(Edges.Top), new SnapTestContainer(Edges.Top | Edges.Right), new SnapTestContainer(Edges.Right), new SnapTestContainer(Edges.Bottom | Edges.Right), new SnapTestContainer(Edges.Bottom), new SnapTestContainer(Edges.Bottom | Edges.Left), } }; foreach (var child in container.Children) addBoxAssert(child); } private void addBoxAssert(SnapTestContainer container) { bool leftSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Left); bool topSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Top); bool rightSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Right); bool bottomSnapped = container.EdgeSnappingContainer.SnappedEdges.HasFlag(Edges.Bottom); AddAssert($"\"{container.Name}\" snaps correctly", () => leftSnapped == container.EdgeSnappingContainer.Padding.Left < 0 && topSnapped == container.EdgeSnappingContainer.Padding.Top < 0 && rightSnapped == container.EdgeSnappingContainer.Padding.Right < 0 && bottomSnapped == container.EdgeSnappingContainer.Padding.Bottom < 0); } private class SnapTestContainer : SnapTargetContainer { internal readonly EdgeSnappingContainer EdgeSnappingContainer; public SnapTestContainer(Edges snappedEdges) { const float inset = 10f; Name = snappedEdges.ToString(); Size = new Vector2(50); Children = new Drawable[] { new Box { Colour = Color4.Blue, RelativeSizeAxes = Axes.Both, }, EdgeSnappingContainer = new EdgeSnappingContainer { SnappedEdges = snappedEdges, Position = new Vector2(inset), Size = Size - new Vector2(inset * 2), Child = new Box { Colour = Color4.Green, RelativeSizeAxes = Axes.Both } } }; } } } }
mit
C#
63f623c7bfb50173cd7f9c388c4d1cf974037448
Add FineCountResponder (wip)
prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15
FineBot/FineBot.BotRunner/Responders/FineCountResponder.cs
FineBot/FineBot.BotRunner/Responders/FineCountResponder.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using FineBot.BotRunner.Responders.Interfaces; using MargieBot.Models; namespace FineBot.BotRunner.Responders { public class FineCountResponder : IFineBotResponder { public bool CanRespond(ResponseContext context) { return false; } public BotMessage GetResponse(ResponseContext context) { return new BotMessage{ Text = "in progress" }; } } }
mit
C#
00f684d6720341c36d3fda15128871e17f921488
Add unit tests for TestId
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade.CoreTests/Util/TestIdTests.cs
src/Arkivverket.Arkade.CoreTests/Util/TestIdTests.cs
using System.Collections.Generic; using System.Linq; using Arkivverket.Arkade.Core.Util; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.CoreTests.Util { public class TestIdTests { [Fact] public void ToStringTest() { var testId = new TestId(TestId.TestKind.Noark5, 15); testId.ToString().Should().Be("N5.15"); } [Fact] public void CompareToTest() { var testId16 = new TestId(TestId.TestKind.Noark5, 16); var testId15 = new TestId(TestId.TestKind.Noark5, 15); var testIds = new List<TestId> { testId16, testId15 }; testIds.Sort(); testIds.First().Should().Be(testId15); } [Fact] public void EqualsTest() { var testIdA = new TestId(TestId.TestKind.Noark5, 15); var testIdB = new TestId(TestId.TestKind.Noark5, 15); testIdA.Should().BeEquivalentTo(testIdB); } } }
agpl-3.0
C#