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 |
|---|---|---|---|---|---|---|---|---|
f80d1016394c2240912ad47b7b14ecc8f1d709ff | Change aliasing of Modded Showdown Import | architdate/PKHeX-Auto-Legality-Mod,architdate/PKHeX-Auto-Legality-Mod | AutoLegality/AutoLegality.Designer.cs | AutoLegality/AutoLegality.Designer.cs | namespace PKHeX.WinForms
{
partial class Main
{
public System.Windows.Forms.ToolStripMenuItem EnableAutoLegality(System.ComponentModel.ComponentResourceManager resources)
{
this.Menu_ShowdownImportPKMModded = new System.Windows.Forms.ToolStripMenuItem();
this.Menu_ShowdownImportPKMModded.Image = ((System.Drawing.Image)(resources.GetObject("Menu_ShowdownImportPKM.Image")));
this.Menu_ShowdownImportPKMModded.Name = "Menu_ShowdownImportPKMModded";
this.Menu_ShowdownImportPKMModded.Size = new System.Drawing.Size(231, 22);
this.Menu_ShowdownImportPKMModded.Text = "Import with Auto-Legality Mod";
this.Menu_ShowdownImportPKMModded.Click += new System.EventHandler(this.ClickShowdownImportPKMModded);
return this.Menu_ShowdownImportPKMModded;
}
private System.Windows.Forms.ToolStripMenuItem Menu_ShowdownImportPKMModded;
}
}
| namespace PKHeX.WinForms
{
partial class Main
{
public System.Windows.Forms.ToolStripMenuItem EnableAutoLegality(System.ComponentModel.ComponentResourceManager resources)
{
this.Menu_ShowdownImportPKMModded = new System.Windows.Forms.ToolStripMenuItem();
this.Menu_ShowdownImportPKMModded.Image = ((System.Drawing.Image)(resources.GetObject("Menu_ShowdownImportPKM.Image")));
this.Menu_ShowdownImportPKMModded.Name = "Menu_ShowdownImportPKMModded";
this.Menu_ShowdownImportPKMModded.Size = new System.Drawing.Size(231, 22);
this.Menu_ShowdownImportPKMModded.Text = "Modded Showdown Import";
this.Menu_ShowdownImportPKMModded.Click += new System.EventHandler(this.ClickShowdownImportPKMModded);
return this.Menu_ShowdownImportPKMModded;
}
private System.Windows.Forms.ToolStripMenuItem Menu_ShowdownImportPKMModded;
}
} | mit | C# |
db24aef530993ee230e9486544d2c35302079366 | Check and add TLS 1.2 to ServicePointManager.SecurityProtocol if missing, instead of replacing existing configuration | Beanstream/beanstream-dotnet,Beanstream-DRWP/beanstream-dotnet | BamboraSDK/Data/WebCommandExecuter.cs | BamboraSDK/Data/WebCommandExecuter.cs | // The MIT License (MIT)
//
// Copyright (c) 2018 Bambora, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Net;
namespace Bambora.NA.SDK.Data
{
/// <summary>
/// Executes web requests. This piece of code is pulled out from HttpWebRequest
/// (which does the heavy lifting of the actual request) so that we can plug in
/// mock responses for unit testing.
/// </summary>
public class WebCommandExecuter : IWebCommandExecuter
{
public WebCommandExecuter ()
{
if(!ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Tls12))
{
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
}
}
public WebCommandResult<T> ExecuteCommand<T>(IWebCommandSpec<T> spec)
{
if(spec == null)
{
throw new ArgumentNullException("spec");
}
var result = new WebCommandResult<T>();
var request = WebRequest.Create(spec.Url);
spec.PrepareRequest(request);
using(var response = request.GetResponse() as HttpWebResponse)
{
if (response == null)
{
throw new Exception("Could not get a response from Bambora API");
}
result.ReturnValue = (int) response.StatusCode;
if(response.StatusCode == (HttpStatusCode) 200)
{
result.Response = spec.MapResponse(response);
}
}
return result;
}
}
} | // The MIT License (MIT)
//
// Copyright (c) 2018 Bambora, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Net;
namespace Bambora.NA.SDK.Data
{
/// <summary>
/// Executes web requests. This piece of code is pulled out from HttpWebRequest
/// (which does the heavy lifting of the actual request) so that we can plug in
/// mock responses for unit testing.
/// </summary>
public class WebCommandExecuter : IWebCommandExecuter
{
public WebCommandExecuter ()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
public WebCommandResult<T> ExecuteCommand<T>(IWebCommandSpec<T> spec)
{
if(spec == null)
{
throw new ArgumentNullException("spec");
}
var result = new WebCommandResult<T>();
var request = WebRequest.Create(spec.Url);
spec.PrepareRequest(request);
using(var response = request.GetResponse() as HttpWebResponse)
{
if (response == null)
{
throw new Exception("Could not get a response from Bambora API");
}
result.ReturnValue = (int) response.StatusCode;
if(response.StatusCode == (HttpStatusCode) 200)
{
result.Response = spec.MapResponse(response);
}
}
return result;
}
}
} | mit | C# |
7bdd593b78430287736fa371363a8b7354fb68b0 | Add LibraryProgramUnit documentation (closes #19) | felipebz/ndapi | Ndapi/LibraryProgramUnit.cs | Ndapi/LibraryProgramUnit.cs | using Ndapi.Core.Handles;
using Ndapi.Enums;
namespace Ndapi
{
/// <summary>
/// Represents a library program unit.
/// </summary>
public class LibraryProgramUnit : NdapiObject
{
internal LibraryProgramUnit(ObjectSafeHandle handle) : base(handle)
{
}
/// <summary>
/// Gets the program unit code.
/// </summary>
public string Text => GetStringProperty(NdapiConstants.D2FP_PGU_TXT);
/// <summary>
/// Gets the program unit type.
/// </summary>
public ProgramUnitType Type => GetNumberProperty<ProgramUnitType>(NdapiConstants.D2FP_PGU_TYP);
}
}
| using Ndapi.Core.Handles;
using Ndapi.Enums;
namespace Ndapi
{
public class LibraryProgramUnit : NdapiObject
{
internal LibraryProgramUnit(ObjectSafeHandle handle) : base(handle)
{
}
public string Text => GetStringProperty(NdapiConstants.D2FP_PGU_TXT);
public ProgramUnitType Type => GetNumberProperty<ProgramUnitType>(NdapiConstants.D2FP_PGU_TYP);
}
}
| mit | C# |
969d3e3f98f77cc1f375ca26c06ec8a1caa1ce1d | Improve the no-repo error message for grr | awaescher/RepoZ,awaescher/RepoZ | RepoZ.Ipc/RepoZIpcClient.cs | RepoZ.Ipc/RepoZIpcClient.cs | using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using NetMQ;
using NetMQ.Sockets;
namespace RepoZ.Ipc
{
public class RepoZIpcClient
{
private string _answer;
private Repository[] _repositories;
public Result GetRepositories() => GetRepositories("list:.*");
public Result GetRepositories(string query)
{
var watch = Stopwatch.StartNew();
_answer = null;
_repositories = null;
using (var client = new RequestSocket()) // connect
{
client.Connect(RepoZIpcEndpoint.Address);
byte[] load = Encoding.UTF8.GetBytes(query);
client.SendFrame(load);
client.ReceiveReady += ClientOnReceiveReady;
client.Poll(TimeSpan.FromMilliseconds(3000));
client.ReceiveReady -= ClientOnReceiveReady;
client.Disconnect(RepoZIpcEndpoint.Address);
}
watch.Stop();
return new Result()
{
Answer = _answer ?? GetErrorMessage(),
DurationMilliseconds = watch.ElapsedMilliseconds,
Repositories = _repositories ?? new Repository[0]
};
}
private string GetErrorMessage()
{
var isRepoZRunning = Process.GetProcessesByName("RepoZ").Any();
return isRepoZRunning
? $"RepoZ is running but does not answer.\nIt seems that it could not listen on {RepoZIpcEndpoint.Address}.\nI don't know anything better than recommending a reboot. Sorry."
: "RepoZ seems not to be running :(";
}
private void ClientOnReceiveReady(object sender, NetMQSocketEventArgs e)
{
_answer = Encoding.UTF8.GetString(e.Socket.ReceiveFrameBytes());
_repositories = _answer.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => Repository.FromString(s))
.Where(r => r != null)
.OrderBy(r => r.Name)
.ToArray();
}
public class Result
{
public string Answer { get; set; }
public long DurationMilliseconds { get; set; }
public Repository[] Repositories { get; set; }
}
}
} | using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using NetMQ;
using NetMQ.Sockets;
namespace RepoZ.Ipc
{
public class RepoZIpcClient
{
private string _answer;
private Repository[] _repositories;
public Result GetRepositories() => GetRepositories("list:.*");
public Result GetRepositories(string query)
{
var watch = Stopwatch.StartNew();
_answer = null;
_repositories = null;
using (var client = new RequestSocket()) // connect
{
client.Connect(RepoZIpcEndpoint.Address);
byte[] load = Encoding.UTF8.GetBytes(query);
client.SendFrame(load);
client.ReceiveReady += ClientOnReceiveReady;
client.Poll(TimeSpan.FromMilliseconds(3000));
client.ReceiveReady -= ClientOnReceiveReady;
client.Disconnect(RepoZIpcEndpoint.Address);
}
watch.Stop();
return new Result()
{
Answer = _answer ?? "RepoZ seems not to be running :(",
DurationMilliseconds = watch.ElapsedMilliseconds,
Repositories = _repositories ?? new Repository[0]
};
}
private void ClientOnReceiveReady(object sender, NetMQSocketEventArgs e)
{
_answer = Encoding.UTF8.GetString(e.Socket.ReceiveFrameBytes());
_repositories = _answer.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => Repository.FromString(s))
.Where(r => r != null)
.OrderBy(r => r.Name)
.ToArray();
}
public class Result
{
public string Answer { get; set; }
public long DurationMilliseconds { get; set; }
public Repository[] Repositories { get; set; }
}
}
} | mit | C# |
3f2371145c8946a3fef9c9aee3f252c6e7f18011 | update cdn location | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.API/App_Start/BundleConfig.cs | WebAPI.API/App_Start/BundleConfig.cs | using System.Web.Optimization;
namespace WebAPI.API
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.UseCdn = true;
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-1.10.1.js"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap",
"//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js").
Include(
"~/Scripts/bootstrap.js",
"~/Scripts/scrollspy.js"));
bundles.Add(new ScriptBundle("~/bundles/site").Include(
"~/Scripts/modernizr-2.6.1.js",
"~/Scripts/site.js"));
bundles.Add(new StyleBundle("~/Content/bundles").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
}
}
} | using System.Web.Optimization;
namespace WebAPI.API
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.UseCdn = true;
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-1.10.1.js"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap",
"//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js").
Include(
"~/Scripts/bootstrap.js",
"~/Scripts/scrollspy.js"));
bundles.Add(new ScriptBundle("~/bundles/site").Include(
"~/Scripts/modernizr-2.6.1.js",
"~/Scripts/site.js"));
bundles.Add(new StyleBundle("~/Content/bundles").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"));
}
}
} | mit | C# |
0b3072df06101007a8dd9eb7f328891a61ec72af | Fix typo | LiquidThinking/Xenon,LiquidThinking/Xenon | Xenon.Tests/XenonTestOptionsTests.cs | Xenon.Tests/XenonTestOptionsTests.cs | using System;
using NUnit.Framework;
namespace Xenon.Tests
{
[TestFixture]
public class XenonTestOptionsTests
{
[Test]
public void IfAssertMethodIsNotSet_WhenAccessedShouldShouldThrowException()
{
var xenonTestOptions = new XenonTestOptions();
var exception = Assert.Catch<Exception>(() =>
{
var assertMethod = xenonTestOptions.AssertMethod;
});
Assert.AreEqual("You must set an AssertMethod", exception.Message);
}
}
}
| using System;
using NUnit.Framework;
namespace Xenon.Tests
{
[TestFixture]
public class XenonTestOptionsTests
{
[Test]
public void IfAssertMethodIsNotSet_WhenAccessedShouldSholdThrowException()
{
var xenonTestOptions = new XenonTestOptions();
var exception = Assert.Catch<Exception>(() =>
{
var assertMethod = xenonTestOptions.AssertMethod;
});
Assert.AreEqual("You must set an AssertMethod", exception.Message);
}
}
}
| mit | C# |
ec7987c6d9c447910686771201358b77aebc4dba | Hide the new, unwanted "Show regional dialects" control | JohnThomson/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop | src/BloomExe/CollectionCreating/LanguageIdControl.cs | src/BloomExe/CollectionCreating/LanguageIdControl.cs | using System;
using System.Linq;
using System.Windows.Forms;
using Bloom.Collection;
using Bloom.ToPalaso;
namespace Bloom.CollectionCreating
{
public partial class LanguageIdControl : UserControl, IPageControl
{
public CollectionSettings _collectionInfo;
private Action<UserControl, bool> _setNextButtonState;
public LanguageIdControl()
{
InitializeComponent();
_lookupISOControl.SelectedLanguage = null;
_lookupISOControl.IsShowRegionalDialectsCheckBoxVisible = false;
}
private void OnLookupISOControlReadinessChanged(object sender, EventArgs e)
{
if (_collectionInfo == null)
return;
if (_lookupISOControl.SelectedLanguage != null)
{
_collectionInfo.Language1Iso639Code = _lookupISOControl.SelectedLanguage.LanguageTag;
_collectionInfo.Language1Name = _lookupISOControl.SelectedLanguage.DesiredName;
_collectionInfo.Country = _lookupISOControl.SelectedLanguage.Countries.FirstOrDefault() ?? string.Empty;
//If there are multiple countries, just leave it blank so they can type something in
if (_collectionInfo.Country.Contains(","))
{
_collectionInfo.Country = "";
}
}
_setNextButtonState(this, _lookupISOControl.SelectedLanguage != null);
}
public void Init(Action<UserControl, bool> setNextButtonState, CollectionSettings collectionInfo)
{
_setNextButtonState = setNextButtonState;
_collectionInfo = collectionInfo;
_lookupISOControl.ReadinessChanged += OnLookupISOControlReadinessChanged;
}
public void NowVisible()
{
_setNextButtonState(this, _lookupISOControl.SelectedLanguage != null);
}
private void _lookupISOControl_Leave(object sender, EventArgs e)
{
_setNextButtonState(this, _lookupISOControl.SelectedLanguage != null);
}
}
}
| using System;
using System.Linq;
using System.Windows.Forms;
using Bloom.Collection;
using Bloom.ToPalaso;
namespace Bloom.CollectionCreating
{
public partial class LanguageIdControl : UserControl, IPageControl
{
public CollectionSettings _collectionInfo;
private Action<UserControl, bool> _setNextButtonState;
public LanguageIdControl()
{
InitializeComponent();
_lookupISOControl.SelectedLanguage = null;
}
private void OnLookupISOControlReadinessChanged(object sender, EventArgs e)
{
if (_collectionInfo == null)
return;
if (_lookupISOControl.SelectedLanguage != null)
{
_collectionInfo.Language1Iso639Code = _lookupISOControl.SelectedLanguage.LanguageTag;
_collectionInfo.Language1Name = _lookupISOControl.SelectedLanguage.DesiredName;
_collectionInfo.Country = _lookupISOControl.SelectedLanguage.Countries.FirstOrDefault() ?? string.Empty;
//If there are multiple countries, just leave it blank so they can type something in
if (_collectionInfo.Country.Contains(","))
{
_collectionInfo.Country = "";
}
}
_setNextButtonState(this, _lookupISOControl.SelectedLanguage != null);
}
public void Init(Action<UserControl, bool> setNextButtonState, CollectionSettings collectionInfo)
{
_setNextButtonState = setNextButtonState;
_collectionInfo = collectionInfo;
_lookupISOControl.ReadinessChanged += OnLookupISOControlReadinessChanged;
}
public void NowVisible()
{
_setNextButtonState(this, _lookupISOControl.SelectedLanguage != null);
}
private void _lookupISOControl_Leave(object sender, EventArgs e)
{
_setNextButtonState(this, _lookupISOControl.SelectedLanguage != null);
}
}
}
| mit | C# |
b769bf114fd0133ab449d2f5e33e8e9dd007e252 | Document format. | lukyad/Eco | Sample/TimeSpanConverter.cs | Sample/TimeSpanConverter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample
{
public static class TimeSpanConverter
{
private static readonly Dictionary<string, Func<double, TimeSpan>> _fromDoubleMethods = new Dictionary<string, Func<double, TimeSpan>> {
{ "ms", TimeSpan.FromMilliseconds },
{ "s", TimeSpan.FromSeconds },
{ "m", TimeSpan.FromMinutes },
{ "h", TimeSpan.FromHours },
{ "d", TimeSpan.FromDays }
};
private static readonly Dictionary<string, Func<TimeSpan, double>> _toDoubleMethods = new Dictionary<string, Func<TimeSpan, double>> {
{ "ms", t => t.TotalMilliseconds },
{ "s", t => t.TotalSeconds },
{ "m", t => t.TotalMinutes },
{ "h", t => t.TotalHours },
{ "d", t => t.TotalDays }
};
public static object FromString(string format, string timeSpan)
{
TimeSpan result;
bool succeed = TryParseTimeSpan(timeSpan, out result);
if (!succeed)
throw new ApplicationException(String.Format("Unsupported TimeSpan format: '{0}'", timeSpan));
return result;
}
public static string ToString(string format, object timeSpan)
{
Func<TimeSpan, double> ToDouble = _toDoubleMethods[format];
return String.Format("{0}{1}", ToDouble((TimeSpan)timeSpan), format);
}
public static bool TryParseTimeSpan(this string timeSpanStr, out TimeSpan timeSpan)
{
timeSpan = default(TimeSpan);
if (String.IsNullOrEmpty(timeSpanStr))
return false;
var parserInfo = _fromDoubleMethods.FirstOrDefault(pair => timeSpanStr.EndsWith(pair.Key));
if (String.IsNullOrEmpty(parserInfo.Key))
return false;
string unitCode = parserInfo.Key;
string valueStr = timeSpanStr.Substring(0, timeSpanStr.Length - unitCode.Length);
double value;
if (!Double.TryParse(valueStr, out value))
return false;
timeSpan = _fromDoubleMethods[unitCode](value);
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample
{
public static class TimeSpanConverter
{
private static readonly Dictionary<string, Func<double, TimeSpan>> _fromDoubleMethods = new Dictionary<string, Func<double, TimeSpan>> {
{ "ms", TimeSpan.FromMilliseconds },
{ "s", TimeSpan.FromSeconds },
{ "m", TimeSpan.FromMinutes },
{ "h", TimeSpan.FromHours },
{ "d", TimeSpan.FromDays }
};
private static readonly Dictionary<string, Func<TimeSpan, double>> _toDoubleMethods = new Dictionary<string, Func<TimeSpan, double>> {
{ "ms", t => t.TotalMilliseconds },
{ "s", t => t.TotalSeconds },
{ "m", t => t.TotalMinutes },
{ "h", t => t.TotalHours },
{ "d", t => t.TotalDays }
};
public static object FromString(string format, string timeSpan)
{
TimeSpan result;
bool succeed = TryParseTimeSpan(timeSpan, out result);
if (!succeed)
throw new ApplicationException(String.Format("Unsupported TimeSpan format: '{0}'", timeSpan));
return result;
}
public static string ToString(string format, object timeSpan)
{
Func<TimeSpan, double> ToDouble = _toDoubleMethods[format];
return String.Format("{0}{1}", ToDouble((TimeSpan)timeSpan), format);
}
public static bool TryParseTimeSpan(this string timeSpanStr, out TimeSpan timeSpan)
{
timeSpan = default(TimeSpan);
if (String.IsNullOrEmpty(timeSpanStr))
return false;
var parserInfo = _fromDoubleMethods.FirstOrDefault(pair => timeSpanStr.EndsWith(pair.Key));
if (String.IsNullOrEmpty(parserInfo.Key))
return false;
string unitCode = parserInfo.Key;
string valueStr = timeSpanStr.Substring(0, timeSpanStr.Length - unitCode.Length);
double value;
if (!Double.TryParse(valueStr, out value))
return false;
timeSpan = _fromDoubleMethods[unitCode](value);
return true;
}
}
}
| apache-2.0 | C# |
44e4ebf146ae7e0c2378a17e4e27ce3e90eb7d58 | switch to JilJsonConverter for giggles. After initial type deserialization, its screamingly fast, which is great for reads | jmkelly/elephanet,jmkelly/elephanet,YoloDev/elephanet,YoloDev/elephanet | Elephanet/StoreConventions.cs | Elephanet/StoreConventions.cs | using System;
using Newtonsoft.Json;
using Elephanet;
using Elephanet.Serialization;
namespace Elephanet
{
public class StoreConventions : IStoreConventions
{
IJsonConverter _jsonConverter;
private TableInfo _tableInfo;
public StoreConventions()
{
_jsonConverter = new JilJsonConverter();
_tableInfo = new TableInfo();
}
public StoreConventions(IJsonConverter jsonConverter)
{
_jsonConverter = jsonConverter;
}
public IJsonConverter JsonConverter
{
get { return _jsonConverter; }
}
public TableInfo TableInfo
{
get { return _tableInfo; }
}
}
}
| using System;
using Newtonsoft.Json;
using Elephanet;
namespace Elephanet
{
public class StoreConventions : IStoreConventions
{
IJsonConverter _jsonConverter;
private TableInfo _tableInfo;
public StoreConventions()
{
_jsonConverter = new JsonConverter();
_tableInfo = new TableInfo();
}
public StoreConventions(IJsonConverter jsonConverter)
{
_jsonConverter = jsonConverter;
}
public IJsonConverter JsonConverter
{
get { return _jsonConverter; }
}
public TableInfo TableInfo
{
get { return _tableInfo; }
}
}
}
| mit | C# |
bd0e06e80a78209f18e5fb5dda30ac16ccb3d749 | Use a copy of the original stream in HttpClient.PostAsync method to allow retries (PostAsync disposes original stream) | PNSolutions/MegaApiClient,gpailler/MegaApiClient | MegaApiClient/WebClient_HttpClient.cs | MegaApiClient/WebClient_HttpClient.cs | namespace CG.Web.MegaApiClient
{
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Net.Http;
using System.Net.Http.Headers;
public class WebClient : IWebClient
{
private const int DefaultResponseTimeout = Timeout.Infinite;
private readonly HttpClient httpClient = new HttpClient();
public WebClient()
: this(DefaultResponseTimeout)
{
this.BufferSize = MegaApiClient.DefaultBufferSize;
}
internal WebClient(int responseTimeout)
{
this.httpClient.Timeout = TimeSpan.FromMilliseconds(responseTimeout);
this.httpClient.DefaultRequestHeaders.UserAgent.Add(this.GenerateUserAgent());
}
public int BufferSize { get; set; }
public string PostRequestJson(Uri url, string jsonData)
{
using (MemoryStream jsonStream = new MemoryStream(jsonData.ToBytes()))
{
return this.PostRequest(url, jsonStream, "application/json");
}
}
public string PostRequestRaw(Uri url, Stream dataStream)
{
return this.PostRequest(url, dataStream, "application/octet-stream");
}
public Stream GetRequestRaw(Uri url)
{
HttpResponseMessage response = this.httpClient.GetAsync(url).Result;
return response.Content.ReadAsStreamAsync().Result;
}
private string PostRequest(Uri url, Stream dataStream, string contentType)
{
// Copy original stream to allow retries
// HttpClient will dispose the source stream at the end of PostAsync call
byte[] buffer = new byte[dataStream.Length];
using (Stream dataStreamCopy = new MemoryStream(buffer))
{
dataStream.CopyTo(dataStreamCopy);
dataStreamCopy.Position = 0;
using (StreamContent content = new StreamContent(dataStreamCopy, this.BufferSize))
{
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
using (HttpResponseMessage response = this.httpClient.PostAsync(url, content).Result)
{
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
{
return streamReader.ReadToEnd();
}
}
}
}
}
private ProductInfoHeaderValue GenerateUserAgent()
{
AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
return new ProductInfoHeaderValue(assemblyName.Name, assemblyName.Version.ToString(2));
}
}
}
| namespace CG.Web.MegaApiClient
{
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Net.Http;
using System.Net.Http.Headers;
public class WebClient : IWebClient
{
private const int DefaultResponseTimeout = Timeout.Infinite;
private readonly HttpClient httpClient = new HttpClient();
public WebClient()
: this(DefaultResponseTimeout)
{
this.BufferSize = MegaApiClient.DefaultBufferSize;
}
internal WebClient(int responseTimeout)
{
this.httpClient.Timeout = TimeSpan.FromMilliseconds(responseTimeout);
this.httpClient.DefaultRequestHeaders.UserAgent.Add(this.GenerateUserAgent());
}
public int BufferSize { get; set; }
public string PostRequestJson(Uri url, string jsonData)
{
using (MemoryStream jsonStream = new MemoryStream(jsonData.ToBytes()))
{
return this.PostRequest(url, jsonStream, "application/json");
}
}
public string PostRequestRaw(Uri url, Stream dataStream)
{
return this.PostRequest(url, dataStream, "application/octet-stream");
}
public Stream GetRequestRaw(Uri url)
{
HttpResponseMessage response = this.httpClient.GetAsync(url).Result;
return response.Content.ReadAsStreamAsync().Result;
}
private string PostRequest(Uri url, Stream dataStream, string contentType)
{
using (StreamContent content = new StreamContent(dataStream, this.BufferSize))
{
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
using (HttpResponseMessage response = this.httpClient.PostAsync(url, content).Result)
{
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
{
return streamReader.ReadToEnd();
}
}
}
}
private ProductInfoHeaderValue GenerateUserAgent()
{
AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
return new ProductInfoHeaderValue(assemblyName.Name, assemblyName.Version.ToString(2));
}
}
}
| mit | C# |
038ff618c24c042b604b7326c1de200cd6ca7db6 | Fix S3 create bucket test | emgarten/Sleet,emgarten/Sleet | test/Sleet.AmazonS3.Tests/AmazonS3FileSystemTests.cs | test/Sleet.AmazonS3.Tests/AmazonS3FileSystemTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NuGet.Test.Helpers;
using Sleet.Test.Common;
namespace Sleet.AmazonS3.Tests
{
public class AmazonS3FileSystemTests
{
[EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)]
public async Task GivenAS3AccountVerifyBucketOperations()
{
using (var testContext = new AmazonS3TestContext())
{
testContext.CreateBucketOnInit = false;
await testContext.InitAsync();
// Verify at the start
(await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse();
(await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse();
// Create
await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None);
(await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue();
(await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue();
await testContext.CleanupAsync();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NuGet.Test.Helpers;
using Sleet.Test.Common;
namespace Sleet.AmazonS3.Tests
{
public class AmazonS3FileSystemTests
{
[EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)]
public async Task GivenAS3AccountVerifyBucketOperations()
{
using (var testContext = new AmazonS3TestContext())
{
testContext.CreateBucketOnInit = false;
await testContext.InitAsync();
// Verify at the start
(await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse();
(await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse();
// Create
await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None);
(await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue();
(await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue();
// Delete
await testContext.FileSystem.DeleteBucket(testContext.Logger, CancellationToken.None);
(await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse();
(await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse();
await testContext.CleanupAsync();
}
}
}
} | mit | C# |
dc6a79a481af4d2c5a3c6b90b6ca92b6b40ec2c7 | Trim end of post on Save. Incase someone hits enter loads and then blows the size of the page. This will stop that. | Jetski5822/NGM.Forum | ViewModels/PostBodyEditorViewModel.cs | ViewModels/PostBodyEditorViewModel.cs | using NGM.Forum.Models;
namespace NGM.Forum.ViewModels {
public class PostBodyEditorViewModel {
public PostPart PostPart { get; set; }
public string Text {
get { return PostPart.Record.Text; }
set { PostPart.Record.Text = string.IsNullOrWhiteSpace(value) ? value : value.TrimEnd(); }
}
public string Format {
get { return PostPart.Record.Format; }
set { PostPart.Record.Format = value; }
}
public string EditorFlavor { get; set; }
}
} | using NGM.Forum.Models;
namespace NGM.Forum.ViewModels {
public class PostBodyEditorViewModel {
public PostPart PostPart { get; set; }
public string Text {
get { return PostPart.Record.Text; }
set { PostPart.Record.Text = value; }
}
public string Format {
get { return PostPart.Record.Format; }
set { PostPart.Record.Format = value; }
}
public string EditorFlavor { get; set; }
}
} | bsd-3-clause | C# |
53e565948d6cb1b2636aab728e61853ac56bdf3e | set tile as parent in model builder | reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap | unity/demo/Assets/Scripts/Scene/UnityModelBuilder.cs | unity/demo/Assets/Scripts/Scene/UnityModelBuilder.cs | using System;
using System.Collections.Generic;
using Assets.Scripts.Scene.Builders;
using UnityEngine;
using UtyDepend;
using UtyMap.Unity;
using Mesh = UtyMap.Unity.Mesh;
namespace Assets.Scripts.Scene
{
/// <summary> Responsible for building Unity game objects from meshes and elements. </summary>
internal class UnityModelBuilder
{
private readonly MaterialProvider _materialProvider;
private Dictionary<string, IElementBuilder> _elementBuilders = new Dictionary<string, IElementBuilder>();
[Dependency]
public UnityModelBuilder(MaterialProvider materialProvider)
{
_materialProvider = materialProvider;
// register custom builders here.
_elementBuilders.Add("info", new PlaceElementBuilder(_materialProvider));
_elementBuilders.Add("label", new LabelElementBuilder());
_elementBuilders.Add("import", new ImportElementBuilder());
}
/// <inheritdoc />
public void BuildElement(Tile tile, Element element)
{
foreach (var pair in _elementBuilders)
{
if (!element.Styles["builders"].Contains(pair.Key))
continue;
var gameObject = pair.Value.Build(tile, element);
gameObject.transform.parent = tile.GameObject.transform;
}
}
/// <inheritdoc />
public void BuildMesh(Tile tile, Mesh mesh)
{
var gameObject = new GameObject(mesh.Name);
var uMesh = new UnityEngine.Mesh();
uMesh.vertices = mesh.Vertices;
uMesh.triangles = mesh.Triangles;
uMesh.colors = mesh.Colors;
uMesh.uv = mesh.Uvs;
uMesh.uv2 = mesh.Uvs2;
uMesh.uv3 = mesh.Uvs3;
uMesh.RecalculateNormals();
gameObject.isStatic = true;
gameObject.AddComponent<MeshFilter>().mesh = uMesh;
// TODO use TextureIndex to select proper material.
string texture = tile.QuadKey.LevelOfDetail == 16
? @"Materials/SurfaceTexturedColored"
: @"Materials/SurfaceColored";
gameObject.AddComponent<MeshRenderer>().sharedMaterial = _materialProvider.GetSharedMaterial(texture);
gameObject.transform.parent = tile.GameObject.transform;
}
}
} | using System;
using System.Collections.Generic;
using Assets.Scripts.Scene.Builders;
using UnityEngine;
using UtyDepend;
using UtyMap.Unity;
using Mesh = UtyMap.Unity.Mesh;
namespace Assets.Scripts.Scene
{
/// <summary> Responsible for building Unity game objects from meshes and elements. </summary>
internal class UnityModelBuilder
{
private readonly MaterialProvider _materialProvider;
private Dictionary<string, IElementBuilder> _elementBuilders = new Dictionary<string, IElementBuilder>();
[Dependency]
public UnityModelBuilder(MaterialProvider materialProvider)
{
_materialProvider = materialProvider;
// register custom builders here.
_elementBuilders.Add("info", new PlaceElementBuilder(_materialProvider));
_elementBuilders.Add("label", new LabelElementBuilder());
_elementBuilders.Add("import", new ImportElementBuilder());
}
/// <inheritdoc />
public void BuildElement(Tile tile, Element element)
{
foreach (var pair in _elementBuilders)
{
if (element.Styles["builders"].Contains(pair.Key))
pair.Value.Build(tile, element);
}
}
/// <inheritdoc />
public void BuildMesh(Tile tile, Mesh mesh)
{
var gameObject = new GameObject(mesh.Name);
var uMesh = new UnityEngine.Mesh();
uMesh.vertices = mesh.Vertices;
uMesh.triangles = mesh.Triangles;
uMesh.colors = mesh.Colors;
uMesh.uv = mesh.Uvs;
uMesh.uv2 = mesh.Uvs2;
uMesh.uv3 = mesh.Uvs3;
uMesh.RecalculateNormals();
gameObject.isStatic = true;
gameObject.AddComponent<MeshFilter>().mesh = uMesh;
// TODO use TextureIndex to select proper material.
string texture = tile.QuadKey.LevelOfDetail == 16
? @"Materials/SurfaceTexturedColored"
: @"Materials/SurfaceColored";
gameObject.AddComponent<MeshRenderer>().sharedMaterial = _materialProvider.GetSharedMaterial(texture);
gameObject.transform.parent = tile.GameObject.transform;
}
}
} | apache-2.0 | C# |
4b9d0941a46b41b7831fa12e81eefec4c9235ba0 | Fix if httpContext is null we cannot wrap it | robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS | src/Umbraco.Web/Net/AspNetHttpContextAccessor.cs | src/Umbraco.Web/Net/AspNetHttpContextAccessor.cs | using System;
using System.Web;
namespace Umbraco.Web
{
internal class AspNetHttpContextAccessor : IHttpContextAccessor
{
public HttpContextBase HttpContext
{
get
{
var httpContext = System.Web.HttpContext.Current;
return httpContext is null ? null : new HttpContextWrapper(httpContext);
}
set
{
throw new NotSupportedException();
}
}
}
}
| using System;
using System.Web;
namespace Umbraco.Web
{
internal class AspNetHttpContextAccessor : IHttpContextAccessor
{
public HttpContextBase HttpContext
{
get
{
return new HttpContextWrapper(System.Web.HttpContext.Current);
}
set
{
throw new NotSupportedException();
}
}
}
}
| mit | C# |
d969135ae866dd9e81086bab345c3f0860844ba4 | Remove Scheduling Race Condition (#28) | bwatts/Totem,bwatts/Totem | Source/Totem.Runtime/Timeline/TimelineSchedule.cs | Source/Totem.Runtime/Timeline/TimelineSchedule.cs | using System;
using System.Linq;
using System.Reactive.Linq;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Schedules points on the timeline to occur in the future
/// </summary>
internal sealed class TimelineSchedule : Connection
{
readonly TimelineScope _timeline;
internal TimelineSchedule(TimelineScope timeline)
{
_timeline = timeline;
}
internal void Push(TimelineMessage message)
{
var timer = null as IDisposable;
timer = Observable
.Timer(new DateTimeOffset(message.Point.Event.When))
.Take(1)
.Subscribe(_ => PushToTimeline(message, timer));
}
void PushToTimeline(TimelineMessage message, IDisposable timer)
{
try
{
timer?.Dispose();
_timeline.PushFromSchedule(message);
}
catch(Exception error)
{
Log.Error(error, "[timeline] Failed to push scheduled event of type {EventType}. The timeline will attempt to push it again after a restart.", message.Point.EventType);
}
}
}
} | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Schedules points on the timeline to occur in the future
/// </summary>
internal sealed class TimelineSchedule : Connection
{
readonly ConcurrentDictionary<IDisposable, bool> _timers = new ConcurrentDictionary<IDisposable, bool>();
readonly TimelineScope _timeline;
internal TimelineSchedule(TimelineScope timeline)
{
_timeline = timeline;
}
protected override void Close()
{
foreach(var timer in _timers.Keys)
{
timer.Dispose();
}
}
internal void Push(TimelineMessage message)
{
var timer = null as IDisposable;
timer = Observable
.Timer(new DateTimeOffset(message.Point.Event.When))
.Take(1)
.Subscribe(_ => PushToTimeline(message, timer));
_timers[timer] = true;
}
void PushToTimeline(TimelineMessage message, IDisposable timer)
{
try
{
bool ignored;
_timers.TryRemove(timer, out ignored);
timer.Dispose();
_timeline.PushFromSchedule(message);
}
catch(Exception error)
{
Log.Error(error, "[timeline] Failed to push scheduled event of type {EventType}. The timeline will attempt to push it again after a restart.", message.Point.EventType);
}
}
}
} | mit | C# |
c293b3b5644f86f6ddf2223990f62c1fd2b8c5f5 | Update DestructuringHelpers.cs | CaptiveAire/Seq.App.YouTrack | src/Seq.App.YouTrack/Helpers/DestructuringHelpers.cs | src/Seq.App.YouTrack/Helpers/DestructuringHelpers.cs | // Copyright 2014-2019 CaptiveAire Systems
//
// 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.
namespace Seq.App.YouTrack.Helpers
{
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
public static class DestructuringHelpers
{
public static object ToDynamic(this object o)
{
switch (o)
{
case IEnumerable<KeyValuePair<string, object>> dictionary:
var result = new ExpandoObject();
var asDict = (IDictionary<string, object>)result;
foreach (var kvp in dictionary)
{
asDict.Add(kvp.Key, ToDynamic(kvp.Value));
}
return result;
case IEnumerable<object> enumerable:
return enumerable.Select(ToDynamic).ToArray();
}
return o;
}
public static object FromDynamic(this object o)
{
switch (o)
{
case IEnumerable<KeyValuePair<string, object>> dictionary:
return dictionary.ToDictionary(kvp => kvp.Key, kvp => FromDynamic(kvp.Value));
case IEnumerable<object> enumerable:
return enumerable.Select(FromDynamic).ToArray();
}
return o;
}
}
}
| namespace Seq.App.YouTrack.Helpers
{
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
public static class DestructuringHelpers
{
public static object ToDynamic(this object o)
{
switch (o)
{
case IEnumerable<KeyValuePair<string, object>> dictionary:
var result = new ExpandoObject();
var asDict = (IDictionary<string, object>)result;
foreach (var kvp in dictionary)
{
asDict.Add(kvp.Key, ToDynamic(kvp.Value));
}
return result;
case IEnumerable<object> enumerable:
return enumerable.Select(ToDynamic).ToArray();
}
return o;
}
public static object FromDynamic(this object o)
{
switch (o)
{
case IEnumerable<KeyValuePair<string, object>> dictionary:
return dictionary.ToDictionary(kvp => kvp.Key, kvp => FromDynamic(kvp.Value));
case IEnumerable<object> enumerable:
return enumerable.Select(FromDynamic).ToArray();
}
return o;
}
}
} | apache-2.0 | C# |
ec0e5d129521872979f4f6009c267ea2e1849252 | Format changes a little | yappy/DollsKit,yappy/DollsKit,yappy/DollsKit,yappy/DollsKit,yappy/DollsKit | Shanghai/HealthCheck.cs | Shanghai/HealthCheck.cs | using System.IO;
using System.Text;
namespace Shanghai
{
class HealthCheck
{
public HealthCheck()
{ }
public void Proc(TaskServer server, string taskName)
{
var msg = new StringBuilder("[Health Check]\n");
msg.AppendFormat("CPU Temp: {0:F3}\n", GetCpuTemp());
double free, total;
GetDiskInfoG(out free, out total);
msg.AppendFormat("Disk: {0:F1}G / {1:F1}G Free ({2}%)",
free, total, (int)(free * 100.0 / total));
TwitterManager.Update(msg.ToString());
}
private static double GetCpuTemp()
{
const string DevFilePath = "/sys/class/thermal/thermal_zone0/temp";
string src;
using (var reader = new StreamReader(DevFilePath))
{
src = reader.ReadLine();
}
return int.Parse(src) / 1000.0;
}
private static void GetDiskInfoG(out double free, out double total)
{
const double Unit = 1024.0 * 1024.0 * 1024.0;
var info = new DriveInfo("/");
free = info.TotalFreeSpace / Unit;
total = info.TotalSize / Unit;
}
}
}
| using System.IO;
using System.Text;
namespace Shanghai
{
class HealthCheck
{
public HealthCheck()
{ }
public void Proc(TaskServer server, string taskName)
{
var msg = new StringBuilder("[Health Check]\n");
msg.AppendFormat("CPU Temp: {0:F3}\n", GetCpuTemp());
double free, total;
GetDiskInfoG(out free, out total);
msg.AppendFormat("Disk: {0:F3}G/{1:F3}G Free ({2}%)",
free, total, (int)(free * 100.0 / total));
TwitterManager.Update(msg.ToString());
}
private static double GetCpuTemp()
{
const string DevFilePath = "/sys/class/thermal/thermal_zone0/temp";
string src;
using (var reader = new StreamReader(DevFilePath))
{
src = reader.ReadLine();
}
return int.Parse(src) / 1000.0;
}
private static void GetDiskInfoG(out double free, out double total)
{
const double Unit = 1024.0 * 1024.0 * 1024.0;
var info = new DriveInfo("/");
free = info.TotalFreeSpace / Unit;
total = info.TotalSize / Unit;
}
}
}
| mit | C# |
9253e8a685040808fd15f7a07c7d827de10135aa | add return_to support | zendesk/zendesk_jwt_sso_examples,zendesk/zendesk_jwt_sso_examples,kietlieng/zendesk_jwt_sso_examples,zendesk/zendesk_jwt_sso_examples,kietlieng/zendesk_jwt_sso_examples,kietlieng/zendesk_jwt_sso_examples,kietlieng/zendesk_jwt_sso_examples,zendesk/zendesk_jwt_sso_examples,kietlieng/zendesk_jwt_sso_examples,zendesk/zendesk_jwt_sso_examples,zendesk/zendesk_jwt_sso_examples,kietlieng/zendesk_jwt_sso_examples,zendesk/zendesk_jwt_sso_examples | c_sharp_handler.cs | c_sharp_handler.cs | // Handler: <%@ WebHandler Language="C#" Class="Zendesk.JWTLogin" CodeBehind="Zendesk.JWTLogin.cs" %>
// Requires: JWT (https://nuget.org/packages/JWT)
// Tested with .NET 4.5
using System;
using System.Web;
using System.Collections.Generic;
namespace Zendesk
{
public class JWTLogin : IHttpHandler
{
private const string SHARED_KEY = "{my zendesk token}";
private const string SUBDOMAIN = "{my zendesk subdomain}";
public void ProcessRequest(HttpContext context)
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int timestamp = (int) t.TotalSeconds;
var payload = new Dictionary<string, object>() {
{ "iat", timestamp },
{ "jti", System.Guid.NewGuid().ToString() }
// { "name", currentUser.name },
// { "email", currentUser.email }
};
string token = JWT.JsonWebToken.Encode(payload, SHARED_KEY, JWT.JwtHashAlgorithm.HS256);
string redirectUrl = "https://" + SUBDOMAIN + ".zendesk.com/access/jwt?jwt=" + token;
string returnTo = context.Request.QueryString["return_to"];
if(return_to != null) {
redirectUrl += "&return_to=" + HttpUtility.UrlEncode(returnTo);
}
context.Response.Redirect(redirectUrl);
}
public bool IsReusable
{
get
{
return true;
}
}
}
}
| // Handler: <%@ WebHandler Language="C#" Class="Zendesk.JWTLogin" CodeBehind="Zendesk.JWTLogin.cs" %>
// Requires: JWT (https://nuget.org/packages/JWT)
// Tested with .NET 4.5
using System;
using System.Web;
using System.Collections.Generic;
namespace Zendesk
{
public class JWTLogin : IHttpHandler
{
private const string SHARED_KEY = "{my zendesk token}";
private const string SUBDOMAIN = "{my zendesk subdomain}";
public void ProcessRequest(HttpContext context)
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int timestamp = (int) t.TotalSeconds;
var payload = new Dictionary<string, object>() {
{ "iat", timestamp },
{ "jti", System.Guid.NewGuid().ToString() }
// { "name", currentUser.name },
// { "email", currentUser.email }
};
string token = JWT.JsonWebToken.Encode(payload, SHARED_KEY, JWT.JwtHashAlgorithm.HS256);
string redirectUrl = "https://" + SUBDOMAIN + ".zendesk.com/access/jwt?jwt=" + token;
context.Response.Redirect(redirectUrl);
}
public bool IsReusable
{
get
{
return true;
}
}
}
}
| apache-2.0 | C# |
6b693893c99da28296864f16fe8e67332b7595d7 | Bump version to 0.27 | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.27.0";
}
}
| #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.26.0";
}
}
| mit | C# |
916f79ea864cb099b2b5ee3a7bf2e5888344021d | Add message inside this class to convey exception | sghaida/ADWS | ADWS/Models/UserInfoResponse.cs | ADWS/Models/UserInfoResponse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace ADWS.Models
{
[DataContract]
public class UserInfoResponse
{
[DataMember]
public string Title { set; get; }
[DataMember]
public string DisplayName { set; get; }
[DataMember]
public string FirstName { set; get; }
[DataMember]
public string LastName { set; get; }
[DataMember]
public string SamAccountName { set; get; }
[DataMember]
public string Upn { set; get; }
[DataMember]
public string EmailAddress { set; get; }
[DataMember]
public string EmployeeId { set; get; }
[DataMember]
public string Department { set; get; }
[DataMember]
public string BusinessPhone { get; set; }
[DataMember]
public string Telephone { get; set; }
[DataMember]
public string SipAccount { set; get; }
[DataMember]
public string PrimaryHomeServerDn { get; set; }
[DataMember]
public string PoolName { set; get; }
[DataMember]
public string PhysicalDeliveryOfficeName { set; get; }
[DataMember]
public string OtherTelphone { get; set; }
[DataMember]
public string Message { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace ADWS.Models
{
[DataContract]
public class UserInfoResponse
{
[DataMember]
public string Title { set; get; }
[DataMember]
public string DisplayName { set; get; }
[DataMember]
public string FirstName { set; get; }
[DataMember]
public string LastName { set; get; }
[DataMember]
public string SamAccountName { set; get; }
[DataMember]
public string Upn { set; get; }
[DataMember]
public string EmailAddress { set; get; }
[DataMember]
public string EmployeeId { set; get; }
[DataMember]
public string Department { set; get; }
[DataMember]
public string BusinessPhone { get; set; }
[DataMember]
public string Telephone { get; set; }
[DataMember]
public string SipAccount { set; get; }
[DataMember]
public string PrimaryHomeServerDn { get; set; }
[DataMember]
public string PoolName { set; get; }
[DataMember]
public string PhysicalDeliveryOfficeName { set; get; }
[DataMember]
public string OtherTelphone { get; set; }
}
} | apache-2.0 | C# |
92393caf164e7af895572036c48fcd4792db346f | Revert "temporary fix for GenericValue to support more conversions: now always backed by a string" | redxdev/DScript | DScript/Context/GenericValue.cs | DScript/Context/GenericValue.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace DScript.Context
{
public struct GenericValue<T> : IValue
{
public static GenericValue<T> Default = new GenericValue<T>(default(T));
private T value;
public GenericValue(T value)
{
this.value = value;
}
public V GetValue<V>()
{
if(this.value == null)
{
return default(V);
}
if(typeof(T) == typeof(V))
{
return (V)(object)this.value;
}
var converter = TypeDescriptor.GetConverter(typeof(V));
if (converter != null && converter.CanConvertFrom(typeof(T)))
{
return (V)converter.ConvertFrom(this.value);
}
return default(V);
}
public bool CanConvert<V>()
{
if (typeof(V) == typeof(T))
return true;
var converter = TypeDescriptor.GetConverter(typeof(V));
return converter != null && converter.CanConvertFrom(typeof(T));
}
public Type GetValueType()
{
return typeof(T);
}
public override string ToString()
{
if (value == null)
return null;
return value.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace DScript.Context
{
public struct GenericValue<T> : IValue
{
public static GenericValue<T> Default = new GenericValue<T>(default(T));
private string value;
public GenericValue(T value)
{
this.value = value == null ? null : value.ToString();
}
public V GetValue<V>()
{
if(this.value == null)
{
return default(V);
}
if(typeof(string) == typeof(V))
{
return (V)(object)this.value;
}
var converter = TypeDescriptor.GetConverter(typeof(V));
if (converter != null && converter.CanConvertFrom(typeof(string)))
{
return (V)converter.ConvertFrom(this.value);
}
return default(V);
}
public bool CanConvert<V>()
{
if (typeof(V) == typeof(string))
return true;
var converter = TypeDescriptor.GetConverter(typeof(V));
return converter != null && converter.CanConvertFrom(typeof(string));
}
public Type GetValueType()
{
return typeof(string);
}
public override string ToString()
{
if (value == null)
return null;
return value.ToString();
}
}
}
| apache-2.0 | C# |
9b0f302db8afd9a853bf3ce749ac7967efef5d02 | Add log for audit api | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.RegistrationTidyUpJob/RegistrationManagement/RegistrationManager.cs | src/SFA.DAS.EmployerUsers.RegistrationTidyUpJob/RegistrationManagement/RegistrationManager.cs | using System;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Azure;
using NLog;
using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser;
using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations;
namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement
{
public class RegistrationManager
{
private readonly IMediator _mediator;
private readonly ILogger _logger;
public RegistrationManager(IMediator mediator, ILogger logger)
{
_mediator = mediator;
_logger = logger;
}
public async Task RemoveExpiredRegistrations()
{
_logger.Info("Starting deletion of expired registrations");
_logger.Info($"AuditApiBaseUrl: {CloudConfigurationManager.GetSetting("AuditApiBaseUrl")}");
try
{
var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery());
_logger.Info($"Found {users.Length} users with expired registrations");
foreach (var user in users)
{
_logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')");
await _mediator.SendAsync(new DeleteUserCommand
{
User = user
});
}
}
catch (Exception ex)
{
_logger.Error(ex);
throw;
}
_logger.Info("Finished deletion of expired registrations");
}
}
}
| using System;
using System.Threading.Tasks;
using MediatR;
using NLog;
using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser;
using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations;
namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement
{
public class RegistrationManager
{
private readonly IMediator _mediator;
private readonly ILogger _logger;
public RegistrationManager(IMediator mediator, ILogger logger)
{
_mediator = mediator;
_logger = logger;
}
public async Task RemoveExpiredRegistrations()
{
_logger.Info("Starting deletion of expired registrations");
try
{
var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery());
_logger.Info($"Found {users.Length} users with expired registrations");
foreach (var user in users)
{
_logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')");
await _mediator.SendAsync(new DeleteUserCommand
{
User = user
});
}
}
catch (Exception ex)
{
_logger.Error(ex);
throw;
}
_logger.Info("Finished deletion of expired registrations");
}
}
}
| mit | C# |
5a669c1e235997546056390f3c530028b1a29e52 | Update Constants.cs | ibamong/aws-sdk-cshape-example | mori9/Utils/Constants.cs | mori9/Utils/Constants.cs | using Amazon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mori9.Utils
{
public class Constants
{
public const string COGNITO_IDENTITY_POOL_ID = "xxxxxxx"; // Enter your ID
public static RegionEndpoint COGNITO_REGION = RegionEndpoint.USEast1; // Enter your region
public static RegionEndpoint DYNAMODB_REGION = RegionEndpoint.APSoutheast1; // Enter your region
}
}
| using Amazon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mori9.Utils
{
public class Constants
{
//public const string FB_APP_ID = "";
//public const string FB_APP_NAME = "My Inventory";
//public const string PROVIDER_NAME = "graph.facebook.com";
public const string COGNITO_IDENTITY_POOL_ID = "us-east-1:976b965c-56ad-4680-9e46-8edef60b095c";
public static RegionEndpoint COGNITO_REGION = RegionEndpoint.USEast1; // N. Virginia
public static RegionEndpoint DYNAMODB_REGION = RegionEndpoint.APSoutheast1; // Singapore
}
}
| apache-2.0 | C# |
468dce6a8bdd04204fdd9f9a1fd09d0ba3a66542 | remove todo only | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Portal/Application/Services/Commitments/Http/CommitmentsApiHttpClientFactory.cs | src/SFA.DAS.EAS.Portal/Application/Services/Commitments/Http/CommitmentsApiHttpClientFactory.cs | using System;
using System.Net.Http;
using SFA.DAS.EAS.Portal.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
namespace SFA.DAS.EAS.Portal.Application.Services.Commitments.Http
{
public class CommitmentsApiHttpClientFactory : ICommitmentsApiHttpClientFactory
{
private readonly CommitmentsApiClientConfiguration _commitmentsApiClientConfiguration;
public CommitmentsApiHttpClientFactory(CommitmentsApiClientConfiguration commitmentsApiClientConfiguration)
{
_commitmentsApiClientConfiguration = commitmentsApiClientConfiguration;
}
public HttpClient CreateHttpClient()
{
var httpClient = new HttpClientBuilder()
.WithDefaultHeaders()
.WithBearerAuthorisationHeader(new JwtBearerTokenGenerator(_commitmentsApiClientConfiguration))
.Build();
httpClient.BaseAddress = new Uri(_commitmentsApiClientConfiguration.BaseUrl);
//todo: set timeout
//httpClient.Timeout = TimeSpan.Parse(_recruitApiClientConfig.TimeoutTimeSpan);
return httpClient;
}
}
} | using System;
using System.Net.Http;
using SFA.DAS.EAS.Portal.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
namespace SFA.DAS.EAS.Portal.Application.Services.Commitments.Http
{
//todo: decide on whether client factories belong with services or separate, and make consistent
// common base class, named instances??
public class CommitmentsApiHttpClientFactory : ICommitmentsApiHttpClientFactory
{
private readonly CommitmentsApiClientConfiguration _commitmentsApiClientConfiguration;
public CommitmentsApiHttpClientFactory(CommitmentsApiClientConfiguration commitmentsApiClientConfiguration)
{
_commitmentsApiClientConfiguration = commitmentsApiClientConfiguration;
}
public HttpClient CreateHttpClient()
{
var httpClient = new HttpClientBuilder()
.WithDefaultHeaders()
.WithBearerAuthorisationHeader(new JwtBearerTokenGenerator(_commitmentsApiClientConfiguration))
.Build();
httpClient.BaseAddress = new Uri(_commitmentsApiClientConfiguration.BaseUrl);
//todo: set timeout
//httpClient.Timeout = TimeSpan.Parse(_recruitApiClientConfig.TimeoutTimeSpan);
return httpClient;
}
}
} | mit | C# |
316c9783751e60545c155a8201c953b496957511 | Move https redirection above basic auth | demyanenko/hutel,demyanenko/hutel,demyanenko/hutel | server/Startup.cs | server/Startup.cs | using System;
using System.IO;
using hutel.Filters;
using hutel.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace server
{
public class Startup
{
private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH";
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddJsonOptions(opt =>
{
opt.SerializerSettings.DateParseHandling = DateParseHandling.None;
});
services.AddScoped<ValidateModelStateAttribute>();
services.AddMemoryCache();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Trace);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRedirectToHttpsMiddleware();
if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1")
{
app.UseBasicAuthMiddleware();
}
app.UseMvc();
app.UseStaticFiles();
}
}
}
| using System;
using System.IO;
using hutel.Filters;
using hutel.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace server
{
public class Startup
{
private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH";
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddJsonOptions(opt =>
{
opt.SerializerSettings.DateParseHandling = DateParseHandling.None;
});
services.AddScoped<ValidateModelStateAttribute>();
services.AddMemoryCache();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Trace);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1")
{
app.UseBasicAuthMiddleware();
}
app.UseRedirectToHttpsMiddleware();
app.UseMvc();
app.UseStaticFiles();
}
}
}
| apache-2.0 | C# |
a44de02468ce978e322f279f0d1e7ca2f4f2d86e | Add assembly informational version | mono/cecil,jbevain/cecil,sailro/cecil,fnajera-rac-de/cecil,SiliconStudio/Mono.Cecil | ProjectInfo.cs | ProjectInfo.cs | //
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
//
// Licensed under the MIT/X11 license.
//
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct ("Mono.Cecil")]
[assembly: AssemblyCopyright ("Copyright © 2008 - 2015 Jb Evain")]
#if !PCL
[assembly: ComVisible (false)]
#endif
[assembly: AssemblyVersion ("0.10.0.0")]
[assembly: AssemblyFileVersion ("0.10.0.0")]
[assembly: AssemblyInformationalVersion ("0.10.0.0-beta")] | //
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
//
// Licensed under the MIT/X11 license.
//
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct ("Mono.Cecil")]
[assembly: AssemblyCopyright ("Copyright © 2008 - 2015 Jb Evain")]
#if !PCL
[assembly: ComVisible (false)]
#endif
[assembly: AssemblyVersion ("0.10.0.0")]
[assembly: AssemblyFileVersion ("0.10.0.0")]
| mit | C# |
ca86920ca95dd0a2ca4a3deb376ce9e58c63900a | Update ServiceProviderFixture.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/ServiceProviderFixture.cs | TIKSN.Framework.IntegrationTests/ServiceProviderFixture.cs | using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using TIKSN.Data.Mongo;
using TIKSN.DependencyInjection;
using TIKSN.Framework.IntegrationTests.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests
{
public class ServiceProviderFixture : IDisposable
{
private readonly IHost host;
public ServiceProviderFixture()
{
this.host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddFrameworkPlatform();
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule<CoreModule>();
builder.RegisterModule<PlatformModule>();
builder.RegisterType<TestMongoRepository>().As<ITestMongoRepository>().InstancePerLifetimeScope();
builder.RegisterType<TestMongoDatabaseProvider>().As<IMongoDatabaseProvider>().SingleInstance();
builder.RegisterType<TestMongoClientProvider>().As<IMongoClientProvider>().SingleInstance();
})
.ConfigureHostConfiguration(builder => { builder.AddInMemoryCollection(GetInMemoryConfiguration()); })
.Build();
static Dictionary<string, string> GetInMemoryConfiguration()
{
return new()
{
{
"ConnectionStrings:Mongo",
"mongodb://localhost:27017/TIKSN_Framework_IntegrationTests?w=majority"
}
};
}
}
public IServiceProvider Services => this.host.Services;
public void Dispose() => this.host?.Dispose();
}
}
| using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using TIKSN.Data.Mongo;
using TIKSN.DependencyInjection;
using TIKSN.Framework.IntegrationTests.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests
{
public class ServiceProviderFixture : IDisposable
{
private readonly IHost host;
public ServiceProviderFixture()
{
host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddFrameworkPlatform();
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule<CoreModule>();
builder.RegisterModule<PlatformModule>();
builder.RegisterType<TestMongoRepository>().As<ITestMongoRepository>().InstancePerLifetimeScope();
builder.RegisterType<TestMongoDatabaseProvider>().As<IMongoDatabaseProvider>().SingleInstance();
builder.RegisterType<TestMongoClientProvider>().As<IMongoClientProvider>().SingleInstance();
})
.ConfigureHostConfiguration(builder => { builder.AddInMemoryCollection(GetInMemoryConfiguration()); })
.Build();
static Dictionary<string, string> GetInMemoryConfiguration()
{
return new()
{
{"ConnectionStrings:Mongo", "mongodb://localhost:27017/TIKSN_Framework_IntegrationTests?w=majority"}
};
}
}
public IServiceProvider Services => host.Services;
public void Dispose()
{
host?.Dispose();
}
}
} | mit | C# |
4e86d22a056ddf5b5a391488fe7dd8715bd7ed11 | write unit test for DeleteOrganizationHandlerAsync #1214 (code review changes) | shanecharles/allReady,binaryjanitor/allReady,enderdickerson/allReady,c0g1t8/allReady,bcbeatty/allReady,GProulx/allReady,VishalMadhvani/allReady,BillWagner/allReady,stevejgordon/allReady,mipre100/allReady,GProulx/allReady,HamidMosalla/allReady,mgmccarthy/allReady,forestcheng/allReady,JowenMei/allReady,pranap/allReady,VishalMadhvani/allReady,HamidMosalla/allReady,GProulx/allReady,HamidMosalla/allReady,HamidMosalla/allReady,JowenMei/allReady,enderdickerson/allReady,MisterJames/allReady,chinwobble/allReady,anobleperson/allReady,enderdickerson/allReady,c0g1t8/allReady,forestcheng/allReady,JowenMei/allReady,VishalMadhvani/allReady,arst/allReady,mgmccarthy/allReady,bcbeatty/allReady,arst/allReady,BillWagner/allReady,BillWagner/allReady,chinwobble/allReady,jonatwabash/allReady,dpaquette/allReady,chinwobble/allReady,binaryjanitor/allReady,GProulx/allReady,c0g1t8/allReady,anobleperson/allReady,MisterJames/allReady,arst/allReady,gitChuckD/allReady,colhountech/allReady,HTBox/allReady,chinwobble/allReady,shanecharles/allReady,enderdickerson/allReady,mipre100/allReady,pranap/allReady,bcbeatty/allReady,JowenMei/allReady,binaryjanitor/allReady,MisterJames/allReady,mgmccarthy/allReady,jonatwabash/allReady,colhountech/allReady,pranap/allReady,binaryjanitor/allReady,mgmccarthy/allReady,gitChuckD/allReady,HTBox/allReady,jonatwabash/allReady,mipre100/allReady,BillWagner/allReady,anobleperson/allReady,pranap/allReady,HTBox/allReady,dpaquette/allReady,dpaquette/allReady,bcbeatty/allReady,gitChuckD/allReady,HTBox/allReady,dpaquette/allReady,VishalMadhvani/allReady,shanecharles/allReady,stevejgordon/allReady,colhountech/allReady,stevejgordon/allReady,anobleperson/allReady,forestcheng/allReady,gitChuckD/allReady,arst/allReady,jonatwabash/allReady,mipre100/allReady,MisterJames/allReady,colhountech/allReady,forestcheng/allReady,c0g1t8/allReady,stevejgordon/allReady,shanecharles/allReady | AllReadyApp/Web-App/AllReady.UnitTest/Areas/Admin/Features/Organizations/DeleteOrganisationHandlerTests.cs | AllReadyApp/Web-App/AllReady.UnitTest/Areas/Admin/Features/Organizations/DeleteOrganisationHandlerTests.cs | using AllReady.Areas.Admin.Features.Organizations;
using AllReady.Models;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Features.Organizations
{
public class DeleteOrganizationHandlerAsyncShould : InMemoryContextTest
{
protected override void LoadTestData()
{
Context.Organizations.Add(new Organization { Id = 1, Name = "Org 1" });
Context.Organizations.Add(new Organization { Id = 2, Name = "Org 2" });
Context.SaveChanges();
}
[Fact]
public async Task DeleteOrganizationThatMatchesOrganizationIdOnCommand()
{
var command = new DeleteOrganizationAsync { Id = 1 };
var handler = new DeleteOrganizationHandlerAsync(Context);
await handler.Handle(command);
var data = Context.Organizations.Count(_ => _.Id == 1);
Assert.Equal(0, data);
}
[Fact]
public async Task NotDeleteOrganizationsThatDoNotMatchOrganizationIdOnCommand()
{
var command = new DeleteOrganizationAsync { Id = 999 };
var handler = new DeleteOrganizationHandlerAsync(Context);
await handler.Handle(command);
Assert.Equal(2, Context.Organizations.Count());
}
}
}
| using AllReady.Areas.Admin.Features.Organizations;
using AllReady.Models;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Features.Organizations
{
public class DeleteOrganizationHandlerAsyncTests : InMemoryContextTest
{
protected override void LoadTestData()
{
Context.Organizations.Add(new Organization { Id = 1, Name = "Org 1" });
Context.Organizations.Add(new Organization { Id = 2, Name = "Org 2" });
Context.SaveChanges();
}
[Fact]
public async Task DeleteExistingOrganization()
{
var command = new DeleteOrganizationAsync { Id = 1 };
var handler = new DeleteOrganizationHandlerAsync(Context);
await handler.Handle(command);
var data = Context.Organizations.Count(_ => _.Id == 1);
Assert.Equal(0, data);
}
[Fact]
public async Task DeleteNonExistantOrganization()
{
var command = new DeleteOrganizationAsync { Id = 999 };
var handler = new DeleteOrganizationHandlerAsync(Context);
await handler.Handle(command);
Assert.Equal(2, Context.Organizations.Count());
}
}
}
| mit | C# |
f3b96f8f50c9dde37741578f1e13fce19d9d0ef9 | add fallback to normal note image | smoogipooo/osu,peppy/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu | osu.Game.Rulesets.Mania/Skinning/LegacyHoldNoteTailPiece.cs | osu.Game.Rulesets.Mania/Skinning/LegacyHoldNoteTailPiece.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 osu.Framework.Bindables;
using osu.Framework.Graphics.Textures;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania.Skinning
{
public class LegacyHoldNoteTailPiece : LegacyNotePiece
{
protected override void OnDirectionChanged(ValueChangedEvent<ScrollingDirection> direction)
{
// Invert the direction
base.OnDirectionChanged(direction.NewValue == ScrollingDirection.Up
? new ValueChangedEvent<ScrollingDirection>(ScrollingDirection.Down, ScrollingDirection.Down)
: new ValueChangedEvent<ScrollingDirection>(ScrollingDirection.Up, ScrollingDirection.Up));
}
protected override Texture GetTexture(ISkinSource skin)
{
return GetTextureFromLookup(skin, LegacyManiaSkinConfigurationLookups.HoldNoteTailImage)
?? GetTextureFromLookup(skin, LegacyManiaSkinConfigurationLookups.HoldNoteHeadImage)
?? GetTextureFromLookup(skin, LegacyManiaSkinConfigurationLookups.NoteImage);
}
}
}
| // 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 osu.Framework.Bindables;
using osu.Framework.Graphics.Textures;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania.Skinning
{
public class LegacyHoldNoteTailPiece : LegacyNotePiece
{
protected override void OnDirectionChanged(ValueChangedEvent<ScrollingDirection> direction)
{
// Invert the direction
base.OnDirectionChanged(direction.NewValue == ScrollingDirection.Up
? new ValueChangedEvent<ScrollingDirection>(ScrollingDirection.Down, ScrollingDirection.Down)
: new ValueChangedEvent<ScrollingDirection>(ScrollingDirection.Up, ScrollingDirection.Up));
}
protected override Texture GetTexture(ISkinSource skin)
{
return GetTextureFromLookup(skin, LegacyManiaSkinConfigurationLookups.HoldNoteTailImage)
?? GetTextureFromLookup(skin, LegacyManiaSkinConfigurationLookups.HoldNoteHeadImage);
}
}
}
| mit | C# |
b6edd17242a2f94da3fe03e9c2bf2833b0d6bdec | Fix TeamWin test scene | EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,johnneijzen/osu,EVAST9919/osu,ppy/osu,ppy/osu,2yangk23/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu | osu.Game.Tournament.Tests/Screens/TestSceneTeamWinScreen.cs | osu.Game.Tournament.Tests/Screens/TestSceneTeamWinScreen.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 osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.TeamWin;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneTeamWinScreen : LadderTestScene
{
[Cached]
private readonly LadderInfo ladder = new LadderInfo();
[BackgroundDependencyLoader]
private void load()
{
var match = new TournamentMatch();
match.Team1.Value = Ladder.Teams.FirstOrDefault(t => t.Acronym.Value == "USA");
match.Team2.Value = Ladder.Teams.FirstOrDefault(t => t.Acronym.Value == "JPN");
match.Round.Value = Ladder.Rounds.FirstOrDefault(g => g.Name.Value == "Finals");
match.Completed.Value = true;
ladder.CurrentMatch.Value = match;
Add(new TeamWinScreen
{
FillMode = FillMode.Fit,
FillAspectRatio = 16 / 9f
});
}
}
}
| // 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 osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.TeamWin;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneTeamWinScreen : LadderTestScene
{
[Cached]
private readonly LadderInfo ladder = new LadderInfo();
[BackgroundDependencyLoader]
private void load()
{
var match = new TournamentMatch();
match.Team1.Value = Ladder.Teams.FirstOrDefault(t => t.Acronym.Value == "USA");
match.Team2.Value = Ladder.Teams.FirstOrDefault(t => t.Acronym.Value == "JPN");
match.Round.Value = Ladder.Rounds.FirstOrDefault(g => g.Name.Value == "Finals");
ladder.CurrentMatch.Value = match;
Add(new TeamWinScreen
{
FillMode = FillMode.Fit,
FillAspectRatio = 16 / 9f
});
}
}
}
| mit | C# |
74fa9dba58babe0d70076da50811e4b3f1ba0e9f | Use port for demo application that doesn't need privileges | RailPhase/RailPhase,LukasBoersma/Web2Sharp,RailPhase/RailPhase,LukasBoersma/Web2Sharp,LukasBoersma/RailPhase,LukasBoersma/RailPhase | RailPhase.Demo/Program.cs | RailPhase.Demo/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RailPhase.Demo
{
class Program
{
static void Main(string[] args)
{
// Create a simple web app and serve content on to URLs.
var app = new App();
// Define the URL patterns to respond to incoming requests.
// Any request that does not match one of these patterns will
// be served by app.NotFoundView, which defaults to a simple
// 404 message.
// Easiest way to respond to a request: return a string
app.AddStringView("^/$", (request) => "Hello World");
// More complex response, see below
app.AddStringView("^/info$", InfoView);
// Start listening for HTTP requests. Default port is 8080.
// This method does never return!
app.RunHttpServer("http://localhost:18080/");
// Now you should be able to visit me in your browser on http://localhost:18080/
}
/// <summary>
/// A view that generates a simple request info page
/// </summary>
static string InfoView(RailPhase.Context context)
{
// Get the template for the info page.
var render = Template.FromFile("InfoTemplate.html");
// Pass the HttpRequest as the template context, because we want
// to display information about the request. Normally, we would
// pass some custom object here, containing the information we
// want to display.
return render(null, context);
}
}
public class DemoData
{
public string Heading;
public string Username;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RailPhase.Demo
{
class Program
{
static void Main(string[] args)
{
// Create a simple web app and serve content on to URLs.
var app = new App();
// Define the URL patterns to respond to incoming requests.
// Any request that does not match one of these patterns will
// be served by app.NotFoundView, which defaults to a simple
// 404 message.
// Easiest way to respond to a request: return a string
app.AddStringView("^/$", (request) => "Hello World");
// More complex response, see below
app.AddStringView("^/info$", InfoView);
// Start listening for HTTP requests. Default port is 8080.
// This method does never return!
app.RunHttpServer();
// Now you should be able to visit me in your browser on http://localhost:8080
}
/// <summary>
/// A view that generates a simple request info page
/// </summary>
static string InfoView(RailPhase.Context context)
{
// Get the template for the info page.
var render = Template.FromFile("InfoTemplate.html");
// Pass the HttpRequest as the template context, because we want
// to display information about the request. Normally, we would
// pass some custom object here, containing the information we
// want to display.
return render(null, context);
}
}
public class DemoData
{
public string Heading;
public string Username;
}
}
| mit | C# |
5587efaadd47ac7274cc3e973d70f0c4fdbed33a | Update Python Runtime dll location (#5398) | QuantConnect/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,AlexCatarino/Lean,JKarathiya/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,jameschch/Lean,StefanoRaggi/Lean,QuantConnect/Lean,QuantConnect/Lean,jameschch/Lean,AlexCatarino/Lean,JKarathiya/Lean,jameschch/Lean,StefanoRaggi/Lean,jameschch/Lean,StefanoRaggi/Lean,jameschch/Lean,JKarathiya/Lean,JKarathiya/Lean,QuantConnect/Lean | Research/QuantConnect.csx | Research/QuantConnect.csx | #r "Python.Runtime.dll"
#r "QuantConnect.Algorithm.dll"
#r "QuantConnect.Algorithm.Framework.dll"
#r "QuantConnect.Common.dll"
#r "QuantConnect.Indicators.dll"
#r "QuantConnect.Research.dll"
#r "NodaTime.dll"
#r "Accord.dll"
#r "Accord.Fuzzy.dll"
#r "Accord.Math.Core.dll"
#r "Accord.Math.dll"
#r "MathNet.Numerics.dll"
#r "Newtonsoft.Json.dll"
#r "QuantConnect.AlgorithmFactory.dll"
#r "QuantConnect.Logging.dll"
#r "QuantConnect.Messaging.dll"
#r "QuantConnect.Configuration.dll"
#r "QuantConnect.Lean.Engine.dll"
#r "QuantConnect.Algorithm.CSharp.dll"
#r "QuantConnect.Api.dll"
// Note: #r directives must be in the beggining of the file
/*
* 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.
*/
/*
* This C# Script File (.csx) can be loaded in a notebook (ipynb file)
* in order to reference QuantConnect assemblies
* https://github.com/scriptcs/scriptcs/wiki/Writing-a-script#referencing-assemblies
*
* Usage:
* #load "QuantConnect.csx"
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using QuantConnect;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Api;
using QuantConnect.Parameters;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Util;
using QuantConnect.Interfaces;
using QuantConnect.Indicators;
using QuantConnect.Research;
using QuantConnect.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Custom;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Forex;
using QuantConnect.Securities.Interfaces;
using QuantConnect.Configuration;
// Loads up a connection to our API for use in the research environment
Api api = new Api();
api.Initialize(Config.GetInt("job-user-id", 1),
Config.Get("api-access-token", "default"),
Config.Get("data-folder")); | #r "pythonnet/Python.Runtime.dll"
#r "QuantConnect.Algorithm.dll"
#r "QuantConnect.Algorithm.Framework.dll"
#r "QuantConnect.Common.dll"
#r "QuantConnect.Indicators.dll"
#r "QuantConnect.Research.dll"
#r "NodaTime.dll"
#r "Accord.dll"
#r "Accord.Fuzzy.dll"
#r "Accord.Math.Core.dll"
#r "Accord.Math.dll"
#r "MathNet.Numerics.dll"
#r "Newtonsoft.Json.dll"
#r "QuantConnect.AlgorithmFactory.dll"
#r "QuantConnect.Logging.dll"
#r "QuantConnect.Messaging.dll"
#r "QuantConnect.Configuration.dll"
#r "QuantConnect.Lean.Engine.dll"
#r "QuantConnect.Algorithm.CSharp.dll"
#r "QuantConnect.Api.dll"
// Note: #r directives must be in the beggining of the file
/*
* 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.
*/
/*
* This C# Script File (.csx) can be loaded in a notebook (ipynb file)
* in order to reference QuantConnect assemblies
* https://github.com/scriptcs/scriptcs/wiki/Writing-a-script#referencing-assemblies
*
* Usage:
* #load "QuantConnect.csx"
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using QuantConnect;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Api;
using QuantConnect.Parameters;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Util;
using QuantConnect.Interfaces;
using QuantConnect.Indicators;
using QuantConnect.Research;
using QuantConnect.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Custom;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Forex;
using QuantConnect.Securities.Interfaces;
using QuantConnect.Configuration;
// Loads up a connection to our API for use in the research environment
Api api = new Api();
api.Initialize(Config.GetInt("job-user-id", 1),
Config.Get("api-access-token", "default"),
Config.Get("data-folder")); | apache-2.0 | C# |
6a2a3e10d5c1bac248b55916e15e64bb57ee5749 | Fix formatting exception when script compilation fails with certain error messages | eatdrinksleepcode/casper,eatdrinksleepcode/casper | Core/CasperException.cs | Core/CasperException.cs | using System;
namespace Casper {
public class CasperException : Exception {
public const int EXIT_CODE_COMPILATION_ERROR = 1;
public const int EXIT_CODE_MISSING_TASK = 2;
public const int EXIT_CODE_CONFIGURATION_ERROR = 3;
public const int EXIT_CODE_TASK_FAILED = 4;
public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255;
private readonly int exitCode;
public CasperException(int exitCode, string message)
: base(message) {
this.exitCode = exitCode;
}
public CasperException(int exitCode, string message, params object[] args)
: this(exitCode, string.Format(message, args)) {
}
public CasperException(int exitCode, Exception innerException)
: base(innerException.Message, innerException) {
this.exitCode = exitCode;
}
public int ExitCode {
get {
return exitCode;
}
}
}
}
| using System;
namespace Casper {
public class CasperException : Exception {
public const int EXIT_CODE_COMPILATION_ERROR = 1;
public const int EXIT_CODE_MISSING_TASK = 2;
public const int EXIT_CODE_CONFIGURATION_ERROR = 3;
public const int EXIT_CODE_TASK_FAILED = 4;
public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255;
private readonly int exitCode;
public CasperException(int exitCode, string message, params object[] args)
: base(string.Format(message, args)) {
this.exitCode = exitCode;
}
public CasperException(int exitCode, Exception innerException)
: base(innerException.Message, innerException) {
this.exitCode = exitCode;
}
public int ExitCode {
get {
return exitCode;
}
}
}
}
| mit | C# |
b05a3bf0ed21a6fd25807f34c69987ead0cee9b0 | Make the client request the RavenDB server version. If we don't do this the client doesn't appear to raise an exception in the case of a dead server so the health check will still return healthy. | lynxx131/dotnet.microservice | src/Dotnet.Microservice/Health/Checks/RavenDbHealthCheck.cs | src/Dotnet.Microservice/Health/Checks/RavenDbHealthCheck.cs | using Raven.Abstractions.Data;
using System;
namespace Dotnet.Microservice.Health.Checks
{
public class RavenDbHealthCheck
{
public static HealthResponse CheckHealth(string connectionString)
{
try
{
ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString);
parser.Parse();
var store = new Raven.Client.Document.DocumentStore
{
Url = parser.ConnectionStringOptions.Url,
DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase
};
store.Initialize();
// Client doesn't seem to throw an exception until we try to do something so let's just do something simple and get the build number of the server.
var build = store.DatabaseCommands.GlobalAdmin.GetBuildNumber();
// Dispose the store object
store.Dispose();
return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase, serverBuild = build.BuildVersion });
}
catch (Exception ex)
{
return HealthResponse.Unhealthy(ex);
}
}
}
}
| using Raven.Abstractions.Data;
using System;
namespace Dotnet.Microservice.Health.Checks
{
public class RavenDbHealthCheck
{
public static HealthResponse CheckHealth(string connectionString)
{
try
{
ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString);
parser.Parse();
var store = new Raven.Client.Document.DocumentStore
{
Url = parser.ConnectionStringOptions.Url,
DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase
};
store.Initialize();
return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase });
}
catch (Exception ex)
{
return HealthResponse.Unhealthy(ex);
}
}
}
}
| isc | C# |
afdf1443a930941711c316dd7713f4e7d3b1ca2b | Correct code comment (#13993) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Mvc/Mvc.Abstractions/src/ModelBinding/IValueProvider.cs | src/Mvc/Mvc.Abstractions/src/ModelBinding/IValueProvider.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
/// <summary>
/// Defines the methods that are required for a value provider.
/// </summary>
public interface IValueProvider
{
/// <summary>
/// Determines whether the collection contains the specified prefix.
/// </summary>
/// <param name="prefix">The prefix to search for.</param>
/// <returns>true if the collection contains the specified prefix; otherwise, false.</returns>
bool ContainsPrefix(string prefix);
/// <summary>
/// Retrieves a value object using the specified key.
/// </summary>
/// <param name="key">The key of the value object to retrieve.</param>
/// <returns>The value object for the specified key. If the exact key is not found, <see cref="ValueProviderResult.None" />.</returns>
ValueProviderResult GetValue(string key);
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
/// <summary>
/// Defines the methods that are required for a value provider.
/// </summary>
public interface IValueProvider
{
/// <summary>
/// Determines whether the collection contains the specified prefix.
/// </summary>
/// <param name="prefix">The prefix to search for.</param>
/// <returns>true if the collection contains the specified prefix; otherwise, false.</returns>
bool ContainsPrefix(string prefix);
/// <summary>
/// Retrieves a value object using the specified key.
/// </summary>
/// <param name="key">The key of the value object to retrieve.</param>
/// <returns>The value object for the specified key. If the exact key is not found, null.</returns>
ValueProviderResult GetValue(string key);
}
}
| apache-2.0 | C# |
0be8ee11749741726f00ae996137fc82e267055c | Fix ResponseMessageTransformer (BodyAsJson) | WireMock-Net/WireMock.Net,StefH/WireMock.Net,StefH/WireMock.Net | src/WireMock.Net/Transformers/ResponseMessageTransformer.cs | src/WireMock.Net/Transformers/ResponseMessageTransformer.cs | using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet;
using Newtonsoft.Json;
using WireMock.Util;
namespace WireMock.Transformers
{
internal static class ResponseMessageTransformer
{
public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
{
bool bodyIsJson = original.BodyAsJson != null;
var responseMessage = new ResponseMessage { StatusCode = original.StatusCode };
if (!bodyIsJson)
{
responseMessage.BodyOriginal = original.Body;
}
var template = new { request = requestMessage };
// Body
var templateBody = Handlebars.Compile(bodyIsJson ? JsonConvert.SerializeObject(original.BodyAsJson) : original.Body);
if (!bodyIsJson)
{
responseMessage.Body = templateBody(template);
}
else
{
responseMessage.BodyAsJson = JsonConvert.DeserializeObject(templateBody(template));
}
// Headers
var newHeaders = new Dictionary<string, WireMockList<string>>();
foreach (var header in original.Headers)
{
var templateHeaderKey = Handlebars.Compile(header.Key);
var templateHeaderValues = header.Value
.Select(Handlebars.Compile)
.Select(func => func(template))
.ToArray();
newHeaders.Add(templateHeaderKey(template), new WireMockList<string>(templateHeaderValues));
}
responseMessage.Headers = newHeaders;
return responseMessage;
}
}
} | using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet;
using WireMock.Util;
namespace WireMock.Transformers
{
internal static class ResponseMessageTransformer
{
public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
{
var responseMessage = new ResponseMessage { StatusCode = original.StatusCode, BodyOriginal = original.Body };
var template = new { request = requestMessage };
// Body
var templateBody = Handlebars.Compile(original.Body);
responseMessage.Body = templateBody(template);
// Headers
var newHeaders = new Dictionary<string, WireMockList<string>>();
foreach (var header in original.Headers)
{
var templateHeaderKey = Handlebars.Compile(header.Key);
var templateHeaderValues = header.Value
.Select(Handlebars.Compile)
.Select(func => func(template))
.ToArray();
newHeaders.Add(templateHeaderKey(template), new WireMockList<string>(templateHeaderValues));
}
responseMessage.Headers = newHeaders;
return responseMessage;
}
}
} | apache-2.0 | C# |
a09ab7bd941c1da9c916bacdb7b78a62615ffe22 | Update LegendaryDroppedPopup.cs | prrovoss/THUD | plugins/Prrovoss/LegendaryDroppedPopup.cs | plugins/Prrovoss/LegendaryDroppedPopup.cs | using Turbo.Plugins.Default;
namespace Turbo.Plugins.Prrovoss
{
public class LegendaryDroppedPopup : BasePlugin, ILootGeneratedHandler
{
public void OnLootGenerated(IItem item, bool gambled)
{
if (item.Quality >= ItemQuality.Legendary)
Hud.RunOnPlugin<PopupNotifications>(plugin =>
{
plugin.Show(item.SnoItem.NameLocalized + (item.AncientRank == 1 ? " (A)" : (item.AncientRank == 2 ? " (P)" : "")) , "Legendary dropped", 10000, "Hurray");
});
}
public LegendaryDroppedPopup()
{
Enabled = true;
}
}
}
| using Turbo.Plugins.Default;
namespace Turbo.Plugins.Prrovoss
{
public class LegendaryDroppedPopup : BasePlugin, ILootGeneratedHandler
{
public void OnLootGenerated(IItem item, bool gambled)
{
if (item.Quality >= ItemQuality.Legendary)
Hud.RunOnPlugin<PopupNotifications>(plugin =>
{
plugin.Show(item.SnoItem.NameLocalized + (item.AncientRank == 1 ? " (A)" : "") + (item.AncientRank == 2 ? " (P)" : ""), "Legendary dropped", 10000, "Hurray");
});
}
public LegendaryDroppedPopup()
{
Enabled = true;
}
}
}
| mit | C# |
dded5e5bcf2527aa10438ff908a4ab267a7d9a2a | Update AlexanderKoehler.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/AlexanderKoehler.cs | src/Firehose.Web/Authors/AlexanderKoehler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AlexanderKoehler : IAmACommunityMember
{
public string FirstName => "Alexander";
public string LastName => "Koehler";
public string ShortBioOrTagLine => "father,system engineer, automation guy, powershell enthusiast";
public string StateOrRegion => "Mengen, Germany";
public string EmailAddress => "planetpowershell@it-koehler.com";
public string TwitterHandle => "ACharburner";
public string GravatarHash => "bc09e87a59be038b93da1e03079aa053";
public string GitHubHandle => "blog-it-koehler-com";
public GeoPosition Position => new GeoPosition(48.03849438437253, 9.326946932715074);
public Uri WebSite => new Uri("https://blog.it-koehler.com/en");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.it-koehler.com/rss"); } }
}
}
| public class AlexanderKoehler : IAmACommunityMember
{
public string FirstName => "Alexander";
public string LastName => "Koehler";
public string ShortBioOrTagLine => "father,system engineer, automation guy, powershell enthusiast";
public string StateOrRegion => "Mengen, Germany";
public string EmailAddress => "planetpowershell@it-koehler.com";
public string TwitterHandle => "ACharburner";
public string GravatarHash => "bc09e87a59be038b93da1e03079aa053";
public string GitHubHandle => "blog-it-koehler-com";
public GeoPosition Position => new GeoPosition(48.03849438437253, 9.326946932715074);
public Uri WebSite => new Uri("https://blog.it-koehler.com/en");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.it-koehler.com/rss"); } }
} | mit | C# |
763c8194ff4fc250ef5829d03b57500ce053ac97 | return null instead of exception | Simocracy/CLSim | CLSim/GUI/Converter.cs | CLSim/GUI/Converter.cs | using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Simocracy.CLSim.GUI
{
/// <summary>
/// Converter for Window Title
/// </summary>
public class TitleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
String subtitle1 = values[0].ToString();
String subtitle2 = values[1].ToString();
return $"{subtitle1} - {subtitle2}";
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
/// <summary>
/// Converts the given text into a visibility for notes in empty text boxes
/// </summary>
/// <seealso cref="https://code.msdn.microsoft.com/windowsapps/How-to-add-a-hint-text-to-ed66a3c6"/>
public class TextInputToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Always test MultiValueConverter inputs for non-null
// (to avoid crash bugs for views in the designer)
if(values[0] is bool && values[1] is bool)
{
bool hasText = !(bool)values[0];
bool hasFocus = (bool)values[1];
if(hasFocus || hasText)
return Visibility.Collapsed;
}
return Visibility.Visible;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
/// <summary>
/// Converts an expanded property into bool
/// </summary>
public class ExpanderToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == parameter;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if(System.Convert.ToBoolean(value))
return parameter;
return null;
}
}
}
| using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Simocracy.CLSim.GUI
{
/// <summary>
/// Converter for Window Title
/// </summary>
public class TitleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
String subtitle1 = values[0].ToString();
String subtitle2 = values[1].ToString();
return $"{subtitle1} - {subtitle2}";
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
/// <summary>
/// Converts the given text into a visibility for notes in empty text boxes
/// </summary>
/// <seealso cref="https://code.msdn.microsoft.com/windowsapps/How-to-add-a-hint-text-to-ed66a3c6"/>
public class TextInputToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Always test MultiValueConverter inputs for non-null
// (to avoid crash bugs for views in the designer)
if(values[0] is bool && values[1] is bool)
{
bool hasText = !(bool)values[0];
bool hasFocus = (bool)values[1];
if(hasFocus || hasText)
return Visibility.Collapsed;
}
return Visibility.Visible;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Converts an expanded property into bool
/// </summary>
public class ExpanderToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == parameter;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if(System.Convert.ToBoolean(value))
return parameter;
return null;
}
}
}
| mit | C# |
c9ab3ce2354e06662eaf475c43c5564a817f929d | Make .net version reporting more detailed | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/Utils/DotNetVersionFinder.cs | src/SyncTrayzor/Utils/DotNetVersionFinder.cs | using Microsoft.Win32;
using System;
namespace SyncTrayzor.Utils
{
public static class DotNetVersionFinder
{
// See https://msdn.microsoft.com/en-us/library/hh925568.aspx#net_d
public static string FindDotNetVersion()
{
try
{
using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
{
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
return $"{CheckFor45DotVersion(releaseKey)} ({releaseKey})";
}
}
catch (Exception e)
{
return $"Unknown ({e.Message})";
}
}
private static string CheckFor45DotVersion(int releaseKey)
{
if (releaseKey == 394271)
{
return "4.6.1 on all other Windows OS versions";
}
if (releaseKey == 394254)
{
return "4.6.1 on Windows 10";
}
if (releaseKey == 393297)
{
return "4.6 on all other Windows OS versions";
}
if (releaseKey == 393295)
{
return "4.6 or later on Windows 10";
}
if ((releaseKey >= 379893))
{
return "4.5.2 or later";
}
if ((releaseKey >= 378675))
{
return "4.5.1 or later";
}
if ((releaseKey >= 378389))
{
return "4.5 or later";
}
// This line should never execute. A non-null release key should mean
// that 4.5 or later is installed.
return "No 4.5 or later version detected";
}
}
}
| using Microsoft.Win32;
using System;
namespace SyncTrayzor.Utils
{
public static class DotNetVersionFinder
{
// See https://msdn.microsoft.com/en-us/library/hh925568.aspx#net_d
public static string FindDotNetVersion()
{
try
{
using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
{
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
return CheckFor45DotVersion(releaseKey);
}
}
catch
{
return "Unknown";
}
}
private static string CheckFor45DotVersion(int releaseKey)
{
if (releaseKey >= 393295)
{
return "4.6 or later";
}
if ((releaseKey >= 379893))
{
return "4.5.2 or later";
}
if ((releaseKey >= 378675))
{
return "4.5.1 or later";
}
if ((releaseKey >= 378389))
{
return "4.5 or later";
}
// This line should never execute. A non-null release key should mean
// that 4.5 or later is installed.
return "No 4.5 or later version detected";
}
}
}
| mit | C# |
12db4d7b40c5f115946da7560bde886e31759900 | remove unused states | judwhite/NsqSharp | NsqSharp/Core/State.cs | NsqSharp/Core/State.cs | namespace NsqSharp.Core
{
// https://github.com/bitly/go-nsq/blob/master/states.go
/// <summary>
/// States
/// </summary>
public enum State
{
/// <summary>Init</summary>
Init = 0,
/// <summary>Disconnected</summary>
Disconnected = 1,
/// <summary>Connected</summary>
Connected = 2,
}
}
| namespace NsqSharp.Core
{
// https://github.com/bitly/go-nsq/blob/master/states.go
/// <summary>
/// States
/// </summary>
public enum State
{
/// <summary>Init</summary>
Init = 0,
/// <summary>Disconnected</summary>
Disconnected = 1,
/// <summary>Connected</summary>
Connected = 2,
/// <summary>Subscribed</summary>
Subscribed = 3,
/// <summary>
/// Closing means CLOSE has started...
/// (responses are ok, but no new messages will be sent)
/// </summary>
Closing = 4,
}
}
| mit | C# |
ebbc8298917db15105130ea2b12e1dab67173a88 | disable HardwareAccelerated | peppy/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu-new | osu.Android/OsuGameActivity.cs | osu.Android/OsuGameActivity.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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid();
protected override void OnCreate(Bundle savedInstanceState)
{
// The default current directory on android is '/'.
// On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage.
// In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory.
System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
| // 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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = true)]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid();
protected override void OnCreate(Bundle savedInstanceState)
{
// The default current directory on android is '/'.
// On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage.
// In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory.
System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
| mit | C# |
2f663622ccaaba1945ea424a0fb19d64ae1c4e33 | Fix CI inspections | NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,ZLima12/osu,johnneijzen/osu,ZLima12/osu,2yangk23/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu | osu.Game/Users/UserActivity.cs | osu.Game/Users/UserActivity.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 osu.Game.Beatmaps;
using osu.Game.Graphics;
using osuTK.Graphics;
namespace osu.Game.Users
{
public abstract class UserActivity
{
public abstract string Status { get; }
public virtual Color4 GetAppropriateColour(OsuColour colours) => colours.GreenDarker;
public class UserActivityModding : UserActivity
{
public override string Status => "Modding a map";
public override Color4 GetAppropriateColour(OsuColour colours) => colours.PurpleDark;
}
public class UserActivityChoosingBeatmap : UserActivity
{
public override string Status => "Choosing a beatmap";
}
public class UserActivityMultiplayerGame : UserActivity
{
public override string Status => "Multiplaying";
}
public class UserActivityEditing : UserActivity
{
public UserActivityEditing(BeatmapInfo info)
{
Beatmap = info;
}
public override string Status => @"Editing a beatmap";
public BeatmapInfo Beatmap { get; }
}
public class UserActivitySoloGame : UserActivity
{
public UserActivitySoloGame(BeatmapInfo info, Rulesets.RulesetInfo ruleset)
{
Beatmap = info;
Ruleset = ruleset;
}
public override string Status => @"Solo Game";
public BeatmapInfo Beatmap { get; }
public Rulesets.RulesetInfo Ruleset { get; }
}
public class UserActivitySpectating : UserActivity
{
public override string Status => @"Spectating a game";
}
public class UserActivityInLobby : UserActivity
{
public override string Status => @"in Multiplayer Lobby";
}
}
}
| // 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 osu.Game.Beatmaps;
using osu.Game.Graphics;
using osuTK.Graphics;
namespace osu.Game.Users
{
public abstract class UserActivity
{
public abstract string Status { get; }
public virtual Color4 GetAppropriateColour(OsuColour colours) => colours.GreenDarker;
public class UserActivityModding : UserActivity
{
public override string Status => "Modding a map";
public override Color4 GetAppropriateColour(OsuColour colours) => colours.PurpleDark;
}
public class UserActivityChoosingBeatmap : UserActivity
{
public override string Status => "Choosing a beatmap";
}
public class UserActivityMultiplayerGame : UserActivity
{
public override string Status => "Multiplaying";
}
public class UserActivityEditing : UserActivity
{
public UserActivityEditing(BeatmapInfo info)
{
Beatmap = info;
}
public override string Status => @"Editing a beatmap";
public BeatmapInfo Beatmap { get; }
}
public class UserActivitySoloGame : UserActivity
{
public UserActivitySoloGame(BeatmapInfo info, Rulesets.RulesetInfo ruleset)
{
Beatmap = info;
Ruleset = ruleset;
}
public override string Status => @"Solo Game";
public BeatmapInfo Beatmap { get; }
public Rulesets.RulesetInfo Ruleset { get; }
}
public class UserActivitySpectating : UserActivity
{
public override string Status => @"Spectating a game";
}
public class UserActivityInLobby : UserActivity
{
public override string Status => @"in Multiplayer Lobby";
}
}
}
| mit | C# |
0ba6b3d465722c77724d51a1351825210885a718 | Update InoadSample.cs | Fody/FodyAddinSamples,Fody/FodyAddinSamples | Samples/InoadSample.cs | Samples/InoadSample.cs | using System;
using System.Diagnostics;
using Ionad;
using Xunit;
public class IonadSample
{
[Fact]
public void Run()
{
DateTimeSubstitute.Current = new DateTime(2000, 1, 1);
var time = DateTime.Now;
Trace.WriteLine(time);
}
[StaticReplacement(typeof(DateTime))]
public static class DateTimeSubstitute
{
public static DateTime Current;
public static DateTime Now => Current;
}
} | using System;
using System.Diagnostics;
using Ionad;
using Xunit;
public class IonadSample
{
[Fact]
public void Run()
{
DateTimeSubstitute.Current = new DateTime(2000, 1, 1);
var time = DateTime.Now;
Debug.WriteLine(time);
}
[StaticReplacement(typeof(DateTime))]
public static class DateTimeSubstitute
{
public static DateTime Current;
public static DateTime Now => Current;
}
} | mit | C# |
660cb7714eea0f1fe8e33952ea1502544ad26713 | Fix argument name param order | graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet | src/GraphQL/Types/InputObjectGraphType.cs | src/GraphQL/Types/InputObjectGraphType.cs | using System;
namespace GraphQL.Types
{
public interface IInputObjectGraphType : IComplexGraphType
{
}
public class InputObjectGraphType : InputObjectGraphType<object>
{
}
public class InputObjectGraphType<TSourceType> : ComplexGraphType<TSourceType>, IInputObjectGraphType
{
public override FieldType AddField(FieldType fieldType)
{
if(fieldType.Type == typeof(ObjectGraphType))
{
throw new ArgumentException("InputObjectGraphType cannot have fields containing a ObjectGraphType.", nameof(fieldType.Type));
}
return base.AddField(fieldType);
}
}
}
| using System;
namespace GraphQL.Types
{
public interface IInputObjectGraphType : IComplexGraphType
{
}
public class InputObjectGraphType : InputObjectGraphType<object>
{
}
public class InputObjectGraphType<TSourceType> : ComplexGraphType<TSourceType>, IInputObjectGraphType
{
public override FieldType AddField(FieldType fieldType)
{
if(fieldType.Type == typeof(ObjectGraphType))
{
throw new ArgumentException(nameof(fieldType.Type),
"InputObjectGraphType cannot have fields containing a ObjectGraphType.");
}
return base.AddField(fieldType);
}
}
}
| mit | C# |
e8c39310746887942cea0aae6d9f71648faaf515 | Apply suggestions from code review | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/ObjectPool/src/IPooledObjectPolicy.cs | src/ObjectPool/src/IPooledObjectPolicy.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.Extensions.ObjectPool
{
/// <summary>
/// Represents a policy for managing pooled objects.
/// </summary>
/// <typeparam name="T">The type of object which is being pooled.</typeparam>
public interface IPooledObjectPolicy<T>
{
/// <summary>
/// Create a <typeparamref name="T"/>.
/// </summary>
/// <returns>The <typeparamref name="T"/> which was created.</returns>
T Create();
/// <summary>
/// Runs some processing when an object was returned to the pool. Can be used to reset the state of an object and indicate if the object should be returned to the pool.
/// </summary>
/// <param name="obj">The object to return to the pool.</param>
/// <returns><see langword="true" /> if the object should be returned to the pool. <see langword="false" /> if it's not possible/desirable for the pool to keep the object.</returns>
bool Return(T obj);
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.Extensions.ObjectPool
{
/// <summary>
/// Represents a policy for managing pooled objects.
/// </summary>
/// <typeparam name="T">The type of object which is being pooled.</typeparam>
public interface IPooledObjectPolicy<T>
{
/// <summary>
/// Create a <typeparamref name="T"/>.
/// </summary>
/// <returns>The <typeparamref name="T"/> which was created.</returns>
T Create();
/// <summary>
/// Runs some processing when an object was returned to the pool. Can be used to reset the state of an object and indicate if the object should be returned to the pool.
/// </summary>
/// <param name="obj">The object to return to the pool.</param>
/// <returns><c>true</c> if the object should be returned to the pool. <c>false</c> if it's not possible/desirable for the pool to keep the object.</returns>
bool Return(T obj);
}
}
| apache-2.0 | C# |
cac2de9d8a3440a294226adef6b925306eddb6e9 | Set version to 1.0.1 | lademone/sendinblue.net | src/SendInBlue/Properties/AssemblyInfo.cs | src/SendInBlue/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("SendInBlue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SendInBlue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("5ab1ead8-3044-48a6-b434-0ff3d8708c4e")]
// 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.1.*")]
[assembly: AssemblyFileVersion("1.0.1")]
| 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("SendInBlue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SendInBlue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("5ab1ead8-3044-48a6-b434-0ff3d8708c4e")]
// 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")]
| apache-2.0 | C# |
b2681df25f7482d87c0ab039d4cce853605fe288 | add comment | xbehave/xbehave.net,mvalipour/xbehave.net,modulexcite/xbehave.net,mvalipour/xbehave.net,modulexcite/xbehave.net,adamralph/xbehave.net,hitesh97/xbehave.net,hitesh97/xbehave.net | src/Xbehave/Internal/ActionTestCommand.cs | src/Xbehave/Internal/ActionTestCommand.cs | // <copyright file="ActionTestCommand.cs" company="Adam Ralph">
// Copyright (c) Adam Ralph. All rights reserved.
// </copyright>
namespace Xbehave.Internal
{
using System;
using System.Diagnostics.CodeAnalysis;
using Xunit.Sdk;
internal class ActionTestCommand : TestCommand
{
private readonly Action action;
public ActionTestCommand(IMethodInfo method, string name, int timeout, Action action)
: base(method, name, timeout)
{
this.action = action;
}
// TODO: address DoNotCatchGeneralExceptionTypes - it seems like this is being done so that the test runner doesn't stop and continues to run teardowns
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Part of the original SubSpec code - will be addressed.")]
public override MethodResult Execute(object testClass)
{
try
{
this.action();
}
catch (Exception ex)
{
return new FailedResult(testMethod, ex, DisplayName);
}
return new PassedResult(testMethod, DisplayName);
}
}
} | // <copyright file="ActionTestCommand.cs" company="Adam Ralph">
// Copyright (c) Adam Ralph. All rights reserved.
// </copyright>
namespace Xbehave.Internal
{
using System;
using System.Diagnostics.CodeAnalysis;
using Xunit.Sdk;
internal class ActionTestCommand : TestCommand
{
private readonly Action action;
public ActionTestCommand(IMethodInfo method, string name, int timeout, Action action)
: base(method, name, timeout)
{
this.action = action;
}
// TODO: address DoNotCatchGeneralExceptionTypes
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Part of the original SubSpec code - will be addressed.")]
public override MethodResult Execute(object testClass)
{
try
{
this.action();
}
catch (Exception ex)
{
return new FailedResult(testMethod, ex, DisplayName);
}
return new PassedResult(testMethod, DisplayName);
}
}
} | mit | C# |
d34c021346f2c1a7263d84d44437c92016f46e06 | allow non empty folders | yaronthurm/Backy | BackyUI/UIUtils.cs | BackyUI/UIUtils.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Backy
{
internal static class UIUtils
{
public static void ScrollToBottom(Control control)
{
SendMessage(control.Handle, WmVscroll, SbBottom, 0x0);
}
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr window, int message, int wparam, int lparam);
private const int SbBottom = 0x7;
private const int WmVscroll = 0x115;
public static string ChooseDirectoryConditionaly(FolderBrowserDialog folderDialog, Func<string, bool> condition, string errorMessage)
{
string ret = "";
while (true)
{
folderDialog.SelectedPath = ret;
var result = folderDialog.ShowDialog();
if (result == DialogResult.OK)
{
ret = folderDialog.SelectedPath;
if (condition(ret))
return ret;
else
MessageBox.Show(errorMessage);
}
else
{
return null;
}
}
}
public static string ChooseAnyFolder()
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowNewFolderButton = true;
var ret = ChooseDirectoryConditionaly(dialog, x => true, "");
return ret;
}
public static string ChooseEmptyFolder()
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowNewFolderButton = true;
var ret = ChooseDirectoryConditionaly(dialog, x => !Directory.GetDirectories(x).Any() && !Directory.GetFiles(x).Any(), "Please choose an empty directory");
return ret;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Backy
{
internal static class UIUtils
{
public static void ScrollToBottom(Control control)
{
SendMessage(control.Handle, WmVscroll, SbBottom, 0x0);
}
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr window, int message, int wparam, int lparam);
private const int SbBottom = 0x7;
private const int WmVscroll = 0x115;
public static string ChooseDirectoryConditionaly(FolderBrowserDialog folderDialog, Func<string, bool> condition, string errorMessage)
{
string ret = "";
while (true)
{
folderDialog.SelectedPath = ret;
var result = folderDialog.ShowDialog();
if (result == DialogResult.OK)
{
ret = folderDialog.SelectedPath;
if (condition(ret))
return ret;
else
MessageBox.Show(errorMessage);
}
else
{
return null;
}
}
}
public static string ChooseEmptyFolder()
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowNewFolderButton = true;
var ret = ChooseDirectoryConditionaly(dialog, x => !Directory.GetDirectories(x).Any() && !Directory.GetFiles(x).Any(), "Please choose an empty directory");
return ret;
}
}
}
| mit | C# |
54440d1211cd96d7a0176e5965a08a3cc3cc7756 | Add it | jogibear9988/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp,sta/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp | websocket-sharp/Net/QueryStringCollection.cs | websocket-sharp/Net/QueryStringCollection.cs | #region License
/*
* QueryStringCollection.cs
*
* This code is derived from System.Net.HttpUtility.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Patrik Torstensson <Patrik.Torstensson@labs2.com>
* - Wictor Wilén (decode/encode functions) <wictor@ibizkit.se>
* - Tim Coleman <tim@timcoleman.com>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Text;
namespace WebSocketSharp.Net
{
internal sealed class QueryStringCollection : NameValueCollection
{
public static QueryStringCollection Parse (string query, Encoding encoding)
{
var ret = new QueryStringCollection ();
if (query == null)
return ret;
var len = query.Length;
if (len == 0)
return ret;
if (len == 1 && query[0] == '?')
return ret;
if (query[0] == '?')
query = query.Substring (1);
if (encoding == null)
encoding = Encoding.UTF8;
var components = query.Split ('&');
foreach (var component in components) {
var i = component.IndexOf ('=');
if (i < 0) {
ret.Add (null, HttpUtility.UrlDecode (component, encoding));
continue;
}
var name = HttpUtility.UrlDecode (component.Substring (0, i), encoding);
var val = component.Length > i + 1
? HttpUtility.UrlDecode (component.Substring (i + 1), encoding)
: String.Empty;
ret.Add (name, val);
}
return ret;
}
public override string ToString ()
{
if (Count == 0)
return String.Empty;
var buff = new StringBuilder ();
foreach (var key in AllKeys)
buff.AppendFormat ("{0}={1}&", key, this[key]);
if (buff.Length > 0)
buff.Length--;
return buff.ToString ();
}
}
}
| #region License
/*
* QueryStringCollection.cs
*
* This code is derived from System.Net.HttpUtility.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Patrik Torstensson <Patrik.Torstensson@labs2.com>
* - Wictor Wilén (decode/encode functions) <wictor@ibizkit.se>
* - Tim Coleman <tim@timcoleman.com>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Text;
namespace WebSocketSharp.Net
{
internal sealed class QueryStringCollection : NameValueCollection
{
public override string ToString ()
{
if (Count == 0)
return String.Empty;
var buff = new StringBuilder ();
foreach (var key in AllKeys)
buff.AppendFormat ("{0}={1}&", key, this[key]);
if (buff.Length > 0)
buff.Length--;
return buff.ToString ();
}
}
}
| mit | C# |
6cad2257793e884a6776312697e648eadedec443 | Switch to new backup email recipient | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Jobs/SqliteBackupJob.cs | Battery-Commander.Web/Jobs/SqliteBackupJob.cs | using FluentEmail.Core;
using FluentScheduler;
using System;
namespace BatteryCommander.Web.Jobs
{
public class SqliteBackupJob : IJob
{
private const String Recipient = "Backups@RedLeg.app";
private readonly IFluentEmail emailSvc;
public SqliteBackupJob(IFluentEmail emailSvc)
{
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
emailSvc
.To(Recipient)
.Subject("Nightly Db Backup")
.Body("Please find the nightly database backup attached.")
.Attach(new FluentEmail.Core.Models.Attachment
{
ContentType = "application/octet-stream",
Filename = "Data.db",
Data = System.IO.File.OpenRead("Data.db")
})
.Send();
}
}
}
| using FluentEmail.Core;
using FluentScheduler;
using System;
namespace BatteryCommander.Web.Jobs
{
public class SqliteBackupJob : IJob
{
private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable
private readonly IFluentEmail emailSvc;
public SqliteBackupJob(IFluentEmail emailSvc)
{
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
emailSvc
.To(Recipient)
.Subject("Nightly Db Backup")
.Body("Please find the nightly database backup attached.")
.Attach(new FluentEmail.Core.Models.Attachment
{
ContentType = "application/octet-stream",
Filename = "Data.db",
Data = System.IO.File.OpenRead("Data.db")
})
.Send();
}
}
} | mit | C# |
70b073220eae8247935cf6580e00f5bcfb4cfb8c | Make GitDiffMarginTextViewOptions a static class | laurentkempe/GitDiffMargin,modulexcite/GitDiffMargin | GitDiffMargin/GitDiffMarginTextViewOptions.cs | GitDiffMargin/GitDiffMarginTextViewOptions.cs | using Microsoft.VisualStudio.Text.Editor;
namespace GitDiffMargin
{
public static class GitDiffMarginTextViewOptions
{
public const string DiffMarginName = EditorDiffMargin.MarginNameConst + "/DiffMarginName";
public static readonly EditorOptionKey<bool> DiffMarginId = new EditorOptionKey<bool>(DiffMarginName);
}
}
| using Microsoft.VisualStudio.Text.Editor;
namespace GitDiffMargin
{
public class GitDiffMarginTextViewOptions
{
public const string DiffMarginName = EditorDiffMargin.MarginNameConst + "/DiffMarginName";
public static readonly EditorOptionKey<bool> DiffMarginId = new EditorOptionKey<bool>(DiffMarginName);
}
} | mit | C# |
7b19c414d5c85dc390618afacf2caa5c3643272f | Use port 8080 | demyanenko/hutel,demyanenko/hutel,demyanenko/hutel | server/Program.cs | server/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace server
{
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://*:8080")
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace server
{
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| apache-2.0 | C# |
a22e62e5b88170ff46b3fef838b697bf5ffe4357 | Remove remaining TODO comment | smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework | osu.Framework/Input/Events/MidiDownEvent.cs | osu.Framework/Input/Events/MidiDownEvent.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 JetBrains.Annotations;
using osu.Framework.Input.States;
namespace osu.Framework.Input.Events
{
public class MidiDownEvent : MidiEvent
{
public MidiDownEvent([NotNull] InputState state, MidiKey key, byte velocity)
: base(state, key, velocity)
{
}
}
}
| // 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 JetBrains.Annotations;
using osu.Framework.Input.States;
namespace osu.Framework.Input.Events
{
public class MidiDownEvent : MidiEvent
{
// TODO: velocity
public MidiDownEvent([NotNull] InputState state, MidiKey key, byte velocity)
: base(state, key, velocity)
{
}
}
}
| mit | C# |
8f2b0e58b33b8afee0e7c890ac2f8fb6fb9226cd | Revert "Resolved CA 2208" | kschecht/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk,Rolstenhouse/sarif-sdk,Rolstenhouse/sarif-sdk,Rolstenhouse/sarif-sdk,kschecht/sarif-sdk,Rolstenhouse/sarif-sdk,Rolstenhouse/sarif-sdk,kschecht/sarif-sdk,kschecht/sarif-sdk,Rolstenhouse/sarif-sdk,Rolstenhouse/sarif-sdk | src/Sarif/PerLanguageOption.cs | src/Sarif/PerLanguageOption.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.CodeAnalysis.Sarif
{
/// <summary>
/// An option that can be specified once per language.
/// </summary>
/// <typeparam name="T"></typeparam>
public class PerLanguageOption<T> : IOption
{
/// <summary>
/// A description of this specificoption.
/// </summary>
public string Description { get; }
/// <summary>
/// Feature this option is associated with.
/// </summary>
public string Feature { get; }
/// <summary>
/// The name of the option.
/// </summary>
public string Name { get; }
/// <summary>
/// The type of the option value.
/// </summary>
public Type Type
{
get { return typeof(T); }
}
/// <summary>
/// The default option value.
/// </summary>
public Func<T> DefaultValue { get; }
public PerLanguageOption(string feature, string name, Func<T> defaultValue, string description = null)
{
if (string.IsNullOrWhiteSpace(feature))
{
throw new ArgumentNullException(nameof(feature));
}
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException(nameof(name));
}
this.Feature = feature;
this.Name = name;
this.DefaultValue = defaultValue;
this.Description = description;
}
Type IOption.Type
{
get { return typeof(T); }
}
object IOption.DefaultValue
{
get { return this.DefaultValue(); }
}
bool IOption.IsPerLanguage
{
get { return true; }
}
public override string ToString()
{
return string.Format("{0} - {1}", this.Feature, this.Name);
}
}
} | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.CodeAnalysis.Sarif
{
/// <summary>
/// An option that can be specified once per language.
/// </summary>
/// <typeparam name="T"></typeparam>
public class PerLanguageOption<T> : IOption
{
/// <summary>
/// A description of this specificoption.
/// </summary>
public string Description { get; }
/// <summary>
/// Feature this option is associated with.
/// </summary>
public string Feature { get; }
/// <summary>
/// The name of the option.
/// </summary>
public string Name { get; }
/// <summary>
/// The type of the option value.
/// </summary>
public Type Type
{
get { return typeof(T); }
}
/// <summary>
/// The default option value.
/// </summary>
public Func<T> DefaultValue { get; }
public PerLanguageOption(string feature, string name, Func<T> defaultValue, string description = null)
{
if (string.IsNullOrWhiteSpace(feature))
{
throw new ArgumentNullException(nameof(feature));
}
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException(nameof(name));
}
this.Feature = feature;
this.Name = name;
this.DefaultValue = defaultValue;
this.Description = description;
}
Type IOption.Type
{
get { return typeof(T); }
}
object IOption.DefaultValue
{
get { return this.DefaultValue(); }
}
bool IOption.IsPerLanguage
{
get { return true; }
}
public override string ToString()
{
return string.Format("{0} - {1}", this.Feature, this.Name);
}
}
} | mit | C# |
34274515c875a7bc90d267020ac2d66eea96520c | fix URL | IdentityModel/IdentityModel2,IdentityModel/IdentityModelv2,IdentityModel/IdentityModelv2,IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel | src/IdentityModel/Client/DiscoveryClient.cs | src/IdentityModel/Client/DiscoveryClient.cs | using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace IdentityModel.Client
{
public class DiscoveryClient
{
private readonly HttpClient _client;
public TimeSpan Timeout
{
set
{
_client.Timeout = value;
}
}
public DiscoveryClient(string baseAddress, HttpMessageHandler innerHandler = null)
{
var handler = innerHandler ?? new HttpClientHandler();
// todo: check slashes
var url = baseAddress + OidcConstants.Discovery.DiscoveryEndpoint;
_client = new HttpClient(handler)
{
BaseAddress = new Uri(url)
};
}
public async Task<DiscoveryResponse> GetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var response = await _client.GetAsync("", cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new DiscoveryResponse(json);
}
else
{
return new DiscoveryResponse(response.StatusCode, response.ReasonPhrase);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace IdentityModel.Client
{
public class DiscoveryClient
{
private readonly HttpClient _client;
public TimeSpan Timeout
{
set
{
_client.Timeout = value;
}
}
public DiscoveryClient(string url, HttpMessageHandler innerHandler = null)
{
var handler = innerHandler ?? new HttpClientHandler();
_client = new HttpClient(handler)
{
BaseAddress = new Uri(url)
};
}
public async Task<DiscoveryResponse> GetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var response = await _client.GetAsync("", cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new DiscoveryResponse(json);
}
else
{
return new DiscoveryResponse(response.StatusCode, response.ReasonPhrase);
}
}
}
} | apache-2.0 | C# |
3a290c768c64c7947574934b52fd391062c069d5 | Bump to version 0.1.0 | Kryptos-FR/markdig.wpf,Kryptos-FR/markdig-wpf | src/Markdig.Xaml/Properties/AssemblyInfo.cs | src/Markdig.Xaml/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// 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("Markdig.Xaml")]
[assembly: AssemblyDescription("a XAML port to CommonMark compliant Markdig.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Markdig.Xaml")]
[assembly: AssemblyCopyright("Copyright © Nicolas Musset 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion(Markdig.Xaml.Markdown.Version)]
[assembly: AssemblyFileVersion(Markdig.Xaml.Markdown.Version)]
namespace Markdig.Xaml
{
public static partial class Markdown
{
public const string Version = "0.1.0";
}
}
| using System.Reflection;
using System.Resources;
// 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("Markdig.Xaml")]
[assembly: AssemblyDescription("a XAML port to CommonMark compliant Markdig.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Markdig.Xaml")]
[assembly: AssemblyCopyright("Copyright © Nicolas Musset 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion(Markdig.Xaml.Markdown.Version)]
[assembly: AssemblyFileVersion(Markdig.Xaml.Markdown.Version)]
namespace Markdig.Xaml
{
public static partial class Markdown
{
public const string Version = "0.0.1";
}
}
| mit | C# |
76f3b9e2f3d217c8431768712d3aaf82af7ada69 | Update EnemyAi.cs | danstev/UnityStuff | Scripts/EnemyAi.cs | Scripts/EnemyAi.cs | using UnityEngine;
using System.Collections;
public class EnemyAi : MonoBehaviour {
public float aggroDistance = 10;
public float meleeDistance = 2;
public float attackPower = 10;
public float speed;
private GameObject[] players = new GameObject[8];
private GameObject target;
private Health targetHealthScript;
void Update () {
players = GameObject.FindGameObjectsWithTag("Player");
target = getTarget();
if(Vector3.Distance(transform.position, target.transform.position) < aggroDistance && target != null)
{
transform.LookAt(target.transform);
move();
}
if(Vector3.Distance(transform.position, target.transform.position) < meleeDistance && target != null)
{
transform.LookAt(target.transform);
targetHealthScript = target.GetComponent<Health>();
targetHealthScript.health -= attackPower * Time.deltaTime;
}
}
GameObject getTarget()
{
float enemyDistance;
float enemyDistanceLow = 0;
GameObject current = GameObject.FindGameObjectWithTag("Player");
foreach(GameObject Player in players)
{
enemyDistance = (Vector3.Distance(transform.position, Player.transform.position));
print(enemyDistance);
if(enemyDistance < enemyDistanceLow && enemyDistanceLow != 0)
{
enemyDistanceLow = enemyDistance;
current = Player;
}
}
return current;
}
void move()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, step);
}
}
| using UnityEngine;
using System.Collections;
public class EnemyAi : MonoBehaviour {
public float aggroDistance = 10;
public float meleeDistance = 2;
public int attackPower = 10;
public float speed;
private GameObject[] players = new GameObject[8];
private GameObject target;
void Update () {
players = GameObject.FindGameObjectsWithTag("Player");
target = getTarget();
if(Vector3.Distance(transform.position, target.transform.position) < aggroDistance && target != null)
{
move();
}
if(Vector3.Distance(transform.position, target.transform.position) < meleeDistance && target != null)
{
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(transform.position, target.transform.position, out hit))
{
hit.transform.SendMessage(("ApplyDamage"), attackPower, SendMessageOptions.DontRequireReceiver);
print("1");
}
}
}
GameObject getTarget()
{
float enemyDistance;
float enemyDistanceLow = 0;
GameObject current = GameObject.FindGameObjectWithTag("Player");
foreach(GameObject Player in players)
{
enemyDistance = (Vector3.Distance(transform.position, Player.transform.position));
print(enemyDistance);
if(enemyDistance < enemyDistanceLow && enemyDistanceLow != 0)
{
enemyDistanceLow = enemyDistance;
current = Player;
}
}
return current;
}
void move()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, step);
}
}
| mit | C# |
31c21a9d3603673a8c7ace55a5d2a2d16809213d | Fix version | gigya/microdot | SolutionVersion.cs | SolutionVersion.cs | #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER 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.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("1.14.0.0")]
[assembly: AssemblyFileVersion("1.14.0.0")]
[assembly: AssemblyInformationalVersion("1.14.0.0")]
// 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)]
[assembly: CLSCompliant(false)]
| #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER 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.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("1.14.2.0")]
[assembly: AssemblyFileVersion("1.14.2.0")]
[assembly: AssemblyInformationalVersion("1.14.2.0")]
// 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)]
[assembly: CLSCompliant(false)]
| apache-2.0 | C# |
d26e3d335c10015451e232c85f6d71f5cb84e0a7 | update AssemblyVersion | gigya/microdot | SolutionVersion.cs | SolutionVersion.cs | #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER 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.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("2.0.3.0")]
[assembly: AssemblyFileVersion("2.0.3.0")]
[assembly: AssemblyInformationalVersion("2.0.3.0")]
// 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)]
[assembly: CLSCompliant(false)]
| #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER 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.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("2.0.2.0")]
[assembly: AssemblyFileVersion("2.0.2.0")]
[assembly: AssemblyInformationalVersion("2.0.2.0")]
// 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)]
[assembly: CLSCompliant(false)]
| apache-2.0 | C# |
cc0c407d4e90e57b80e6dc51cc11a906d6dd8b6c | Update Errors.cs | appel1/ExcelDataReader,vassav/ExcelDataReader,ExcelDataReader/ExcelDataReader,vassav/ExcelDataReader | src/ExcelDataReader/Errors.cs | src/ExcelDataReader/Errors.cs | namespace ExcelDataReader
{
internal static class Errors
{
public const string ErrorStreamWorkbookNotFound = "Neither stream 'Workbook' nor 'Book' was found in file.";
public const string ErrorWorkbookIsNotStream = "Workbook directory entry is not a Stream.";
public const string ErrorWorkbookGlobalsInvalidData = "Error reading Workbook Globals - Stream has invalid data.";
public const string ErrorFatBadSector = "Error reading as FAT table : There's no such sector in FAT.";
public const string ErrorFatRead = "Error reading stream from FAT area.";
public const string ErrorHeaderSignature = "Invalid file signature.";
public const string ErrorHeaderOrder = "Invalid byte order specified in header.";
public const string ErrorBiffRecordSize = "Buffer size is less than minimum BIFF record size.";
public const string ErrorBiffIlegalBefore = "BIFF Stream error: Moving before stream start.";
public const string ErrorBiffIlegalAfter = "BIFF Stream error: Moving after stream end.";
public const string ErrorDirectoryEntryArray = "Directory Entry error: Array is too small.";
public const string ErrorCompoundNoOpenXml = "Detected compound document, but not a valid OpenXml file.";
public const string ErrorZipNoOpenXml = "Detected ZIP file, but not a valid OpenXml file.";
public const string ErrorInvalidPassword = "Invalid password.";
}
}
| namespace ExcelDataReader
{
internal static class Errors
{
public const string ErrorStreamWorkbookNotFound = "Neither stream 'Workbook' nor 'Book' was found in file.";
public const string ErrorWorkbookIsNotStream = "Workbook directory entry is not a Stream.";
public const string ErrorWorkbookGlobalsInvalidData = "Error reading Workbook Globals - Stream has invalid data.";
public const string ErrorFatBadSector = "Error reading as FAT table : There's no such sector in FAT.";
public const string ErrorFatRead = "Error reading stream from FAT area.";
public const string ErrorHeaderSignature = "Invalid file signature.";
public const string ErrorHeaderOrder = "Invalid byte order specified in header.";
public const string ErrorBiffRecordSize = "Buffer size is less than minimum BIFF record size.";
public const string ErrorBiffIlegalBefore = "BIFF Stream error: Moving before stream start.";
public const string ErrorBiffIlegalAfter = "BIFF Stream error: Moving after stream end.";
public const string ErrorDirectoryEntryArray = "Directory Entry error: Array is too small.";
public const string ErrorCompoundNoOpenXml = "Detected compound document, but not a valid OpenXml file.";
public const string ErrorZipNoOpenXml = "Detected ZIP file, but but not a valid OpenXml file.";
public const string ErrorInvalidPassword = "Invalid password.";
}
}
| mit | C# |
5a706ecefdcbf071e593cae1b1859bf260d7f730 | Complete RegexPhoneNumbers | Melkiah/GitubExerciseHomework | RegexExercises/MatchPhoneNumbers/MatchPhoneNumbers.cs | RegexExercises/MatchPhoneNumbers/MatchPhoneNumbers.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MatchPhoneNumbers
{
class MatchPhoneNumbers
{
static void Main(string[] args)
{
string regex = @"\+359( |-)2(\1)\d{3}(\1)\d{4}\b";
string input = "+359 2 222 2222,359-2-222-2222, +359/2/222/2222, +359-2 222 2222 +359 2-222-2222, +359-2-222-222, +359-2-222-22222 +359-2-222-2222";
MatchCollection matchedPhonenumbers = Regex.Matches(input, regex);
string[] collection = matchedPhonenumbers.Cast<Match>().Select(x => x.Value.ToString()).ToArray();
Console.WriteLine(String.Join(", ", collection));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MatchPhoneNumbers
{
class MatchPhoneNumbers
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
b2990927492de801bc1116590487f6f98afb4316 | fix menu typo | jonathanantoine/UWP-Anniversary-Quoi-de-neuf,jonathanantoine/UWP-Anniversary-Update---Quoi-de-neuf | UWPWhatsNew/UWPWhatsNew/Views/Shell/ShellViewModel.cs | UWPWhatsNew/UWPWhatsNew/Views/Shell/ShellViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UWPWhatsNew.Common;
using UWPWhatsNew.Views.Shell;
namespace UWPWhatsNew.Views
{
public class ShellViewModel : BindableBase
{
private List<AvailableItem<Type>> _availableSamples;
public List<AvailableItem<Type>> AvailableSamples
{
get { return _availableSamples; }
set { SetProperty(ref _availableSamples, value); }
}
public ShellViewModel()
{
AvailableSamples = new List<AvailableItem<Type>>
{
new AvailableItem<Type>("Animated GIF", typeof(AnimatedGif.AnimatedGifPage),"/Assets/Images/IconGIF.png"),
new AvailableItem<Type>("Connected Apps", typeof(ConnectedApps.ConnectedAppPage),"/Assets/Images/IconConnected.png"),
new AvailableItem<Type>("Connected Apps", typeof(ConnectedApps.ConnectedAppPage),"/Assets/Images/IconSingleProcess.png"),
new AvailableItem<Type>("Connected Apps", typeof(ConnectedApps.ConnectedAppPage),"/Assets/Images/IconInk.png")
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UWPWhatsNew.Common;
using UWPWhatsNew.Views.Shell;
namespace UWPWhatsNew.Views
{
public class ShellViewModel : BindableBase
{
private List<AvailableItem<Type>> _availableSamples;
public List<AvailableItem<Type>> AvailableSamples
{
get { return _availableSamples; }
set { SetProperty(ref _availableSamples, value); }
}
public ShellViewModel()
{
AvailableSamples = new List<AvailableItem<Type>>
{
new AvailableItem<Type>("Animaged GIF", typeof(AnimatedGif.AnimatedGifPage),"/Assets/Images/IconGIF.png"),
new AvailableItem<Type>("Connected Apps", typeof(ConnectedApps.ConnectedAppPage),"/Assets/Images/IconConnected.png"),
new AvailableItem<Type>("Connected Apps", typeof(ConnectedApps.ConnectedAppPage),"/Assets/Images/IconSingleProcess.png"),
new AvailableItem<Type>("Connected Apps", typeof(ConnectedApps.ConnectedAppPage),"/Assets/Images/IconInk.png")
};
}
}
}
| mit | C# |
5d715e191cedd59f7a21271b359ee931db3cc054 | Fix null object error parsing CoinChoose.com data | IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner | MultiMiner.Coinchoose.Api/CoinInformation.cs | MultiMiner.Coinchoose.Api/CoinInformation.cs | using Newtonsoft.Json.Linq;
using System;
namespace MultiMiner.Coinchoose.Api
{
public class CoinInformation
{
public string Symbol { get; set; }
public string Name { get; set; }
public string Algorithm { get; set; }
public int CurrentBlocks { get; set; }
public double Difficulty { get; set; }
public double Reward { get; set; }
public double MinimumBlockTime { get; set; }
public Int64 NetworkHashRate { get; set; }
public double Price { get; set; }
public string Exchange { get; set; }
public double Profitability { get; set; }
public double AdjustedProfitability { get; set; }
public double AverageProfitability { get; set; }
public double AverageHashRate { get; set; }
public void PopulateFromJson(JToken jToken)
{
Symbol = jToken.Value<string>("symbol");
Name = jToken.Value<string>("name");
Algorithm = jToken.Value<string>("algo");
try
{
CurrentBlocks = jToken.Value<int>("currentBlocks");
}
catch (InvalidCastException)
{
//handle System.InvalidCastException: Null object cannot be converted to a value type.
//tried this but didn't work: if (jToken["currentBlocks"] != null)
CurrentBlocks = 0;
}
Difficulty = jToken.Value<double>("difficulty");
Reward = jToken.Value<double>("reward");
try
{
MinimumBlockTime = jToken.Value<double>("minBlockTime"); //this one can be null too (?)
}
catch (InvalidCastException)
{
//handle System.InvalidCastException: Null object cannot be converted to a value type.
//tried this but didn't work: if (jToken["currentBlocks"] != null)
MinimumBlockTime = 0;
}
NetworkHashRate = jToken.Value<Int64>("networkhashrate");
Price = jToken.Value<double>("price");
Exchange = jToken.Value<string>("exchange");
Profitability = jToken.Value<double>("ratio");
AdjustedProfitability = jToken.Value<double>("adjustedratio");
AverageProfitability = jToken.Value<double>("avgProfit");
AverageHashRate = jToken.Value<double>("avgHash");
}
}
}
| using Newtonsoft.Json.Linq;
using System;
namespace MultiMiner.Coinchoose.Api
{
public class CoinInformation
{
public string Symbol { get; set; }
public string Name { get; set; }
public string Algorithm { get; set; }
public int CurrentBlocks { get; set; }
public double Difficulty { get; set; }
public double Reward { get; set; }
public double MinimumBlockTime { get; set; }
public Int64 NetworkHashRate { get; set; }
public double Price { get; set; }
public string Exchange { get; set; }
public double Profitability { get; set; }
public double AdjustedProfitability { get; set; }
public double AverageProfitability { get; set; }
public double AverageHashRate { get; set; }
public void PopulateFromJson(JToken jToken)
{
Symbol = jToken.Value<string>("symbol");
Name = jToken.Value<string>("name");
Algorithm = jToken.Value<string>("algo");
try
{
CurrentBlocks = jToken.Value<int>("currentBlocks");
}
catch (InvalidCastException)
{
//handle System.InvalidCastException: Null object cannot be converted to a value type.
//tried this but didn't work: if (jToken["currentBlocks"] != null)
CurrentBlocks = 0;
}
Difficulty = jToken.Value<double>("difficulty");
Reward = jToken.Value<double>("reward");
MinimumBlockTime = jToken.Value<double>("minBlockTime"); //this one can be null too (?)
NetworkHashRate = jToken.Value<Int64>("networkhashrate");
Price = jToken.Value<double>("price");
Exchange = jToken.Value<string>("exchange");
Profitability = jToken.Value<double>("ratio");
AdjustedProfitability = jToken.Value<double>("adjustedratio");
AverageProfitability = jToken.Value<double>("avgProfit");
AverageHashRate = jToken.Value<double>("avgHash");
}
}
}
| mit | C# |
9ecdd04c6f7b2e48c46345186a70facfab06a0dd | Deploy in correct folder if instance name not set | Codestellation/Galaxy,Codestellation/Galaxy,Codestellation/Galaxy | src/Galaxy/Domain/Deployment.cs | src/Galaxy/Domain/Deployment.cs | using System.Linq;
using System.ServiceProcess;
using Codestellation.Galaxy.Infrastructure;
using Nejdb.Bson;
using System;
namespace Codestellation.Galaxy.Domain
{
public class Deployment
{
private string _deployLogFolder;
private string _fileOverridesFolder;
public ObjectId Id { get; internal set; }
//public string ServiceName { get; set; }
public string InstanceName { get; set; }
public ObjectId FeedId { get; set; }
public string Status { get; set; }
public string PackageId { get; set; }
public Version PackageVersion { get; set; }
public FileList KeepOnUpdate { get; set; }
public string GetServiceName()
{
if (string.IsNullOrWhiteSpace(InstanceName))
{
return PackageId;
}
return string.Format("{0}${1}", PackageId, InstanceName);
}
public string GetDeployFolder(string baseFolder)
{
if (string.IsNullOrWhiteSpace(InstanceName))
{
return Folder.Combine(baseFolder, PackageId);
}
return Folder.Combine(baseFolder, string.Format("{0}-{1}", PackageId, InstanceName));
}
public string GetDeployLogFolder()
{
return _deployLogFolder ?? (_deployLogFolder = BuildServiceFolder("BuildLogs"));
}
public string GetFilesFolder()
{
return _fileOverridesFolder ?? (_fileOverridesFolder = BuildServiceFolder("FileOverrides"));
}
private string BuildServiceFolder(string subfolder)
{
return Folder.Combine(Folder.BasePath, Id.ToString() , subfolder);
}
public string GetServiceState()
{
ServiceController[] services = ServiceController.GetServices();
var controller = services.SingleOrDefault(item => item.ServiceName == GetServiceName());
if (controller == null)
{
return "NotFound";
}
return controller.Status.ToString();
}
public string GetServiceHostFileName()
{
return string.Format("{0}.exe", PackageId);
}
}
}
| using System.Linq;
using System.ServiceProcess;
using Codestellation.Galaxy.Infrastructure;
using Nejdb.Bson;
using System;
namespace Codestellation.Galaxy.Domain
{
public class Deployment
{
private string _deployLogFolder;
private string _fileOverridesFolder;
public ObjectId Id { get; internal set; }
//public string ServiceName { get; set; }
public string InstanceName { get; set; }
public ObjectId FeedId { get; set; }
public string Status { get; set; }
public string PackageId { get; set; }
public Version PackageVersion { get; set; }
public FileList KeepOnUpdate { get; set; }
public string GetServiceName()
{
if (string.IsNullOrWhiteSpace(InstanceName))
{
return PackageId;
}
return string.Format("{0}${1}", PackageId, InstanceName);
}
public string GetDeployFolder(string baseFolder)
{
return Folder.Combine(baseFolder, string.Format("{0}-{1}", PackageId, InstanceName));
}
public string GetDeployLogFolder()
{
return _deployLogFolder ?? (_deployLogFolder = BuildServiceFolder("BuildLogs"));
}
public string GetFilesFolder()
{
return _fileOverridesFolder ?? (_fileOverridesFolder = BuildServiceFolder("FileOverrides"));
}
private string BuildServiceFolder(string subfolder)
{
return Folder.Combine(Folder.BasePath, Id.ToString() , subfolder);
}
public string GetServiceState()
{
ServiceController[] services = ServiceController.GetServices();
var controller = services.SingleOrDefault(item => item.ServiceName == GetServiceName());
if (controller == null)
{
return "NotFound";
}
return controller.Status.ToString();
}
public string GetServiceHostFileName()
{
return string.Format("{0}.exe", PackageId);
}
}
}
| apache-2.0 | C# |
07d9d4d0bc44c52ef25f7541b224d050737ee46f | Generalize Optional on item type. | plioi/parsley | src/Parsley/Grammar.Optional.cs | src/Parsley/Grammar.Optional.cs | using System.Diagnostics.CodeAnalysis;
namespace Parsley;
public static partial class Grammar
{
/// <summary>
/// Optional(p) is equivalent to p whenever p succeeds or when p fails after consuming input.
/// If p fails without consuming input, Optional(p) succeeds.
/// </summary>
public static Parser<TItem, TValue?> Optional<TItem, TValue>(Parser<TItem, TValue> parser)
where TValue : class
{
var nothing = default(TValue).SucceedWithThisValue<TItem, TValue?>();
return Choice(
from x in parser
select (TValue?)x, nothing);
}
/// <summary>
/// Optional(p) is equivalent to p whenever p succeeds or when p fails after consuming input.
/// If p fails without consuming input, Optional(p) succeeds.
/// </summary>
[SuppressMessage("ReSharper", "MethodOverloadWithOptionalParameter",
Justification = "This warning is inaccurate. The other `struct` " +
"overload does not in fact hide this one.")]
public static Parser<TItem, TValue?> Optional<TItem, TValue>(Parser<TItem, TValue> parser, TValue? ignoredOverloadResolver = null)
where TValue : struct
{
var nothing = default(TValue?).SucceedWithThisValue<TItem, TValue?>();
return Choice(parser.Select(x => (TValue?)x), nothing);
}
}
| using System.Diagnostics.CodeAnalysis;
namespace Parsley;
public static partial class Grammar
{
/// <summary>
/// Optional(p) is equivalent to p whenever p succeeds or when p fails after consuming input.
/// If p fails without consuming input, Optional(p) succeeds.
/// </summary>
public static Parser<char, TValue?> Optional<TValue>(Parser<char, TValue> parser)
where TValue : class
{
var nothing = default(TValue).SucceedWithThisValue<char, TValue?>();
return Choice(
from x in parser
select (TValue?)x, nothing);
}
/// <summary>
/// Optional(p) is equivalent to p whenever p succeeds or when p fails after consuming input.
/// If p fails without consuming input, Optional(p) succeeds.
/// </summary>
[SuppressMessage("ReSharper", "MethodOverloadWithOptionalParameter",
Justification = "This warning is inaccurate. The other `struct` " +
"overload does not in fact hide this one.")]
public static Parser<char, TValue?> Optional<TValue>(Parser<char, TValue> parser, TValue? ignoredOverloadResolver = null)
where TValue : struct
{
var nothing = default(TValue?).SucceedWithThisValue<char, TValue?>();
return Choice(parser.Select(x => (TValue?)x), nothing);
}
}
| mit | C# |
57aaa171b8ad7f33b4dcd21c992eb2c5aabd82ec | build error | Arch/UnitOfWork | src/Microsoft.EntityFrameworkCore.UnitOfWork/PagedList/IQueryablePageListExtensions.cs | src/Microsoft.EntityFrameworkCore.UnitOfWork/PagedList/IQueryablePageListExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.EntityFrameworkCore
{
public static class IQueryablePageListExtensions
{
/// <summary>
/// Converts the specified source to <see cref="IPagedList{T}"/> by the specified <paramref name="pageIndex"/> and <paramref name="pageSize"/>.
/// </summary>
/// <typeparam name="T">The type of the source.</typeparam>
/// <param name="source">The source to paging.</param>
/// <param name="pageIndex">The index of the page.</param>
/// <param name="pageSize">The size of the page.</param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken" /> to observe while waiting for the task to complete.
/// </param>
/// <param name="indexFrom">The start index value.</param>
/// <returns>An instance of the inherited from <see cref="IPagedList{T}"/> interface.</returns>
public static async Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> source, int pageIndex, int pageSize, int indexFrom = 0, CancellationToken cancellationToken = default(CancellationToken))
{
var count = await source.CountAsync(cancellationToken).ConfigureAwait(false);
var items = await source.Skip((pageIndex - indexFrom) * pageSize).Take(pageSize).ToListAsync(cancellationToken).ConfigureAwait(false);
var pagedList = new PagedList<T>()
{
PageIndex = pageIndex,
PageSize = pageSize,
IndexFrom = indexFrom,
TotalCount = count,
Items = items
};
return pagedList;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.EntityFrameworkCore
{
public static class IQueryablePageListExtensions
{
/// <summary>
/// Converts the specified source to <see cref="IPagedList{T}"/> by the specified <paramref name="pageIndex"/> and <paramref name="pageSize"/>.
/// </summary>
/// <typeparam name="T">The type of the source.</typeparam>
/// <param name="source">The source to paging.</param>
/// <param name="pageIndex">The index of the page.</param>
/// <param name="pageSize">The size of the page.</param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken" /> to observe while waiting for the task to complete.
/// </param>
/// <param name="indexFrom">The start index value.</param>
/// <returns>An instance of the inherited from <see cref="IPagedList{T}"/> interface.</returns>
public static async Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> source, int pageIndex, int pageSize, int indexFrom = 0, CancellationToken cancellationToken = default(CancellationToken))
{
var count = await source.CountAsync(cancellationToken).ConfigureAwait(false);
var items = await source.Skip((pageIndex - indexFrom) * pageSize).Take(pageSize).ToListAsync(cancellationToken).ConfigureAwait(false);
var pagedList = new PagedList<T>()
{
PageIndex = pageIndex,
PageSize = pageSize,
IndexFrom = indexFrom,
TotalCount = count,
Items = items
};
return pagedList;
}
}
}
| mit | C# |
ab3bbe797c4080b16dd1d2e3886aeea50c2ad8b0 | Delete commented code | poxet/InfluxDB.Net,jamesholcomb/InfluxDB.Net,ovjhc/InfluxDB.Net,poxet/InfluxDB.Net,ovjhc/InfluxDB.Net,ziyasal/InfluxDB.Net,jamesholcomb/InfluxDB.Net,ziyasal/InfluxDB.Net | src/InfluxDB.Net.Tests/ClientIntegrationTests.cs | src/InfluxDB.Net.Tests/ClientIntegrationTests.cs | using System;
using NUnit.Framework;
using FluentAssertions;
using InfluxDB.Net.Core;
using InfluxDB.Net.Models;
using System.Collections.Generic;
namespace InfluxDB.Net.Tests
{
public class ClientIntegrationTests : TestBase
{
private IInfluxDb _client;
private string _sutDb;
protected override void FinalizeSetUp()
{
_client = new InfluxDb("http://principalstrickland-delorean-1.c.influxdb.com:8086", "root", "root");
_sutDb = Guid.NewGuid().ToString("N").Substring(10);
}
[Test]
public void Ping_Test()
{
Pong pong = _client.Ping();
pong.Should().NotBeNull();
pong.Status.Should().BeEquivalentTo("ok");
}
[Test]
public void Create_DB_Test()
{
CreateDbResponse response = _client.CreateDatabase(_sutDb);
response.Success.Should().BeTrue();
}
[Test]
public void Create_DB_WithConfig_Test()
{
CreateDbResponse response = _client.CreateDatabase(new DatabaseConfiguration
{
Name = Guid.NewGuid().ToString("N").Substring(10)
});
response.Success.Should().BeTrue();
}
[Test]
public void Write_DB_Test()
{
}
[Test]
public void DescribeDatabases_Test()
{
List<Database> databases = _client.DescribeDatabases();
databases.Should().NotBeNullOrEmpty();
}
[Test]
public void Delete_Database_Test()
{
InfluxDbResponse response = _client.DeleteDatabase("AT");
response.Success.Should().BeTrue();
}
}
} | using System;
using NUnit.Framework;
using FluentAssertions;
using InfluxDB.Net.Core;
using InfluxDB.Net.Models;
using System.Collections.Generic;
namespace InfluxDB.Net.Tests
{
public class ClientIntegrationTests : TestBase
{
private IInfluxDb _client;
private string _sutDb;
protected override void FinalizeSetUp()
{
_client = new InfluxDb("http://principalstrickland-delorean-1.c.influxdb.com:8086", "root", "root");
_sutDb = Guid.NewGuid().ToString("N").Substring(10);
}
[Test]
public void Ping_Test()
{
Pong pong = _client.Ping();
pong.Should().NotBeNull();
pong.Status.Should().BeEquivalentTo("ok");
}
[Test]
public void Connect_Test()
{
_client.Should().NotBeNull();
}
[Test]
public void Create_DB_Test()
{
CreateDbResponse response = _client.CreateDatabase(_sutDb);
response.Success.Should().BeTrue();
}
[Test]
public void Create_DB_WithConfig_Test()
{
CreateDbResponse response = _client.CreateDatabase(new DatabaseConfiguration
{
Name = Guid.NewGuid().ToString("N").Substring(10)
});
response.Success.Should().BeTrue();
}
[Test]
public void Write_DB_Test()
{
// _client.Write(_sutDb,TimeUnit.Unit.Minutes,new Serie[]
// {
// new Serie
// {
// }
// })
}
[Test]
public void DescribeDatabases_Test()
{
List<Database> databases = _client.DescribeDatabases();
databases.Should().NotBeNullOrEmpty();
}
[Test]
public void Delete_Database_Test()
{
InfluxDbResponse response = _client.DeleteDatabase("AT");
response.Success.Should().BeTrue();
}
}
} | unlicense | C# |
679e1a0f1e393aa549b9958984c2ccd46abe0159 | Increase version of | kant2002/Dub | Dub/CommonAssemblyInfo.cs | Dub/CommonAssemblyInfo.cs | // -----------------------------------------------------------------------
// <copyright file="CommonAssemblyInfo.cs" company="Andrey Kurdiumov">
// Copyright (c) Andrey Kurdiumov. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyCopyright("Copyright Andrey Kurdiumov 2014-2015")]
[assembly: AssemblyCompany("Andrey Kurdiumov")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.2.9.0")]
[assembly: AssemblyFileVersion("0.2.9.0")]
| // -----------------------------------------------------------------------
// <copyright file="CommonAssemblyInfo.cs" company="Andrey Kurdiumov">
// Copyright (c) Andrey Kurdiumov. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyCopyright("Copyright Andrey Kurdiumov 2014-2015")]
[assembly: AssemblyCompany("Andrey Kurdiumov")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.2.8.0")]
[assembly: AssemblyFileVersion("0.2.8.0")]
| apache-2.0 | C# |
df10fce1f7f71e5587cce4e4cd1f86441ff5166a | Change SimpleDateFormatter to use system culture | Dagwaging/log4net,Dagwaging/log4net,Dagwaging/log4net | src/log4net/DateFormatter/SimpleDateFormatter.cs | src/log4net/DateFormatter/SimpleDateFormatter.cs | #region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you 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.
//
#endregion
using System;
using System.IO;
namespace log4net.DateFormatter
{
/// <summary>
/// Formats the <see cref="DateTime"/> using the <see cref="M:DateTime.ToString(string, IFormatProvider)"/> method.
/// </summary>
/// <remarks>
/// <para>
/// Formats the <see cref="DateTime"/> using the <see cref="DateTime"/> <see cref="M:DateTime.ToString(string, IFormatProvider)"/> method.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class SimpleDateFormatter : IDateFormatter
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="format">The format string.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="SimpleDateFormatter" /> class
/// with the specified format string.
/// </para>
/// <para>
/// The format string must be compatible with the options
/// that can be supplied to <see cref="M:DateTime.ToString(string, IFormatProvider)"/>.
/// </para>
/// </remarks>
public SimpleDateFormatter(string format)
{
m_formatString = format;
}
#endregion Public Instance Constructors
#region Implementation of IDateFormatter
/// <summary>
/// Formats the date using <see cref="M:DateTime.ToString(string, IFormatProvider)"/>.
/// </summary>
/// <param name="dateToFormat">The date to convert to a string.</param>
/// <param name="writer">The writer to write to.</param>
/// <remarks>
/// <para>
/// Uses the date format string supplied to the constructor to call
/// the <see cref="M:DateTime.ToString(string, IFormatProvider)"/> method to format the date.
/// </para>
/// </remarks>
virtual public void FormatDate(DateTime dateToFormat, TextWriter writer)
{
writer.Write(dateToFormat.ToString(m_formatString));
}
#endregion
#region Private Instance Fields
/// <summary>
/// The format string used to format the <see cref="DateTime" />.
/// </summary>
/// <remarks>
/// <para>
/// The format string must be compatible with the options
/// that can be supplied to <see cref="M:DateTime.ToString(string, IFormatProvider)"/>.
/// </para>
/// </remarks>
private readonly string m_formatString;
#endregion Private Instance Fields
}
}
| #region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you 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.
//
#endregion
using System;
using System.IO;
namespace log4net.DateFormatter
{
/// <summary>
/// Formats the <see cref="DateTime"/> using the <see cref="M:DateTime.ToString(string, IFormatProvider)"/> method.
/// </summary>
/// <remarks>
/// <para>
/// Formats the <see cref="DateTime"/> using the <see cref="DateTime"/> <see cref="M:DateTime.ToString(string, IFormatProvider)"/> method.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class SimpleDateFormatter : IDateFormatter
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="format">The format string.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="SimpleDateFormatter" /> class
/// with the specified format string.
/// </para>
/// <para>
/// The format string must be compatible with the options
/// that can be supplied to <see cref="M:DateTime.ToString(string, IFormatProvider)"/>.
/// </para>
/// </remarks>
public SimpleDateFormatter(string format)
{
m_formatString = format;
}
#endregion Public Instance Constructors
#region Implementation of IDateFormatter
/// <summary>
/// Formats the date using <see cref="M:DateTime.ToString(string, IFormatProvider)"/>.
/// </summary>
/// <param name="dateToFormat">The date to convert to a string.</param>
/// <param name="writer">The writer to write to.</param>
/// <remarks>
/// <para>
/// Uses the date format string supplied to the constructor to call
/// the <see cref="M:DateTime.ToString(string, IFormatProvider)"/> method to format the date.
/// </para>
/// </remarks>
virtual public void FormatDate(DateTime dateToFormat, TextWriter writer)
{
writer.Write(dateToFormat.ToString(m_formatString, System.Globalization.DateTimeFormatInfo.InvariantInfo));
}
#endregion
#region Private Instance Fields
/// <summary>
/// The format string used to format the <see cref="DateTime" />.
/// </summary>
/// <remarks>
/// <para>
/// The format string must be compatible with the options
/// that can be supplied to <see cref="M:DateTime.ToString(string, IFormatProvider)"/>.
/// </para>
/// </remarks>
private readonly string m_formatString;
#endregion Private Instance Fields
}
}
| apache-2.0 | C# |
b62bf367206c774e43830d674b44b77078334f66 | Implement basic receiver loop | brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync | projects/CommSample/source/CommSample.App/Receiver.cs | projects/CommSample/source/CommSample.App/Receiver.cs | //-----------------------------------------------------------------------
// <copyright file="Receiver.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CommSample
{
using System;
using System.Threading.Tasks;
internal sealed class Receiver
{
private readonly MemoryChannel channel;
private readonly Logger logger;
private readonly int bufferSize;
public Receiver(MemoryChannel channel, Logger logger, int bufferSize)
{
this.channel = channel;
this.logger = logger;
this.bufferSize = bufferSize;
}
public async Task RunAsync()
{
this.logger.WriteLine("Receiver starting...");
byte[] buffer = new byte[this.bufferSize];
long totalBytes = 0;
int bytesRead;
do
{
bytesRead = await this.channel.ReceiveAsync(buffer);
totalBytes += bytesRead;
}
while (bytesRead > 0);
this.logger.WriteLine("Receiver completed. Received {0} bytes.", totalBytes);
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="Receiver.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CommSample
{
using System;
using System.Threading.Tasks;
internal sealed class Receiver
{
private readonly MemoryChannel channel;
private readonly Logger logger;
private readonly int bufferSize;
public Receiver(MemoryChannel channel, Logger logger, int bufferSize)
{
this.channel = channel;
this.logger = logger;
this.bufferSize = bufferSize;
}
public async Task RunAsync()
{
this.logger.WriteLine("Receiver starting...");
byte[] buffer = new byte[this.bufferSize];
int bytesReceived = await this.channel.ReceiveAsync(buffer);
this.logger.WriteLine("Receiver completed. Received {0} bytes.", bytesReceived);
}
}
}
| unlicense | C# |
d720d6748b3998dceeec7d8b00ad9816e0b8e903 | Update NotesRepository.cs | CarmelSoftware/MVCDataRepositoryXML | Models/NotesRepository.cs | Models/NotesRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
| ////// TODO
The repo here will take care of all CRUD operations
| mit | C# |
a70ba9cdc8308f669610f8700ff7e735f8ded893 | Fix build issue due to missing #ifs | dupdob/NFluent,tpierrain/NFluent,tpierrain/NFluent,NFluent/NFluent,tpierrain/NFluent,NFluent/NFluent,dupdob/NFluent,dupdob/NFluent | tests/NFluent.Tests/FromIssues/UserReportedIssues2.cs | tests/NFluent.Tests/FromIssues/UserReportedIssues2.cs | using System.Collections.Generic;
#if DOTNET_45
using System;
using System.Threading.Tasks;
#endif
using NUnit.Framework;
namespace NFluent.Tests.FromIssues
{
[TestFixture]
public class UserReportedIssues2
{
[Test]
public void should_recognize_autoproperty_readonly_values()
{
var someClass = new SomeClass("Hello"){Other ="world", Values = new Dictionary<string, string>{["key1"] = "value1"}};
Check.That(someClass).HasFieldsWithSameValues(new {Other = "world", Values = new Dictionary<string, string> { ["key1"] = "value1" } });
}
#if DOTNET_45
[Test]
public void reproduce_issue_204()
{
Check.ThatAsyncCode(() => Execute(5)).Throws<Exception>();
}
private Task<int> Execute(int i)
{
if (i == 5)
{
throw new Exception("bad");
}
return Task.FromResult(i);
}
#endif
private class BaseClass
{
public string Id { get; }
public BaseClass(string id)
{
Id = id;
}
}
private class SomeClass: BaseClass
{
public SomeClass(string id): base(id)
{
}
public string Salt => Id;
public string Other { get; set; }
public Dictionary<string, string> Values { get; set; }
}
}
} | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace NFluent.Tests.FromIssues
{
[TestFixture]
public class UserReportedIssues2
{
[Test]
public void should_recognize_autoproperty_readonly_values()
{
var someClass = new SomeClass("Hello"){Other ="world", Values = new Dictionary<string, string>{["key1"] = "value1"}};
Check.That(someClass).HasFieldsWithSameValues(new {Other = "world", Values = new Dictionary<string, string> { ["key1"] = "value1" } });
}
#if DOTNET_45
[Test]
public void reproduce_issue_204()
{
Check.ThatAsyncCode(() => Execute(5)).Throws<Exception>();
}
private Task<int> Execute(int i)
{
if (i == 5)
{
throw new Exception("bad");
}
return Task.FromResult(i);
}
#endif
private class BaseClass
{
public string Id { get; }
public BaseClass(string id)
{
Id = id;
}
}
private class SomeClass: BaseClass
{
public SomeClass(string id): base(id)
{
}
public string Salt => Id;
public string Other { get; set; }
public Dictionary<string, string> Values { get; set; }
}
}
} | apache-2.0 | C# |
c69d98763a64979edaf7bb780947c31c1aafe2a7 | Change quotations format in Source | smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk | main/Smartsheet/Api/Models/Source.cs | main/Smartsheet/Api/Models/Source.cs | // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// 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.
// %[license]
namespace Smartsheet.Api.Models
{
/// <summary>
/// Represents individual user settings for a specific sheet.
/// User settings may be updated even on sheets where the current user only has read access (e.g. viewer permissions or a read-only sheet). </summary>
public class Source : IdentifiableModel
{
private string type;
/// <summary>
/// Type of this source. "sheet" or "template"
/// </summary>
/// <returns> "sheet" or "template" </returns>
public string Type
{
get { return type; }
set { type = value; }
}
}
} | // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// 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.
// %[license]
namespace Smartsheet.Api.Models
{
/// <summary>
/// Represents individual user settings for a specific sheet.
/// User settings may be updated even on sheets where the current user only has read access (e.g. viewer permissions or a read-only sheet). </summary>
public class Source : IdentifiableModel
{
private string type;
/// <summary>
/// Type of this source. “sheet” or “template”
/// </summary>
/// <returns> “sheet” or “template” </returns>
public string Type
{
get { return type; }
set { type = value; }
}
}
} | apache-2.0 | C# |
24995ed7dbfdf7aa284197fa77e9d619e3d60a14 | Fix Korean Calendar Test (#36429) | ViktorHofer/corefx,ViktorHofer/corefx,BrennanConroy/corefx,ericstj/corefx,ericstj/corefx,ViktorHofer/corefx,BrennanConroy/corefx,BrennanConroy/corefx,wtgodbe/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx | src/System.Globalization.Calendars/tests/KoreanCalendar/KoreanCalendarTwoDigitYearMax.cs | src/System.Globalization.Calendars/tests/KoreanCalendar/KoreanCalendarTwoDigitYearMax.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 Xunit;
namespace System.Globalization.Tests
{
public class KoreanCalendarTwoDigitYearMax
{
[Fact]
public void TwoDigitYearMax_Get()
{
var calendar = new KoreanCalendar();
Assert.True(calendar.TwoDigitYearMax == 4362 || calendar.TwoDigitYearMax == 4382, $"Unexpected calendar.TwoDigitYearMax {calendar.TwoDigitYearMax}");
}
[Theory]
[InlineData(99)]
[InlineData(2016)]
public void TwoDigitYearMax_Set(int newTwoDigitYearMax)
{
Calendar calendar = new KoreanCalendar();
calendar.TwoDigitYearMax = newTwoDigitYearMax;
Assert.Equal(newTwoDigitYearMax, calendar.TwoDigitYearMax);
}
}
}
| // 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 Xunit;
namespace System.Globalization.Tests
{
public class KoreanCalendarTwoDigitYearMax
{
[Fact]
public void TwoDigitYearMax_Get()
{
var calendar = new KoreanCalendar();
Assert.True(calendar.TwoDigitYearMax == 4362 || calendar.TwoDigitYearMax == 4382, $"Unexpected calendar.TwoDigitYearMax {calendar.TwoDigitYearMax}");
Assert.Equal(4362, new KoreanCalendar().TwoDigitYearMax);
}
[Theory]
[InlineData(99)]
[InlineData(2016)]
public void TwoDigitYearMax_Set(int newTwoDigitYearMax)
{
Calendar calendar = new KoreanCalendar();
calendar.TwoDigitYearMax = newTwoDigitYearMax;
Assert.Equal(newTwoDigitYearMax, calendar.TwoDigitYearMax);
}
}
}
| mit | C# |
468c30d5d6ef7e98dc399de7badd766702b632d6 | Update AccommodationType.cs | nikola02333/WebKurs,nikola02333/WebKurs,nikola02333/WebKurs | BookingApp/BookingApp/Models/AccommodationType.cs | BookingApp/BookingApp/Models/AccommodationType.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookingApp.Models
{
public class AccommodationType
{
public int AccommodationTypeId { get; set; }
public string name { get; set; }
public List<Accommodation> l_Accommodation { get; set; }
//
public AccommodationType()
{
}
~AccommodationType()
{
}
}//end AccommodationType
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookingApp.Models
{
public class AccommodationType
{
public int AccommodationTypeId { get; set; }
private string name { get; set; }
public List<Accommodation> l_Accommodation { get; set; }
//
public AccommodationType()
{
}
~AccommodationType()
{
}
}//end AccommodationType
} | mit | C# |
5f4b013d3ff4234c836e6a7ef39936d32815096a | Fix up how we generate debugging info for var simple. | gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT | LINQToTTree/LINQToTTreeLib/Variables/VarSimple.cs | LINQToTTree/LINQToTTreeLib/Variables/VarSimple.cs | using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
Declare = false;
}
public IValue InitialValue { get; set; }
/// <summary>
/// Get/Set if this variable needs to be declared.
/// </summary>
public bool Declare { get; set; }
/// <summary>
/// TO help with debugging...
/// </summary>
/// <returns></returns>
public override string ToString()
{
var s = string.Format("{0} {1}", Type.Name, VariableName);
if (InitialValue != null)
s = string.Format("{0} = {1}", s, InitialValue.RawValue);
return s;
}
public void RenameRawValue(string oldname, string newname)
{
if (InitialValue != null)
InitialValue.RenameRawValue(oldname, newname);
if (RawValue == oldname)
{
RawValue = newname;
VariableName = newname;
}
}
}
}
| using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
Declare = false;
}
public IValue InitialValue { get; set; }
/// <summary>
/// Get/Set if this variable needs to be declared.
/// </summary>
public bool Declare { get; set; }
/// <summary>
/// TO help with debugging...
/// </summary>
/// <returns></returns>
public override string ToString()
{
return VariableName + " = (" + Type.Name + ") " + RawValue;
}
public void RenameRawValue(string oldname, string newname)
{
if (InitialValue != null)
InitialValue.RenameRawValue(oldname, newname);
if (RawValue == oldname)
{
RawValue = newname;
VariableName = newname;
}
}
}
}
| lgpl-2.1 | C# |
357c707be2ddae08998f1602959a2a3093b07b8d | Update PingMessage.cs (#7876) | fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Messages/Client/PingMessage.cs | UnityProject/Assets/Scripts/Messages/Client/PingMessage.cs | using Mirror;
using UnityEngine;
namespace Messages.Client
{
public class PingMessage : ClientMessage<PingMessage.NetMessage>
{
public struct NetMessage : NetworkMessage { }
public override void Process(NetMessage msg)
{
Server.UpdateConnectedPlayersMessage.Send();
}
public static NetMessage Send()
{
NetMessage msg = new NetMessage();
Send(msg);
return msg;
}
}
}
| using Mirror;
using UnityEngine;
namespace Messages.Client
{
public class PingMessage : ClientMessage<PingMessage.NetMessage>
{
public struct NetMessage : NetworkMessage { }
public override void Process(NetMessage msg)
{
Server.UpdateConnectedPlayersMessage.Send();
}
public static NetMessage Send()
{
NetMessage msg = new NetMessage();
Send();
return msg;
}
}
} | agpl-3.0 | C# |
c627965ac1578c2e961138be3e3a1260966a8e51 | Reset font weight to 300. | flamestream/taction,flamestream/taction,flamestream/taction | App/CustomUIElement/HoldButton.cs | App/CustomUIElement/HoldButton.cs | using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using static Taction.Config;
namespace Taction.CustomUIElement {
/// <summary>
/// A button that supports holding down to execute key command.
/// </summary>
internal class HoldButton : Button {
private App App => (App)Application.Current;
internal KeyCommand KeyCommand { set; get; }
public HoldButton(IPanelItemSpecs specs, StackPanel panel = null) {
var s = (HoldButtonSpecs)specs;
this.KeyCommand = InputSimulatorHelper.ParseKeyCommand(s.keyCommand);
this.Content = s.text != null ?
s.text :
s.keyCommand;
if (panel == null || panel.Orientation == Orientation.Vertical)
this.Height = s.size;
else
this.Width = s.size;
}
protected override void OnTouchDown(TouchEventArgs e) {
base.OnTouchDown(e);
// Style change
this.FontWeight = FontWeight.FromOpenTypeWeight(500);
// Set activation flag
this.Tag = true;
App.inputSimulator.SimulateKeyDown(this.KeyCommand);
}
protected override void OnTouchLeave(TouchEventArgs e) {
// Activation flag check
// @NOTE Needed because TouchLeave can be triggered without TouchDown
if (this.Tag == null) return;
this.Tag = null;
// Style change
this.FontWeight = FontWeight.FromOpenTypeWeight(300);
App.inputSimulator.SimulateKeyUp(this.KeyCommand);
}
}
}
| using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using static Taction.Config;
namespace Taction.CustomUIElement {
/// <summary>
/// A button that supports holding down to execute key command.
/// </summary>
internal class HoldButton : Button {
private App App => (App)Application.Current;
internal KeyCommand KeyCommand { set; get; }
public HoldButton(IPanelItemSpecs specs, StackPanel panel = null) {
var s = (HoldButtonSpecs)specs;
this.KeyCommand = InputSimulatorHelper.ParseKeyCommand(s.keyCommand);
this.Content = s.text != null ?
s.text :
s.keyCommand;
if (panel == null || panel.Orientation == Orientation.Vertical)
this.Height = s.size;
else
this.Width = s.size;
}
protected override void OnTouchDown(TouchEventArgs e) {
base.OnTouchDown(e);
// Style change
this.FontWeight = FontWeight.FromOpenTypeWeight(500);
// Set activation flag
this.Tag = true;
App.inputSimulator.SimulateKeyDown(this.KeyCommand);
}
protected override void OnTouchLeave(TouchEventArgs e) {
// Activation flag check
// @NOTE Needed because TouchLeave can be triggered without TouchDown
if (this.Tag == null) return;
this.Tag = null;
// Style change
this.FontWeight = FontWeight.FromOpenTypeWeight(200);
App.inputSimulator.SimulateKeyUp(this.KeyCommand);
}
}
}
| mit | C# |
4e9abd41c0680cef72b034d942f5f9f11e947382 | improve error messages | chkr1011/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet | Source/MQTTnet/Serializer/MqttPacketBodyReader.cs | Source/MQTTnet/Serializer/MqttPacketBodyReader.cs | using System;
using System.Text;
namespace MQTTnet.Serializer
{
public class MqttPacketBodyReader
{
private readonly byte[] _buffer;
private int _offset;
public MqttPacketBodyReader(byte[] buffer, int offset)
{
_buffer = buffer;
_offset = offset;
}
public int Length => _buffer.Length - _offset;
public bool EndOfStream => _offset == _buffer.Length;
public byte ReadByte()
{
ValidateReceiveBuffer(1);
return _buffer[_offset++];
}
public ArraySegment<byte> ReadRemainingData()
{
return new ArraySegment<byte>(_buffer, _offset, _buffer.Length - _offset);
}
public ushort ReadUInt16()
{
ValidateReceiveBuffer(2);
var msb = _buffer[_offset++];
var lsb = _buffer[_offset++];
return (ushort)(msb << 8 | lsb);
}
public ArraySegment<byte> ReadWithLengthPrefix()
{
var length = ReadUInt16();
ValidateReceiveBuffer(length);
var result = new ArraySegment<byte>(_buffer, _offset, length);
_offset += length;
return result;
}
private void ValidateReceiveBuffer(ushort length)
{
if (_buffer.Length < _offset + length)
{
throw new ArgumentOutOfRangeException(nameof(_buffer), $"expected at least {_offset + length} bytes but there are only {_buffer.Length} bytes");
}
}
public string ReadStringWithLengthPrefix()
{
var buffer = ReadWithLengthPrefix();
return Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
}
}
}
| using System;
using System.Text;
namespace MQTTnet.Serializer
{
public class MqttPacketBodyReader
{
private readonly byte[] _buffer;
private int _offset;
public MqttPacketBodyReader(byte[] buffer, int offset)
{
_buffer = buffer;
_offset = offset;
}
public int Length => _buffer.Length - _offset;
public bool EndOfStream => _offset == _buffer.Length;
public byte ReadByte()
{
return _buffer[_offset++];
}
public ArraySegment<byte> ReadRemainingData()
{
return new ArraySegment<byte>(_buffer, _offset, _buffer.Length - _offset);
}
public ushort ReadUInt16()
{
var msb = _buffer[_offset++];
var lsb = _buffer[_offset++];
return (ushort)(msb << 8 | lsb);
}
public ArraySegment<byte> ReadWithLengthPrefix()
{
var length = ReadUInt16();
var result = new ArraySegment<byte>(_buffer, _offset, length);
_offset += length;
return result;
}
public string ReadStringWithLengthPrefix()
{
var buffer = ReadWithLengthPrefix();
return Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
}
}
}
| mit | C# |
d9a1a147af9448f5bb3ff06684cc868e44f96556 | update pull interval to 15min | streetmilk/CoinStatIngester | CoinStatIngester/AutofacConfig.cs | CoinStatIngester/AutofacConfig.cs | using Autofac;
using CoinStatIngester.Data;
using CoinStatIngester.Infrastructure;
using System.Net.Http;
namespace CoinStatIngester
{
public class AutofacConfig
{
public ContainerBuilder Build()
{
var builder = new ContainerBuilder();
builder.RegisterType<HttpClient>().UsingConstructor();
builder.RegisterType<WhatToMineStatRepo>().As<IStatRepo>();
builder.RegisterType<CsvStatWriter>().As<IStatWriter>().WithParameter("writeLocation", "C:\\stats\\");
builder.RegisterType<Controller>().WithParameter("callIntervalInMinutes", 15);
return builder;
}
}
} | using Autofac;
using CoinStatIngester.Data;
using CoinStatIngester.Infrastructure;
using System.Net.Http;
namespace CoinStatIngester
{
public class AutofacConfig
{
public ContainerBuilder Build()
{
var builder = new ContainerBuilder();
builder.RegisterType<HttpClient>().UsingConstructor();
builder.RegisterType<WhatToMineStatRepo>().As<IStatRepo>();
builder.RegisterType<CsvStatWriter>().As<IStatWriter>().WithParameter("writeLocation", "C:\\stats\\");
builder.RegisterType<Controller>().WithParameter("callIntervalInMinutes", 1);
return builder;
}
}
} | mit | C# |
66082e0bb197d3023b7f21f203df4fd031446bcb | update S_ANSWER_INTERACTIVE for p103 | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TeraPacketParser/Messages/S_ANSWER_INTERACTIVE.cs | TeraPacketParser/Messages/S_ANSWER_INTERACTIVE.cs | namespace TeraPacketParser.Messages
{
public class S_ANSWER_INTERACTIVE : ParsedMessage
{
public string Name { get; }
public uint PlayerId { get; }
public uint ServerId { get; }
public bool HasGuild { get; }
public bool HasParty { get; }
public int Level { get; }
public int TemplateId { get; }
public S_ANSWER_INTERACTIVE(TeraMessageReader reader) : base(reader)
{
var nameOffset = reader.ReadUInt16();
reader.Skip(4); // type
if (reader.Factory.ReleaseVersion / 100 >= 103)
{
PlayerId = reader.ReadUInt32();
}
TemplateId = reader.ReadInt32();
Level = reader.ReadInt32();
HasParty = reader.ReadBoolean();
HasGuild = reader.ReadBoolean();
ServerId = reader.ReadUInt32();
reader.RepositionAt(nameOffset);
Name = reader.ReadTeraString();
}
}
} |
namespace TeraPacketParser.Messages
{
public class S_ANSWER_INTERACTIVE : ParsedMessage
{
public string Name { get; private set; }
public bool HasGuild { get; private set; }
public bool HasParty { get; private set; }
public uint Level { get; private set; }
public uint Model { get; private set; }
public S_ANSWER_INTERACTIVE(TeraMessageReader reader) : base(reader)
{
reader.Skip(2+4);
Model = reader.ReadUInt32();
Level = reader.ReadUInt32();
HasParty = reader.ReadBoolean();
HasGuild = reader.ReadBoolean();
reader.Skip(4); //server ID
Name = reader.ReadTeraString();
}
}
}
| mit | C# |
f6fd773ae7ba95363809e3507019478f091afd73 | Add sanity test for 800 (DCCC). | pvasys/PillarRomanNumeralKata | VasysRomanNumeralsKataTest/ToRomanNumeralsTest.cs | VasysRomanNumeralsKataTest/ToRomanNumeralsTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VasysRomanNumeralsKata;
namespace VasysRomanNumeralsKataTest
{
[TestClass]
public class ToRomanNumeralsTest
{
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
{
int ten = 10;
Assert.IsTrue(ten.ToRomanNumeral() == "X");
}
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
{
int oneThousand = 1000;
Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
int nineHundred = 900;
Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
int fiveHundred = 500;
Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
int fourHundred = 400;
Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
int oneHundred = 100;
Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
int twoHundred = 200;
Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
int threeHundred = 300;
Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
int twoThousand = 2000;
Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM");
int sixHundred = 600;
Assert.IsTrue(sixHundred.ToRomanNumeral() == "DC");
int sevenHundred = 700;
Assert.IsTrue(sevenHundred.ToRomanNumeral() == "DCC");
int eightHundred = 800;
Assert.IsTrue(eightHundred.ToRomanNumeral() == "DCCC");
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VasysRomanNumeralsKata;
namespace VasysRomanNumeralsKataTest
{
[TestClass]
public class ToRomanNumeralsTest
{
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
{
int ten = 10;
Assert.IsTrue(ten.ToRomanNumeral() == "X");
}
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
{
int oneThousand = 1000;
Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
int nineHundred = 900;
Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
int fiveHundred = 500;
Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
int fourHundred = 400;
Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
int oneHundred = 100;
Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
int twoHundred = 200;
Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
int threeHundred = 300;
Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
int twoThousand = 2000;
Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM");
int sixHundred = 600;
Assert.IsTrue(sixHundred.ToRomanNumeral() == "DC");
int sevenHundred = 700;
Assert.IsTrue(sevenHundred.ToRomanNumeral() == "DCC");
}
}
}
| mit | C# |
cdeaa6190b61f69adc0518cf3a7883e17dc65b6d | define the Bitswap API #61 | richardschneider/net-ipfs-core | src/CoreApi/IBitswapApi.cs | src/CoreApi/IBitswapApi.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Ipfs.CoreApi
{
/// <summary>
/// Data trading module for IPFS. Its purpose is to request blocks from and
/// send blocks to other peers in the network.
/// </summary>
/// <remarks>
/// Bitswap has two primary jobs (1) Attempt to acquire blocks from the network that
/// have been requested by the client and (2) Judiciously(though strategically)
/// send blocks in its possession to other peers who want them.
/// </remarks>
/// <seealso href="https://github.com/ipfs/specs/tree/master/bitswap">Bitswap spec</seealso>
public interface IBitswapApi
{
/// <summary>
/// Gets a block from the IPFS network.
/// </summary>
/// <param name="id">
/// The <see cref="Cid"/> of the <see cref="IDataBlock">block</see>.
/// </param>
/// <param name="cancel">
/// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised.
/// </param>
/// <returns>
/// A task that represents the asynchronous get operation. The task's value
/// contains the block's id and data.
/// </returns>
/// <remarks>
/// Waits for another peer to supply the block with the <paramref name="id"/>.
/// </remarks>
Task<IDataBlock> GetAsync(Cid id, CancellationToken cancel = default(CancellationToken));
/// <summary>
/// The blocks that are needed by a peer.
/// </summary>
/// <param name="peer">
/// The id of an IPFS peer. If not specified (e.g. null), then the local
/// peer is used.
/// </param>
/// <param name="cancel">
/// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised.
/// </param>
/// <returns>
/// A task that represents the asynchronous operation. The task's value
/// contains the sequence of blocks needed by the <paramref name="peer"/>.
/// </returns>
Task<IEnumerable<Cid>> WantsAsync(MultiHash peer = null, CancellationToken cancel = default(CancellationToken));
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Ipfs.CoreApi
{
/// <summary>
/// Interact with the bitswap agent.
/// </summary>
/// <remarks>
/// <note>Not yet ready for prime time.</note>
/// </remarks>
/// <seealso href="https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/BITSWAP.md">Bitswap API spec</seealso>
public interface IBitswapApi
{
}
}
| mit | C# |
1268429af166302f369034003aa4463b160da891 | Update validation.cake | xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents | .ci/validation.cake | .ci/validation.cake | #addin nuget:?package=Xamarin.Nuget.Validator&version=1.1.1
using Xamarin.Nuget.Validator;
// SECTION: Arguments and Settings
var ROOT_DIR = (DirectoryPath)Argument ("root", ".");
var ROOT_OUTPUT_DIR = ROOT_DIR.Combine ("output");
var PACKAGE_NAMESPACES = Argument ("n", Argument ("namespaces", ""))
.Split (new [] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries)
.ToList ();
PACKAGE_NAMESPACES.AddRange (new [] {
"Xamarin",
});
// SECTION: Main Script
Information ("");
Information ("Script Arguments:");
Information (" Root directory: {0}", MakeAbsolute (ROOT_DIR));
Information (" Root output directory: {0}", ROOT_OUTPUT_DIR);
Information (" Valid package namespaces: {0}", string.Join (", ", PACKAGE_NAMESPACES));
Information ("");
// SECTION: Validate Output
var options = new NugetValidatorOptions {
Copyright = "© Microsoft Corporation. All rights reserved.",
Author = "Microsoft",
Owner = "", // Was "Microsoft", but this is no longer supported in nuspec: https://docs.microsoft.com/en-us/nuget/reference/msbuild-targets#pack-target
NeedsProjectUrl = true,
NeedsLicenseUrl = true,
ValidateRequireLicenseAcceptance = true,
ValidPackageNamespace = PACKAGE_NAMESPACES.ToArray (),
};
var nupkgFiles = GetFiles (ROOT_OUTPUT_DIR + "/**/*.nupkg");
Information ("Found {0} NuGet packages to validate.", nupkgFiles.Count);
var hasErrors = false;
foreach (var nupkgFile in nupkgFiles) {
Information ("Verifying NuGet metadata of {0}...", nupkgFile);
var result = NugetValidator.Validate (nupkgFile.FullPath, options);
if (result.Success) {
Information ("NuGet metadata validation passed.");
} else {
Error ($"NuGet metadata validation failed for {nupkgFile}:");
Error (string.Join (Environment.NewLine + " ", result.ErrorMessages));
hasErrors = true;
// Update DevOps
Warning ($"##vso[task.logissue type=warning]NuGet metadata validation failed for {nupkgFile}.");
}
}
if (hasErrors)
throw new Exception ($"Invalid NuGet metadata found.");
| #addin nuget:?package=Xamarin.Nuget.Validator&version=1.1.1
using Xamarin.Nuget.Validator;
// SECTION: Arguments and Settings
var ROOT_DIR = (DirectoryPath)Argument ("root", ".");
var ROOT_OUTPUT_DIR = ROOT_DIR.Combine ("output");
var PACKAGE_NAMESPACES = Argument ("n", Argument ("namespaces", ""))
.Split (new [] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries)
.ToList ();
PACKAGE_NAMESPACES.AddRange (new [] {
"Xamarin",
});
// SECTION: Main Script
Information ("");
Information ("Script Arguments:");
Information (" Root directory: {0}", MakeAbsolute (ROOT_DIR));
Information (" Root output directory: {0}", ROOT_OUTPUT_DIR);
Information (" Valid package namespaces: {0}", string.Join (", ", PACKAGE_NAMESPACES));
Information ("");
// SECTION: Validate Output
var options = new NugetValidatorOptions {
Copyright = "© Microsoft Corporation. All rights reserved.",
Author = "Microsoft",
// Owner = "Microsoft", - No longer supported in nuspec: https://docs.microsoft.com/en-us/nuget/reference/msbuild-targets#pack-target
NeedsProjectUrl = true,
NeedsLicenseUrl = true,
ValidateRequireLicenseAcceptance = true,
ValidPackageNamespace = PACKAGE_NAMESPACES.ToArray (),
};
var nupkgFiles = GetFiles (ROOT_OUTPUT_DIR + "/**/*.nupkg");
Information ("Found {0} NuGet packages to validate.", nupkgFiles.Count);
var hasErrors = false;
foreach (var nupkgFile in nupkgFiles) {
Information ("Verifying NuGet metadata of {0}...", nupkgFile);
var result = NugetValidator.Validate (nupkgFile.FullPath, options);
if (result.Success) {
Information ("NuGet metadata validation passed.");
} else {
Error ($"NuGet metadata validation failed for {nupkgFile}:");
Error (string.Join (Environment.NewLine + " ", result.ErrorMessages));
hasErrors = true;
// Update DevOps
Warning ($"##vso[task.logissue type=warning]NuGet metadata validation failed for {nupkgFile}.");
}
}
if (hasErrors)
throw new Exception ($"Invalid NuGet metadata found.");
| mit | C# |
115e051dbd3b2fbe7eb5e42d7252bd89f3911a50 | make DefaultRequestExecutionPolicy.Default can be set | vinhch/BizwebSharp | src/BizwebSharp/Infrastructure/RequestPolicies/DefaultRequestExecutionPolicy.cs | src/BizwebSharp/Infrastructure/RequestPolicies/DefaultRequestExecutionPolicy.cs | using System.Threading.Tasks;
using RestSharp.Portable;
namespace BizwebSharp.Infrastructure.RequestPolicies
{
public class DefaultRequestExecutionPolicy : IRequestExecutionPolicy
{
public async Task<T> Run<T>(IRestClient client, ICustomRestRequest request,
ExecuteRequestAsync<T> executeRequestAsync)
{
return (await executeRequestAsync(client)).Result;
}
public static IRequestExecutionPolicy Default { get; set; } = new DefaultRequestExecutionPolicy();
}
} | using System.Threading.Tasks;
using RestSharp.Portable;
namespace BizwebSharp.Infrastructure.RequestPolicies
{
public class DefaultRequestExecutionPolicy : IRequestExecutionPolicy
{
public async Task<T> Run<T>(IRestClient client, ICustomRestRequest request,
ExecuteRequestAsync<T> executeRequestAsync)
{
return (await executeRequestAsync(client)).Result;
}
public static IRequestExecutionPolicy Default { get; } = new DefaultRequestExecutionPolicy();
}
} | mit | C# |
4d49c1b6f01200ec2d0b08d3db53d1d27813a378 | refactor solr out as multiple search can be use | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/IAlert.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/IAlert.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
interface IAlert
{
List<UserAlert> GetUserAlertSchedules(string scheudle);
JSONRootObject GetSearchAlert(string query);
Task SendAlert(string email, string link, JSONRootObject results, object mailResponse);
bool UpdateUserSendDate(Guid userID, DateTime date);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
interface IAlert
{
List<UserAlert> GetUserAlertSchedules(string scheudle);
JSONRootObject GetSearchAlertViaSolr(string query);
Task SendAlert(string email, string link, JSONRootObject results, object mailResponse);
bool UpdateUserSendDate(Guid userID, DateTime date);
}
}
| apache-2.0 | C# |
adcac94847a3878f003165139af1fdca925332a2 | update login close loading and login view | cv13399/Mai_Project | Mai_project/Assets/MyUIManager.cs | Mai_project/Assets/MyUIManager.cs | using UnityEngine;
using System.Collections;
public class MyUIManager : MonoBehaviour
{
public UILabel loadingLabel;
public UIPanel loadingPanel;
public UIPanel loginPanel;
public UIEventListener LoginBtn;
// Use this for initialization
void Start ()
{
ButtonEventInitialize();
}
void ButtonEventInitialize()
{
LoginBtn.onClick += (GameObject g) =>
{
print("Login");
StartCoroutine(LoadingAnimation());
};
}
public IEnumerator LoadingAnimation()
{
loadingPanel.gameObject.SetActive(true);
string[] text = new string[] { "Loading", "Loading.", "Loading..", "Loading..." };
for (int i = 0; i < text.Length; i++)
{
loadingLabel.text = text[i];
yield return new WaitForSeconds(0.5f);
}
loadingPanel.gameObject.SetActive(false);
}
}
| using UnityEngine;
using System.Collections;
public class MyUIManager : MonoBehaviour
{
public UILabel loadingLabel;
public UIPanel loadingPanel;
public UIEventListener LoginBtn;
// Use this for initialization
void Start ()
{
ButtonEventInitialize();
}
void ButtonEventInitialize()
{
LoginBtn.onClick += (GameObject g) =>
{
print("Login");
};
}
public IEnumerator LoadingAnimation()
{
loadingPanel.gameObject.SetActive(true);
string[] text = new string[] { "Loading", "Loading.", "Loading..", "Loading..." };
for (int i = 0; i < text.Length; i++)
{
loadingLabel.text = text[i];
yield return new WaitForSeconds(0.5f);
}
loadingPanel.gameObject.SetActive(false);
}
}
| mit | C# |
c374f8cb7f34175b0ee7e2976d086ae18daf124a | Remove unused code | nwoolls/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner | MultiMiner.Xgminer.Api/ApiVerb.cs | MultiMiner.Xgminer.Api/ApiVerb.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer.Api
{
public static class ApiVerb
{
public const string Devs = "devs";
public const string Quit = "quit";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer.Api
{
public static class ApiVerb
{
public const string Config = "config";
public const string Devs = "devs";
public const string Quit = "quit";
}
}
| mit | C# |
5920f24c3aa63b54852bbabd7ef0f46fd1ff2460 | Refactor UsersEndpoint to inherit ApiEndpoint | TattsGroup/octokit.net,cH40z-Lord/octokit.net,ChrisMissal/octokit.net,shiftkey-tester/octokit.net,brramos/octokit.net,shiftkey-tester/octokit.net,SamTheDev/octokit.net,takumikub/octokit.net,hitesh97/octokit.net,eriawan/octokit.net,nsrnnnnn/octokit.net,devkhan/octokit.net,SamTheDev/octokit.net,geek0r/octokit.net,shana/octokit.net,SmithAndr/octokit.net,octokit/octokit.net,hahmed/octokit.net,rlugojr/octokit.net,yonglehou/octokit.net,rlugojr/octokit.net,eriawan/octokit.net,hahmed/octokit.net,chunkychode/octokit.net,alfhenrik/octokit.net,alfhenrik/octokit.net,octokit/octokit.net,kdolan/octokit.net,dlsteuer/octokit.net,M-Zuber/octokit.net,fake-organization/octokit.net,khellang/octokit.net,TattsGroup/octokit.net,chunkychode/octokit.net,magoswiat/octokit.net,mminns/octokit.net,Sarmad93/octokit.net,gdziadkiewicz/octokit.net,khellang/octokit.net,SmithAndr/octokit.net,ivandrofly/octokit.net,mminns/octokit.net,gabrielweyer/octokit.net,yonglehou/octokit.net,gdziadkiewicz/octokit.net,thedillonb/octokit.net,shana/octokit.net,M-Zuber/octokit.net,darrelmiller/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,editor-tools/octokit.net,octokit-net-test-org/octokit.net,octokit-net-test-org/octokit.net,nsnnnnrn/octokit.net,Sarmad93/octokit.net,Red-Folder/octokit.net,gabrielweyer/octokit.net,editor-tools/octokit.net,thedillonb/octokit.net,kolbasov/octokit.net,dampir/octokit.net,shiftkey/octokit.net,forki/octokit.net,michaKFromParis/octokit.net,fffej/octokit.net,SLdragon1989/octokit.net,ivandrofly/octokit.net,devkhan/octokit.net,octokit-net-test/octokit.net,shiftkey/octokit.net,naveensrinivasan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,bslliw/octokit.net,dampir/octokit.net,adamralph/octokit.net,daukantas/octokit.net | Octopi/Endpoints/UsersEndpoint.cs | Octopi/Endpoints/UsersEndpoint.cs | using System;
using System.Threading.Tasks;
using Octopi.Http;
namespace Octopi.Endpoints
{
/// <summary>
/// Supports the ability to get and update users via the GitHub API v3.
/// http://developer.github.com/v3/users/
/// </summary>
public class UsersEndpoint : ApiEndpoint<User>, IUsersEndpoint
{
static readonly Uri userEndpoint = new Uri("/user", UriKind.Relative);
public UsersEndpoint(IConnection connection) : base(connection)
{
}
/// <summary>
/// Returns a <see cref="User"/> for the specified login (username). Returns the
/// Authenticated <see cref="User"/> if no login (username) is given.
/// </summary>
/// <param name="login">Optional GitHub login (username)</param>
/// <returns>A <see cref="User"/></returns>
public async Task<User> Get(string login)
{
Ensure.ArgumentNotNullOrEmptyString(login, "login");
var endpoint = new Uri(string.Format("/users/{0}", login), UriKind.Relative);
return await Get(endpoint);
}
/// <summary>
/// Returns a <see cref="User"/> for the current authenticated user.
/// </summary>
/// <exception cref="AuthenticationException">Thrown if the client is not authenticated.</exception>
/// <returns>A <see cref="User"/></returns>
public async Task<User> Current()
{
return await Get(userEndpoint);
}
/// <summary>
/// Update the specified <see cref="UserUpdate"/>.
/// </summary>
/// <param name="user"></param>
/// <exception cref="AuthenticationException">Thrown if the client is not authenticated.</exception>
/// <returns>A <see cref="User"/></returns>
public async Task<User> Update(UserUpdate user)
{
Ensure.ArgumentNotNull(user, "user");
return await Update(userEndpoint, user);
}
}
}
| using System;
using System.Threading.Tasks;
using Octopi.Http;
namespace Octopi.Endpoints
{
/// <summary>
/// Supports the ability to get and update users via the GitHub API v3.
/// http://developer.github.com/v3/users/
/// </summary>
public class UsersEndpoint : IUsersEndpoint
{
static readonly Uri userEndpoint = new Uri("/user", UriKind.Relative);
readonly IConnection connection;
public UsersEndpoint(IConnection connection)
{
Ensure.ArgumentNotNull(connection, "client");
this.connection = connection;
}
/// <summary>
/// Returns a <see cref="User"/> for the specified login (username). Returns the
/// Authenticated <see cref="User"/> if no login (username) is given.
/// </summary>
/// <param name="login">Optional GitHub login (username)</param>
/// <returns>A <see cref="User"/></returns>
public async Task<User> Get(string login)
{
Ensure.ArgumentNotNullOrEmptyString(login, "login");
var endpoint = new Uri(string.Format("/users/{0}", login), UriKind.Relative);
var res = await connection.GetAsync<User>(endpoint);
return res.BodyAsObject;
}
/// <summary>
/// Returns a <see cref="User"/> for the current authenticated user.
/// </summary>
/// <exception cref="AuthenticationException">Thrown if the client is not authenticated.</exception>
/// <returns>A <see cref="User"/></returns>
public async Task<User> Current()
{
var res = await connection.GetAsync<User>(userEndpoint);
return res.BodyAsObject;
}
/// <summary>
/// Update the specified <see cref="UserUpdate"/>.
/// </summary>
/// <param name="user"></param>
/// <exception cref="AuthenticationException">Thrown if the client is not authenticated.</exception>
/// <returns>A <see cref="User"/></returns>
public async Task<User> Update(UserUpdate user)
{
Ensure.ArgumentNotNull(user, "user");
var res = await connection.PatchAsync<User>(userEndpoint, user);
return res.BodyAsObject;
}
}
}
| mit | C# |
54462d1cf749771167fba0efc0fbf52f13c75010 | use default value for `MaxTransactionsPerBlock` | AntShares/AntShares,shargon/neo | neo/Settings.cs | neo/Settings.cs | using Microsoft.Extensions.Configuration;
using Neo.Core;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Neo
{
internal class Settings
{
public uint Magic { get; private set; }
public byte AddressVersion { get; private set; }
public int MaxTransactionsPerBlock { get; private set; }
public string[] StandbyValidators { get; private set; }
public string[] SeedList { get; private set; }
public IReadOnlyDictionary<TransactionType, Fixed8> SystemFee { get; private set; }
public static Settings Default { get; private set; }
static Settings()
{
IConfigurationSection section = new ConfigurationBuilder().AddJsonFile("protocol.json").Build().GetSection("ProtocolConfiguration");
Default = new Settings(section);
}
public Settings(IConfigurationSection section)
{
this.Magic = uint.Parse(section.GetSection("Magic").Value);
this.AddressVersion = byte.Parse(section.GetSection("AddressVersion").Value);
this.MaxTransactionsPerBlock = GetValueOrDefault(section.GetSection("MaxTransactionsPerBlock"), 500, p => int.Parse(p));
this.StandbyValidators = section.GetSection("StandbyValidators").GetChildren().Select(p => p.Value).ToArray();
this.SeedList = section.GetSection("SeedList").GetChildren().Select(p => p.Value).ToArray();
this.SystemFee = section.GetSection("SystemFee").GetChildren().ToDictionary(p => (TransactionType)Enum.Parse(typeof(TransactionType), p.Key, true), p => Fixed8.Parse(p.Value));
}
public T GetValueOrDefault<T>(IConfigurationSection section, T defaultValue, Func<string, T> selector)
{
if (section.Value == null) return defaultValue;
return selector(section.Value);
}
}
}
| using Microsoft.Extensions.Configuration;
using Neo.Core;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Neo
{
internal class Settings
{
public uint Magic { get; private set; }
public byte AddressVersion { get; private set; }
public int MaxTransactionsPerBlock { get; private set; }
public string[] StandbyValidators { get; private set; }
public string[] SeedList { get; private set; }
public IReadOnlyDictionary<TransactionType, Fixed8> SystemFee { get; private set; }
public static Settings Default { get; private set; }
static Settings()
{
IConfigurationSection section = new ConfigurationBuilder().AddJsonFile("protocol.json").Build().GetSection("ProtocolConfiguration");
Default = new Settings
{
Magic = uint.Parse(section.GetSection("Magic").Value),
AddressVersion = byte.Parse(section.GetSection("AddressVersion").Value),
MaxTransactionsPerBlock = int.Parse(section.GetSection("MaxTransactionsPerBlock").Value),
StandbyValidators = section.GetSection("StandbyValidators").GetChildren().Select(p => p.Value).ToArray(),
SeedList = section.GetSection("SeedList").GetChildren().Select(p => p.Value).ToArray(),
SystemFee = section.GetSection("SystemFee").GetChildren().ToDictionary(p => (TransactionType)Enum.Parse(typeof(TransactionType), p.Key, true), p => Fixed8.Parse(p.Value)),
};
}
}
}
| mit | C# |
a3d7e0a35b67faae7cfba92f84a931e269acac88 | Update summary | HelloKitty/Booma.Proxy | src/Booma.Proxy.Packets.PatchServer/Payloads/Server/PatchingFileCheckRequestPayload.cs | src/Booma.Proxy.Packets.PatchServer/Payloads/Server/PatchingFileCheckRequestPayload.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Requests a file check for updating
/// </summary>
[WireDataContract]
[PatchServerPacketPayload(PatchNetworkOperationCodes.PATCH_FILE_INFO)]
public sealed class PatchingFileCheckRequestPayload : PSOBBPatchPacketPayloadServer
{
/// <summary>
/// Patch file index
/// </summary>
[WireMember(1)]
public int PatchFileIndex { get; }
/// <summary>
/// Patch file name
/// </summary>
[KnownSize(32)]
[WireMember(2)]
public string PatchFileName { get; }
public PatchingFileCheckRequestPayload(int patchFileIndex, string patchFileName)
{
if (patchFileIndex < 0) throw new ArgumentOutOfRangeException(nameof(patchFileIndex));
if (string.IsNullOrWhiteSpace(patchFileName)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(patchFileName));
if (patchFileName.Length > 32) throw new ArgumentException("File name cannot be longer than 32 characters", nameof(patchFileName));
PatchFileIndex = patchFileIndex;
PatchFileName = patchFileName;
}
//Serializer ctor
private PatchingFileCheckRequestPayload()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Sets the file we are going to update
/// </summary>
[WireDataContract]
[PatchServerPacketPayload(PatchNetworkOperationCodes.PATCH_FILE_INFO)]
public sealed class PatchingFileCheckRequestPayload : PSOBBPatchPacketPayloadServer
{
/// <summary>
/// Patch file index
/// </summary>
[WireMember(1)]
public int PatchFileIndex { get; }
/// <summary>
/// Patch file name
/// </summary>
[KnownSize(32)]
[WireMember(2)]
public string PatchFileName { get; }
public PatchingFileCheckRequestPayload(int patchFileIndex, string patchFileName)
{
if (patchFileIndex < 0) throw new ArgumentOutOfRangeException(nameof(patchFileIndex));
if (string.IsNullOrWhiteSpace(patchFileName)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(patchFileName));
if (patchFileName.Length > 32) throw new ArgumentException("File name cannot be longer than 32 characters", nameof(patchFileName));
PatchFileIndex = patchFileIndex;
PatchFileName = patchFileName;
}
//Serializer ctor
private PatchingFileCheckRequestPayload()
{
}
}
}
| agpl-3.0 | C# |
aa0c8c08247a54a5424009e00785dfc7de481b04 | add track function | GRGSIBERIA/maya-camera | MayaCamera.cs | MayaCamera.cs | using UnityEngine;
using System.Collections;
public class MayaCamera : MonoBehaviour {
public float dollySpeed = 1f;
public float tumbleSpeed = 1f;
public float trackSpeed = 1f;
Vector3 prevMousePosition;
Vector3 prevMouseSpeed;
public Vector3 mouseSpeed;
public Vector3 mouseAccel;
// Use this for initialization
void Start () {
prevMousePosition = Input.mousePosition;
mouseSpeed = Vector3.zero;
mouseAccel = Vector3.zero;
}
// Update is called once per frame
void Update () {
CalculateMousePhisics();
Tumble();
Dolly();
Track();
}
void Tumble()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(0))
{
// NbN, tumble
}
}
void Dolly()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(1))
{
// ENbN, dolly
var dollied_local = Camera.main.transform.localPosition;
dollied_local.z -= mouseSpeed.y * dollySpeed;
Camera.main.transform.localPosition = dollied_local;
}
}
void Track()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(2))
{
// NbN, track
Camera.main.transform.localPosition -= mouseSpeed;
}
}
void CalculateMousePhisics()
{
// }EX̑xxvZ
mouseSpeed = Input.mousePosition - prevMousePosition;
mouseAccel = mouseSpeed - prevMouseSpeed;
prevMouseSpeed = mouseSpeed;
prevMousePosition = Input.mousePosition;
}
}
| using UnityEngine;
using System.Collections;
public class MayaCamera : MonoBehaviour {
public float dollySpeed;
public float tumbleSpeed;
public float trackSpeed;
Vector3 prevMousePosition;
Vector3 prevMouseSpeed;
public Vector3 mouseSpeed;
public Vector3 mouseAccel;
// Use this for initialization
void Start () {
prevMousePosition = Input.mousePosition;
mouseSpeed = Vector3.zero;
mouseAccel = Vector3.zero;
}
// Update is called once per frame
void Update () {
CalculateMousePhisics();
Tumble();
Dolly();
Track();
}
void Tumble()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(0))
{
// NbN, tumble
}
}
void Dolly()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(1))
{
// ENbN, dolly
Camera.main.transform.localPosition += mouseSpeed * dollySpeed;
}
}
void Track()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(2))
{
// NbN, track
}
}
void CalculateMousePhisics()
{
// }EX̑xxvZ
mouseSpeed = Input.mousePosition - prevMousePosition;
mouseAccel = mouseSpeed - prevMouseSpeed;
prevMouseSpeed = mouseSpeed;
prevMousePosition = Input.mousePosition;
}
}
| bsd-3-clause | C# |
af2481875f0617b09922decef722d27c29bc93c6 | update to 2.0.0 | urielha/log4stash,urielha/log4stash | src/log4stash/AssemblyVersionInfo.cs | src/log4stash/AssemblyVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("2.0.0")] | using System.Reflection;
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")] | mit | C# |
751381401a1470435937b419e2dd681d78eaf595 | Make interval configurable in Scheduler | Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates | CurrencyRates.WindowsService/Scheduler.cs | CurrencyRates.WindowsService/Scheduler.cs | using CurrencyRates.Base.Service;
using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;
namespace CurrencyRates.WindowsService
{
public partial class Scheduler : ServiceBase
{
static int EventId;
readonly int Interval;
readonly Synchronizer Synchronizer;
public Scheduler(Synchronizer synchronizer, int interval = 60000)
{
Synchronizer = synchronizer;
Interval = interval;
InitializeComponent();
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry(GetType().FullName + " started.", EventLogEntryType.Information, ++EventId);
var timer = new Timer() { Interval = Interval };
timer.Elapsed += OnTimer;
timer.Start();
}
protected override void OnStop()
{
EventLog.WriteEntry(GetType().FullName + " stopped.", EventLogEntryType.Information, ++EventId);
}
void OnTimer(object sender, ElapsedEventArgs args)
{
Synchronizer.SyncAll();
EventLog.WriteEntry("Synchronized rates.", EventLogEntryType.Information, ++EventId);
}
}
}
| using CurrencyRates.Base.Service;
using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;
namespace CurrencyRates.WindowsService
{
public partial class Scheduler : ServiceBase
{
static int EventId;
readonly Synchronizer Synchronizer;
public Scheduler(Synchronizer synchronizer)
{
Synchronizer = synchronizer;
InitializeComponent();
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry(GetType().Name + " started.", EventLogEntryType.Information, ++EventId);
var timer = new Timer() { Interval = 60000 };
timer.Elapsed += OnTimer;
timer.Start();
}
protected override void OnStop()
{
EventLog.WriteEntry(GetType().Name + " stopped.", EventLogEntryType.Information, ++EventId);
}
void OnTimer(object sender, ElapsedEventArgs args)
{
Synchronizer.SyncAll();
EventLog.WriteEntry("Synchronized rates.", EventLogEntryType.Information, ++EventId);
}
}
}
| mit | C# |
b4eebdecb02ea1d2680b0240edd98eafbd2ad94b | Update PointDrawNode.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Modules/Renderer/SkiaSharp/Nodes/PointDrawNode.cs | src/Core2D/Modules/Renderer/SkiaSharp/Nodes/PointDrawNode.cs | #nullable enable
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using SkiaSharp;
using Core2D.Spatial;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class PointDrawNode : DrawNode, IPointDrawNode
{
public PointShapeViewModel Point { get; set; }
public double PointSize { get; set; }
public SKRect Rect { get; set; }
public PointDrawNode(PointShapeViewModel point, ShapeStyleViewModel? pointStyleViewModel, double pointSize)
{
Style = pointStyleViewModel;
Point = point;
PointSize = pointSize;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = true; // Point.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = true; // Point.State.HasFlag(ShapeStateFlags.Size);
var rect2 = Rect2.FromPoints(Point.X - PointSize, Point.Y - PointSize, Point.X + PointSize, Point.Y + PointSize);
Rect = SKRect.Create((float)rect2.X, (float)rect2.Y, (float)rect2.Width, (float)rect2.Height);
Center = new SKPoint(Rect.MidX, Rect.MidY);
}
public override void OnDraw(object? dc, double zoom)
{
if (dc is not SKCanvas canvas)
{
return;
}
canvas.DrawRect(Rect, Fill);
canvas.DrawRect(Rect, Stroke);
}
}
| #nullable enable
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using SkiaSharp;
using Core2D.Spatial;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class PointDrawNode : DrawNode, IPointDrawNode
{
public PointShapeViewModel Point { get; set; }
public double PointSize { get; set; }
public SKRect Rect { get; set; }
public PointDrawNode(PointShapeViewModel point, ShapeStyleViewModel? pointStyleViewModel, double pointSize)
{
Style = pointStyleViewModel;
Point = point;
PointSize = pointSize;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = true; // Point.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = true; // Point.State.HasFlag(ShapeStateFlags.Size);
var rect2 = Rect2.FromPoints(Point.X - PointSize, Point.Y - PointSize, Point.X + PointSize, Point.Y + PointSize, 0, 0);
Rect = SKRect.Create((float)rect2.X, (float)rect2.Y, (float)rect2.Width, (float)rect2.Height);
Center = new SKPoint(Rect.MidX, Rect.MidY);
}
public override void OnDraw(object dc, double zoom)
{
var canvas = dc as SKCanvas;
canvas.DrawRect(Rect, Fill);
canvas.DrawRect(Rect, Stroke);
}
}
| mit | C# |
3d0117c9db154350440072db56d488d7afd3ddae | Fix finalization warning message for Cairo.Path. | openmedicus/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp | cairo/Path.cs | cairo/Path.cs | //
// Mono.Cairo.Context.cs
//
// Author:
// Miguel de Icaza (miguel@novell.com)
//
// This is an OO wrapper API for the Cairo API.
//
// Copyright 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using Cairo;
namespace Cairo {
public class Path : IDisposable
{
internal IntPtr handle = IntPtr.Zero;
internal Path (IntPtr handle)
{
this.handle = handle;
}
~Path ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposing){
Console.Error.WriteLine ("Cairo.Path: called from finalization thread, programmer is missing a call to Dispose");
return;
}
if (handle == IntPtr.Zero)
return;
NativeMethods.cairo_path_destroy (handle);
handle = IntPtr.Zero;
}
}
}
| //
// Mono.Cairo.Context.cs
//
// Author:
// Miguel de Icaza (miguel@novell.com)
//
// This is an OO wrapper API for the Cairo API.
//
// Copyright 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using Cairo;
namespace Cairo {
public class Path : IDisposable
{
internal IntPtr handle = IntPtr.Zero;
internal Path (IntPtr handle)
{
this.handle = handle;
}
~Path ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposing){
Console.Error.WriteLine ("Cairo.Context: called from finalization thread, programmer is missing a call to Dispose");
return;
}
if (handle == IntPtr.Zero)
return;
NativeMethods.cairo_path_destroy (handle);
handle = IntPtr.Zero;
}
}
}
| lgpl-2.1 | C# |
ee3a03c58cf27ac1af34450706c0e73f1a900dbb | Update EmployerAccountsApiHttpClientFactory.cs | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Application/Services/EmployerAccountsApi/Http/EmployerAccountsApiHttpClientFactory.cs | src/SFA.DAS.EmployerApprenticeshipsService.Application/Services/EmployerAccountsApi/Http/EmployerAccountsApiHttpClientFactory.cs | using System;
using System.Net.Http;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
namespace SFA.DAS.EAS.Application.Services.EmployerAccountsApi.Http
{
public class EmployerAccountsApiHttpClientFactory : IEmployerAccountsApiHttpClientFactory
{
private readonly EmployerAccountsApiConfiguration _employerAccountsApiConfig;
public EmployerAccountsApiHttpClientFactory(EmployerAccountsApiConfiguration employerAccountsApiConfig)
{
_employerAccountsApiConfig = employerAccountsApiConfig;
}
public HttpClient CreateHttpClient()
{
var httpClient = new HttpClientBuilder()
.WithDefaultHeaders()
.WithBearerAuthorisationHeader(new AzureActiveDirectoryBearerTokenGenerator(_employerAccountsApiConfig))
.Build();
httpClient.BaseAddress = new Uri(_employerAccountsApiConfig.BaseUrl);
httpClient.Timeout = TimeSpan.Parse(_employerAccountsApiConfig.TimeoutTimeSpan);
return httpClient;
}
}
}
| using System;
using System.Net.Http;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
namespace SFA.DAS.EAS.Application.Services.EmployerAccountsApi.Http
{
public class EmployerAccountsApiHttpClientFactory : IEmployerAccountsApiHttpClientFactory
{
private readonly EmployerAccountsApiConfiguration _employerAccountsApiConfig;
public EmployerAccountsApiHttpClientFactory(EmployerAccountsApiConfiguration employerAccountsApiConfig)
{
_employerAccountsApiConfig = employerAccountsApiConfig;
}
public HttpClient CreateHttpClient()
{
var httpClient = new HttpClientBuilder()
.WithDefaultHeaders()
//.WithBearerAuthorisationHeader(new AzureActiveDirectoryBearerTokenGenerator(_employerAccountsApiConfig))
.Build();
httpClient.BaseAddress = new Uri(_employerAccountsApiConfig.BaseUrl);
httpClient.Timeout = TimeSpan.Parse(_employerAccountsApiConfig.TimeoutTimeSpan);
return httpClient;
}
}
}
| mit | C# |
b1f52a92fcd825a4a2b2f25319c19633bfb29204 | reset AssemblyVersion to 1.0.0.0 | nataren/NServiceKit.Redis,MindTouch/NServiceKit.Redis,NServiceKit/NServiceKit.Redis | src/ServiceStack.Redis/Properties/AssemblyInfo.cs | src/ServiceStack.Redis/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("ServiceStack.Redis")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServiceStack.Redis")]
[assembly: AssemblyCopyright("Copyright © ServiceStack 2013")]
[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("70a33fa7-9f81-418d-bb25-6a4be6648ae4")]
// 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("3.9.60.0")]
[assembly: InternalsVisibleTo("ServiceStack.Redis.Tests")]
| 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("ServiceStack.Redis")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServiceStack.Redis")]
[assembly: AssemblyCopyright("Copyright © ServiceStack 2013")]
[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("70a33fa7-9f81-418d-bb25-6a4be6648ae4")]
// 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("3.9.60.0")]
//[assembly: AssemblyFileVersion("3.9.60.0")]
[assembly: InternalsVisibleTo("ServiceStack.Redis.Tests")]
| bsd-3-clause | C# |
1cc4fd3c20a1b6100b5436f5d08abc5b7395d425 | Update Palindrome-Checker.cs | DeanCabral/Code-Snippets | Console/Palindrome-Checker.cs | Console/Palindrome-Checker.cs | class Palindrome
{
static void Main(string[] args)
{
GetUserInput();
}
static void GetUserInput()
{
string input = "";
string output = "";
Console.Write("Enter a word: ");
input = Console.ReadLine();
input = input.ToLower();
output = Palindrome.IsPalindrome(input) ? "This word is a Palindrome. True." : "This word is not a Palindrome. False.";
Console.WriteLine(output);
Console.WriteLine();
GetUserInput();
}
static bool IsPalindrome(string word)
{
List<char> characters = new List<char>();
int count = 0;
foreach (char c in word)
{
characters.Add(c);
}
for (int i = 0; i < characters.Count; i++)
{
if (characters[i] == characters[(characters.Count - 1) - i]) count++;
}
return word.Length == count;
}
}
| class Palindrome
{
static void Main(string[] args)
{
GetUserInput();
}
static void GetUserInput()
{
string input = "";
string output = "";
Console.Write("Enter a word: ");
input = Console.ReadLine();
output = Palindrome.IsPalindrome(input) ? "This word is a Palindrome. True." : "This word is not a Palindrome. False.";
Console.WriteLine(output);
Console.WriteLine();
GetUserInput();
}
static bool IsPalindrome(string word)
{
List<char> characters = new List<char>();
int count = 0;
foreach (char c in word)
{
characters.Add(c);
}
for (int i = 0; i < characters.Count; i++)
{
if (characters[i] == characters[(characters.Count - 1) - i]) count++;
}
return word.Length == count;
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.