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 |
|---|---|---|---|---|---|---|---|---|
40084c5e39cddbd5adb310e839bc52d7e6d69d23 | Fix indentation | realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet | Tests/WeaverTests/Realm.FakeForWeaverTests/RealmObject.cs | Tests/WeaverTests/Realm.FakeForWeaverTests/RealmObject.cs | /* Copyright 2015 Realm Inc - All Rights Reserved
* Proprietary and Confidential
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Realms
{
public class RealmObject
{
public List<string> LogList = new List<string>();
public void LogString(string s)
{
LogList.Add(s);
}
public void LogCall(string parameters = "", [CallerMemberName] string caller = "")
{
var stackTrace = new StackTrace(1, false);
var type = stackTrace.GetFrame(0).GetMethod().DeclaringType;
LogString(type.Name + "." + caller + "(" + parameters + ")");
}
protected T GetValue<T>(string propertyName)
{
LogCall($"{nameof(propertyName)} = \"{propertyName}\"");
return default(T);
}
protected void SetValue<T>(string propertyName, T value)
{
LogCall($"{nameof(propertyName)} = \"{propertyName}\", {nameof(value)} = {value}");
}
}
}
| /* Copyright 2015 Realm Inc - All Rights Reserved
* Proprietary and Confidential
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Realms
{
public class RealmObject
{
public List<string> LogList = new List<string>();
public void LogString(string s)
{
LogList.Add(s);
}
public void LogCall(string parameters = "", [CallerMemberName] string caller = "")
{
var stackTrace = new StackTrace(1, false);
var type = stackTrace.GetFrame(0).GetMethod().DeclaringType;
LogString(type.Name + "." + caller + "(" + parameters + ")");
}
protected T GetValue<T>(string propertyName)
{
LogCall($"{nameof(propertyName)} = \"{propertyName}\"");
return default(T);
}
protected void SetValue<T>(string propertyName, T value)
{
LogCall($"{nameof(propertyName)} = \"{propertyName}\", {nameof(value)} = {value}");
}
}
}
| apache-2.0 | C# |
aa1e71579bf28ef38f8c205ff67ab93adf4b8992 | fix for non-3dtouch devices | mopsicus/unity-ios-3dtouch-fix | FixiOS3DTouch.cs | FixiOS3DTouch.cs | using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Collections;
using System.IO;
using UnityEditor.iOS.Xcode;
using System.Collections.Generic;
public class iOSPostBuildProcess {
[PostProcessBuild]
public static void iOSPostProcess(BuildTarget buildTarget, string pathToBuiltProject) {
if (buildTarget == BuildTarget.iOS) {
Fix3DTouchDelay (pathToBuiltProject);
}
}
private static void Fix3DTouchDelay (string pathToBuiltProject) {
string targetString = "[self onUpdateSurfaceSize:frame.size];";
string targetString2 = "- (void)touchesBegan";
string targetString3 = "@interface UnityView : UnityRenderingView";
string filePath = Path.Combine(pathToBuiltProject, "Classes");
filePath = Path.Combine(filePath, "UI");
filePath = Path.Combine(filePath, "UnityView.mm");
if (File.Exists(filePath)) {
string classFile = File.ReadAllText(filePath);
string newClassFile = classFile.Replace (targetString, "[self onUpdateSurfaceSize:frame.size];\n\rUILongPressGestureRecognizer *longPR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:NULL];\nlongPR.delaysTouchesBegan = false;\nlongPR.minimumPressDuration = 0;\nlongPR.delegate = self;\n[self addGestureRecognizer:longPR];");
newClassFile = newClassFile.Replace (targetString2, "- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {\nif ([[self traitCollection] forceTouchCapability] == UIForceTouchCapabilityAvailable) {\nCGPoint point= [touch locationInView:touch.view];\nif (point.x < 35) {\nNSSet *set = [NSSet setWithObjects:touch, nil];\nUnitySendTouchesBegin(set, NULL);\n}\n}\n}\n\r- (void)touchesBegan");
if (classFile.Length != newClassFile.Length) {
File.WriteAllText(filePath, newClassFile);
Debug.Log("Fix3DTouchDelay succeeded for file: " + filePath);
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- Target string not found: \"" + targetString + "\"");
}
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- File not found: " + filePath);
}
filePath = Path.Combine(pathToBuiltProject, "Classes");
filePath = Path.Combine(filePath, "UI");
filePath = Path.Combine(filePath, "UnityView.h");
if (File.Exists(filePath)) {
string classFile = File.ReadAllText(filePath);
string newClassFile = classFile.Replace (targetString3, "@interface UnityView : UnityRenderingView <UIGestureRecognizerDelegate>");
if (classFile.Length != newClassFile.Length) {
File.WriteAllText(filePath, newClassFile);
Debug.Log("Fix3DTouchDelay succeeded for file: " + filePath);
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- Target string not found: \"" + targetString3 + "\"");
}
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- File not found: " + filePath);
}
}
}
| using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Collections;
using System.IO;
using UnityEditor.iOS.Xcode;
using System.Collections.Generic;
public class iOSPostBuildProcess {
[PostProcessBuild]
public static void iOSPostProcess(BuildTarget buildTarget, string pathToBuiltProject) {
if (buildTarget == BuildTarget.iOS) {
Fix3DTouchDelay (pathToBuiltProject);
}
}
private static void Fix3DTouchDelay (string pathToBuiltProject) {
string targetString = "[self onUpdateSurfaceSize:frame.size];";
string targetString2 = "- (void)touchesBegan";
string targetString3 = "@interface UnityView : UnityRenderingView";
string filePath = Path.Combine(pathToBuiltProject, "Classes");
filePath = Path.Combine(filePath, "UI");
filePath = Path.Combine(filePath, "UnityView.mm");
if (File.Exists(filePath)) {
string classFile = File.ReadAllText(filePath);
string newClassFile = classFile.Replace (targetString, "[self onUpdateSurfaceSize:frame.size];\n\rUILongPressGestureRecognizer *longPR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:NULL];\nlongPR.delaysTouchesBegan = false;\nlongPR.minimumPressDuration = 0;\nlongPR.delegate = self;\n[self addGestureRecognizer:longPR];");
newClassFile = newClassFile.Replace (targetString2, "- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {\nCGPoint point= [touch locationInView:touch.view];\nif (point.x < 35) {\nNSSet *set = [NSSet setWithObjects:touch, nil];\nUnitySendTouchesBegin(set, NULL);\n}\n}\n\r- (void)touchesBegan");
if (classFile.Length != newClassFile.Length) {
File.WriteAllText(filePath, newClassFile);
Debug.Log("Fix3DTouchDelay succeeded for file: " + filePath);
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- Target string not found: \"" + targetString + "\"");
}
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- File not found: " + filePath);
}
filePath = Path.Combine(pathToBuiltProject, "Classes");
filePath = Path.Combine(filePath, "UI");
filePath = Path.Combine(filePath, "UnityView.h");
if (File.Exists(filePath)) {
string classFile = File.ReadAllText(filePath);
string newClassFile = classFile.Replace (targetString3, "@interface UnityView : UnityRenderingView <UIGestureRecognizerDelegate>");
if (classFile.Length != newClassFile.Length) {
File.WriteAllText(filePath, newClassFile);
Debug.Log("Fix3DTouchDelay succeeded for file: " + filePath);
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- Target string not found: \"" + targetString3 + "\"");
}
} else {
Debug.LogWarning("Fix3DTouchDelay FAILED -- File not found: " + filePath);
}
}
} | mit | C# |
77d04fb6d1bf05cb58aaf1a4f664f475c8d4069c | raise events for coin filtering properties. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Controls/WalletExplorer/CoinViewModel.cs | WalletWasabi.Gui/Controls/WalletExplorer/CoinViewModel.cs | using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Gui.ViewModels;
using ReactiveUI;
using WalletWasabi.Models;
using NBitcoin;
using System.Reactive.Linq;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class CoinViewModel : ViewModelBase
{
private bool _isSelected;
private int _privacyLevel;
private string _history;
public CoinViewModel(SmartCoin model)
{
Model = model;
model.WhenAnyValue(x => x.Confirmed).ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
{
this.RaisePropertyChanged(nameof(Confirmed));
});
model.WhenAnyValue(x => x.SpentOrCoinJoinInProcess).ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
{
this.RaisePropertyChanged(nameof(SpentOrCoinJoinInProcess));
});
model.WhenAnyValue(x => x.CoinJoinInProcess).ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
{
this.RaisePropertyChanged(nameof(CoinJoinInProgress));
});
}
public SmartCoin Model { get; }
public bool Confirmed => Model.Confirmed;
public bool CoinJoinInProgress => Model.CoinJoinInProcess;
public bool SpentOrCoinJoinInProcess => Model.SpentOrCoinJoinInProcess;
public int Confirmations => Global.IndexDownloader.BestHeight.Value - Model.Height.Value;
public bool IsSelected
{
get { return _isSelected; }
set { this.RaiseAndSetIfChanged(ref _isSelected, value); }
}
public Money Amount => Model.Amount;
public string AmountBtc => Model.Amount.ToString(false, true);
public string Label => Model.Label;
public int Height => Model.Height;
public int PrivacyLevel
{
get { return _privacyLevel; }
set { this.RaiseAndSetIfChanged(ref _privacyLevel, value); }
}
public string TransactionId => Model.TransactionId.ToString();
public uint OutputIndex => Model.Index;
public int AnonymitySet => Model.AnonymitySet;
public string InCoinJoin => Model.CoinJoinInProcess ? "Yes" : "No";
public string History
{
get { return _history; }
set { this.RaiseAndSetIfChanged(ref _history, value); }
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Gui.ViewModels;
using ReactiveUI;
using WalletWasabi.Models;
using NBitcoin;
using System.Reactive.Linq;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class CoinViewModel : ViewModelBase
{
private bool _isSelected;
private int _privacyLevel;
private string _history;
public CoinViewModel(SmartCoin model)
{
Model = model;
model.WhenAnyValue(x => x.Confirmed).ObserveOn(RxApp.MainThreadScheduler).Subscribe(confirmed =>
{
this.RaisePropertyChanged(nameof(Confirmed));
});
}
public SmartCoin Model { get; }
public bool Confirmed => Model.Confirmed;
public int Confirmations => Global.IndexDownloader.BestHeight.Value - Model.Height.Value;
public bool IsSelected
{
get { return _isSelected; }
set { this.RaiseAndSetIfChanged(ref _isSelected, value); }
}
public Money Amount => Model.Amount;
public string AmountBtc => Model.Amount.ToString(false, true);
public string Label => Model.Label;
public int Height => Model.Height;
public int PrivacyLevel
{
get { return _privacyLevel; }
set { this.RaiseAndSetIfChanged(ref _privacyLevel, value); }
}
public string TransactionId => Model.TransactionId.ToString();
public uint OutputIndex => Model.Index;
public int AnonymitySet => Model.AnonymitySet;
public string InCoinJoin => Model.CoinJoinInProcess ? "Yes" : "No";
public string History
{
get { return _history; }
set { this.RaiseAndSetIfChanged(ref _history, value); }
}
}
}
| mit | C# |
31cc47c4bbde1910115cc650350d555c474e79fe | Correct variable name. | icedream/gmadsharp | src/addoncreator/Addon/MinifiedLuaAddonFileInfo.cs | src/addoncreator/Addon/MinifiedLuaAddonFileInfo.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace GarrysMod.AddonCreator.Addon
{
/// <summary>
/// Wrapper around another file info for optimizing Lua files.
/// </summary>
public class MinifiedLuaAddonFileInfo : AddonFileInfo
{
private readonly AddonFileInfo _fi;
private byte[] _content;
private readonly string _stripCommentsRegex = string.Join("|", new[]
{
// block comments
@"\/\*.*?\*\/",
@"\-\-\[\[.*?\]\]",
// line comments
@"//([^\r\n]*?)(?<linebreak>[\r\n]+)",
@"\-\-([^\r\n]*?)(?<linebreak>[\r\n]+)",
// Unnecessary whitespace
@"^[\s]*$",
@"[\s]*$",
@"^[\s]*"
});
private string _luaCode;
public MinifiedLuaAddonFileInfo(AddonFileInfo actual)
{
_fi = actual;
}
public override byte[] GetContents()
{
if (_content != null)
return _content;
_luaCode = Encoding.UTF8.GetString(_fi.GetContents());
string oldLuaCode;
do
{
oldLuaCode = _luaCode;
_luaCode = Regex.Replace(_luaCode, _stripCommentsRegex,
m => m.Groups["linebreak"] != null ? m.Groups["linebreak"].Value : "", RegexOptions.Multiline | RegexOptions.Singleline);
_luaCode = _luaCode.Trim();
} while (oldLuaCode != _luaCode);
_content = Encoding.UTF8.GetBytes(_luaCode);
return _content;
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace GarrysMod.AddonCreator.Addon
{
/// <summary>
/// Wrapper around another file info for optimizing Lua files.
/// </summary>
public class MinifiedLuaAddonFileInfo : AddonFileInfo
{
private readonly AddonFileInfo _fi;
private byte[] _content;
private readonly string _stripCommentsRegex = string.Join("|", new[]
{
// block comments
@"\/\*.*?\*\/",
@"\-\-\[\[.*?\]\]",
// line comments
@"//([^\r\n]*?)(?<linebreak>[\r\n]+)",
@"\-\-([^\r\n]*?)(?<linebreak>[\r\n]+)",
// Unnecessary whitespace
@"^[\s]*$",
@"[\s]*$",
@"^[\s]*"
});
private string _luaCode;
public MinifiedLuaAddonFileInfo(AddonFileInfo actual)
{
_fi = actual;
}
public override byte[] GetContents()
{
if (_content != null)
return _content;
_luaCode = Encoding.UTF8.GetString(_fi.GetContents());
string _oldLuaCode;
do
{
_oldLuaCode = _luaCode;
_luaCode = Regex.Replace(_luaCode, _stripCommentsRegex,
m => m.Groups["linebreak"] != null ? m.Groups["linebreak"].Value : "", RegexOptions.Multiline | RegexOptions.Singleline);
_luaCode = _luaCode.Trim();
} while (_oldLuaCode != _luaCode);
_content = Encoding.UTF8.GetBytes(_luaCode);
return _content;
}
}
} | mit | C# |
b0bf8e0782fcefecc6c245fd09d8c7660a1a64b2 | remove unused parameter | Wox-launcher/Wox,Wox-launcher/Wox,qianlifeng/Wox,qianlifeng/Wox,qianlifeng/Wox | Wox.Infrastructure/Constant.cs | Wox.Infrastructure/Constant.cs | using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
namespace Wox.Infrastructure
{
public static class Constant
{
public const string Wox = "Wox";
public const string Plugins = "Plugins";
private static Assembly Assembly;
public static string ProgramDirectory;
public static string ExecutablePath;
public static string ApplicationDirectory;
public static string RootDirectory;
public static string PreinstalledDirectory;
public const string Issue = "https://github.com/Wox-launcher/Wox/issues/new";
public static string Version;
public static readonly int ThumbnailSize = 64;
public static string ImagesDirectory;
public static string DefaultIcon;
public static string ErrorIcon;
public static string PythonPath;
public static string EverythingSDKPath;
public static void Initialize()
{
Assembly = Assembly.GetExecutingAssembly();
Version = FileVersionInfo.GetVersionInfo(Assembly.Location.NonNull()).ProductVersion;
ProgramDirectory = Directory.GetParent(Assembly.Location.NonNull()).ToString();
ApplicationDirectory = Directory.GetParent(ProgramDirectory).ToString();
RootDirectory = Directory.GetParent(ApplicationDirectory).ToString();
ExecutablePath = Path.Combine(ProgramDirectory, Wox + ".exe");
ImagesDirectory = Path.Combine(ProgramDirectory, "Images");
PreinstalledDirectory = Path.Combine(ProgramDirectory, Plugins);
DefaultIcon = Path.Combine(ImagesDirectory, "app.png");
ErrorIcon = Path.Combine(ImagesDirectory, "app_error.png");
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
namespace Wox.Infrastructure
{
public static class Constant
{
public const string Wox = "Wox";
public const string Plugins = "Plugins";
private static Assembly Assembly;
public static string ProgramDirectory;
public static string ExecutablePath;
public static string ApplicationDirectory;
public static string RootDirectory;
public static string PreinstalledDirectory;
public const string Issue = "https://github.com/Wox-launcher/Wox/issues/new";
public static string Version;
public static readonly int ThumbnailSize = 64;
public static string ImagesDirectory;
public static string DefaultIcon;
public static string ErrorIcon;
public static string PythonPath;
public static string EverythingSDKPath;
public static void Initialize(string workingDirectory = "")
{
Assembly = Assembly.GetExecutingAssembly();
Version = FileVersionInfo.GetVersionInfo(Assembly.Location.NonNull()).ProductVersion;
if (String.IsNullOrEmpty(workingDirectory))
{
ProgramDirectory = Directory.GetParent(Assembly.Location.NonNull()).ToString();
}
else
{
ProgramDirectory = workingDirectory;
}
ApplicationDirectory = Directory.GetParent(ProgramDirectory).ToString();
RootDirectory = Directory.GetParent(ApplicationDirectory).ToString();
ExecutablePath = Path.Combine(ProgramDirectory, Wox + ".exe");
ImagesDirectory = Path.Combine(ProgramDirectory, "Images");
PreinstalledDirectory = Path.Combine(ProgramDirectory, Plugins);
DefaultIcon = Path.Combine(ImagesDirectory, "app.png");
ErrorIcon = Path.Combine(ImagesDirectory, "app_error.png");
}
}
}
| mit | C# |
2c1eec8681ebf49fa9d721175a35b9fa70b6d149 | support HipChat notify and message_format options | mvbalaw/MvbaCore.ThirdParty,mvbalaw/MvbaCore.ThirdParty,mvbalaw/MvbaCore.ThirdParty | src/MvbaCore.ThirdParty/HipChatNotificationService.cs | src/MvbaCore.ThirdParty/HipChatNotificationService.cs | // * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **************************************************************************
using System;
using System.Web;
using MvbaCore.Extensions;
using MvbaCore.ThirdParty.Json;
namespace MvbaCore.ThirdParty
{
public interface IHipChatNotificationService
{
Notification<HipChatResult> Notify(HipChatMessage hipChatMessage);
}
public class HipChatNotificationService : IHipChatNotificationService
{
private const string ApiUrl = "http://api.hipchat.com/v1/rooms/message?auth_token={0}&format=json";
public HipChatNotificationService(IWebServiceClient webServiceClient)
{
_webServiceClient = webServiceClient;
}
private readonly IWebServiceClient _webServiceClient;
public Notification<HipChatResult> Notify(HipChatMessage hipChatMessage)
{
try
{
var content = "room_id=" + HttpUtility.UrlEncode(hipChatMessage.RoomId)
+ "&from=" + HttpUtility.UrlEncode(hipChatMessage.From)
+ "&message=" + HttpUtility.UrlEncode(hipChatMessage.Message)
+ "&color=" + hipChatMessage.Color.OrDefault().Key
+ "&message_format=" + hipChatMessage.MessageFormat.OrDefault().Key
+ "¬ify=" + (hipChatMessage.Notify ? 1 : 0);
var result = _webServiceClient.Post(String.Format(ApiUrl, hipChatMessage.ApiKey), content, "application/x-www-form-urlencoded");
return JsonUtility.Deserialize<HipChatResult>(result);
}
catch (Exception exception)
{
return new Notification<HipChatResult>(Notification.ErrorFor(exception.ToString()));
}
}
}
public class HipChatResult
{
public string status;
}
public class HipChatTextColor : NamedConstant<HipChatTextColor>
{
private HipChatTextColor(string key)
{
base.Add(key, this);
}
[DefaultKey]
public static readonly HipChatTextColor Gray = new HipChatTextColor("gray");
public static readonly HipChatTextColor Green = new HipChatTextColor("green");
public static readonly HipChatTextColor Purple = new HipChatTextColor("purple");
public static readonly HipChatTextColor Red = new HipChatTextColor("red");
public static readonly HipChatTextColor Yellow = new HipChatTextColor("yellow");
}
public class HipChatMessageFormat : NamedConstant<HipChatMessageFormat>
{
private HipChatMessageFormat(string key)
{
base.Add(key, this);
}
[DefaultKey]
public static readonly HipChatMessageFormat Html = new HipChatMessageFormat("html");
public static readonly HipChatMessageFormat Text = new HipChatMessageFormat("text");
}
public class HipChatMessage
{
public HipChatTextColor Color { get; set; }
public string From { get; set; }
public string Message { get; set; }
public HipChatMessageFormat MessageFormat { get; set; }
public string RoomId { get; set; }
public string ApiKey { get; set; }
public bool Notify { get; set; }
}
} | // * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **************************************************************************
using System;
using System.Web;
using MvbaCore.Extensions;
using MvbaCore.ThirdParty.Json;
namespace MvbaCore.ThirdParty
{
public interface IHipChatNotificationService
{
Notification<HipChatResult> Notify(HipChatMessage hipChatMessage);
}
public class HipChatNotificationService : IHipChatNotificationService
{
private const string ApiUrl = "http://api.hipchat.com/v1/rooms/message?auth_token={0}&format=json";
public HipChatNotificationService(IWebServiceClient webServiceClient)
{
_webServiceClient = webServiceClient;
}
private readonly IWebServiceClient _webServiceClient;
public Notification<HipChatResult> Notify(HipChatMessage hipChatMessage)
{
try
{
var content = "room_id=" + HttpUtility.UrlEncode(hipChatMessage.RoomId)
+ "&from=" + HttpUtility.UrlEncode(hipChatMessage.From)
+ "&message=" + HttpUtility.UrlEncode(hipChatMessage.Message)
+ "&color=" + hipChatMessage.Color.OrDefault().Key;
var result = _webServiceClient.Post(String.Format(ApiUrl, hipChatMessage.ApiKey), content, "application/x-www-form-urlencoded");
return JsonUtility.Deserialize<HipChatResult>(result);
}
catch (Exception exception)
{
return new Notification<HipChatResult>(Notification.ErrorFor(exception.ToString()));
}
}
}
public class HipChatResult
{
public string status;
}
public class HipChatTextColor : NamedConstant<HipChatTextColor>
{
private HipChatTextColor(string key)
{
base.Add(key, this);
}
[DefaultKey]
public static readonly HipChatTextColor Gray = new HipChatTextColor("gray");
public static readonly HipChatTextColor Green = new HipChatTextColor("green");
public static readonly HipChatTextColor Purple = new HipChatTextColor("purple");
public static readonly HipChatTextColor Red = new HipChatTextColor("red");
public static readonly HipChatTextColor Yellow = new HipChatTextColor("yellow");
}
public class HipChatMessage
{
public HipChatTextColor Color { get; set; }
public string From { get; set; }
public string Message { get; set; }
public string RoomId { get; set; }
public string ApiKey { get; set; }
}
} | mit | C# |
dfc45fc3f5491dffa00b9c0ba3fcfa98dbbe8396 | Update messages | PioneerCode/pioneer-blog,PioneerCode/pioneer-blog,PioneerCode/pioneer-blog,PioneerCode/pioneer-blog | src/Pioneer.Blog/Controllers/Web/ContactController.cs | src/Pioneer.Blog/Controllers/Web/ContactController.cs | using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Pioneer.Blog.Model;
using Pioneer.Blog.Model.Views;
using Pioneer.Blog.Service;
namespace Pioneer.Blog.Controllers.Web
{
/// <summary>
///
/// </summary>
public class ContactController : Controller
{
private readonly ICommunicationService _communicationService;
public ContactController(ICommunicationService communicationService)
{
_communicationService = communicationService;
}
/// <summary>
/// GET: Contact
/// </summary>
public IActionResult Index()
{
ViewBag.Description = "Contact Chad Ramos at Pioneer Code. .NET, C#, The Web, Open Source, Programming and more.";
ViewBag.IsValid = true;
ViewBag.Selected = "contact";
return View();
}
// POST: /Contact/send
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Send(ContactViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
ViewBag.IsValid = false;
return View("~/Views/Contact/Index.cshtml");
}
var response = _communicationService.SendContactEmailNotification(model);
ViewBag.IsValid = true;
ViewBag.Selected = "contact";
switch (response.Status)
{
case OperationStatus.Ok:
ViewBag.MessageSent = true;
break;
case OperationStatus.Error:
ViewBag.IsValid = false;
ModelState.AddModelError("", "Sorry, our email servers are acting funny. For the time being, you can send us an email directly using the address located to your left.");
break;
}
return View("~/Views/Contact/Index.cshtml");
}
}
} | using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Pioneer.Blog.Model;
using Pioneer.Blog.Model.Views;
using Pioneer.Blog.Service;
namespace Pioneer.Blog.Controllers.Web
{
/// <summary>
///
/// </summary>
public class ContactController : Controller
{
private readonly ICommunicationService _communicationService;
public ContactController(ICommunicationService communicationService)
{
_communicationService = communicationService;
}
/// <summary>
/// GET: Contact
/// </summary>
public IActionResult Index()
{
ViewBag.Description = "Contact Chad Ramos at Pioneer Code. .NET, C#, The Web, Open Source, Programming and more.";
ViewBag.IsValid = true;
ViewBag.Selected = "contact";
return View();
}
// POST: /Contact/send
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Send(ContactViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
ViewBag.IsValid = false;
return View("~/Views/Contact/Index.cshtml");
}
var response = _communicationService.SendContactEmailNotification(model);
ViewBag.IsValid = true;
ViewBag.Selected = "contact";
switch (response.Status)
{
case OperationStatus.Ok:
ViewBag.MessageSent = true;
break;
case OperationStatus.Error:
ViewBag.IsValid = false;
ModelState.AddModelError("", "Sorry, we had an issue with sending your email. Please try again later. ");
break;
}
return View("~/Views/Contact/Index.cshtml");
}
}
} | mit | C# |
19926fc0770b359de9ec6613182c5448a9713cf4 | Make sure Open and Close only executes once | ghkim69/win-beacon,huysentruitw/win-beacon | src/WinBeacon.Stack/Transports/LibUsb/LibUsbDevice.cs | src/WinBeacon.Stack/Transports/LibUsb/LibUsbDevice.cs | /*
* Copyright 2015 Huysentruit Wouter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.ObjectModel;
using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
namespace WinBeacon.Stack.Transports.LibUsb
{
/// <summary>
/// LibUsbDotNet.UsbDevice wrapper that implements ILibUsbDevice.
/// </summary>
internal class LibUsbDevice : ILibUsbDevice
{
private UsbDevice usbDevice;
public int Vid { get; private set; }
public int Pid { get; private set; }
public LibUsbDevice(int vid, int pid)
{
Vid = vid;
Pid = pid;
}
public void Open()
{
if (usbDevice != null)
return;
usbDevice = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(Vid, Pid));
}
public void Close()
{
if (usbDevice == null)
return;
usbDevice.Close();
usbDevice = null;
}
public ReadOnlyCollection<UsbConfigInfo> Configs
{
get { return usbDevice.Configs; }
}
public UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID)
{
return usbDevice.OpenEndpointReader(readEndpointID);
}
public UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID)
{
return usbDevice.OpenEndpointWriter(writeEndpointID);
}
public bool ControlTransfer(ref UsbSetupPacket setupPacket, object buffer, int bufferLength, out int lengthTransferred)
{
return usbDevice.ControlTransfer(ref setupPacket, buffer, bufferLength, out lengthTransferred);
}
}
}
| /*
* Copyright 2015 Huysentruit Wouter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.ObjectModel;
using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
namespace WinBeacon.Stack.Transports.LibUsb
{
/// <summary>
/// LibUsbDotNet.UsbDevice wrapper that implements ILibUsbDevice.
/// </summary>
internal class LibUsbDevice : ILibUsbDevice
{
private UsbDevice usbDevice;
public int Vid { get; private set; }
public int Pid { get; private set; }
public LibUsbDevice(int vid, int pid)
{
Vid = vid;
Pid = pid;
}
public void Open()
{
usbDevice = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(Vid, Pid));
}
public void Close()
{
usbDevice.Close();
}
public ReadOnlyCollection<UsbConfigInfo> Configs
{
get { return usbDevice.Configs; }
}
public UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID)
{
return usbDevice.OpenEndpointReader(readEndpointID);
}
public UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID)
{
return usbDevice.OpenEndpointWriter(writeEndpointID);
}
public bool ControlTransfer(ref UsbSetupPacket setupPacket, object buffer, int bufferLength, out int lengthTransferred)
{
return usbDevice.ControlTransfer(ref setupPacket, buffer, bufferLength, out lengthTransferred);
}
}
}
| mit | C# |
718e62a9a28af7f5185bc7e363d32e92e735878a | Remove appveyor safety guard | Abc-Arbitrage/zerio | build/scripts/utilities.cake | build/scripts/utilities.cake | #tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
_versionContext.Git = GitVersion();
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
} | #tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
_versionContext.Git = GitVersion();
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
// if(!AppVeyor.IsRunningOnAppVeyor)
// {
// Information("Not running under AppVeyor");
// return;
// }
Information("Running under AppVeyor");
Information("Updating AppVeyor build version to " + VersionContext.BuildVersion);
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
} | mit | C# |
d7ff6103dbd90e0d5c720dd853ece24dd23db710 | Update api to match new URL | CareerHub/.NET-CareerHub-API-Client,CareerHub/.NET-CareerHub-API-Client | Client/API/Integrations/Workflows/WorkflowProgressApi.cs | Client/API/Integrations/Workflows/WorkflowProgressApi.cs | using CareerHub.Client.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CareerHub.Client.API.Integrations.Workflows {
internal class WorkflowProgressApi : IWorkflowProgressApi {
private const string ApiBase = "api/integrations/v1/workflows";
private readonly OAuthHttpClient client = null;
public WorkflowProgressApi(string baseUrl, string accessToken) {
client = new OAuthHttpClient(baseUrl, ApiBase, accessToken);
}
public Task<IEnumerable<ProgressModel>> Get(int workflowId) {
string resource = GetResource(workflowId);
return client.GetResource<IEnumerable<ProgressModel>>(resource);
}
private string GetResource(int workflowId, string resource = "") {
return String.Format("{0}/progress/{1}", workflowId, resource);
}
}
}
| using CareerHub.Client.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CareerHub.Client.API.Integrations.Workflows {
internal class WorkflowProgressApi : IWorkflowProgressApi {
private const string ApiBase = "api/integrations/v1/workflows/progress";
private readonly OAuthHttpClient client = null;
public WorkflowProgressApi(string baseUrl, string accessToken) {
client = new OAuthHttpClient(baseUrl, ApiBase, accessToken);
}
public Task<IEnumerable<ProgressModel>> Get(int id) {
return client.GetResource<IEnumerable<ProgressModel>>(id.ToString());
}
}
}
| mit | C# |
689cad375040993f1211606c9ebec3161bbd023b | Update BarcodeCustomSize.cs | aspose-barcode/Aspose.BarCode-for-.NET,asposebarcode/Aspose_BarCode_NET,aspose-barcode/Aspose.BarCode-for-.NET,aspose-barcode/Aspose.BarCode-for-.NET,asposebarcode/Aspose_BarCode_NET,asposebarcode/Aspose_BarCode_NET | Examples/CSharp/ManageBarcodeImages/BarcodeCustomSize.cs | Examples/CSharp/ManageBarcodeImages/BarcodeCustomSize.cs | using Aspose.BarCode.Generation;
/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/
namespace Aspose.BarCode.Examples.CSharp.ManageBarCodeImages
{
class BarcodeCustomSize
{
public static void Run()
{
// ExStart:BarcodeCustomSize
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ManageBarCodesImages();
// Instantiate barcode object and set CodeText & Barcode Symbology
BarCodeGenerator generator = new BarCodeGenerator(EncodeTypes.Code39Standard, "1234567890")
{
AutoSizeMode = AutoSizeMode.Nearest
};
generator.BarCodeHeight.Millimeters = 50;
generator.BarCodeWidth.Millimeters = 120;
generator.Save(dataDir + "barcode-custom-size_out.jpg");
// ExEnd:BarcodeCustomSize
}
}
}
| using Aspose.BarCode.Generation;
/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/
namespace Aspose.BarCode.Examples.CSharp.ManageBarCodeImages
{
class BarcodeCustomSize
{
public static void Run()
{
// ExStart:BarcodeCustomSize
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ManageBarCodesImages();
// Instantiate barcode object and set CodeText & Barcode Symbology
BarCodeGenerator generator = new BarCodeGenerator(EncodeTypes.Code39Standard, "1234567890")
{
AutoSizeMode = AutoSizeMode.None
};
generator.BarCodeHeight.Pixels = 50;
generator.BarCodeWidth.Pixels = 120;
generator.Save(dataDir + "barcode-custom-size_out.jpg");
// ExEnd:BarcodeCustomSize
}
}
}
| mit | C# |
0f04913f179e9f16ff751cc18011eb0a12f62bde | fix broken unit test | reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap | unity/library/UtyMap.Unity.Tests/Maps/Data/MapTileAdapterTests.cs | unity/library/UtyMap.Unity.Tests/Maps/Data/MapTileAdapterTests.cs | using Moq;
using NUnit.Framework;
using UtyMap.Unity.Core;
using UtyMap.Unity.Core.Models;
using UtyMap.Unity.Core.Tiling;
using UtyMap.Unity.Infrastructure.Diagnostic;
using UtyMap.Unity.Infrastructure.Primitives;
using UtyMap.Unity.Maps.Data;
using UtyRx;
namespace UtyMap.Unity.Tests.Maps.Data
{
[TestFixture]
public class MapTileAdapterTests
{
private Mock<IObserver<Union<Element, Mesh>>> _observer;
private MapTileAdapter _adapter;
[TestFixtureSetUp]
public void SetUp()
{
var tile = new Tile(new QuadKey(), new Mock<Stylesheet>("").Object, new Mock<IProjection>().Object);
_observer = new Mock<IObserver<Union<Element, Mesh>>>();
_adapter = new MapTileAdapter(tile, _observer.Object, new DefaultTrace());
}
[TestCase("barrier")]
[TestCase("building")]
public void CanAdaptTheSameNonTerrainMeshOnlyOnce(string name)
{
name += ":42";
for (int i = 0; i < 2; ++i)
_adapter.AdaptMesh(name, new[] {.0, 0, 0}, 3, new[] {0, 0, 0}, 3, new[] {0, 0, 0}, 3, new[] {.0, 0, 0, .0, 0, 0}, 6);
_observer.Verify(o => o.OnNext(It.IsAny<Union<Element, Mesh>>()), Times.Once);
}
}
}
| using Moq;
using NUnit.Framework;
using UtyMap.Unity.Core;
using UtyMap.Unity.Core.Models;
using UtyMap.Unity.Core.Tiling;
using UtyMap.Unity.Infrastructure.Diagnostic;
using UtyMap.Unity.Infrastructure.Primitives;
using UtyMap.Unity.Maps.Data;
using UtyRx;
namespace UtyMap.Unity.Tests.Maps.Data
{
[TestFixture]
public class MapTileAdapterTests
{
private Mock<IObserver<Union<Element, Mesh>>> _observer;
private MapTileAdapter _adapter;
[TestFixtureSetUp]
public void SetUp()
{
var tile = new Tile(new QuadKey(), new Mock<Stylesheet>("").Object, new Mock<IProjection>().Object);
_observer = new Mock<IObserver<Union<Element, Mesh>>>();
_adapter = new MapTileAdapter(tile, _observer.Object, new DefaultTrace());
}
[TestCase("barrier")]
[TestCase("building")]
public void CanAdaptTheSameNonTerrainMeshOnlyOnce(string name)
{
name += ":42";
_adapter.AdaptMesh(name, new[] { .0, 0, 0 }, 3, new[] { 0, 0, 0 }, 3, new[] { 0, 0, 0 }, 3, new[] { .0, 0, 0 }, 3);
_adapter.AdaptMesh(name, new[] { .0, 0, 0 }, 3, new[] { 0, 0, 0 }, 3, new[] { 0, 0, 0 }, 3, new[] { .0, 0, 0 }, 3);
_observer.Verify(o => o.OnNext(It.IsAny<Union<Element, Mesh>>()), Times.Once);
}
}
}
| apache-2.0 | C# |
64e9c5e9ba50924903ec6e280b68552d878e00f5 | add return xmldoc in markdown unordered list | UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu | osu.Game/Graphics/Containers/Markdown/OsuMarkdownUnorderedListItem.cs | osu.Game/Graphics/Containers/Markdown/OsuMarkdownUnorderedListItem.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.Graphics;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownUnorderedListItem : OsuMarkdownListItem
{
private const float left_padding = 20;
private readonly int level;
public OsuMarkdownUnorderedListItem(int level)
{
this.level = level;
Padding = new MarginPadding { Left = left_padding };
}
protected override SpriteText CreateMarker() => base.CreateMarker().With(t =>
{
t.Text = GetTextMarker(level);
t.Font = t.Font.With(size: t.Font.Size / 2);
t.Origin = Anchor.Centre;
t.X = -left_padding / 2;
t.Y = t.Font.Size;
});
/// <summary>
/// Get text marker based on <paramref name="level"/>
/// </summary>
/// <param name="level">The markdown level of current list item.</param>
/// <returns>The marker string of this list item</returns>
protected virtual string GetTextMarker(int level)
{
switch (level)
{
case 1:
return "●";
case 2:
return "○";
default:
return "■";
}
}
}
}
| // 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.Graphics;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownUnorderedListItem : OsuMarkdownListItem
{
private const float left_padding = 20;
private readonly int level;
public OsuMarkdownUnorderedListItem(int level)
{
this.level = level;
Padding = new MarginPadding { Left = left_padding };
}
protected override SpriteText CreateMarker() => base.CreateMarker().With(t =>
{
t.Text = GetTextMarker(level);
t.Font = t.Font.With(size: t.Font.Size / 2);
t.Origin = Anchor.Centre;
t.X = -left_padding / 2;
t.Y = t.Font.Size;
});
/// <summary>
/// Get text marker based on <paramref name="level"/>
/// </summary>
/// <param name="level">The markdown level of current list item.</param>
/// <returns></returns>
protected virtual string GetTextMarker(int level)
{
switch (level)
{
case 1:
return "●";
case 2:
return "○";
default:
return "■";
}
}
}
}
| mit | C# |
cfa39c9d0da94eca03884387c592326f251cc7d4 | fix wrongly placed fontfamily parameter | wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex | tests/Avalonia.RenderTests/Controls/TextBlockTests.cs | tests/Avalonia.RenderTests/Controls/TextBlockTests.cs | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;
#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
public class TextBlockTests : TestBase
{
public TextBlockTests()
: base(@"Controls\TextBlock")
{
}
[Fact]
public async Task Wrapping_NoWrap()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new TextBlock
{
FontFamily = new FontFamily("Courier New"),
Background = Brushes.Red,
FontSize = 12,
Foreground = Brushes.Black,
Text = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit",
VerticalAlignment = VerticalAlignment.Top,
TextWrapping = TextWrapping.NoWrap,
}
};
await RenderToFile(target);
CompareImages();
}
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;
#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
public class TextBlockTests : TestBase
{
public TextBlockTests()
: base(@"Controls\TextBlock")
{
}
[Fact]
public async Task Wrapping_NoWrap()
{
Decorator target = new Decorator
{
FontFamily = new FontFamily("Courier New"),
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new TextBlock
{
Background = Brushes.Red,
FontSize = 12,
Foreground = Brushes.Black,
Text = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit",
VerticalAlignment = VerticalAlignment.Top,
TextWrapping = TextWrapping.NoWrap,
}
};
await RenderToFile(target);
CompareImages();
}
}
}
| mit | C# |
6d99b1419e61b6dd4946494eea2f89cb10d9c6d9 | create CreateWebHostBuilder static method to be able to run integration tests | ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate | test/aspnet-core-demo/AbpAspNetCoreDemo/Program.cs | test/aspnet-core-demo/AbpAspNetCoreDemo/Program.cs | using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace AbpAspNetCoreDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIIS()
.UseIISIntegration()
.UseStartup<Startup>();
}
}
}
| using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace AbpAspNetCoreDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Run();
}
public static IWebHost CreateWebHostBuilder(string[] args)
{
return new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIIS()
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
}
}
| mit | C# |
bb97eae8b1b46df5162a6502a282b0915527dd6b | Update outdated exception references in xmldoc | NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu | osu.Game/Online/RealtimeMultiplayer/IMultiplayerServer.cs | osu.Game/Online/RealtimeMultiplayer/IMultiplayerServer.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.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="InvalidStateException">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task LeaveRoom();
/// <summary>
/// Transfer the host of the currently joined room to another user in the room.
/// </summary>
/// <param name="userId">The new user which is to become host.</param>
/// <exception cref="NotHostException">A user other than the current host is attempting to transfer host.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task TransferHost(long userId);
/// <summary>
/// As the host, update the settings of the currently joined room.
/// </summary>
/// <param name="settings">The new settings to apply.</param>
/// <exception cref="NotHostException">A user other than the current host is attempting to transfer host.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task ChangeSettings(MultiplayerRoomSettings settings);
/// <summary>
/// Change the local user state in the currently joined room.
/// </summary>
/// <param name="newState">The proposed new state.</param>
/// <exception cref="InvalidStateChangeException">If the state change requested is not valid, given the previous state or room state.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task ChangeState(MultiplayerUserState newState);
/// <summary>
/// As the host of a room, start the match.
/// </summary>
/// <exception cref="NotHostException">A user other than the current host is attempting to start the game.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
/// <exception cref="InvalidStateException">If an attempt to start the game occurs when the game's (or users') state disallows it.</exception>
Task StartMatch();
}
}
| // 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.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="AlreadyInRoomException">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task LeaveRoom();
/// <summary>
/// Transfer the host of the currently joined room to another user in the room.
/// </summary>
/// <param name="userId">The new user which is to become host.</param>
/// <exception cref="NotHostException">A user other than the current host is attempting to transfer host.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task TransferHost(long userId);
/// <summary>
/// As the host, update the settings of the currently joined room.
/// </summary>
/// <param name="settings">The new settings to apply.</param>
/// <exception cref="NotHostException">A user other than the current host is attempting to transfer host.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task ChangeSettings(MultiplayerRoomSettings settings);
/// <summary>
/// Change the local user state in the currently joined room.
/// </summary>
/// <param name="newState">The proposed new state.</param>
/// <exception cref="InvalidStateChangeException">If the state change requested is not valid, given the previous state or room state.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task ChangeState(MultiplayerUserState newState);
/// <summary>
/// As the host of a room, start the match.
/// </summary>
/// <exception cref="NotHostException">A user other than the current host is attempting to start the game.</exception>
/// <exception cref="NotJoinedRoomException">If the user is not in a room.</exception>
Task StartMatch();
}
}
| mit | C# |
094b0c545a089271128d0073c268ced3c7173192 | Refactor out constants | Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving | XamarinApp/MyTrips/MyTrips.iOS/Screens/TripsTableViewController.cs | XamarinApp/MyTrips/MyTrips.iOS/Screens/TripsTableViewController.cs | using Foundation;
using System;
using UIKit;
using MyTrips.ViewModel;
using Humanizer;
namespace MyTrips.iOS
{
public partial class TripsTableViewController : UITableViewController
{
const string TRIP_CELL_IDENTIFIER = "TRIP_CELL_IDENTIFIER";
const string PAST_TRIP_SEGUE_IDENTIFIER = "pastTripSegue";
PastTripsViewModel ViewModel { get; set; }
public TripsTableViewController (IntPtr handle) : base (handle)
{
}
public override async void ViewDidLoad()
{
base.ViewDidLoad();
ViewModel = new PastTripsViewModel();
await ViewModel.ExecuteLoadPastTripsCommandAsync();
}
public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier == PAST_TRIP_SEGUE_IDENTIFIER)
{
var controller = segue.DestinationViewController as CurrentTripViewController;
var indexPath = TableView.IndexPathForCell(sender as UITableViewCell);
var trip = ViewModel.Trips[indexPath.Row];
controller.PastTripsDetailViewModel = new PastTripsDetailViewModel(trip);
}
}
#region UITableViewSource
public override nint RowsInSection(UITableView tableView, nint section)
{
return ViewModel.Trips.Count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell(TRIP_CELL_IDENTIFIER) as TripTableViewCell;
if (cell == null)
{
cell = new TripTableViewCell(new NSString(TRIP_CELL_IDENTIFIER));
}
var trip = ViewModel.Trips[indexPath.Row];
cell.LocationName = trip.TripId;
cell.TimeAgo = trip.TimeAgo;
cell.Distance = trip.TotalDistance;
return cell;
}
#endregion
}
} | using Foundation;
using System;
using UIKit;
using MyTrips.ViewModel;
using Humanizer;
namespace MyTrips.iOS
{
public partial class TripsTableViewController : UITableViewController
{
const string TRIP_CELL_IDENTIFIER = "TRIP_CELL_IDENTIFIER";
PastTripsViewModel ViewModel { get; set; }
public TripsTableViewController (IntPtr handle) : base (handle)
{
}
public override async void ViewDidLoad()
{
base.ViewDidLoad();
ViewModel = new PastTripsViewModel();
await ViewModel.ExecuteLoadPastTripsCommandAsync();
}
public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier == "pastTripSegue")
{
var controller = segue.DestinationViewController as CurrentTripViewController;
var indexPath = TableView.IndexPathForCell(sender as UITableViewCell);
var trip = ViewModel.Trips[indexPath.Row];
controller.PastTripsDetailViewModel = new PastTripsDetailViewModel(trip);
}
}
#region UITableViewSource
public override nint RowsInSection(UITableView tableView, nint section)
{
return ViewModel.Trips.Count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell(TRIP_CELL_IDENTIFIER) as TripTableViewCell;
if (cell == null)
{
cell = new TripTableViewCell(new NSString(TRIP_CELL_IDENTIFIER));
}
var trip = ViewModel.Trips[indexPath.Row];
cell.LocationName = trip.TripId;
cell.TimeAgo = trip.TimeAgo;
cell.Distance = trip.TotalDistance;
cell.SelectedBackgroundView = new UIView(cell.Frame) { BackgroundColor = cell.BackgroundColor.Lighten(2) };
return cell;
}
#endregion
}
} | mit | C# |
f4fb4d5ad150174c46c8bb64dda2511baa933047 | Include trailing whitespace in textbox width. | grokys/Avalonia | Avalonia.Direct2D1/Media/Direct2D1FormattedText.cs | Avalonia.Direct2D1/Media/Direct2D1FormattedText.cs | // -----------------------------------------------------------------------
// <copyright file="Direct2D1FormattedText.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Avalonia.Direct2D1.Media
{
using Avalonia.Media;
using Avalonia.Platform;
using SharpDX.DirectWrite;
public class Direct2D1FormattedText : IPlatformFormattedText
{
public Direct2D1FormattedText(string text, Typeface typeface, double fontSize)
{
Factory factory = ((Direct2D1PlatformFactory)PlatformFactory.Instance).DirectWriteFactory;
TextFormat format = new TextFormat(
factory,
typeface.FontFamily.Source,
(float)fontSize);
this.DirectWriteTextLayout = new TextLayout(
factory,
text,
format,
float.MaxValue,
float.MaxValue);
}
public TextLayout DirectWriteTextLayout
{
get;
private set;
}
public double Width
{
get { return this.DirectWriteTextLayout.Metrics.WidthIncludingTrailingWhitespace; }
}
public double Height
{
get { return this.DirectWriteTextLayout.Metrics.Height; }
}
public int GetCaretIndex(Point p)
{
SharpDX.Bool isTrailingHit;
SharpDX.Bool isInside;
HitTestMetrics result = this.DirectWriteTextLayout.HitTestPoint(
(float)p.X,
(float)p.Y,
out isTrailingHit,
out isInside);
return result.TextPosition + (isTrailingHit ? 1 : 0);
}
public Point GetCaretPosition(int caretIndex)
{
float x;
float y;
this.DirectWriteTextLayout.HitTestTextPosition(caretIndex, false, out x, out y);
return new Point(x, y);
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="Direct2D1FormattedText.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Avalonia.Direct2D1.Media
{
using Avalonia.Media;
using Avalonia.Platform;
using SharpDX.DirectWrite;
public class Direct2D1FormattedText : IPlatformFormattedText
{
public Direct2D1FormattedText(string text, Typeface typeface, double fontSize)
{
Factory factory = ((Direct2D1PlatformFactory)PlatformFactory.Instance).DirectWriteFactory;
TextFormat format = new TextFormat(
factory,
typeface.FontFamily.Source,
(float)fontSize);
this.DirectWriteTextLayout = new TextLayout(
factory,
text,
format,
float.MaxValue,
float.MaxValue);
}
public TextLayout DirectWriteTextLayout
{
get;
private set;
}
public double Width
{
get { return this.DirectWriteTextLayout.Metrics.Width; }
}
public double Height
{
get { return this.DirectWriteTextLayout.Metrics.Height; }
}
public int GetCaretIndex(Point p)
{
SharpDX.Bool isTrailingHit;
SharpDX.Bool isInside;
HitTestMetrics result = this.DirectWriteTextLayout.HitTestPoint(
(float)p.X,
(float)p.Y,
out isTrailingHit,
out isInside);
return result.TextPosition + (isTrailingHit ? 1 : 0);
}
public Point GetCaretPosition(int caretIndex)
{
float x;
float y;
this.DirectWriteTextLayout.HitTestTextPosition(caretIndex, false, out x, out y);
return new Point(x, y);
}
}
}
| mit | C# |
caa3f82fd387b281b009d499b8b29942bb53bd5c | Set main page of bit application of cs client if no main page is provided (Due error/delay in initialization) | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | src/CSharpClient/Bit.CSharpClient.All/BitApplication.cs | src/CSharpClient/Bit.CSharpClient.All/BitApplication.cs | using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;
namespace Bit
{
public abstract class BitApplication : PrismApplication
{
protected BitApplication(IPlatformInitializer platformInitializer = null)
: base(platformInitializer)
{
if (MainPage == null)
MainPage = new ContentPage { Title = "DefaultPage" };
}
protected override void OnInitialized()
{
IConnectivity connectivity = Container.Resolve<IConnectivity>();
IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();
connectivity.ConnectivityChanged += (sender, e) =>
{
eventAggregator.GetEvent<ConnectivityChangedEvent>()
.Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
};
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
}
}
}
| using Autofac;
using Bit.Model.Events;
using Plugin.Connectivity.Abstractions;
using Prism;
using Prism.Autofac;
using Prism.Events;
using Prism.Ioc;
using Xamarin.Forms;
namespace Bit
{
public abstract class BitApplication : PrismApplication
{
protected BitApplication(IPlatformInitializer platformInitializer = null)
: base(platformInitializer)
{
MainPage = new ContentPage { };
}
protected override void OnInitialized()
{
IConnectivity connectivity = Container.Resolve<IConnectivity>();
IEventAggregator eventAggregator = Container.Resolve<IEventAggregator>();
connectivity.ConnectivityChanged += (sender, e) =>
{
eventAggregator.GetEvent<ConnectivityChangedEvent>()
.Publish(new ConnectivityChangedEvent { IsConnected = e.IsConnected });
};
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.GetBuilder().Register<IContainerProvider>(c => Container).SingleInstance().PreserveExistingDefaults();
}
}
}
| mit | C# |
81f7daa1cc8b145e57e29bd6f8f5e785a677cfe9 | Remove eager Dispose on ThreadSafeEnumerator | avifatal/framework,AlejandroCano/framework,signumsoftware/framework,AlejandroCano/framework,signumsoftware/framework,avifatal/framework | Signum.Utilities/Synchronization/ThreadSafeEnumerator.cs | Signum.Utilities/Synchronization/ThreadSafeEnumerator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
namespace Signum.Utilities.Synchronization
{
public class TreadSafeEnumerator<T>: IEnumerable<T>, IEnumerator<T>
{
object key = new object();
IEnumerator<T> enumerator;
volatile bool moveNext = true;
readonly ThreadLocal<T> current = new ThreadLocal<T>();
public TreadSafeEnumerator(IEnumerable<T> source)
{
enumerator = source.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public T Current
{
get { return current.Value; }
}
object IEnumerator.Current
{
get { return current.Value; }
}
public bool MoveNext()
{
lock (key)
{
if (moveNext && (moveNext = enumerator.MoveNext()))
current.Value = enumerator.Current;
else
current.Value = default(T);
return moveNext;
}
}
public void Reset()
{
throw new NotImplementedException();
}
public void Dispose()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
namespace Signum.Utilities.Synchronization
{
public class TreadSafeEnumerator<T>: IEnumerable<T>, IEnumerator<T>
{
object key = new object();
IEnumerator<T> enumerator;
volatile bool moveNext = true;
readonly ThreadLocal<T> current = new ThreadLocal<T>();
public TreadSafeEnumerator(IEnumerable<T> source)
{
enumerator = source.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public T Current
{
get { return current.Value; }
}
object IEnumerator.Current
{
get { return current.Value; }
}
public bool MoveNext()
{
lock (key)
{
if (moveNext && (moveNext = enumerator.MoveNext()))
current.Value = enumerator.Current;
else
current.Value = default(T);
return moveNext;
}
}
public void Reset()
{
throw new NotImplementedException();
}
public void Dispose()
{
current.Dispose();
}
}
}
| mit | C# |
ebb1165b14b0d8f0a6151d8d323f231529e6f67e | Handle nullable enum default values (dotnet/extensions#531) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Shared/ParameterDefaultValue/ParameterDefaultValue.cs | src/Shared/ParameterDefaultValue/ParameterDefaultValue.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.
using System;
using System.Reflection;
namespace Microsoft.Extensions.Internal
{
internal class ParameterDefaultValue
{
private static readonly Type _nullable = typeof(Nullable<>);
public static bool TryGetDefaultValue(ParameterInfo parameter, out object defaultValue)
{
bool hasDefaultValue;
var tryToGetDefaultValue = true;
defaultValue = null;
try
{
hasDefaultValue = parameter.HasDefaultValue;
}
catch (FormatException) when (parameter.ParameterType == typeof(DateTime))
{
// Workaround for https://github.com/dotnet/corefx/issues/12338
// If HasDefaultValue throws FormatException for DateTime
// we expect it to have default value
hasDefaultValue = true;
tryToGetDefaultValue = false;
}
if (hasDefaultValue)
{
if (tryToGetDefaultValue)
{
defaultValue = parameter.DefaultValue;
}
// Workaround for https://github.com/dotnet/corefx/issues/11797
if (defaultValue == null && parameter.ParameterType.IsValueType)
{
defaultValue = Activator.CreateInstance(parameter.ParameterType);
}
// Handle nullable enums
if (defaultValue != null &&
parameter.ParameterType.IsGenericType &&
parameter.ParameterType.GetGenericTypeDefinition() == _nullable
)
{
var underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);
if (underlyingType != null && underlyingType.IsEnum)
{
defaultValue = Enum.ToObject(underlyingType, defaultValue);
}
}
}
return hasDefaultValue;
}
}
}
| // 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.
using System;
using System.Reflection;
namespace Microsoft.Extensions.Internal
{
internal class ParameterDefaultValue
{
public static bool TryGetDefaultValue(ParameterInfo parameter, out object defaultValue)
{
bool hasDefaultValue;
var tryToGetDefaultValue = true;
defaultValue = null;
try
{
hasDefaultValue = parameter.HasDefaultValue;
}
catch (FormatException) when (parameter.ParameterType == typeof(DateTime))
{
// Workaround for https://github.com/dotnet/corefx/issues/12338
// If HasDefaultValue throws FormatException for DateTime
// we expect it to have default value
hasDefaultValue = true;
tryToGetDefaultValue = false;
}
if (hasDefaultValue)
{
if (tryToGetDefaultValue)
{
defaultValue = parameter.DefaultValue;
}
// Workaround for https://github.com/dotnet/corefx/issues/11797
if (defaultValue == null && parameter.ParameterType.IsValueType)
{
defaultValue = Activator.CreateInstance(parameter.ParameterType);
}
}
return hasDefaultValue;
}
}
}
| apache-2.0 | C# |
1faa6f018b8d4c79faf55dfda4593dba82bd1ac1 | Switch to use IServiceCollection | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Mvc/ServiceCollectionExtensions.cs | src/Microsoft.AspNet.Mvc/ServiceCollectionExtensions.cs | // Copyright (c) Microsoft Open Technologies, 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 CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
// WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
// TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing
// permissions and limitations under the License.
using Microsoft.AspNet.ConfigurationModel;
using Microsoft.AspNet.DependencyInjection;
namespace Microsoft.AspNet.Mvc
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddMvc(this IServiceCollection services)
{
return services.Add(MvcServices.GetDefaultServices());
}
public static IServiceCollection AddMvc(this IServiceCollection services, IConfiguration configuration)
{
return services.Add(MvcServices.GetDefaultServices(configuration));
}
}
}
| // Copyright (c) Microsoft Open Technologies, 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 CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
// WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
// TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing
// permissions and limitations under the License.
using Microsoft.AspNet.ConfigurationModel;
using Microsoft.AspNet.DependencyInjection;
namespace Microsoft.AspNet.Mvc
{
public static class ServiceCollectionExtensions
{
public static ServiceCollection AddMvc(this ServiceCollection services)
{
return services.Add(MvcServices.GetDefaultServices());
}
public static ServiceCollection AddMvc(this ServiceCollection services, IConfiguration configuration)
{
return services.Add(MvcServices.GetDefaultServices(configuration));
}
}
}
| apache-2.0 | C# |
48ae539f8fb74b762acc769045ac0f8585be9ac0 | Add strong-name signature to Microsoft.Management.Infrastructure | TravisEz13/PowerShell,PaulHigin/PowerShell,KarolKaczmarek/PowerShell,bmanikm/PowerShell,kmosher/PowerShell,bmanikm/PowerShell,TravisEz13/PowerShell,bingbing8/PowerShell,bmanikm/PowerShell,bingbing8/PowerShell,daxian-dbw/PowerShell,JamesWTruher/PowerShell-1,bingbing8/PowerShell,bingbing8/PowerShell,bingbing8/PowerShell,jsoref/PowerShell,kmosher/PowerShell,kmosher/PowerShell,KarolKaczmarek/PowerShell,KarolKaczmarek/PowerShell,bmanikm/PowerShell,JamesWTruher/PowerShell-1,jsoref/PowerShell,KarolKaczmarek/PowerShell,daxian-dbw/PowerShell,jsoref/PowerShell,daxian-dbw/PowerShell,JamesWTruher/PowerShell-1,JamesWTruher/PowerShell-1,TravisEz13/PowerShell,kmosher/PowerShell,KarolKaczmarek/PowerShell,daxian-dbw/PowerShell,PaulHigin/PowerShell,jsoref/PowerShell,bmanikm/PowerShell,PaulHigin/PowerShell,TravisEz13/PowerShell,jsoref/PowerShell,kmosher/PowerShell,PaulHigin/PowerShell | src/Microsoft.Management.Infrastructure/AssemblyInfo.cs | src/Microsoft.Management.Infrastructure/AssemblyInfo.cs | using System.Runtime.CompilerServices;
using System.Reflection;
#if CORECLR
[assembly:InternalsVisibleTo("System.Management.Automation")]
[assembly:AssemblyFileVersionAttribute("1.0.0.0")]
[assembly:AssemblyVersion("1.0.0.0")]
#else
[assembly:System.Resources.NeutralResourcesLanguage("en")]
[assembly:System.Runtime.InteropServices.ComVisible(false)]
[assembly:System.Reflection.AssemblyVersion("1.0.0.0")]
[assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")]
[assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")]
[assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")]
[assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")]
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("XmlServerStore,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("System.Management.Automation,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("XmlServerStore,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.CloudInfrastructure.Test.Common,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.Windows.DSC.CoreConfProviders,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.Monitoring.Commands,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.Management.Infrastructure.CimCmdlets,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly:AssemblyKeyFileAttribute(@"..\..\src\monad\monad\src\graphicalhost\visualstudiopublic.snk")]
[assembly:System.Reflection.AssemblyDelaySign(true)]
#endif
| using System.Runtime.CompilerServices;
using System.Reflection;
[assembly:InternalsVisibleTo("System.Management.Automation")]
[assembly:AssemblyFileVersionAttribute("1.0.0.0")]
[assembly:AssemblyVersion("1.0.0.0")]
| mit | C# |
a902c39b659baa4cb31ca3ced861b5bc1a4400e7 | Update ActionModule.cs | DigitalFlow/Xrm-Oss-Interfacing | src/interface/Xrm.Oss.CrmListener/Modules/ActionModule.cs | src/interface/Xrm.Oss.CrmListener/Modules/ActionModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MassTransit;
using Microsoft.Xrm.Sdk;
using Nancy;
using NLog;
using Xrm.Oss.Interfacing.Domain.Implementations;
namespace Xrm.Oss.CrmListener.Modules
{
public class ActionModule : NancyModule
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public ActionModule(IPublisherControlWrapper publisherRegistration, IOrganizationService service, IBusControl busControl)
{
Get["trigger/{action}/{entity}/{id}"] = parameters =>
{
var action = parameters.action?.Value;
var entity = parameters.entity?.Value;
var id = parameters.id?.Value;
var guid = Guid.Empty;
if(!Guid.TryParse(id, out guid)){
return HttpStatusCode.BadRequest;
}
var message = new CrmMessage
{
Scenario = new Scenario(action, entity),
RecordId = guid
};
publisherRegistration.RouteMessage(message, service, busControl);
return HttpStatusCode.OK;
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MassTransit;
using Microsoft.Xrm.Sdk;
using Nancy;
using NLog;
using Xrm.Oss.Interfacing.Domain.Implementations;
namespace Xrm.Oss.CrmListener.Modules
{
public class ActionModule : NancyModule
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public ActionModule(IPublisherControlWrapper publisherRegistration, /*IOrganizationService service,*/ IBusControl busControl)
{
Get["trigger/{action}/{entity}/{id}"] = parameters =>
{
var action = parameters.action?.Value;
var entity = parameters.entity?.Value;
var id = parameters.id?.Value;
var guid = Guid.Empty;
if(!Guid.TryParse(id, out guid)){
return HttpStatusCode.BadRequest;
}
var message = new CrmMessage
{
Scenario = new Scenario(action, entity),
RecordId = guid
};
publisherRegistration.RouteMessage(message, null, busControl);
return HttpStatusCode.OK;
};
}
}
}
| mit | C# |
b54de4b8fce633b9ab6318f8cff651424c53c35b | Fix insulated gloves (#11079) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Shared/Electrocution/ElectrocutionEvents.cs | Content.Shared/Electrocution/ElectrocutionEvents.cs | using Content.Shared.Inventory;
namespace Content.Shared.Electrocution
{
public sealed class ElectrocutionAttemptEvent : CancellableEntityEventArgs, IInventoryRelayEvent
{
public SlotFlags TargetSlots { get; }
public readonly EntityUid TargetUid;
public readonly EntityUid? SourceUid;
public float SiemensCoefficient = 1f;
public ElectrocutionAttemptEvent(EntityUid targetUid, EntityUid? sourceUid, float siemensCoefficient, SlotFlags targetSlots)
{
TargetUid = targetUid;
TargetSlots = targetSlots;
SourceUid = sourceUid;
SiemensCoefficient = siemensCoefficient;
}
}
public sealed class ElectrocutedEvent : EntityEventArgs
{
public readonly EntityUid TargetUid;
public readonly EntityUid? SourceUid;
public readonly float SiemensCoefficient;
public ElectrocutedEvent(EntityUid targetUid, EntityUid? sourceUid, float siemensCoefficient)
{
TargetUid = targetUid;
SourceUid = sourceUid;
SiemensCoefficient = siemensCoefficient;
}
}
}
| using Content.Shared.Inventory;
namespace Content.Shared.Electrocution
{
public sealed class ElectrocutionAttemptEvent : CancellableEntityEventArgs, IInventoryRelayEvent
{
public SlotFlags TargetSlots { get; }
public readonly EntityUid TargetUid;
public readonly EntityUid? SourceUid;
public float SiemensCoefficient = 1f;
public ElectrocutionAttemptEvent(EntityUid targetUid, EntityUid? sourceUid, float siemensCoefficient, SlotFlags targetSlots)
{
TargetUid = targetUid;
TargetSlots = TargetSlots;
SourceUid = sourceUid;
SiemensCoefficient = siemensCoefficient;
}
}
public sealed class ElectrocutedEvent : EntityEventArgs
{
public readonly EntityUid TargetUid;
public readonly EntityUid? SourceUid;
public readonly float SiemensCoefficient;
public ElectrocutedEvent(EntityUid targetUid, EntityUid? sourceUid, float siemensCoefficient)
{
TargetUid = targetUid;
SourceUid = sourceUid;
SiemensCoefficient = siemensCoefficient;
}
}
}
| mit | C# |
bea9e8c5fc87f86a2020da6fcc25a13db8a59fb6 | fix test | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | test/WeihanLi.Common.Test/HelpersTest/StringHelperTest.cs | test/WeihanLi.Common.Test/HelpersTest/StringHelperTest.cs | using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class StringHelperTest
{
[Fact]
public void HideSensitiveInfo()
{
var testString = "12345678901";
Assert.Equal("132****5489", StringHelper.HideTelDetails("13212345489"));
Assert.Equal("123***901", StringHelper.HideSensitiveInfo(testString, 3, 3, sensitiveCharCount: 3));
Assert.Equal("1****", StringHelper.HideSensitiveInfo(testString, 11, 1));
Assert.Equal("***1", StringHelper.HideSensitiveInfo(testString, 11, 1, 3, false));
}
}
}
| using WeihanLi.Common.Helpers;
using Xunit;
namespace WeihanLi.Common.Test.HelpersTest
{
public class StringHelperTest
{
[Fact]
public void HideSensitiveInfo()
{
var testString = "12345678901";
Assert.Equal("132****5489", StringHelper.HideTelDetails("13212345489"));
Assert.Equal("123***901", StringHelper.HideSensitiveInfo(testString, 3, 3, sensitiveCharCount: 3));
Assert.Equal("1****", StringHelper.HideSensitiveInfo(testString, 11, 1));
Assert.Equal("***1", StringHelper.HideSensitiveInfo(testString, 11, 1, false, 3));
}
}
}
| mit | C# |
166df22fd58a1c197725945134e5388053c993f3 | Fix thumbnails on MT | xamarin/Xamarin.Mobile,orand/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile,xamarin/Xamarin.Mobile,moljac/Xamarin.Mobile,nexussays/Xamarin.Mobile | MonoTouch/MonoMobile.Extensions/Contacts/Contact.cs | MonoTouch/MonoMobile.Extensions/Contacts/Contact.cs | using System.Collections.Generic;
using MonoTouch.AddressBook;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Xamarin.Contacts
{
public class Contact
{
internal Contact (ABPerson person)
{
Id = person.Id.ToString();
this.person = person;
}
public string Id
{
get;
private set;
}
public bool IsAggregate
{
get;
private set;
}
public string DisplayName
{
get;
internal set;
}
public string Prefix
{
get;
internal set;
}
public string FirstName
{
get;
internal set;
}
public string MiddleName
{
get;
internal set;
}
public string LastName
{
get;
internal set;
}
public string Nickname
{
get;
internal set;
}
public string Suffix
{
get;
internal set;
}
public IEnumerable<Address> Addresses
{
get;
internal set;
}
public IEnumerable<InstantMessagingAccount> InstantMessagingAccounts
{
get;
internal set;
}
public IEnumerable<Website> Websites
{
get;
internal set;
}
public IEnumerable<Organization> Organizations
{
get;
internal set;
}
public IEnumerable<Note> Notes
{
get;
internal set;
}
public IEnumerable<Email> Emails
{
get;
internal set;
}
public IEnumerable<Phone> Phones
{
get;
internal set;
}
public UIImage PhotoThumbnail
{
get
{
LoadThumbnail();
return this.thumbnail;
}
}
private readonly ABPerson person;
private bool thumbnailLoaded;
private UIImage thumbnail;
[DllImport ("/System/Library/Frameworks/AddressBook.framework/AddressBook")]
private static extern IntPtr ABPersonCopyImageDataWithFormat (IntPtr handle, ABPersonImageFormat format);
private void LoadThumbnail()
{
if (this.thumbnailLoaded)
return;
this.thumbnailLoaded = false;
if (!this.person.HasImage)
return;
NSData imageData = new NSData (ABPersonCopyImageDataWithFormat (person.Handle, ABPersonImageFormat.Thumbnail));
if (imageData != null)
this.thumbnail = new UIImage (imageData);
}
}
} | using System.Collections.Generic;
using MonoTouch.AddressBook;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Xamarin.Contacts
{
public class Contact
{
internal Contact (ABPerson person)
{
Id = person.Id.ToString();
this.person = person;
}
public string Id
{
get;
private set;
}
public bool IsAggregate
{
get;
private set;
}
public string DisplayName
{
get;
internal set;
}
public string Prefix
{
get;
internal set;
}
public string FirstName
{
get;
internal set;
}
public string MiddleName
{
get;
internal set;
}
public string LastName
{
get;
internal set;
}
public string Nickname
{
get;
internal set;
}
public string Suffix
{
get;
internal set;
}
public IEnumerable<Address> Addresses
{
get;
internal set;
}
public IEnumerable<InstantMessagingAccount> InstantMessagingAccounts
{
get;
internal set;
}
public IEnumerable<Website> Websites
{
get;
internal set;
}
public IEnumerable<Organization> Organizations
{
get;
internal set;
}
public IEnumerable<Note> Notes
{
get;
internal set;
}
public IEnumerable<Email> Emails
{
get;
internal set;
}
public IEnumerable<Phone> Phones
{
get;
internal set;
}
public UIImage PhotoThumbnail
{
get
{
LoadThumbnail();
return this.thumbnail;
}
}
private readonly ABPerson person;
private bool thumbnailLoaded;
private UIImage thumbnail;
private void LoadThumbnail()
{
if (this.thumbnailLoaded)
return;
this.thumbnailLoaded = false;
if (!this.person.HasImage)
return;
using (NSData imageData = this.person.Image)
{
if (imageData != null)
this.thumbnail = new UIImage (imageData);
}
}
}
} | apache-2.0 | C# |
6b1949824efa707f4457b551c35cc9853f6530ab | Add Subscribe test | runceel/ReactiveProperty,runceel/ReactiveProperty,runceel/ReactiveProperty | Test/ReactiveProperty.Tests/ReactiveCommandTest.cs | Test/ReactiveProperty.Tests/ReactiveCommandTest.cs | using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Reactive.Bindings;
using System.Reactive.Linq;
using Microsoft.Reactive.Testing;
using System.Reactive.Subjects;
using System.Threading;
namespace ReactiveProperty.Tests
{
[TestClass]
public class ReactiveCommandTest : ReactiveTest
{
[TestMethod]
public void ReactiveCommandAllFlow()
{
var testScheduler = new TestScheduler();
var @null = (object)null;
var recorder1 = testScheduler.CreateObserver<object>();
var recorder2 = testScheduler.CreateObserver<object>();
var cmd = new ReactiveCommand();
cmd.Subscribe(recorder1);
cmd.Subscribe(recorder2);
cmd.CanExecute().Is(true);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Dispose();
cmd.CanExecute().Is(false);
cmd.Dispose(); // dispose again
recorder1.Messages.Is(
OnNext(0, @null),
OnNext(10, @null),
OnNext(20, @null),
OnCompleted<object>(30));
recorder2.Messages.Is(
OnNext(0, @null),
OnNext(10, @null),
OnNext(20, @null),
OnCompleted<object>(30));
}
[TestMethod]
public void ReactiveCommandSubscribe()
{
var testScheduler = new TestScheduler();
var recorder1 = testScheduler.CreateObserver<int>();
var recorder2 = testScheduler.CreateObserver<int>();
var cmd = new ReactiveCommand();
int counter = 0;
Action countUp = () => counter++;
cmd.Subscribe(countUp);
Action recordAction1 = () => recorder1.OnNext(counter);
cmd.Subscribe(recordAction1);
Action recordAction2 = () => recorder2.OnNext(counter);
cmd.Subscribe(recordAction2);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Execute(); testScheduler.AdvanceBy(10);
recorder1.Messages.Is(
OnNext(0, 1),
OnNext(10, 2),
OnNext(20, 3));
recorder2.Messages.Is(
OnNext(0, 1),
OnNext(10, 2),
OnNext(20, 3));
}
}
}
| using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Reactive.Bindings;
using System.Reactive.Linq;
using Microsoft.Reactive.Testing;
using System.Reactive.Subjects;
using System.Threading;
namespace ReactiveProperty.Tests
{
[TestClass]
public class ReactiveCommandTest : ReactiveTest
{
[TestMethod]
public void ReactiveCommandAllFlow()
{
var testScheduler = new TestScheduler();
var @null = (object)null;
var recorder1 = testScheduler.CreateObserver<object>();
var recorder2 = testScheduler.CreateObserver<object>();
var cmd = new ReactiveCommand();
cmd.Subscribe(recorder1);
cmd.Subscribe(recorder2);
cmd.CanExecute().Is(true);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Execute(); testScheduler.AdvanceBy(10);
cmd.Dispose();
cmd.CanExecute().Is(false);
cmd.Dispose(); // dispose again
recorder1.Messages.Is(
OnNext(0, @null),
OnNext(10, @null),
OnNext(20, @null),
OnCompleted<object>(30));
recorder2.Messages.Is(
OnNext(0, @null),
OnNext(10, @null),
OnNext(20, @null),
OnCompleted<object>(30));
}
}
}
| mit | C# |
dcbd7ce00d9bde0a025c59862fb7e9e79e3f0e3a | fix plugin name | datumcorp/cordova-plugin-volstatus,sxagan/cordova-plugin-mfsutils,clement360/Cordova-Hello-JNI-Plugin,sxagan/cordova-plugin-mfsutils,clement360/Cordova-Hello-JNI-Plugin,datumcorp/cordova-plugin-volstatus,clement360/Cordova-Hello-JNI-Plugin | src/wp7/Hello.cs | src/wp7/Hello.cs | using WP7CordovaClassLib.Cordova;
using WP7CordovaClassLib.Cordova.Commands;
using WP7CordovaClassLib.Cordova.JSON;
namespace Cordova.Extension.Commands
{
public class Hello : BaseCommand
{
public void greet(string args)
{
string name = JsonHelper.Deserialize<string>(args);
string message = "Hello, " + name;
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
DispatchCommandResult(result);
}
}
}
| using WP7CordovaClassLib.Cordova;
using WP7CordovaClassLib.Cordova.Commands;
using WP7CordovaClassLib.Cordova.JSON;
namespace Cordova.Extension.Commands
{
public class HelloPlugin : BaseCommand
{
public void greet(string args)
{
string name = JsonHelper.Deserialize<string>(args);
string message = "Hello, " + name;
PluginResult result =
new PluginResult(PluginResult.Status.OK, message);
DispatchCommandResult(result);
}
}
}
| mit | C# |
515d34efe08cd0de8ae99c8a0716f7278cc184b4 | Expand the misspelled member name test | jonathanvdc/ecsc | tests/cs-errors/misspelled-name/MisspelledMemberName.cs | tests/cs-errors/misspelled-name/MisspelledMemberName.cs | using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
public Counter Decrement<T>()
{
Count--;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
WriteLine(printCoutner.Increment().Count);
WriteLine(printCounter.Dcrement<int>().Count);
}
} | using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
WriteLine(printCoutner.Increment().Count);
}
} | mit | C# |
64ca0f1404a4bba6929718dbd1580a8b92cf262b | drop and recreate database on schema change | jonsequitur/Alluvial | Alluvial.Tests/Infrastructure/AlluvialSqlTestsDbContext.cs | Alluvial.Tests/Infrastructure/AlluvialSqlTestsDbContext.cs | using System.Data.Entity;
namespace Alluvial.Tests
{
public class AlluvialSqlTestsDbContext : DbContext
{
static AlluvialSqlTestsDbContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AlluvialSqlTestsDbContext>());
}
public AlluvialSqlTestsDbContext() : base(@"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=AlluvialSqlTests")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Event>()
.HasKey(e => new { e.Id, e.SequenceNumber });
modelBuilder.Entity<Event>()
.Property(e => e.Id)
.HasMaxLength(64);
}
public DbSet<Event> Events { get; set; }
}
} | using System.Data.Entity;
namespace Alluvial.Tests
{
public class AlluvialSqlTestsDbContext : DbContext
{
static AlluvialSqlTestsDbContext()
{
Database.SetInitializer(new AlluvialSqlTestsDbInitializer());
}
public AlluvialSqlTestsDbContext() : base(@"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=AlluvialSqlTests")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Event>()
.HasKey(e => new { e.Id, e.SequenceNumber });
modelBuilder.Entity<Event>()
.Property(e => e.Id)
.HasMaxLength(64);
}
public DbSet<Event> Events { get; set; }
public class AlluvialSqlTestsDbInitializer : CreateDatabaseIfNotExists<AlluvialSqlTestsDbContext>
{
}
}
} | mit | C# |
433d619490ad7f6fb5d0853a899caec6bba580a8 | Fix .NET Core build following test folder renaming | criteo/kafka-sharp,criteo/kafka-sharp | kafka-sharp/kafka-sharp/Properties/AssemblyInfo.cs | kafka-sharp/kafka-sharp/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("kafka-sharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("kafka-sharp")]
[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("e6692333-8e76-4b7b-b3f6-5fd5c20cb741")]
// 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")]
// For testing purpose
[assembly: InternalsVisibleTo("Kafka.UTest")]
#if NET_CORE
[assembly: InternalsVisibleTo("kafka-sharp.UTest")] // dotnet core considers the directory name when building the assembly
#endif
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
| 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("kafka-sharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("kafka-sharp")]
[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("e6692333-8e76-4b7b-b3f6-5fd5c20cb741")]
// 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")]
// For testing purpose
[assembly: InternalsVisibleTo("Kafka.UTest")]
#if NET_CORE
[assembly: InternalsVisibleTo("tests-kafka-sharp")] // dotnet core considers the directory name when building the assembly
#endif
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
| apache-2.0 | C# |
5f957db6a7865b07a28ddcc33fd63ecfe4f797a9 | remove additional syntax | BaylorRae/discover-objects-with-property | DiscoverObjectsWithPropertyType/ObjectsWithPropertyType.cs | DiscoverObjectsWithPropertyType/ObjectsWithPropertyType.cs | using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace DiscoverObjectsWithPropertyType
{
public static class ObjectsWithPropertyType
{
public static IList<Type> Discover<T>()
{
var types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
types.AddRange(Discover<T>(assembly));
return types;
}
public static IList<Type> Discover<T>(Assembly assembly)
{
return assembly.GetTypes()
.Where(t => HasPropertyWithType<T>(t))
.Select(t => t).ToList();
}
public static IDictionary<Type, IEnumerable<string>> DiscoverWithMapping<T>(Assembly assembly)
{
return Discover<T>(assembly)
.Select(t => new { Type = t, Properties = PropertiesWithType<T>(t) })
.ToDictionary(x => x.Type, x => x.Properties);
}
private static IEnumerable<string> PropertiesWithType<T>(Type type)
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return properties
.Where(QueryForType<T>(type))
.Select(p => p.Name);
}
public static bool HasPropertyWithType<T>(Type type)
{
return PropertiesWithType<T>(type).Any();
}
private static Func<PropertyInfo, bool> QueryForType<T>(Type type)
{
return p =>
// find direct property type
p.PropertyType == typeof(T) ||
// find within generic type arguments
// ICollection<MyHidingType>
p.PropertyType.GenericTypeArguments.Any(a => a == typeof(T));
}
}
}
| using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace DiscoverObjectsWithPropertyType
{
public static class ObjectsWithPropertyType
{
public static IList<Type> Discover<T>()
{
var types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
types.AddRange(Discover<T>(assembly));
return types;
}
public static IList<Type> Discover<T>(Assembly assembly)
{
return assembly.GetTypes()
.Where(t => HasPropertyWithType<T>(t))
.Select(t => t).ToList();
}
public static IDictionary<Type, IEnumerable<string>> DiscoverWithMapping<T>(Assembly assembly)
{
return Discover<T>(assembly)
.Select(t => new { Type = t, Properties = PropertiesWithType<T>(t) })
.ToDictionary(x => x.Type, x => x.Properties);
}
private static IEnumerable<string> PropertiesWithType<T>(Type type)
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return properties
.Where(QueryForType<T>(type))
.Select(p => p.Name);
}
public static bool HasPropertyWithType<T>(Type type)
{
return PropertiesWithType<T>(type).Any();
}
private static Func<PropertyInfo, bool> QueryForType<T>(Type type)
{
return new Func<PropertyInfo,bool>(p =>
// find direct property type
p.PropertyType == typeof(T) ||
// find within generic type arguments
// ICollection<MyHidingType>
p.PropertyType.GenericTypeArguments.Any(a => a == typeof(T))
);
}
}
}
| mit | C# |
4d432c1c83d4620ff84e53233aebe8d450e53906 | bump version | distantcam/Anotar,Fody/Anotar,modulexcite/Anotar,mstyura/Anotar | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("1.4.4.0")]
[assembly: AssemblyFileVersion("1.4.4.0")]
| mit | C# |
f01ced575ff37f46fc175ba896bb1c3540be61df | Update Dashboard Text | tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS | Portal.CMS.Web/Areas/Admin/Views/Dashboard/_Welcome.cshtml | Portal.CMS.Web/Areas/Admin/Views/Dashboard/_Welcome.cshtml | <div class="col-xs-12 col-md-6 col-lg-4">
<div class="box high">
<div class="box-title">Welcome to Portal CMS</div>
<h3>What is Portal CMS?</h3>
<p>Portal CMS is a fully featured and responsive content management system with a powerful integrated page builder.</p>
<h3>Contribute</h3>
<p>Portal CMS is open source, contribute code to improve and enhance Portal CMS on GitHub.</p>
<h3>Contact</h3>
<p>Send us your comments and feedback about Portal CMS: <a href="mailto:spam@tommcclean.me">Send Email</a></p>
<div class="admin-container x2">
<a href="http://portalcms.online" class="admin-item" data-title="View Repository"><span class="glyphicon glyphicon-globe"></span>Learn More</a>
<a href="https://github.com/tommcclean/PortalCMS" class="admin-item" data-title="View Repository"><span class="glyphicon glyphicon-globe"></span>Repository</a>
</div>
</div>
</div> | <div class="col-xs-12 col-md-6 col-lg-4">
<div class="box high">
<div class="box-title">Welcome to Portal CMS</div>
<h3>What is Portal CMS?</h3>
<p>Portal is a flexible and easy to use Content Management System.</p><p>Create Blog Posts and Galleries for visitors to see and comment on.</p>
<br />
<h3>Submit Feedback</h3>
<p>To submit feedback about Portal CMS contact the <a href="mailto:spam@tommcclean.me">Developer by email.</a></p>
</div>
</div> | mit | C# |
91e59d0e5bd9480a6b163369d5d7ed7284f34735 | Simplify method invocation | madsbangh/EasyButtons | Assets/EasyButtons/Editor/ButtonEditor.cs | Assets/EasyButtons/Editor/ButtonEditor.cs | using System.Linq;
using UnityEngine;
using UnityEditor;
namespace EasyButtons
{
/// <summary>
/// Custom inspector for MonoBehaviour including derived classes.
/// </summary>
[CustomEditor(typeof(MonoBehaviour), true)]
public class ButtonEditor : Editor
{
public override void OnInspectorGUI()
{
// Loop through all methods with the Button attribute and no arguments
foreach (var method in target.GetType().GetMethods()
.Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
.Where(m => m.GetParameters().Length == 0))
{
// Draw a button which invokes the method
if (GUILayout.Button(method.Name))
{
method.Invoke(target, null);
}
}
// Draw the rest of the inspector as usual
DrawDefaultInspector();
}
}
}
| using System.Linq;
using UnityEngine;
using UnityEditor;
namespace EasyButtons
{
/// <summary>
/// Custom inspector for MonoBehaviour including derived classes.
/// </summary>
[CustomEditor(typeof(MonoBehaviour), true)]
public class ButtonEditor : Editor
{
public override void OnInspectorGUI()
{
// Loop through all methods with the Button attribute and no arguments
foreach (var method in target.GetType().GetMethods()
.Where(m => m.GetCustomAttributes(typeof(ButtonAttribute), true).Length > 0)
.Where(m => m.GetParameters().Length == 0))
{
// Draw a button which invokes the method
if (GUILayout.Button(method.Name))
{
method.Invoke(target, new object[0]);
}
}
// Draw the rest of the inspector as usual
DrawDefaultInspector();
}
}
}
| mit | C# |
86622693a9f1a5c628c9e87d1955136d226347ff | Fix enumerator resource leak. | rubenv/tripod,rubenv/tripod | src/Core/Tripod.Core/Tripod.Base/RecursiveDirectoryEnumerator.cs | src/Core/Tripod.Core/Tripod.Base/RecursiveDirectoryEnumerator.cs | //
// RecursiveDirectoryEnumerator.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// 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.Collections;
using System.Collections.Generic;
using GLib;
namespace Tripod.Base
{
public class RecursiveFileEnumerator : IEnumerable<File>
{
Uri root;
public RecursiveFileEnumerator (Uri root)
{
this.root = root;
}
IEnumerable<File> ScanForFiles (File root)
{
var enumerator = root.EnumerateChildren ("standard::name,standard::type", FileQueryInfoFlags.None, null);
foreach (FileInfo info in enumerator) {
File file = root.GetChild (info.Name);
if (info.FileType == FileType.Regular) {
yield return file;
} else if (info.FileType == FileType.Directory) {
foreach (var child in ScanForFiles (file)) {
yield return child;
}
}
}
enumerator.Close (null);
}
public IEnumerator<File> GetEnumerator ()
{
var file = FileFactory.NewForUri (root);
return ScanForFiles (file).GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
}
| //
// RecursiveDirectoryEnumerator.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// 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.Collections;
using System.Collections.Generic;
using GLib;
namespace Tripod.Base
{
public class RecursiveFileEnumerator : IEnumerable<File>
{
Uri root;
public RecursiveFileEnumerator (Uri root)
{
this.root = root;
}
IEnumerable<File> ScanForFiles (File root)
{
var enumerator = root.EnumerateChildren ("standard::name,standard::type", FileQueryInfoFlags.None, null);
foreach (FileInfo info in enumerator) {
File file = root.GetChild (info.Name);
if (info.FileType == FileType.Regular) {
yield return file;
} else if (info.FileType == FileType.Directory) {
foreach (var child in ScanForFiles (file)) {
yield return child;
}
}
}
}
public IEnumerator<File> GetEnumerator ()
{
var file = FileFactory.NewForUri (root);
return ScanForFiles (file).GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
}
| mit | C# |
0ce7b4b4173c4cdd4e38ccd1fc57192f31917769 | Use direct nuget public feed URLs | JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support | nuget-extensions/nuget-tests/src/NuGetConstants.cs | nuget-extensions/nuget-tests/src/NuGetConstants.cs | namespace JetBrains.TeamCity.NuGet.Tests
{
public static class NuGetConstants
{
public const string DefaultFeedUrl_v1 = "https://packages.nuget.org/v1/FeedService.svc/";
public const string DefaultFeedUrl_v2 = "https://www.nuget.org/api/v2/";
public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
}
}
| namespace JetBrains.TeamCity.NuGet.Tests
{
public static class NuGetConstants
{
public const string DefaultFeedUrl_v1 = "https://go.microsoft.com/fwlink/?LinkID=206669";
public const string DefaultFeedUrl_v2 = "https://go.microsoft.com/fwlink/?LinkID=230477";
public const string NuGetDevFeed = "https://dotnet.myget.org/F/nuget-build/api/v2/";
}
} | apache-2.0 | C# |
f0cc58910cb4044ba8165f0f57d51cba9aef4b53 | fix infinite loop | xamarin/monotouch-samples,xamarin/monotouch-samples,xamarin/monotouch-samples | ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGContextExtensions.cs | ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGContextExtensions.cs | using CoreGraphics;
namespace SpeedSketch
{
public static class CGContextExtensions
{
public static void Move (this CGContext context, CGPoint point)
{
context.MoveTo (point.X, point.Y);
}
public static void AddLine (this CGContext context, CGPoint point)
{
context.AddLineToPoint (point.X, point.Y);
}
}
}
| using CoreGraphics;
namespace SpeedSketch
{
public static class CGContextExtensions
{
public static void Move (this CGContext context, CGPoint point)
{
context.MoveTo (point.X, point.Y);
}
public static void AddLine (this CGContext context, CGPoint point)
{
context.AddLine (point);
}
}
}
| mit | C# |
0cc73f228c38482b821ea304e5ee49dc1a573c8f | Fix Path | benaadams/corefxlab,ericstj/corefxlab,tarekgh/corefxlab,ericstj/corefxlab,ericstj/corefxlab,ericstj/corefxlab,ahsonkhan/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,KrzysztofCwalina/corefxlab,joshfree/corefxlab,tarekgh/corefxlab,KrzysztofCwalina/corefxlab,dotnet/corefxlab,adamsitnik/corefxlab,dotnet/corefxlab,ahsonkhan/corefxlab,benaadams/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,whoisj/corefxlab,adamsitnik/corefxlab,whoisj/corefxlab,joshfree/corefxlab | src/System.IO.FileSystem.Watcher.Polling/System/IO/FileChange.cs | src/System.IO.FileSystem.Watcher.Polling/System/IO/FileChange.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.Diagnostics;
namespace System.IO.FileSystem
{
public struct FileChange
{
string _directory;
string _path;
ChangeType _chageType;
internal FileChange(string directory, string path, ChangeType type)
{
Debug.Assert(path != null);
_directory = directory;
_path = path;
_chageType = type;
}
public string Name
{
get
{
return _path;
}
}
public ChangeType ChangeType
{
get
{
return _chageType;
}
}
public string Directory
{
get
{
return _directory;
}
}
public string Path
{
get
{
return _path;
}
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
namespace System.IO.FileSystem
{
public struct FileChange
{
string _directory;
string _path;
ChangeType _chageType;
internal FileChange(string directory, string path, ChangeType type)
{
Debug.Assert(path != null);
_directory = directory;
_path = path;
_chageType = type;
}
public string Name
{
get
{
return _path;
}
}
public ChangeType ChangeType
{
get
{
return _chageType;
}
}
public string Directory
{
get
{
return _directory;
}
}
public string Path
{
get
{
return Directory + '\\' + Name;
}
}
}
}
| mit | C# |
2436ee589d25d77e159b09b63b88fcacddf06f40 | Remove incorrect API response | smoogipoo/osu,2yangk23/osu,peppy/osu,peppy/osu,ppy/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu,ZLima12/osu,DrabWeb/osu,ppy/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,naoey/osu,naoey/osu,EVAST9919/osu,peppy/osu-new,UselessToucan/osu,2yangk23/osu,johnneijzen/osu,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,EVAST9919/osu | osu.Game/Online/API/Requests/JoinChannelRequest.cs | osu.Game/Online/API/Requests/JoinChannelRequest.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.Chat;
using osu.Game.Users;
namespace osu.Game.Online.API.Requests
{
public class JoinChannelRequest : APIRequest
{
private readonly Channel channel;
private readonly User user;
public JoinChannelRequest(Channel channel, User user)
{
this.channel = channel;
this.user = user;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
return req;
}
protected override string Target => $@"chat/channels/{channel.Id}/users/{user.Id}";
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.Chat;
using osu.Game.Users;
namespace osu.Game.Online.API.Requests
{
public class JoinChannelRequest : APIRequest<Channel>
{
private readonly Channel channel;
private readonly User user;
public JoinChannelRequest(Channel channel, User user)
{
this.channel = channel;
this.user = user;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
return req;
}
protected override string Target => $@"chat/channels/{channel.Id}/users/{user.Id}";
}
}
| mit | C# |
331b380dd5d7c17f47d1a127c9ed674a7ae88724 | add namespace. | scienceagora4dim/Stereoscopic4D | Assets/Stereoscopic4D/Scripts/Transform4D.cs | Assets/Stereoscopic4D/Scripts/Transform4D.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Stereoscopic4D {
/// <summary>
/// This class extends GameObject to 4D transform
/// </summary>
public class Transform4D : MonoBehaviour {
/// <summary>
/// w position.
/// </summary>
public float w;
[Header("Rotation with W")]
/// <summary>
/// The XZ rotation.
/// </summary>
public float xz;
/// <summary>
/// The YZ rotation.
/// </summary>
public float yz;
/// <summary>
/// The XY rotation.
/// </summary>
public float xy;
/// <summary>
/// Gets or sets the 4D position.
/// </summary>
/// <value>The 4D position.</value>
public Vector4 position {
get {
Vector3 pos = transform.position;
return new Vector4 (pos.x, pos.y, pos.z, w);
}
set {
transform.position = new Vector3 (value.x, value.y, value.z);
w = value.w;
}
}
/// <summary>
/// Gets or sets the world rotation with w.
/// </summary>
/// <value>The local rotation with w.</value>
public Quaternion rotationWithW {
get {
return Quaternion.Euler (xz, yz, xy);
}
set {
Vector3 angles = value.eulerAngles;
xz = angles.x;
yz = angles.y;
xy = angles.z;
}
}
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This class extends GameObject to 4D transform
/// </summary>
public class Transform4D : MonoBehaviour {
/// <summary>
/// w position.
/// </summary>
public float w;
[Header("Rotation with W")]
/// <summary>
/// The XZ rotation.
/// </summary>
public float xz;
/// <summary>
/// The YZ rotation.
/// </summary>
public float yz;
/// <summary>
/// The XY rotation.
/// </summary>
public float xy;
/// <summary>
/// Gets or sets the 4D position.
/// </summary>
/// <value>The 4D position.</value>
public Vector4 position {
get {
Vector3 pos = transform.position;
return new Vector4 (pos.x, pos.y, pos.z, w);
}
set {
transform.position = new Vector3 (value.x, value.y, value.z);
w = value.w;
}
}
/// <summary>
/// Gets or sets the world rotation with w.
/// </summary>
/// <value>The local rotation with w.</value>
public Quaternion rotationWithW {
get {
return Quaternion.Euler (xz, yz, xy);
}
set {
Vector3 angles = value.eulerAngles;
xz = angles.x;
yz = angles.y;
xy = angles.z;
}
}
}
| mit | C# |
91bbb4b0c4ea6609a2cd57c0b64c9fa7662224e6 | use fixed precision for AvrTime and StdDev. | alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,redknightlois/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,redknightlois/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,redknightlois/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Ky7m/BenchmarkDotNet | BenchmarkDotNet/Reports/BenchmarkTimeSpan.cs | BenchmarkDotNet/Reports/BenchmarkTimeSpan.cs | namespace BenchmarkDotNet.Reports
{
public class BenchmarkTimeSpan
{
public double Nanoseconds { get; }
public double Microseconds => Nanoseconds / 1000;
public double Milliseconds => Nanoseconds / 1000 / 1000;
public double Seconds => Nanoseconds / 1000 / 1000 / 1000;
public BenchmarkTimeSpan(double nanoseconds)
{
Nanoseconds = nanoseconds;
}
public override string ToString()
{
// Use fixed decimal precision for all numbers here so everything aligns nicely
// in the tabular reports. Four decimal places seems a good compromise.
// Note extra space between number and "s" to align that nicely too.
if (Nanoseconds < 1000)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:N4} ns", Nanoseconds);
if (Microseconds < 1000)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:N4} us", Microseconds);
if (Milliseconds < 1000)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:N4} ms", Milliseconds);
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:N4} s", Seconds);
}
}
} | namespace BenchmarkDotNet.Reports
{
public class BenchmarkTimeSpan
{
public double Nanoseconds { get; }
public double Microseconds => Nanoseconds / 1000;
public double Milliseconds => Nanoseconds / 1000 / 1000;
public double Seconds => Nanoseconds / 1000 / 1000 / 1000;
public BenchmarkTimeSpan(double nanoseconds)
{
Nanoseconds = nanoseconds;
}
public override string ToString()
{
if (Nanoseconds < 0.001)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.000000} ns", Nanoseconds);
if (Nanoseconds < 0.01)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.00000} ns", Nanoseconds);
if (Nanoseconds < 0.1)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.0000} ns", Nanoseconds);
if (Nanoseconds < 1)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.000} ns", Nanoseconds);
if (Nanoseconds < 1000)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.00} ns", Nanoseconds);
if (Microseconds < 1000)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.00} us", Microseconds);
if (Milliseconds < 1000)
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.00} ms", Milliseconds);
return string.Format(EnvironmentHelper.MainCultureInfo, "{0:0.00} s", Seconds);
}
}
} | mit | C# |
5fbac9001dedbef39d1402f1ec3a7539944c679c | Update version for 6.2 release | braegelno5/Bonobo-Git-Server,crowar/Bonobo-Git-Server,gencer/Bonobo-Git-Server,crowar/Bonobo-Git-Server,gencer/Bonobo-Git-Server,crowar/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,gencer/Bonobo-Git-Server,crowar/Bonobo-Git-Server,gencer/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,crowar/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,kfarnung/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,igoryok-zp/Bonobo-Git-Server,braegelno5/Bonobo-Git-Server,crowar/Bonobo-Git-Server | Bonobo.Git.Server/Properties/AssemblyInfo.cs | Bonobo.Git.Server/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web;
// 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("Bonobo Git Server")]
[assembly: AssemblyDescription("Git server for IIS.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jakub Chodounský")]
[assembly: AssemblyProduct("Bonobo Git Server")]
[assembly: AssemblyCopyright("Copyright © Jakub Chodounský 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8e4b4ef1-11ba-490f-94bb-1a000f3f5a03")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.2.0.0")]
[assembly: AssemblyFileVersion("6.2.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web;
// 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("Bonobo Git Server")]
[assembly: AssemblyDescription("Git server for IIS.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jakub Chodounský")]
[assembly: AssemblyProduct("Bonobo Git Server")]
[assembly: AssemblyCopyright("Copyright © Jakub Chodounský 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8e4b4ef1-11ba-490f-94bb-1a000f3f5a03")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.1.0.0")]
[assembly: AssemblyFileVersion("6.1.0.0")]
| mit | C# |
38eb597d230b4fed8b1842f2b62a9897711e4047 | fix dumb stuff. | RevitAirflowDesigner/RevitAirflowDesigner,RevitAirflowDesigner/RevitAirflowDesigner | revit_addin/AirflowDesigner/ExternalApp.cs | revit_addin/AirflowDesigner/ExternalApp.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.UI;
namespace AirflowDesigner
{
public class ExternalApp : IExternalApplication
{
private Autodesk.Revit.UI.UIControlledApplication _app;
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
_app = application;
buildUI();
return Result.Succeeded;
}
private void buildUI()
{
var panel = _app.CreateRibbonPanel(Tab.AddIns, "Airflow" + Environment.NewLine + "Designer");
var save = new PushButtonData("AirflowDesigner", "Airflow Designer", System.Reflection.Assembly.GetExecutingAssembly().Location, "AirflowDesigner.Command");
save.ToolTip = "Analyze the model for airflow, help make decisions";
save.LongDescription = "Look at possible shaft locations";
//save.LargeImage = getImage("LifeSaver.Images.lifesaver-32.png");
//save.Image = getImage("LifeSaver.Images.lifesaver-16.png");
panel.AddItem(save);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.UI;
namespace AirflowDesigner
{
public class ExternalApp : IExternalApplication
{
private Autodesk.Revit.UI.UIControlledApplication _app;
public Result OnShutdown(UIControlledApplication application)
{
_app = application;
buildUI();
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
return Result.Succeeded;
}
private void buildUI()
{
var panel = _app.CreateRibbonPanel(Tab.AddIns, "Airflow" + Environment.NewLine + "Designer");
var save = new PushButtonData("AirflowDesigner", "Airflow Designer", System.Reflection.Assembly.GetExecutingAssembly().Location, "AirflowDesigner.Command");
save.ToolTip = "Analyze the model for airflow, help make decisions";
save.LongDescription = "Look at possible shaft locations";
//save.LargeImage = getImage("LifeSaver.Images.lifesaver-32.png");
//save.Image = getImage("LifeSaver.Images.lifesaver-16.png");
panel.AddItem(save);
}
}
}
| mit | C# |
9a76f71cd5bceb550234d62b212bbe104f21dff2 | Increase interpolation offset safety value | gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Client/Systems/SettingsSys/SettingsSystem.cs | Client/Systems/SettingsSys/SettingsSystem.cs | using LunaClient.Base;
using LunaClient.Localization;
using LunaClient.Network;
using LunaCommon.Enums;
using System;
using System.Text;
namespace LunaClient.Systems.SettingsSys
{
public class SettingsSystem : MessageSystem<SettingsSystem, SettingsMessageSender, SettingsMessageHandler>
{
public static SettingStructure CurrentSettings { get; }
public static SettingsServerStructure ServerSettings { get; private set; } = new SettingsServerStructure();
private static readonly StringBuilder Builder = new StringBuilder();
public override string SystemName { get; } = nameof(SettingsSystem);
static SettingsSystem() => CurrentSettings = SettingsReadSaveHandler.ReadSettings();
protected override void OnDisabled()
{
base.OnDisabled();
ServerSettings = new SettingsServerStructure();
}
public static void SaveSettings()
{
SettingsReadSaveHandler.SaveSettings(CurrentSettings);
}
public static bool ValidateSettings()
{
Builder.Length = 0;
var validationResult = true;
if ((int) ServerSettings.TerrainQuality != PQSCache.PresetList.presetIndex)
{
validationResult = false;
Builder.Append($"Your terrain quality ({((TerrainQuality)PQSCache.PresetList.presetIndex).ToString()}) " +
$"does not match the server quality ({ServerSettings.TerrainQuality.ToString()}).");
}
if (!validationResult)
{
NetworkConnection.Disconnect(Builder.ToString());
}
return validationResult;
}
/// <summary>
/// Here we can adjust local settings to what we received from the server
/// </summary>
public void AdjustLocalSettings()
{
//Increase the interpolation offset if necessary
var minRecommendedInterpolationOffset = TimeSpan.FromMilliseconds(ServerSettings.SecondaryVesselUpdatesMsInterval * 4).TotalSeconds;
if (CurrentSettings.InterpolationOffsetSeconds < minRecommendedInterpolationOffset)
{
LunaScreenMsg.PostScreenMessage(LocalizationContainer.ScreenText.IncreasedInterpolationOffset, 30, ScreenMessageStyle.UPPER_RIGHT);
LunaLog.LogWarning(LocalizationContainer.ScreenText.IncreasedInterpolationOffset);
CurrentSettings.InterpolationOffsetSeconds = minRecommendedInterpolationOffset;
}
}
}
}
| using LunaClient.Base;
using LunaClient.Localization;
using LunaClient.Network;
using LunaCommon.Enums;
using System;
using System.Text;
namespace LunaClient.Systems.SettingsSys
{
public class SettingsSystem : MessageSystem<SettingsSystem, SettingsMessageSender, SettingsMessageHandler>
{
public static SettingStructure CurrentSettings { get; }
public static SettingsServerStructure ServerSettings { get; private set; } = new SettingsServerStructure();
private static readonly StringBuilder Builder = new StringBuilder();
public override string SystemName { get; } = nameof(SettingsSystem);
static SettingsSystem() => CurrentSettings = SettingsReadSaveHandler.ReadSettings();
protected override void OnDisabled()
{
base.OnDisabled();
ServerSettings = new SettingsServerStructure();
}
public static void SaveSettings()
{
SettingsReadSaveHandler.SaveSettings(CurrentSettings);
}
public static bool ValidateSettings()
{
Builder.Length = 0;
var validationResult = true;
if ((int) ServerSettings.TerrainQuality != PQSCache.PresetList.presetIndex)
{
validationResult = false;
Builder.Append($"Your terrain quality ({((TerrainQuality)PQSCache.PresetList.presetIndex).ToString()}) " +
$"does not match the server quality ({ServerSettings.TerrainQuality.ToString()}).");
}
if (!validationResult)
{
NetworkConnection.Disconnect(Builder.ToString());
}
return validationResult;
}
/// <summary>
/// Here we can adjust local settings to what we received from the server
/// </summary>
public void AdjustLocalSettings()
{
//Increase the interpolation offset if necessary
var minRecommendedInterpolationOffset = TimeSpan.FromMilliseconds(ServerSettings.SecondaryVesselUpdatesMsInterval * 3).TotalSeconds;
if (CurrentSettings.InterpolationOffsetSeconds < minRecommendedInterpolationOffset)
{
LunaScreenMsg.PostScreenMessage(LocalizationContainer.ScreenText.IncreasedInterpolationOffset, 30, ScreenMessageStyle.UPPER_RIGHT);
CurrentSettings.InterpolationOffsetSeconds = minRecommendedInterpolationOffset;
}
}
}
}
| mit | C# |
8a8c26924ecad03d7a7c83e6ef1366360c69f792 | Fix RepairMultiplier | gakada/KanColleViewer,KatoriKai/KanColleViewer,heartfelt-fancy/KanColleViewer,gakada/KanColleViewer,BossaGroove/KanColleViewer,kookxiang/KanColleViewer,gakada/KanColleViewer,yuyuvn/KanColleViewer,bllue78/KanColleViewer,Astrologers/KanColleViewer,AnnaKutou/KanColleViewer | Grabacr07.KanColleWrapper/Models/ShipType.cs | Grabacr07.KanColleWrapper/Models/ShipType.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grabacr07.KanColleWrapper.Models.Raw;
using Grabacr07.KanColleWrapper.Internal;
namespace Grabacr07.KanColleWrapper.Models
{
/// <summary>
/// 艦種を表します。
/// </summary>
public class ShipType : RawDataWrapper<kcsapi_mst_stype>, IIdentifiable
{
public int Id
{
get { return this.RawData.api_id; }
}
public string Name
{
get
{
return KanColleClient.Current.Translations.GetTranslation(RawData.api_name, TranslationType.ShipTypes, this.RawData, this.Id);
}
}
public int SortNumber
{
get { return this.RawData.api_sortno; }
}
public double RepairMultiplier
{
get
{
return this.RawData.api_scnt * 0.5;
}
}
public ShipType(kcsapi_mst_stype rawData) : base(rawData) { }
public override string ToString()
{
return string.Format("ID = {0}, Name = \"{1}\"", this.Id, this.Name);
}
#region static members
private static readonly ShipType dummy = new ShipType(new kcsapi_mst_stype
{
api_id = 999,
api_sortno = 999,
api_name = "不審船",
});
public static ShipType Dummy
{
get { return dummy; }
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grabacr07.KanColleWrapper.Models.Raw;
using Grabacr07.KanColleWrapper.Internal;
namespace Grabacr07.KanColleWrapper.Models
{
/// <summary>
/// 艦種を表します。
/// </summary>
public class ShipType : RawDataWrapper<kcsapi_mst_stype>, IIdentifiable
{
public int Id
{
get { return this.RawData.api_id; }
}
public string Name
{
get
{
return KanColleClient.Current.Translations.GetTranslation(RawData.api_name, TranslationType.ShipTypes, this.RawData, this.Id);
}
}
public int SortNumber
{
get { return this.RawData.api_sortno; }
}
public double RepairMultiplier
{
get
{
switch ((ShipTypeId)this.Id)
{
case ShipTypeId.Submarine:
return 0.5;
case ShipTypeId.HeavyCruiser:
case ShipTypeId.RepairShip:
case ShipTypeId.FastBattleship:
case ShipTypeId.LightAircraftCarrier:
return 1.5;
case ShipTypeId.Battleship:
case ShipTypeId.Superdreadnought:
case ShipTypeId.AerialBattleship:
case ShipTypeId.AircraftCarrier:
case ShipTypeId.ArmoredAircraftCarrier:
return 2;
default:
return 1;
}
}
}
public ShipType(kcsapi_mst_stype rawData) : base(rawData) { }
public override string ToString()
{
return string.Format("ID = {0}, Name = \"{1}\"", this.Id, this.Name);
}
#region static members
private static readonly ShipType dummy = new ShipType(new kcsapi_mst_stype
{
api_id = 999,
api_sortno = 999,
api_name = "不審船",
});
public static ShipType Dummy
{
get { return dummy; }
}
#endregion
}
}
| mit | C# |
4b59421343ab2a5af8497b910071289dd9f3c0af | Convert candidates to an array. | brendanjbaker/Bakery | src/Bakery.Cqrs.SimpleInjector/Bakery/Cqrs/SimpleInjectorDispatcher.cs | src/Bakery.Cqrs.SimpleInjector/Bakery/Cqrs/SimpleInjectorDispatcher.cs | namespace Bakery.Cqrs
{
using SimpleInjector;
using System;
using System.Linq;
using System.Threading.Tasks;
public class SimpleInjectorDispatcher
: IDispatcher
{
private readonly Container container;
public SimpleInjectorDispatcher(Container container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
this.container = container;
}
public async Task CommandAsync<TCommand>(TCommand command)
where TCommand : ICommand
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(typeof(TCommand));
foreach (var handler in handlers)
await handler.HandleAsync(command);
}
public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
var handlers = container.GetAllInstances(handlerType).ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(query.GetType());
if (handlers.Multiple())
throw new MultipleRegistrationsFoundException(query.GetType());
dynamic handler = handlers.Single();
return await handler.HandleAsync(query as dynamic);
}
}
}
| namespace Bakery.Cqrs
{
using SimpleInjector;
using System;
using System.Linq;
using System.Threading.Tasks;
public class SimpleInjectorDispatcher
: IDispatcher
{
private readonly Container container;
public SimpleInjectorDispatcher(Container container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
this.container = container;
}
public async Task CommandAsync<TCommand>(TCommand command)
where TCommand : ICommand
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var handlers = container.GetAllInstances<ICommandHandler<TCommand>>().ToArray();
if (!handlers.Any())
throw new NoRegistrationFoundException(typeof(TCommand));
foreach (var handler in handlers)
await handler.HandleAsync(command);
}
public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
var handlers = container.GetAllInstances(handlerType);
if (!handlers.Any())
throw new NoRegistrationFoundException(query.GetType());
if (handlers.Multiple())
throw new MultipleRegistrationsFoundException(query.GetType());
dynamic handler = handlers.Single();
return await handler.HandleAsync(query as dynamic);
}
}
}
| mit | C# |
d169e64767635f5868b1ff524d44aa97bdfc5f19 | add labels | Xarlot/NGitLab | NGitLab/NGitLab/Models/MergeRequestUpdate.cs | NGitLab/NGitLab/Models/MergeRequestUpdate.cs | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace NGitLab.Models {
[DataContract]
public class MergeRequestUpdate {
[DataMember(Name = "source_branch")]
public string SourceBranch { get; set; }
[DataMember(Name = "target_branch")]
public string TargetBranch { get; set; }
[DataMember(Name = "assignee_id")]
public int? AssigneeId { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "description")]
public string Description;
[DataMember(Name = "labels")]
public string Labels;
[DataMember(Name = "state_event")]
[JsonConverter(typeof(StringEnumConverter))]
public MergeRequestUpdateState? NewState { get; set; }
}
// ReSharper disable InconsistentNaming
public enum MergeRequestUpdateState {
close,
reopen,
merge,
}
} | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace NGitLab.Models {
[DataContract]
public class MergeRequestUpdate {
[DataMember(Name = "source_branch")]
public string SourceBranch { get; set; }
[DataMember(Name = "target_branch")]
public string TargetBranch { get; set; }
[DataMember(Name = "assignee_id")]
public int? AssigneeId { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "description")]
public string Description;
[DataMember(Name = "state_event")]
[JsonConverter(typeof(StringEnumConverter))]
public MergeRequestUpdateState? NewState { get; set; }
}
// ReSharper disable InconsistentNaming
public enum MergeRequestUpdateState {
close,
reopen,
merge,
}
} | mit | C# |
103eac17a6627eadaf82b0b9c06112340aaa2d5e | Fix eample packet handler | RainwayApp/sachiel-net | SachielExample/Handlers/FilePacketHandler.cs | SachielExample/Handlers/FilePacketHandler.cs | using System;
using System.Collections.Generic;
using ProtoBuf;
using Sachiel;
using Sachiel.Messages;
using Sachiel.Messages.Packets;
using SachielExample.Models;
namespace SachielExample.Handlers
{
[ProtoContract]
[SachielHeader(Endpoint = "TreeResponse")]
internal class TreeResponse : Message
{
[ProtoMember(1)]
public FileTree Tree { get; set; }
}
internal class FilePacketHandler : PacketHandler
{
private PacketCallback _callback;
private Consumer _consumer;
private Message _message;
private Packet _packet;
public override void HandlePacket(Consumer consumer, Packet packet)
{
_consumer = consumer;
_packet = packet;
_message = _packet.Message;
SyncKey = _message.Header.SyncKey;
_callback = new PacketCallback {Endpoint = _message.Header.Endpoint };
switch (_message.Header.Endpoint)
{
case "RequestFileTree":
RequestFileTree();
break;
}
}
protected override string SyncKey { get; set; }
private void RequestFileTree()
{
var fileRequest = (RequestFileTree) _message.Source;
Console.WriteLine($"Request for {fileRequest.Path} received");
var response = new TreeResponse {Tree = new FileTree(fileRequest.Path)};
_callback.Response = response.Serialize();
_consumer.Reply(_callback);
}
}
} | using System;
using System.Collections.Generic;
using ProtoBuf;
using Sachiel;
using Sachiel.Messages;
using Sachiel.Messages.Packets;
using SachielExample.Models;
namespace SachielExample.Handlers
{
[ProtoContract]
[SachielHeader(Endpoint = "TreeResponse")]
internal class TreeResponse : Message
{
[ProtoMember(1)]
public FileTree Tree { get; set; }
}
internal class FilePacketHandler : PacketHandler
{
private PacketCallback _callback;
private Consumer _consumer;
private Message _message;
private Packet _packet;
public override void HandlePacket(Consumer consumer, Packet packet)
{
_consumer = consumer;
_packet = packet;
_message = _packet.Message;
SyncKey = _message.Header.SyncKey;
_callback = new PacketCallback {Endpoint = _message.Header.Endpoint };
switch (_message.Header.Endpoint)
{
case "RequestFileTree":
RequestFileTree();
break;
}
}
protected override string SyncKey { get; set; }
private void RequestFileTree()
{
var fileRequest = (RequestFileTree) _message;
Console.WriteLine($"Request for {fileRequest.Path} received");
var response = new TreeResponse {Tree = new FileTree(fileRequest.Path)};
_callback.Response = response.Serialize();
_consumer.Reply(_callback);
}
}
} | apache-2.0 | C# |
0e1b50b38d4860f4bb38dfc5649f804faa131f58 | Fix Clear-Bitmap being completely broken now, oops. | Prof9/PixelPet | PixelPet/Workbench.cs | PixelPet/Workbench.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
this.Bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
this.Graphics = Graphics.FromImage(this.Bitmap);
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace PixelPet {
/// <summary>
/// PixelPet workbench instance.
/// </summary>
public class Workbench {
public IList<Color> Palette { get; }
public Bitmap Bitmap { get; private set; }
public Graphics Graphics { get; private set; }
public MemoryStream Stream { get; private set; }
public Workbench() {
this.Palette = new List<Color>();
ClearBitmap(8, 8);
this.Stream = new MemoryStream();
}
public void ClearBitmap(int width, int height) {
Bitmap bmp = null;
try {
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
SetBitmap(bmp);
} finally {
if (bmp != null) {
bmp.Dispose();
}
}
this.Graphics.Clear(Color.Transparent);
this.Graphics.Flush();
}
public void SetBitmap(Bitmap bmp) {
if (this.Graphics != null) {
this.Graphics.Dispose();
}
if (this.Bitmap != null) {
this.Bitmap.Dispose();
}
this.Bitmap = bmp;
this.Graphics = Graphics.FromImage(this.Bitmap);
}
}
}
| mit | C# |
2fed704da29568f6f16c29c0036748020373e01c | Fix method documentation | nuhaven/Nuhaven.Collections.Generic.Extensions | src/Nuhaven.Collections.Generic.Extensions/EnumerableExtensions.cs | src/Nuhaven.Collections.Generic.Extensions/EnumerableExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Nuhaven.Collections.Generic
{
public static class EnumerableExtensions
{
/// <summary>
/// Tells if a Enumerable is null or empty
/// </summary>
/// <param name="value">The IEnumerable instance</param>
/// <returns>Returns true if the enumerable is empty or null</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> value) =>
null == value || !value.Any();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Nuhaven.Collections.Generic
{
public static class EnumerableExtensions
{
/// <summary>
/// Tells if a Enumerable is null or empty
/// </summary>
/// </remarks>
/// <param name="value">The IEnumerable instance</param>
/// <returns>Returns true if the enumerable is empty or null</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> value) =>
null == value || !value.Any();
}
}
| mit | C# |
1ecae82116daddcf9426ac793323cf1ffb50412f | add undefined message dir | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TeraPacketParser/Data/MessageDirection.cs | TeraPacketParser/Data/MessageDirection.cs | namespace TeraPacketParser.Data
{
public enum MessageDirection
{
Undefined = 0,
ClientToServer = 1,
ServerToClient = 2
}
} | namespace TeraPacketParser.Data
{
public enum MessageDirection
{
ClientToServer = 1,
ServerToClient = 2
}
} | mit | C# |
d841f814e9ac5f499c2e15cfcf3b8d0e66b0869c | bump version | ntent-ad/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,DeonHeyns/Metrics.NET,alhardy/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,huoxudong125/Metrics.NET,mnadel/Metrics.NET,Recognos/Metrics.NET | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Iulian Margarintescu @ Erata.NET")]
[assembly: AssemblyProduct("Metrics.NET")]
[assembly: AssemblyCopyright("Copyright Iulian Margarintescu © 2014")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.6")]
[assembly: AssemblyFileVersion("0.1.6")]
[assembly: AssemblyInformationalVersion("0.1.6")] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Iulian Margarintescu @ Erata.NET")]
[assembly: AssemblyProduct("Metrics.NET")]
[assembly: AssemblyCopyright("Copyright Iulian Margarintescu © 2014")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.5")]
[assembly: AssemblyFileVersion("0.1.5")]
[assembly: AssemblyInformationalVersion("0.1.5")] | apache-2.0 | C# |
444208c0fba117a7b212ba3510ee5d343a3532c0 | Allow manually specifying your own app descriptor XML file. | roblillack/monoberry,roblillack/monoberry,roblillack/monoberry,roblillack/monoberry | tooling/Debug.cs | tooling/Debug.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace MonoBerry.Tool
{
public class Debug : Command
{
public override string Name {
get { return "debug"; }
}
public override string Description {
get { return "Runs an assembly on a BlackBerry device in dev mode."; }
}
public override void Execute (IList<string> parameters)
{
var appName = Path.GetFileNameWithoutExtension (parameters [0]);
var device = GetDevice (parameters);
var file = parameters [0];
if (file.EndsWith (".exe")) {
Package p = Application.GetCommand<Package> ();
p.CreateAppDescriptor (parameters [0], device.Architecture, true);
file = "app-descriptor.xml";
} else if (file.EndsWith (".xml")) {
// nothing to do …
} else {
throw new ArgumentException (String.Format ("Unknown file format: {0}", file));
}
// TODO: blackberry-nativepackager -package assemblyname.bar app-descriptor.xml
// -devMode -target bar-debug -installApp -launchApp -device XXX -password XXX
// /Developer/SDKs/bbndk-10.0.4-beta/host/macosx/x86/usr/bin/blackberry-nativepackager
var cmd = String.Format ("{0}/usr/bin/blackberry-nativepackager -package {1}.bar {2} " +
"-devMode -target bar-debug -installApp -launchApp -device {3} -password {4}",
Application.Configuration.QNXHostPath,
appName,
file,
device.IP,
device.Password);
Run (cmd);
}
private static void Run (string cmd)
{
try {
using (Process proc = Process.Start ("/bin/sh", String.Format ("-c '{0}'", cmd))) {
proc.WaitForExit();
}
} catch (Exception e) {
throw new Error (String.Format ("Error running command {0}: {1}", cmd, e.Message));
}
}
private Device GetDevice (IList<string> parameters)
{
var devs = Application.Configuration.GetDevices ();
if (devs.Count == 1) {
var e = devs.Values.GetEnumerator ();
e.MoveNext ();
return e.Current;
} else if (devs.Count == 0) {
throw new Error ("No devices configured.");
} else if (parameters.Count == 2) {
return devs [parameters [1]];
}
throw new Error ("Please specify a device.");
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace MonoBerry.Tool
{
public class Debug : Command
{
public override string Name {
get { return "debug"; }
}
public override string Description {
get { return "Runs an assembly on a BlackBerry device in dev mode."; }
}
public override void Execute (IList<string> parameters)
{
var appName = Path.GetFileNameWithoutExtension (parameters [0]);
var device = GetDevice (parameters);
Package p = Application.GetCommand<Package> ();
p.CreateAppDescriptor (parameters [0], device.Architecture, true);
// TODO: blackberry-nativepackager -package assemblyname.bar app-descriptor.xml
// -devMode -target bar-debug -installApp -launchApp -device XXX -password XXX
// /Developer/SDKs/bbndk-10.0.4-beta/host/macosx/x86/usr/bin/blackberry-nativepackager
var cmd = String.Format ("{0}/usr/bin/blackberry-nativepackager -package {1}.bar {2} " +
"-devMode -target bar-debug -installApp -launchApp -device {3} -password {4}",
Application.Configuration.QNXHostPath,
appName,
"app-descriptor.xml",
device.IP,
device.Password);
Run (cmd);
}
private static void Run (string cmd)
{
try {
using (Process proc = Process.Start ("/bin/sh", String.Format ("-c '{0}'", cmd))) {
proc.WaitForExit();
}
} catch (Exception e) {
throw new Error (String.Format ("Error running command {0}: {1}", cmd, e.Message));
}
}
private Device GetDevice (IList<string> parameters)
{
var devs = Application.Configuration.GetDevices ();
if (devs.Count == 1) {
var e = devs.Values.GetEnumerator ();
e.MoveNext ();
return e.Current;
} else if (devs.Count == 0) {
throw new Error ("No devices configured.");
} else if (parameters.Count == 2) {
return devs [parameters [1]];
}
throw new Error ("Please specify a device.");
}
}
}
| mit | C# |
a7df08f41bc1d3897087b4eb6a466d2ad9bdfe3b | Add colons for consistency | mono/dbus-sharp,arfbtwn/dbus-sharp,openmedicus/dbus-sharp,arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,openmedicus/dbus-sharp,Tragetaschen/dbus-sharp | tools/Monitor.cs | tools/Monitor.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class Monitor
{
public static void Main (string[] args)
{
Connection bus;
if (args.Length >= 1) {
string arg = args[0];
switch (arg)
{
case "--system":
bus = Bus.System;
break;
case "--session":
bus = Bus.Session;
break;
default:
Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]");
Console.Error.WriteLine (" If no watch expressions are provided, defaults will be used.");
return;
}
} else {
bus = Bus.Session;
}
if (args.Length > 1) {
//install custom match rules only
for (int i = 1 ; i != args.Length ; i++)
bus.AddMatch (args[i]);
} else {
//no custom match rules, install the defaults
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
}
while (true) {
Message msg = bus.ReadMessage ();
if (msg == null)
break;
PrintMessage (msg);
Console.WriteLine ();
}
}
internal static void PrintMessage (Message msg)
{
Console.WriteLine ("Message (" + msg.Header.Endianness + " endian, v" + msg.Header.MajorVersion + "):");
Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType);
Console.WriteLine ("\t" + "Flags: " + msg.Header.Flags);
Console.WriteLine ("\t" + "Serial: " + msg.Header.Serial);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine ("\t" + hf.Code + ": " + hf.Value);
Console.WriteLine ("\tHeader Fields:");
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine ("\t\t" + field.Key + ": " + field.Value);
Console.WriteLine ("\tBody (" + msg.Header.Length + " bytes):");
if (msg.Body != null) {
MessageReader reader = new MessageReader (msg);
//TODO: this needs to be done more intelligently
try {
foreach (DType dtype in msg.Signature.GetBuffer ()) {
if (dtype == DType.Invalid)
continue;
object arg;
reader.GetValue (dtype, out arg);
Console.WriteLine ("\t\t" + dtype + ": " + arg);
}
} catch {
Console.WriteLine ("\t\tmonitor is too dumb to decode message body");
}
}
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class Monitor
{
public static void Main (string[] args)
{
Connection bus;
if (args.Length >= 1) {
string arg = args[0];
switch (arg)
{
case "--system":
bus = Bus.System;
break;
case "--session":
bus = Bus.Session;
break;
default:
Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]");
Console.Error.WriteLine (" If no watch expressions are provided, defaults will be used.");
return;
}
} else {
bus = Bus.Session;
}
if (args.Length > 1) {
//install custom match rules only
for (int i = 1 ; i != args.Length ; i++)
bus.AddMatch (args[i]);
} else {
//no custom match rules, install the defaults
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
}
while (true) {
Message msg = bus.ReadMessage ();
if (msg == null)
break;
PrintMessage (msg);
Console.WriteLine ();
}
}
internal static void PrintMessage (Message msg)
{
Console.WriteLine ("Message (" + msg.Header.Endianness + " endian, v" + msg.Header.MajorVersion + ")");
Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType);
Console.WriteLine ("\t" + "Flags: " + msg.Header.Flags);
Console.WriteLine ("\t" + "Serial: " + msg.Header.Serial);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine ("\t" + hf.Code + ": " + hf.Value);
Console.WriteLine ("\tHeader Fields:");
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine ("\t\t" + field.Key + ": " + field.Value);
Console.WriteLine ("\tBody (" + msg.Header.Length + " bytes)");
if (msg.Body != null) {
MessageReader reader = new MessageReader (msg);
//TODO: this needs to be done more intelligently
try {
foreach (DType dtype in msg.Signature.GetBuffer ()) {
if (dtype == DType.Invalid)
continue;
object arg;
reader.GetValue (dtype, out arg);
Console.WriteLine ("\t\t" + dtype + ": " + arg);
}
} catch {
Console.WriteLine ("\t\tmonitor is too dumb to decode message body");
}
}
}
}
| mit | C# |
52ba0af37675519fa5be8298ee446324533b073a | Fix stackowerflow | prifio/Assignment2 | Assignment2Application/Assignment2Application/FibonacciGenerator.cs | Assignment2Application/Assignment2Application/FibonacciGenerator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment2Application
{
public class FibonacciGenerator
{
/// <summary>
/// Return n-th Fibonacci number.
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
List<long> F;
public FibonacciGenerator()
{
F = new List<long>();
F.Add(1);
F.Add(1);
}
public long Get(int n)
{
if (n > 1e6)
return 0;
if (n < F.Count)
return F[n];
long res = Get(n - 1) + Get(n - 2);
F.Add(res);
return res;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment2Application
{
public class FibonacciGenerator
{
/// <summary>
/// Return n-th Fibonacci number.
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
List<long> F;
public FibonacciGenerator()
{
F = new List<long>();
F.Add(1);
F.Add(1);
}
public long Get(int n)
{
if (n < F.Count)
return F[n];
long res = Get(n - 1) + Get(n - 2);
F.Add(res);
return res;
}
}
}
| mit | C# |
a74e873b983678993ca7d3c4c6d20468d052e9b7 | remove useless using | ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game.Rulesets.Taiko/Edit/TaikoHitObjectComposer.cs | osu.Game.Rulesets.Taiko/Edit/TaikoHitObjectComposer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Tools;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Screens.Edit.Compose.Components;
namespace osu.Game.Rulesets.Taiko.Edit
{
public class TaikoHitObjectComposer : HitObjectComposer<TaikoHitObject>
{
public TaikoHitObjectComposer(TaikoRuleset ruleset)
: base(ruleset)
{
}
protected override IReadOnlyList<HitObjectCompositionTool> CompositionTools => new HitObjectCompositionTool[]
{
new HitCompositionTool(),
new DrumRollCompositionTool(),
new SwellCompositionTool()
};
protected override ComposeBlueprintContainer CreateBlueprintContainer()
=> new TaikoBlueprintContainer(this);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Tools;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Screens.Edit.Compose.Components;
namespace osu.Game.Rulesets.Taiko.Edit
{
public class TaikoHitObjectComposer : HitObjectComposer<TaikoHitObject>
{
public TaikoHitObjectComposer(TaikoRuleset ruleset)
: base(ruleset)
{
}
protected override IReadOnlyList<HitObjectCompositionTool> CompositionTools => new HitObjectCompositionTool[]
{
new HitCompositionTool(),
new DrumRollCompositionTool(),
new SwellCompositionTool()
};
protected override ComposeBlueprintContainer CreateBlueprintContainer()
=> new TaikoBlueprintContainer(this);
}
}
| mit | C# |
cfd70ca40adbf51e715dd57aaf19221114a256a3 | Update GraphiteProcedures.cs | PeteGoo/graphite-client,peschuster/graphite-client | source/Graphite.TSql/GraphiteProcedures.cs | source/Graphite.TSql/GraphiteProcedures.cs | using System;
using System.Net;
using System.Data;
using System.IO;
using Microsoft.SqlServer.Server;
namespace Graphite.TSql
{
public class GraphiteProcedures
{
[SqlProcedure]
public static void GraphiteSend(string host, int port, string key, int value)
{
IPAddress address = Helpers.ParseAddress(host);
using (var pipe = new TcpPipe(address, port))
{
try
{
pipe.Send(GraphiteFormatter.Format(key, value));
}
catch (InvalidOperationException exception)
{
SqlContext.Pipe.Send(exception.Message);
}
}
}
[SqlProcedure]
public static void GraphiteSendSeries(string host, int port, string Series, out string returnString)
{
IPAddress address = Helpers.ParseAddress(host);
using (var pipe = new TcpPipe(address, port))
{
returnString = "";
try
{
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(Series));
//DataTable dt = ds.Tables[0];
foreach (DataRow dr in ds.Tables[0].Rows)
{
pipe.Send(GraphiteFormatter.Format(dr[0].ToString(), Convert.ToInt32(dr[1].ToString())));
}
returnString = ds.Tables[0].Rows.Count + " values sent";
}
catch (InvalidOperationException exception)
{
SqlContext.Pipe.Send(exception.Message);
returnString = exception.Message;
}
}
}
}
}
| using System;
using System.Net;
using Microsoft.SqlServer.Server;
namespace Graphite.TSql
{
public class GraphiteProcedures
{
[SqlProcedure]
public static void GraphiteSend(string host, int port, string key, int value)
{
IPAddress address = Helpers.ParseAddress(host);
using (var pipe = new TcpPipe(address, port))
{
try
{
pipe.Send(GraphiteFormatter.Format(key, value));
}
catch (InvalidOperationException exception)
{
SqlContext.Pipe.Send(exception.Message);
}
}
}
}
}
| mit | C# |
0b4bece3c287d0896c7432a0cf31329100b0de1a | Save method added to BlogPostController | Mart-Bogdan/.Net-Architectural-Patterns,Mart-Bogdan/.Net-Architectural-Patterns | WebApp/Controllers/Api/BlogPostController.cs | WebApp/Controllers/Api/BlogPostController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApp.Abstract;
using WebApp.Abstract.Security;
using WebApp.Api.Models.Requests;
using WebApp.Api.Models.Responces;
using WorkWithDB.DAL.Abstract;
using WorkWithDB.Entity;
using WorkWithDB.Entity.Views;
namespace WebApp.Controllers.Api
{
public class BlogPostController : ApiController
{
private IAccessTokenValidator _tokenValidator = BlFactory.AccessTokenValidator;
[HttpGet]
public Result<List<BlogPost>> GetPostsOfCurrentUser(string userToken)
{
var result =
_tokenValidator.ValidateToken(userToken);
if (result != null)
{
using (var uow = UnitOfWorkFactory.CreateInstance())
{
return new Result<List<BlogPost>>(uow.BlogPostRepository.GetByUserId(result.Id).ToList());
}
}
return Result<List<BlogPost>>.Forbidden;
}
[HttpGet]
public Result<List<BlogPostWithAuthor>> GetAllWithUserNick(string userToken)
{
var result =
_tokenValidator.ValidateToken(userToken);
if (result != null)
{
using (var uow = UnitOfWorkFactory.CreateInstance())
{
return new Result<List<BlogPostWithAuthor>>(uow.BlogPostRepository.GetAllWithUserNick().ToList());
}
}
return Result<List<BlogPostWithAuthor>>.Forbidden;
}
[HttpPost]
public Result<int> Save(string userToken,[FromBody]BlogPost currentPost)
{
var result =
_tokenValidator.ValidateToken(userToken);
if (result != null)
{
using (var uow = UnitOfWorkFactory.CreateInstance())
{
int returnedVal = uow.BlogPostRepository.Insert(currentPost);
uow.Commit();
return new Result<int>(returnedVal);
}
}
return Result<int>.Forbidden;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApp.Abstract;
using WebApp.Abstract.Security;
using WebApp.Api.Models.Requests;
using WebApp.Api.Models.Responces;
using WorkWithDB.DAL.Abstract;
using WorkWithDB.Entity;
using WorkWithDB.Entity.Views;
namespace WebApp.Controllers.Api
{
public class BlogPostController : ApiController
{
private IAccessTokenValidator _tokenValidator = BlFactory.AccessTokenValidator;
[HttpGet]
public Result<List<BlogPost>> GetPostsOfCurrentUser(string userToken)
{
var result =
_tokenValidator.ValidateToken(userToken);
if (result != null)
{
using (var uow = UnitOfWorkFactory.CreateInstance())
{
return new Result<List<BlogPost>>(uow.BlogPostRepository.GetByUserId(result.Id).ToList());
}
}
return new Result<List<BlogPost>>();
}
[HttpGet]
public Result<List<BlogPostWithAuthor>> GetAllWithUserNick(string userToken)
{
var result =
_tokenValidator.ValidateToken(userToken);
if (result != null)
{
using (var uow = UnitOfWorkFactory.CreateInstance())
{
return new Result<List<BlogPostWithAuthor>>(uow.BlogPostRepository.GetAllWithUserNick().ToList());
}
}
return new Result<List<BlogPostWithAuthor>>();
}
}
}
| mit | C# |
59938e911b89aba9afc07575b328d8fdfad18fcb | Change versioning information. x2 | CXuesong/WikiClientLibrary | WikiClientLibrary/Properties/AssemblyInfo.cs | WikiClientLibrary/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("WikiClientLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WikiClientLibrary")]
[assembly: AssemblyCopyright("版权所有(C) 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("zh-Hans")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3")]
//[assembly: AssemblyFileVersion("0.2")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("WikiClientLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WikiClientLibrary")]
[assembly: AssemblyCopyright("版权所有(C) 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("zh-Hans")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2")]
//[assembly: AssemblyFileVersion("0.2")]
| apache-2.0 | C# |
094594ce641784c11eb9a63b2558d7c9a64c0e79 | Improve Monitor tool slightly | openmedicus/dbus-sharp,openmedicus/dbus-sharp,arfbtwn/dbus-sharp,arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp | tools/Monitor.cs | tools/Monitor.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
class BusMonitor
{
public static void Main (string[] args)
{
Connection bus;
if (args.Length >= 1) {
string arg = args[0];
switch (arg)
{
case "--system":
bus = Bus.System;
break;
case "--session":
bus = Bus.Session;
break;
default:
Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]");
Console.Error.WriteLine (" If no watch expressions are provided, defaults will be used.");
return;
}
} else {
bus = Bus.Session;
}
if (args.Length > 1) {
//install custom match rules only
for (int i = 1 ; i != args.Length ; i++)
bus.AddMatch (args[i]);
} else {
//no custom match rules, install the defaults
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
}
while (true) {
Message msg = bus.ReadMessage ();
if (msg == null)
break;
PrintMessage (msg);
Console.WriteLine ();
}
}
const string indent = " ";
internal static void PrintMessage (Message msg)
{
Console.WriteLine ("Message (" + msg.Header.Endianness + " endian, v" + msg.Header.MajorVersion + "):");
Console.WriteLine (indent + "Type: " + msg.Header.MessageType);
Console.WriteLine (indent + "Flags: " + msg.Header.Flags);
Console.WriteLine (indent + "Serial: " + msg.Header.Serial);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine (indent + hf.Code + ": " + hf.Value);
Console.WriteLine (indent + "Header Fields:");
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine (indent + indent + field.Key + ": " + field.Value);
Console.WriteLine (indent + "Body (" + msg.Header.Length + " bytes):");
if (msg.Body != null) {
MessageReader reader = new MessageReader (msg);
//TODO: this needs to be done more intelligently
int argNum = 0;
foreach (Signature sig in msg.Signature.GetParts ()) {
if (!sig.IsPrimitive)
break;
object arg = reader.ReadValue (sig[0]);
Console.Write (indent + indent + "arg" + argNum + " " + sig + ": ");
Console.WriteLine (arg);
argNum++;
}
}
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class Monitor
{
public static void Main (string[] args)
{
Connection bus;
if (args.Length >= 1) {
string arg = args[0];
switch (arg)
{
case "--system":
bus = Bus.System;
break;
case "--session":
bus = Bus.Session;
break;
default:
Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]");
Console.Error.WriteLine (" If no watch expressions are provided, defaults will be used.");
return;
}
} else {
bus = Bus.Session;
}
if (args.Length > 1) {
//install custom match rules only
for (int i = 1 ; i != args.Length ; i++)
bus.AddMatch (args[i]);
} else {
//no custom match rules, install the defaults
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
}
while (true) {
Message msg = bus.ReadMessage ();
if (msg == null)
break;
PrintMessage (msg);
Console.WriteLine ();
}
}
const string indent = " ";
internal static void PrintMessage (Message msg)
{
Console.WriteLine ("Message (" + msg.Header.Endianness + " endian, v" + msg.Header.MajorVersion + "):");
Console.WriteLine (indent + "Type: " + msg.Header.MessageType);
Console.WriteLine (indent + "Flags: " + msg.Header.Flags);
Console.WriteLine (indent + "Serial: " + msg.Header.Serial);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine (indent + hf.Code + ": " + hf.Value);
Console.WriteLine (indent + "Header Fields:");
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine (indent + indent + field.Key + ": " + field.Value);
Console.WriteLine (indent + "Body (" + msg.Header.Length + " bytes):");
if (msg.Body != null) {
MessageReader reader = new MessageReader (msg);
//TODO: this needs to be done more intelligently
//TODO: number the args
try {
foreach (DType dtype in msg.Signature.GetBuffer ()) {
if (dtype == DType.Invalid)
continue;
object arg = reader.ReadValue (dtype);
Console.WriteLine (indent + indent + dtype + ": " + arg);
}
} catch {
Console.WriteLine (indent + indent + "monitor is too dumb to decode message body");
}
}
}
}
| mit | C# |
13e745aac0c2a4c8539247b6a646ce9a8650eef4 | update version comment | yasokada/unity-150908-udpTimeGraph | Assets/AppInfo.cs | Assets/AppInfo.cs | using UnityEngine;
using System.Collections;
/*
* v0.10 2015/09/12
* - add monthly, yearly time scale
* - fix daily, weekly graph miscalculation
* v0.9 2015/09/12
* - add Test related GameObjects and scripts
* v0.8 2015/09/12
* - can show x scale in daily and weekly (monthly and yearly not yet)
* v0.7 2015/09/12
* - graph date is kept as <System.DateTime, float> so that x axis scale can be changed to weekly, etc.
* v0.6 2015/09/12
* - move several functions to MyPanelUtils.cs
* v0.5 2015/09/11
* - display ymin and ymax on the left of the panel (graphScale)
* v0.4 2015/09/10
* - can handle set,yrange command
*/
namespace NS_appInfo // NS stands for NameSpace
{
public static class AppInfo
{
public const string Version = "v0.10";
public const string Name = "udpTimeGraph";
}
}
| using UnityEngine;
using System.Collections;
/*
* v0.9 2015/09/12
* - add Test related GameObjects and scripts
* v0.8 2015/09/12
* - can show x scale in daily and weekly (monthly and yearly not yet)
* v0.7 2015/09/12
* - graph date is kept as <System.DateTime, float> so that x axis scale can be changed to weekly, etc.
* v0.6 2015/09/12
* - move several functions to MyPanelUtils.cs
* v0.5 2015/09/11
* - display ymin and ymax on the left of the panel (graphScale)
* v0.4 2015/09/10
* - can handle set,yrange command
*/
namespace NS_appInfo // NS stands for NameSpace
{
public static class AppInfo
{
public const string Version = "v0.8";
public const string Name = "udpTimeGraph";
}
}
| mit | C# |
31cd0583c2a4e6ec8a2f747352d1b92faa8b58dc | Use templated version of Resources.Load | greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d | Assets/HappyFunTimes/HappyFunTimesCore/Server/HFTWebFileLoader.cs | Assets/HappyFunTimes/HappyFunTimesCore/Server/HFTWebFileLoader.cs | using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
namespace HappyFunTimes
{
public class HFTWebFileLoader
{
// TODO: Put this in one place
static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";
static public void LoadFiles(HFTWebFileDB db)
{
TextAsset dirTxt = Resources.Load<TextAsset>(HFT_WEB_DIR);
if (dirTxt == null)
{
Debug.LogError("could not load: " + HFT_WEB_DIR);
return;
}
Deserializer deserializer = new Deserializer();
string[] files = deserializer.Deserialize<string[] >(dirTxt.text);
foreach (string file in files)
{
string path = HFT_WEB_PATH + file;
TextAsset asset = Resources.Load(path) as TextAsset;
if (asset == null)
{
Debug.LogError("Could not load: " + path);
}
else
{
db.AddFile(file, asset.bytes);
}
}
}
}
} // namespace HappyFunTimes
| using DeJson;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
namespace HappyFunTimes
{
public class HFTWebFileLoader
{
// TODO: Put this in one place
static private string HFT_WEB_PATH = "HappyFunTimesAutoGeneratedDoNotEdit/";
static private string HFT_WEB_DIR = "HappyFunTimesAutoGeneratedDoNotEdit/__dir__";
static public void LoadFiles(HFTWebFileDB db)
{
TextAsset dirTxt = Resources.Load(HFT_WEB_DIR, typeof(TextAsset)) as TextAsset;
if (dirTxt == null)
{
Debug.LogError("could not load: " + HFT_WEB_DIR);
return;
}
Deserializer deserializer = new Deserializer();
string[] files = deserializer.Deserialize<string[] >(dirTxt.text);
foreach (string file in files)
{
string path = HFT_WEB_PATH + file;
TextAsset asset = Resources.Load(path) as TextAsset;
if (asset == null)
{
Debug.LogError("Could not load: " + path);
}
else
{
db.AddFile(file, asset.bytes);
}
}
}
}
} // namespace HappyFunTimes
| bsd-3-clause | C# |
16c8df4c5ebb5abd78b9a2d25b36f3ab62add3a4 | Correct assembly version | collector-bank/common-restapi-aspnet | Collector.Common.Infrastructure.WebApi/Properties/AssemblyInfo.cs | Collector.Common.Infrastructure.WebApi/Properties/AssemblyInfo.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Collector AB">
// Copyright © Collector AB. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
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("Collector.Common.Infrastructure.WebApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Collector.Common.Infrastructure.WebApi")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("bd2f012d-cc2e-45cf-8d33-52ab06c315e3")]
// 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("0.2.0")]
[assembly: AssemblyFileVersion("0.2.0")]
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Collector AB">
// Copyright © Collector AB. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
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("Collector.Common.Infrastructure.WebApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Collector.Common.Infrastructure.WebApi")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("bd2f012d-cc2e-45cf-8d33-52ab06c315e3")]
// 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("0.1.3")]
[assembly: AssemblyFileVersion("0.1.3")]
| apache-2.0 | C# |
a7a51c9138ae10cd3c6b410338418cfd2f6b35cc | rename ondemandavailability fields | dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk | SnapMD.VirtualCare.ApiModels/Scheduling/OnDemandAvailabilityResponse.cs | SnapMD.VirtualCare.ApiModels/Scheduling/OnDemandAvailabilityResponse.cs | namespace SnapMD.VirtualCare.ApiModels.Scheduling
{
/// <summary>
/// Response Model for OnDemandAvailability
/// </summary>
/// <seealso cref="SnapMD.VirtualCare.ApiModels.Scheduling.OnDemandAvailabilityRequest" />
public class OnDemandAvailabilityResponse : OnDemandAvailabilityRequest
{
/// <summary>
/// Gets or sets a value indicating whether [provider has ondemand enabled].
/// </summary>
/// <value>
/// <c>true</c> if [provider has ondemand enabled]; otherwise, <c>false</c>.
/// </value>
public bool ProviderOnDemandEnabled { get; set; }
/// <summary>
/// Gets or sets the count of ondemand availability blocks at the moment.
/// </summary>
/// <value>
/// The count of ondemand availability blocks at the moment.
/// </value>
public int OnDemandAvailabilityBlockCount { get; set; }
}
}
| namespace SnapMD.VirtualCare.ApiModels.Scheduling
{
/// <summary>
/// Response Model for OnDemandAvailability
/// </summary>
/// <seealso cref="SnapMD.VirtualCare.ApiModels.Scheduling.OnDemandAvailabilityRequest" />
public class OnDemandAvailabilityResponse : OnDemandAvailabilityRequest
{
/// <summary>
/// Gets or sets a value indicating whether [provider on demand].
/// </summary>
/// <value>
/// <c>true</c> if [provider on demand]; otherwise, <c>false</c>.
/// </value>
public bool ProviderOnDemand { get; set; }
/// <summary>
/// Gets or sets the on demand availability.
/// </summary>
/// <value>
/// The on demand availability.
/// </value>
public int OnDemandAvailability { get; set; }
}
}
| apache-2.0 | C# |
7507fc8b57d69244f5202728c7e2265784ac1fe5 | Update ServiceCollectionExtensions.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/DependencyInjection/ServiceCollectionExtensions.cs | TIKSN.Framework.Core/DependencyInjection/ServiceCollectionExtensions.cs | using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using TIKSN.FileSystem;
namespace TIKSN.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddFrameworkPlatform(this IServiceCollection services)
{
services.AddFrameworkCore();
services.TryAddSingleton<IKnownFolders, KnownFolders>();
return services;
}
}
}
| using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using TIKSN.FileSystem;
namespace TIKSN.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddFrameworkPlatform(this IServiceCollection services)
{
services.AddFrameworkCore();
services.TryAddSingleton<IKnownFolders, KnownFolders>();
return services;
}
}
} | mit | C# |
c8a9bfe5c74d186666d028a7991d9b58b639cdfd | add null check | siyo-wang/IdentityServer4,IdentityServer/IdentityServer4,siyo-wang/IdentityServer4,MienDev/IdentityServer4,jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,MienDev/IdentityServer4,siyo-wang/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,chrisowhite/IdentityServer4,chrisowhite/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4 | src/IdentityServer4/IdentityServerTools.cs | src/IdentityServer4/IdentityServerTools.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityServer4.Extensions;
using System.Security.Claims;
using IdentityServer4.Services;
using IdentityModel;
using System;
namespace IdentityServer4
{
public class IdentityServerTools
{
internal readonly IHttpContextAccessor _contextAccessor;
private readonly ITokenCreationService _tokenCreation;
public IdentityServerTools(IHttpContextAccessor contextAccessor, ITokenCreationService tokenCreation)
{
_tokenCreation = tokenCreation;
_contextAccessor = contextAccessor;
}
public virtual async Task<string> IssueJwtAsync(int lifetime, IEnumerable<Claim> claims)
{
if (claims == null) throw new ArgumentNullException(nameof(claims));
var issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri();
var token = new Token
{
Issuer = issuer,
Lifetime = lifetime,
Claims = new HashSet<Claim>(claims, new ClaimComparer())
};
return await _tokenCreation.CreateTokenAsync(token);
}
}
} | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityServer4.Extensions;
using System.Security.Claims;
using IdentityServer4.Services;
using IdentityModel;
namespace IdentityServer4
{
public class IdentityServerTools
{
internal readonly IHttpContextAccessor _contextAccessor;
private readonly ITokenCreationService _tokenCreation;
public IdentityServerTools(IHttpContextAccessor contextAccessor, ITokenCreationService tokenCreation)
{
_tokenCreation = tokenCreation;
_contextAccessor = contextAccessor;
}
public virtual async Task<string> IssueJwtAsync(int lifetime, IEnumerable<Claim> claims)
{
var issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri();
var token = new Token
{
Issuer = issuer,
Lifetime = lifetime,
Claims = new HashSet<Claim>(claims, new ClaimComparer())
};
return await _tokenCreation.CreateTokenAsync(token);
}
}
} | apache-2.0 | C# |
ca2a440b71f7d78bec51102e84d62a828fcd8902 | Fix object reference bug | zumicts/Audiotica | Windows/Audiotica.Windows/AppEngine/Bootstrppers/LibraryBootstrapper.cs | Windows/Audiotica.Windows/AppEngine/Bootstrppers/LibraryBootstrapper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Storage;
using Audiotica.Core.Extensions;
using Audiotica.Core.Windows.Helpers;
using Audiotica.Database.Services.Interfaces;
using Audiotica.Windows.Services.Interfaces;
using Autofac;
namespace Audiotica.Windows.AppEngine.Bootstrppers
{
public class LibraryBootstrapper : AppBootStrapper
{
public override void OnStart(IComponentContext context)
{
var service = context.Resolve<ILibraryService>();
var insights = context.Resolve<IInsightsService>();
using (var timer = insights.TrackTimeEvent("LibraryLoaded"))
{
service.Load();
timer.AddProperty("Track count", service.Tracks.Count.ToString());
}
var matchingService = context.Resolve<ILibraryMatchingService>();
matchingService.OnStartup();
CleanupFiles(s => !service.Tracks.Any(p => p.ArtistArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Artists/");
CleanupFiles(s => !service.Tracks.Any(p => p.ArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Albums/");
}
private static async void CleanupFiles(Func<string, bool> shouldDelete, string folderPath)
{
var folder = await StorageHelper.GetFolderAsync(folderPath);
if (folder == null) return;
var files = await folder.GetFilesAsync();
foreach (var file in files.Where(file => shouldDelete(file.Name)))
await file.DeleteAsync();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Storage;
using Audiotica.Core.Extensions;
using Audiotica.Core.Windows.Helpers;
using Audiotica.Database.Services.Interfaces;
using Audiotica.Windows.Services.Interfaces;
using Autofac;
namespace Audiotica.Windows.AppEngine.Bootstrppers
{
public class LibraryBootstrapper : AppBootStrapper
{
public override void OnStart(IComponentContext context)
{
var service = context.Resolve<ILibraryService>();
var insights = context.Resolve<IInsightsService>();
using (var timer = insights.TrackTimeEvent("LibraryLoaded"))
{
service.Load();
timer.AddProperty("Track count", service.Tracks.Count.ToString());
}
var matchingService = context.Resolve<ILibraryMatchingService>();
matchingService.OnStartup();
CleanupFiles(s => !service.Tracks.Any(p => p.ArtistArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Artists/");
CleanupFiles(s => !service.Tracks.Any(p => p.ArtworkUri?.EndsWithIgnoreCase(s) ?? false), "Library/Images/Albums/");
}
private static async void CleanupFiles(Func<string, bool> shouldDelete, string folderPath)
{
var folder = await StorageHelper.GetFolderAsync(folderPath);
var files = await folder.GetFilesAsync();
foreach (var file in files.Where(file => shouldDelete(file.Name)))
{
await file.DeleteAsync();
}
}
}
} | apache-2.0 | C# |
7a5e7789cfb4a189140268e7b003f9ce454e56bf | bump version | vevix/DigitalOcean.Indicator | DigitalOcean.Indicator/Properties/AssemblyInfo.cs | DigitalOcean.Indicator/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("DigitalOcean.Indicator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DigitalOcean.Indicator")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
[assembly: AssemblyFileVersion("1.0.0")] | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("DigitalOcean.Indicator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DigitalOcean.Indicator")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")] | mit | C# |
733b5ddea96114ee8ad6ad24cbd739341077543b | Load characters in MapStatePacketTranslator | ethanmoffat/EndlessClient | EOLib/Net/Translators/MapStatePacketTranslator.cs | EOLib/Net/Translators/MapStatePacketTranslator.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EOLib.Domain.Character;
using EOLib.Domain.Map;
using EOLib.Domain.NPC;
namespace EOLib.Net.Translators
{
public abstract class MapStatePacketTranslator<T> : IPacketTranslator<T>
where T : ITranslatedData
{
public abstract T TranslatePacket(IPacket packet);
protected IEnumerable<ICharacter> GetCharacters(IPacket packet)
{
var numCharacters = packet.ReadChar();
for (int i = 0; i < numCharacters; ++i)
{
var name = packet.ReadBreakString();
name = char.ToUpper(name[0]) + name.Substring(1);
var id = packet.ReadShort();
var mapID = packet.ReadShort();
var xLoc = packet.ReadShort();
var yLoc = packet.ReadShort();
var direction = (EODirection)packet.ReadChar();
packet.ReadChar(); //value is always 6? Unknown use
var guildTag = packet.ReadString(3);
var level = packet.ReadChar();
var gender = packet.ReadChar();
var hairStyle = packet.ReadChar();
var hairColor = packet.ReadChar();
var race = packet.ReadChar();
var maxHP = packet.ReadShort();
var hp = packet.ReadShort();
var maxTP = packet.ReadShort();
var tp = packet.ReadShort();
var boots = packet.ReadShort();
packet.Seek(6, SeekOrigin.Current); //0s
var armor = packet.ReadShort();
packet.Seek(2, SeekOrigin.Current); //0
var hat = packet.ReadShort();
var shield = packet.ReadShort();
var weapon = packet.ReadShort();
var sitState = (SitState) packet.ReadChar();
var hidden = packet.ReadChar() != 0;
var stats = new CharacterStats()
.WithNewStat(CharacterStat.Level, level)
.WithNewStat(CharacterStat.HP, hp)
.WithNewStat(CharacterStat.MaxHP, maxHP)
.WithNewStat(CharacterStat.TP, tp)
.WithNewStat(CharacterStat.MaxTP, maxTP);
var renderProps = new CharacterRenderProperties()
.WithDirection(direction)
.WithGender(gender)
.WithHairStyle(hairStyle)
.WithHairColor(hairColor)
.WithRace(race)
.WithBootsGraphic(boots)
.WithArmorGraphic(armor)
.WithHatGraphic(hat)
.WithShieldGraphic(shield)
.WithWeaponGraphic(weapon)
.WithSitState(sitState)
.WithIsHidden(hidden);
yield return new Character()
.WithName(name)
.WithID(id)
.WithMapID(mapID)
.WithMapX(xLoc)
.WithMapY(yLoc)
.WithGuildTag(guildTag)
.WithStats(stats)
.WithRenderProperties(renderProps);
}
}
protected IEnumerable<NPC> GetNPCs(IPacket packet)
{
return Enumerable.Empty<NPC>();
}
protected IEnumerable<MapItem> GetMapItems(IPacket packet)
{
return Enumerable.Empty<MapItem>();
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EOLib.Domain.Character;
using EOLib.Domain.Map;
using EOLib.Domain.NPC;
namespace EOLib.Net.Translators
{
public abstract class MapStatePacketTranslator<T> : IPacketTranslator<T>
where T : ITranslatedData
{
public abstract T TranslatePacket(IPacket packet);
protected IEnumerable<ICharacter> GetCharacters(IPacket packet)
{
var numCharacters = packet.ReadChar();
for (int i = 0; i < numCharacters; ++i)
{
var name = packet.ReadBreakString();
name = char.ToUpper(name[0]) + name.Substring(1);
var id = packet.ReadShort();
var mapID = packet.ReadShort();
var xLoc = packet.ReadShort();
var yLoc = packet.ReadShort();
var direction = packet.ReadShort();
packet.ReadChar(); //value is always 6? Unknown use
var guildTag = packet.ReadString(3);
var level = packet.ReadChar();
var gender = packet.ReadChar();
var hairStyle = packet.ReadChar();
var hairColor = packet.ReadChar();
var race = packet.ReadChar();
var maxHP = packet.ReadShort();
var hp = packet.ReadShort();
var MaxTP = packet.ReadShort();
var tp = packet.ReadShort();
var boots = packet.ReadShort();
packet.Seek(6, SeekOrigin.Current); //0s
var armor = packet.ReadShort();
packet.Seek(2, SeekOrigin.Current); //0
var hat = packet.ReadShort();
var shield = packet.ReadShort();
var weapon = packet.ReadShort();
var sitState = (SitState) packet.ReadChar();
var hidden = packet.ReadChar() != 0;
yield return new Character();
}
}
protected IEnumerable<NPC> GetNPCs(IPacket packet)
{
return Enumerable.Empty<NPC>();
}
protected IEnumerable<MapItem> GetMapItems(IPacket packet)
{
return Enumerable.Empty<MapItem>();
}
}
}
| mit | C# |
c976085b1e1d91ffdfc24a138c6e1c1c2348ada6 | Fix `StatementBlockAst.ToString()` | ForNeVeR/Pash,JayBazuzi/Pash,sburnicki/Pash,sillvan/Pash,sburnicki/Pash,JayBazuzi/Pash,WimObiwan/Pash,sburnicki/Pash,sillvan/Pash,ForNeVeR/Pash,WimObiwan/Pash,mrward/Pash,Jaykul/Pash,WimObiwan/Pash,JayBazuzi/Pash,mrward/Pash,sillvan/Pash,Jaykul/Pash,mrward/Pash,sburnicki/Pash,Jaykul/Pash,ForNeVeR/Pash,sillvan/Pash,WimObiwan/Pash,mrward/Pash,JayBazuzi/Pash,Jaykul/Pash,ForNeVeR/Pash | Source/System.Management/Automation/Language/StatementBlockAst.cs | Source/System.Management/Automation/Language/StatementBlockAst.cs | // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
namespace System.Management.Automation.Language
{
public class StatementBlockAst : Ast
{
public StatementBlockAst(IScriptExtent extent, IEnumerable<StatementAst> statements, IEnumerable<TrapStatementAst> traps)
: base(extent)
{
this.Statements = statements.ToReadOnlyCollection();
this.Traps = traps.ToReadOnlyCollection();
}
public ReadOnlyCollection<StatementAst> Statements { get; private set; }
public ReadOnlyCollection<TrapStatementAst> Traps { get; private set; }
internal override IEnumerable<Ast> Children
{
get
{
foreach (var item in this.Statements) yield return item;
foreach (var item in this.Traps) yield return item;
foreach (var item in base.Children) yield return item;
}
}
public override string ToString()
{
if (this.Statements.Any())
{
return string.Format("{{ {0} ... }}", this.Statements.First());
}
else
{
return "{ }";
}
}
}
}
| // Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
namespace System.Management.Automation.Language
{
public class StatementBlockAst : Ast
{
public StatementBlockAst(IScriptExtent extent, IEnumerable<StatementAst> statements, IEnumerable<TrapStatementAst> traps)
: base(extent)
{
this.Statements = statements.ToReadOnlyCollection();
this.Traps = traps.ToReadOnlyCollection();
}
public ReadOnlyCollection<StatementAst> Statements { get; private set; }
public ReadOnlyCollection<TrapStatementAst> Traps { get; private set; }
internal override IEnumerable<Ast> Children
{
get
{
foreach (var item in this.Statements) yield return item;
foreach (var item in this.Traps) yield return item;
foreach (var item in base.Children) yield return item;
}
}
public override string ToString()
{
if (this.Statements.Any())
{
return string.Format("{ {0} ... }", this.Statements.First());
}
else
{
return "{ }";
}
}
}
}
| bsd-3-clause | C# |
f319049ec3b4721cd5e69a6f00032016fb3b2070 | Update ExceptionlessExceptionTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/ExceptionlessExceptionTelemeter.cs | TIKSN.Core/Analytics/Telemetry/ExceptionlessExceptionTelemeter.cs | using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Exceptionless;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessExceptionTelemeter : ExceptionlessTelemeterBase, IExceptionTelemeter
{
public async Task TrackException(Exception exception)
{
try
{
exception.ToExceptionless().Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public async Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel)
{
try
{
exception.ToExceptionless().SetType(severityLevel.ToString()).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
| using Exceptionless;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessExceptionTelemeter : ExceptionlessTelemeterBase, IExceptionTelemeter
{
public ExceptionlessExceptionTelemeter()
{
}
public async Task TrackException(Exception exception)
{
try
{
exception.ToExceptionless().Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public async Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel)
{
try
{
exception.ToExceptionless().SetType(severityLevel.ToString()).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
} | mit | C# |
c1261d70c7e81be06e038e24713d2a96c4e3ec12 | Add support for finding 64-bit Opera browser | freenet/wintray,freenet/wintray | Browsers/Opera.cs | Browsers/Opera.cs | using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
namespace FreenetTray.Browsers
{
class Opera : IBrowser
{
private readonly string _path;
private readonly bool _isInstalled;
private static string OperaRegistryKey = @"Software\Opera Software\Last Stable Install Path";
private static string RegistryPathForView(RegistryView view) {
RegistryKey hive = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, view);
RegistryKey key = hive.OpenSubKey(OperaRegistryKey);
if (key == null) {
return null;
}
string value = key.GetValue("opera.exe") as string;
return value;
}
// find the path to opera, preferring 64-bit if available
private static string RegistryPath {
get {
if (Environment.Is64BitOperatingSystem) {
var path64 = RegistryPathForView(RegistryView.Registry64);
if (path64 != null) {
return path64;
}
var path32 = RegistryPathForView(RegistryView.Registry32);
if (path32 != null) {
return path32;
}
return null;
}
else {
var path32 = RegistryPathForView(RegistryView.Registry32);
if (path32 != null) {
return path32;
}
return null;
}
}
}
public Opera()
{
/*
* TODO: Opera 26 adds launcher.exe and does not support -newprivatetab. Documentation
* on what it supports in its place, if anything, has not been forthcoming.
*/
// Key present with Opera 21.
var possiblePath = RegistryPath;
_isInstalled = File.Exists(possiblePath);
if (_isInstalled)
{
_path = possiblePath;
}
}
public bool Open(Uri target)
{
if (!IsAvailable())
{
return false;
}
// See http://www.opera.com/docs/switches
Process.Start(_path, "-newprivatetab " + target);
return true;
}
public bool IsAvailable()
{
return _isInstalled;
}
public string GetName()
{
return "Opera";
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
namespace FreenetTray.Browsers
{
class Opera : IBrowser
{
private readonly string _path;
private readonly bool _isInstalled;
public Opera()
{
/*
* TODO: Opera 26 adds launcher.exe and does not support -newprivatetab. Documentation
* on what it supports in its place, if anything, has not been forthcoming.
*/
// Key present with Opera 21.
var possiblePath = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last Stable Install Path", null) + "opera.exe";
_isInstalled = File.Exists(possiblePath);
if (_isInstalled)
{
_path = possiblePath;
}
}
public bool Open(Uri target)
{
if (!IsAvailable())
{
return false;
}
// See http://www.opera.com/docs/switches
Process.Start(_path, "-newprivatetab " + target);
return true;
}
public bool IsAvailable()
{
return _isInstalled;
}
public string GetName()
{
return "Opera";
}
}
}
| mit | C# |
c8167b9cd7e865edb4c421df6dacd2025e9c591a | Use the correct string for the warning key. (patch by olivier) | dipeshc/BTDeploy | src/MonoTorrent/MonoTorrent.Tracker/RequestParameters.cs | src/MonoTorrent/MonoTorrent.Tracker/RequestParameters.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker
{
public abstract class RequestParameters : EventArgs
{
protected internal static readonly string FailureKey = "failure reason";
protected internal static readonly string WarningKey = "warning message";
private IPAddress remoteAddress;
private NameValueCollection parameters;
private BEncodedDictionary response;
public abstract bool IsValid { get; }
public NameValueCollection Parameters
{
get { return parameters; }
}
public BEncodedDictionary Response
{
get { return response; }
}
public IPAddress RemoteAddress
{
get { return remoteAddress; }
protected set { remoteAddress = value; }
}
protected RequestParameters(NameValueCollection parameters, IPAddress address)
{
this.parameters = parameters;
remoteAddress = address;
response = new BEncodedDictionary();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker
{
public abstract class RequestParameters : EventArgs
{
protected internal static readonly string FailureKey = "failure reason";
protected internal static readonly string WarningKey = "warning"; //FIXME: Check this, i know it's wrong!
private IPAddress remoteAddress;
private NameValueCollection parameters;
private BEncodedDictionary response;
public abstract bool IsValid { get; }
public NameValueCollection Parameters
{
get { return parameters; }
}
public BEncodedDictionary Response
{
get { return response; }
}
public IPAddress RemoteAddress
{
get { return remoteAddress; }
protected set { remoteAddress = value; }
}
protected RequestParameters(NameValueCollection parameters, IPAddress address)
{
this.parameters = parameters;
remoteAddress = address;
response = new BEncodedDictionary();
}
}
}
| mit | C# |
2eb09ee543e5ce9e34e895b5d2a6fbff79d6ddc6 | improve docs for IAsyncStreamReader | kumaralokgithub/grpc,perumaalgoog/grpc,PeterFaiman/ruby-grpc-minimal,arkmaxim/grpc,simonkuang/grpc,mehrdada/grpc,kriswuollett/grpc,daniel-j-born/grpc,rjshade/grpc,jcanizales/grpc,rjshade/grpc,donnadionne/grpc,ejona86/grpc,thinkerou/grpc,kriswuollett/grpc,ejona86/grpc,vsco/grpc,muxi/grpc,msmania/grpc,andrewpollock/grpc,a-veitch/grpc,msmania/grpc,muxi/grpc,dklempner/grpc,sreecha/grpc,matt-kwong/grpc,infinit/grpc,soltanmm-google/grpc,yugui/grpc,ejona86/grpc,y-zeng/grpc,malexzx/grpc,vsco/grpc,kpayson64/grpc,tengyifei/grpc,chrisdunelm/grpc,chrisdunelm/grpc,soltanmm/grpc,hstefan/grpc,jcanizales/grpc,y-zeng/grpc,thunderboltsid/grpc,ejona86/grpc,quizlet/grpc,greasypizza/grpc,yugui/grpc,grani/grpc,vsco/grpc,mehrdada/grpc,bogdandrutu/grpc,tengyifei/grpc,hstefan/grpc,carl-mastrangelo/grpc,grani/grpc,yongni/grpc,andrewpollock/grpc,matt-kwong/grpc,kpayson64/grpc,murgatroid99/grpc,muxi/grpc,a-veitch/grpc,murgatroid99/grpc,podsvirov/grpc,royalharsh/grpc,yugui/grpc,kskalski/grpc,jboeuf/grpc,MakMukhi/grpc,7anner/grpc,soltanmm/grpc,apolcyn/grpc,murgatroid99/grpc,jcanizales/grpc,apolcyn/grpc,mehrdada/grpc,thinkerou/grpc,vjpai/grpc,wcevans/grpc,a-veitch/grpc,ncteisen/grpc,soltanmm/grpc,matt-kwong/grpc,grpc/grpc,Crevil/grpc,Vizerai/grpc,Crevil/grpc,murgatroid99/grpc,PeterFaiman/ruby-grpc-minimal,kskalski/grpc,jboeuf/grpc,thunderboltsid/grpc,deepaklukose/grpc,vjpai/grpc,zhimingxie/grpc,LuminateWireless/grpc,MakMukhi/grpc,makdharma/grpc,vjpai/grpc,andrewpollock/grpc,Vizerai/grpc,vjpai/grpc,dgquintas/grpc,ipylypiv/grpc,soltanmm-google/grpc,geffzhang/grpc,ppietrasa/grpc,dklempner/grpc,wcevans/grpc,andrewpollock/grpc,jcanizales/grpc,muxi/grpc,daniel-j-born/grpc,ipylypiv/grpc,thunderboltsid/grpc,nicolasnoble/grpc,baylabs/grpc,pszemus/grpc,donnadionne/grpc,dgquintas/grpc,infinit/grpc,kpayson64/grpc,deepaklukose/grpc,simonkuang/grpc,bogdandrutu/grpc,jcanizales/grpc,kpayson64/grpc,malexzx/grpc,yugui/grpc,vsco/grpc,hstefan/grpc,podsvirov/grpc,jtattermusch/grpc,firebase/grpc,philcleveland/grpc,tengyifei/grpc,ipylypiv/grpc,kskalski/grpc,ctiller/grpc,Vizerai/grpc,kriswuollett/grpc,chrisdunelm/grpc,kpayson64/grpc,chrisdunelm/grpc,nicolasnoble/grpc,soltanmm-google/grpc,7anner/grpc,fuchsia-mirror/third_party-grpc,sreecha/grpc,nicolasnoble/grpc,murgatroid99/grpc,dgquintas/grpc,y-zeng/grpc,ppietrasa/grpc,ejona86/grpc,baylabs/grpc,malexzx/grpc,infinit/grpc,adelez/grpc,muxi/grpc,pmarks-net/grpc,pszemus/grpc,firebase/grpc,fuchsia-mirror/third_party-grpc,soltanmm-google/grpc,jtattermusch/grpc,geffzhang/grpc,tengyifei/grpc,thunderboltsid/grpc,mehrdada/grpc,tengyifei/grpc,ejona86/grpc,stanley-cheung/grpc,deepaklukose/grpc,7anner/grpc,firebase/grpc,yang-g/grpc,kskalski/grpc,mehrdada/grpc,dgquintas/grpc,stanley-cheung/grpc,7anner/grpc,grani/grpc,fuchsia-mirror/third_party-grpc,y-zeng/grpc,simonkuang/grpc,jboeuf/grpc,firebase/grpc,grpc/grpc,msmania/grpc,msmania/grpc,malexzx/grpc,geffzhang/grpc,carl-mastrangelo/grpc,a11r/grpc,vjpai/grpc,ctiller/grpc,thunderboltsid/grpc,kumaralokgithub/grpc,vsco/grpc,murgatroid99/grpc,podsvirov/grpc,donnadionne/grpc,pmarks-net/grpc,grpc/grpc,chrisdunelm/grpc,grani/grpc,kumaralokgithub/grpc,philcleveland/grpc,Vizerai/grpc,dgquintas/grpc,geffzhang/grpc,pszemus/grpc,sreecha/grpc,daniel-j-born/grpc,rjshade/grpc,nicolasnoble/grpc,vjpai/grpc,vjpai/grpc,soltanmm/grpc,yongni/grpc,jtattermusch/grpc,royalharsh/grpc,LuminateWireless/grpc,mehrdada/grpc,carl-mastrangelo/grpc,mehrdada/grpc,Vizerai/grpc,geffzhang/grpc,carl-mastrangelo/grpc,tengyifei/grpc,ctiller/grpc,ctiller/grpc,thunderboltsid/grpc,ncteisen/grpc,soltanmm/grpc,yang-g/grpc,rjshade/grpc,greasypizza/grpc,firebase/grpc,a11r/grpc,chrisdunelm/grpc,yongni/grpc,deepaklukose/grpc,royalharsh/grpc,sreecha/grpc,MakMukhi/grpc,yongni/grpc,mehrdada/grpc,royalharsh/grpc,pszemus/grpc,donnadionne/grpc,apolcyn/grpc,andrewpollock/grpc,jtattermusch/grpc,jtattermusch/grpc,grpc/grpc,kumaralokgithub/grpc,zhimingxie/grpc,kpayson64/grpc,nicolasnoble/grpc,andrewpollock/grpc,thinkerou/grpc,jtattermusch/grpc,soltanmm/grpc,wcevans/grpc,royalharsh/grpc,dgquintas/grpc,ctiller/grpc,thinkerou/grpc,makdharma/grpc,perumaalgoog/grpc,simonkuang/grpc,wcevans/grpc,podsvirov/grpc,stanley-cheung/grpc,quizlet/grpc,makdharma/grpc,a11r/grpc,chrisdunelm/grpc,msmania/grpc,yang-g/grpc,nicolasnoble/grpc,fuchsia-mirror/third_party-grpc,y-zeng/grpc,dgquintas/grpc,hstefan/grpc,kskalski/grpc,ejona86/grpc,jboeuf/grpc,carl-mastrangelo/grpc,pszemus/grpc,baylabs/grpc,daniel-j-born/grpc,mehrdada/grpc,perumaalgoog/grpc,Vizerai/grpc,murgatroid99/grpc,apolcyn/grpc,donnadionne/grpc,muxi/grpc,msmania/grpc,nicolasnoble/grpc,7anner/grpc,baylabs/grpc,carl-mastrangelo/grpc,arkmaxim/grpc,jtattermusch/grpc,MakMukhi/grpc,hstefan/grpc,murgatroid99/grpc,jtattermusch/grpc,grani/grpc,PeterFaiman/ruby-grpc-minimal,dklempner/grpc,jboeuf/grpc,stanley-cheung/grpc,jtattermusch/grpc,7anner/grpc,soltanmm/grpc,msmania/grpc,deepaklukose/grpc,geffzhang/grpc,y-zeng/grpc,malexzx/grpc,kriswuollett/grpc,ctiller/grpc,ppietrasa/grpc,ncteisen/grpc,donnadionne/grpc,Crevil/grpc,adelez/grpc,a-veitch/grpc,makdharma/grpc,kskalski/grpc,LuminateWireless/grpc,firebase/grpc,wcevans/grpc,malexzx/grpc,baylabs/grpc,firebase/grpc,a11r/grpc,adelez/grpc,ncteisen/grpc,daniel-j-born/grpc,wcevans/grpc,dklempner/grpc,stanley-cheung/grpc,LuminateWireless/grpc,simonkuang/grpc,adelez/grpc,jtattermusch/grpc,zhimingxie/grpc,a11r/grpc,ncteisen/grpc,quizlet/grpc,a11r/grpc,MakMukhi/grpc,tengyifei/grpc,hstefan/grpc,zhimingxie/grpc,ctiller/grpc,bogdandrutu/grpc,grani/grpc,pmarks-net/grpc,bogdandrutu/grpc,dgquintas/grpc,andrewpollock/grpc,pszemus/grpc,carl-mastrangelo/grpc,thunderboltsid/grpc,a11r/grpc,muxi/grpc,ctiller/grpc,yongni/grpc,ipylypiv/grpc,infinit/grpc,thunderboltsid/grpc,rjshade/grpc,thinkerou/grpc,hstefan/grpc,ppietrasa/grpc,PeterFaiman/ruby-grpc-minimal,quizlet/grpc,ipylypiv/grpc,vsco/grpc,Vizerai/grpc,pmarks-net/grpc,carl-mastrangelo/grpc,malexzx/grpc,PeterFaiman/ruby-grpc-minimal,yang-g/grpc,sreecha/grpc,grani/grpc,pszemus/grpc,zhimingxie/grpc,apolcyn/grpc,sreecha/grpc,msmania/grpc,mehrdada/grpc,7anner/grpc,ncteisen/grpc,podsvirov/grpc,perumaalgoog/grpc,royalharsh/grpc,podsvirov/grpc,chrisdunelm/grpc,kskalski/grpc,apolcyn/grpc,nicolasnoble/grpc,thinkerou/grpc,fuchsia-mirror/third_party-grpc,daniel-j-born/grpc,Crevil/grpc,tengyifei/grpc,philcleveland/grpc,LuminateWireless/grpc,stanley-cheung/grpc,MakMukhi/grpc,msmania/grpc,a-veitch/grpc,ncteisen/grpc,malexzx/grpc,nicolasnoble/grpc,infinit/grpc,fuchsia-mirror/third_party-grpc,ppietrasa/grpc,dklempner/grpc,dklempner/grpc,vjpai/grpc,pmarks-net/grpc,sreecha/grpc,matt-kwong/grpc,vsco/grpc,7anner/grpc,jcanizales/grpc,donnadionne/grpc,carl-mastrangelo/grpc,apolcyn/grpc,grani/grpc,firebase/grpc,Crevil/grpc,makdharma/grpc,chrisdunelm/grpc,jboeuf/grpc,ipylypiv/grpc,vsco/grpc,perumaalgoog/grpc,muxi/grpc,pmarks-net/grpc,kpayson64/grpc,rjshade/grpc,philcleveland/grpc,pmarks-net/grpc,arkmaxim/grpc,muxi/grpc,vjpai/grpc,bogdandrutu/grpc,royalharsh/grpc,ejona86/grpc,ctiller/grpc,vjpai/grpc,soltanmm/grpc,bogdandrutu/grpc,thunderboltsid/grpc,perumaalgoog/grpc,adelez/grpc,stanley-cheung/grpc,dgquintas/grpc,donnadionne/grpc,mehrdada/grpc,adelez/grpc,matt-kwong/grpc,ipylypiv/grpc,Vizerai/grpc,PeterFaiman/ruby-grpc-minimal,philcleveland/grpc,muxi/grpc,a11r/grpc,sreecha/grpc,apolcyn/grpc,jboeuf/grpc,quizlet/grpc,donnadionne/grpc,thinkerou/grpc,Vizerai/grpc,pmarks-net/grpc,firebase/grpc,ncteisen/grpc,yang-g/grpc,yongni/grpc,dklempner/grpc,daniel-j-born/grpc,wcevans/grpc,yongni/grpc,deepaklukose/grpc,stanley-cheung/grpc,wcevans/grpc,jtattermusch/grpc,jboeuf/grpc,quizlet/grpc,jcanizales/grpc,firebase/grpc,zhimingxie/grpc,simonkuang/grpc,chrisdunelm/grpc,jboeuf/grpc,perumaalgoog/grpc,greasypizza/grpc,rjshade/grpc,andrewpollock/grpc,7anner/grpc,ppietrasa/grpc,simonkuang/grpc,dgquintas/grpc,geffzhang/grpc,greasypizza/grpc,arkmaxim/grpc,kriswuollett/grpc,vjpai/grpc,kumaralokgithub/grpc,ncteisen/grpc,Vizerai/grpc,soltanmm-google/grpc,deepaklukose/grpc,adelez/grpc,MakMukhi/grpc,LuminateWireless/grpc,firebase/grpc,hstefan/grpc,kriswuollett/grpc,MakMukhi/grpc,carl-mastrangelo/grpc,grpc/grpc,kriswuollett/grpc,geffzhang/grpc,kpayson64/grpc,fuchsia-mirror/third_party-grpc,a-veitch/grpc,podsvirov/grpc,donnadionne/grpc,hstefan/grpc,philcleveland/grpc,fuchsia-mirror/third_party-grpc,zhimingxie/grpc,grpc/grpc,ctiller/grpc,arkmaxim/grpc,zhimingxie/grpc,muxi/grpc,ejona86/grpc,ncteisen/grpc,soltanmm-google/grpc,matt-kwong/grpc,jboeuf/grpc,philcleveland/grpc,andrewpollock/grpc,quizlet/grpc,grani/grpc,thinkerou/grpc,apolcyn/grpc,ipylypiv/grpc,daniel-j-born/grpc,LuminateWireless/grpc,philcleveland/grpc,stanley-cheung/grpc,kumaralokgithub/grpc,ejona86/grpc,ejona86/grpc,jboeuf/grpc,rjshade/grpc,arkmaxim/grpc,infinit/grpc,matt-kwong/grpc,greasypizza/grpc,arkmaxim/grpc,philcleveland/grpc,greasypizza/grpc,soltanmm/grpc,ipylypiv/grpc,MakMukhi/grpc,fuchsia-mirror/third_party-grpc,matt-kwong/grpc,yang-g/grpc,ppietrasa/grpc,nicolasnoble/grpc,daniel-j-born/grpc,murgatroid99/grpc,matt-kwong/grpc,LuminateWireless/grpc,nicolasnoble/grpc,yugui/grpc,donnadionne/grpc,jcanizales/grpc,bogdandrutu/grpc,sreecha/grpc,bogdandrutu/grpc,PeterFaiman/ruby-grpc-minimal,yugui/grpc,jtattermusch/grpc,carl-mastrangelo/grpc,greasypizza/grpc,kriswuollett/grpc,royalharsh/grpc,grpc/grpc,deepaklukose/grpc,dgquintas/grpc,podsvirov/grpc,zhimingxie/grpc,ppietrasa/grpc,sreecha/grpc,stanley-cheung/grpc,a-veitch/grpc,infinit/grpc,kpayson64/grpc,nicolasnoble/grpc,kumaralokgithub/grpc,PeterFaiman/ruby-grpc-minimal,kpayson64/grpc,makdharma/grpc,infinit/grpc,arkmaxim/grpc,grpc/grpc,baylabs/grpc,yugui/grpc,ejona86/grpc,greasypizza/grpc,Crevil/grpc,deepaklukose/grpc,perumaalgoog/grpc,adelez/grpc,kskalski/grpc,simonkuang/grpc,a-veitch/grpc,Crevil/grpc,carl-mastrangelo/grpc,sreecha/grpc,pszemus/grpc,yang-g/grpc,baylabs/grpc,sreecha/grpc,PeterFaiman/ruby-grpc-minimal,ncteisen/grpc,vjpai/grpc,y-zeng/grpc,donnadionne/grpc,grpc/grpc,baylabs/grpc,makdharma/grpc,ctiller/grpc,wcevans/grpc,kriswuollett/grpc,malexzx/grpc,yongni/grpc,makdharma/grpc,thinkerou/grpc,a-veitch/grpc,infinit/grpc,quizlet/grpc,jcanizales/grpc,kpayson64/grpc,pszemus/grpc,stanley-cheung/grpc,PeterFaiman/ruby-grpc-minimal,arkmaxim/grpc,Vizerai/grpc,pmarks-net/grpc,perumaalgoog/grpc,thinkerou/grpc,thinkerou/grpc,Crevil/grpc,stanley-cheung/grpc,yongni/grpc,kskalski/grpc,vsco/grpc,soltanmm-google/grpc,y-zeng/grpc,yang-g/grpc,pszemus/grpc,geffzhang/grpc,Crevil/grpc,dklempner/grpc,rjshade/grpc,soltanmm-google/grpc,ppietrasa/grpc,grpc/grpc,royalharsh/grpc,ctiller/grpc,yugui/grpc,mehrdada/grpc,chrisdunelm/grpc,kumaralokgithub/grpc,thinkerou/grpc,tengyifei/grpc,grpc/grpc,dklempner/grpc,LuminateWireless/grpc,fuchsia-mirror/third_party-grpc,quizlet/grpc,firebase/grpc,makdharma/grpc,pszemus/grpc,ncteisen/grpc,soltanmm-google/grpc,bogdandrutu/grpc,baylabs/grpc,grpc/grpc,yang-g/grpc,murgatroid99/grpc,yugui/grpc,podsvirov/grpc,a11r/grpc,greasypizza/grpc,kumaralokgithub/grpc,y-zeng/grpc,muxi/grpc,jboeuf/grpc,adelez/grpc,simonkuang/grpc,pszemus/grpc | src/csharp/Grpc.Core/IAsyncStreamReader.cs | src/csharp/Grpc.Core/IAsyncStreamReader.cs | #region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grpc.Core
{
/// <summary>
/// A stream of messages to be read.
/// Messages can be awaited <c>await reader.MoveNext()</c>, that returns <c>true</c>
/// if there is a message available and <c>false</c> if there are no more messages
/// (i.e. the stream has been closed).
/// <para>
/// On the client side, the last invocation of <c>MoveNext()</c> either returns <c>false</c>
/// if the call has finished successfully or throws <c>RpcException</c> if call finished
/// with an error. Once the call finishes, subsequent invocations of <c>MoveNext()</c> will
/// continue yielding the same result (returning <c>false</c> or throwing an exception).
/// </para>
/// <para>
/// On the server side, <c>MoveNext()</c> does not throw exceptions.
/// In case of a failure, the request stream will appear to be finished
/// (<c>MoveNext</c> will return <c>false</c>) and the <c>CancellationToken</c>
/// associated with the call will be cancelled to signal the failure.
/// </para>
/// </summary>
/// <typeparam name="T">The message type.</typeparam>
public interface IAsyncStreamReader<T> : IAsyncEnumerator<T>
{
}
}
| #region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grpc.Core
{
/// <summary>
/// A stream of messages to be read.
/// </summary>
/// <typeparam name="T">The message type.</typeparam>
public interface IAsyncStreamReader<T> : IAsyncEnumerator<T>
{
// TODO(jtattermusch): consider just using IAsyncEnumerator instead of this interface.
}
}
| apache-2.0 | C# |
29130bfee61da39f1210786544fb3df7f86af396 | Add implicit conversion from CancellationTokenSource to CancellationToken | patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,genail/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity | src/Assets/Scripts/Cancellation/CancellationTokenSource.cs | src/Assets/Scripts/Cancellation/CancellationTokenSource.cs | namespace PatchKit.Unity.Patcher.Cancellation
{
internal class CancellationTokenSource
{
public bool IsCancelled { get; private set; }
public CancellationTokenSource()
{
IsCancelled = false;
}
public void Cancel()
{
IsCancelled = true;
}
public CancellationToken Token
{
get { return new CancellationToken(this); }
}
public static implicit operator CancellationToken(CancellationTokenSource cancellationTokenSource)
{
return cancellationTokenSource.Token;
}
}
} | namespace PatchKit.Unity.Patcher.Cancellation
{
internal class CancellationTokenSource
{
public bool IsCancelled { get; private set; }
public CancellationTokenSource()
{
IsCancelled = false;
}
public void Cancel()
{
IsCancelled = true;
}
public CancellationToken Token
{
get { return new CancellationToken(this); }
}
}
} | mit | C# |
a325805b7882774dd06c08e9869e130317275d0f | Clean up LowLevelStringConverter now that it's in Common | tijoytom/corert,gregkalapos/corert,krytarowski/corert,botaberg/corert,kyulee1/corert,shrah/corert,yizhang82/corert,kyulee1/corert,sandreenko/corert,krytarowski/corert,yizhang82/corert,sandreenko/corert,botaberg/corert,shrah/corert,shrah/corert,kyulee1/corert,sandreenko/corert,gregkalapos/corert,yizhang82/corert,kyulee1/corert,botaberg/corert,sandreenko/corert,gregkalapos/corert,krytarowski/corert,tijoytom/corert,gregkalapos/corert,tijoytom/corert,botaberg/corert,yizhang82/corert,tijoytom/corert,shrah/corert,krytarowski/corert | src/Common/src/Internal/Runtime/LowLevelStringConverter.cs | src/Common/src/Internal/Runtime/LowLevelStringConverter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
namespace Internal.Runtime
{
/// <summary>
/// Extension methods that provide low level ToString() equivalents for some of the core types.
/// Calling regular ToString() on these types goes through a lot of the CultureInfo machinery
/// which is not low level enough to be used everywhere.
/// </summary>
internal static class LowLevelStringConverter
{
private const string HexDigits = "0123456789ABCDEF";
// TODO: Rename to ToHexString()
public static string LowLevelToString(this int arg)
{
return ((uint)arg).LowLevelToString();
}
// TODO: Rename to ToHexString()
public static string LowLevelToString(this uint arg)
{
StringBuilder sb = new StringBuilder(8);
int shift = 4 * 8;
while (shift > 0)
{
shift -= 4;
int digit = (int)((arg >> shift) & 0xF);
sb.Append(HexDigits[digit]);
}
return sb.ToString();
}
public static string LowLevelToString(this IntPtr arg)
{
StringBuilder sb = new StringBuilder(IntPtr.Size * 4);
ulong num = (ulong)arg;
int shift = IntPtr.Size * 8;
while (shift > 0)
{
shift -= 4;
int digit = (int)((num >> shift) & 0xF);
sb.Append(HexDigits[digit]);
}
return sb.ToString();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using Internal.Runtime.Augments;
namespace Internal.Runtime
{
/// <summary>
/// Extension methods that provide low level ToString() equivalents for some of the core types.
/// Calling regular ToString() on these types goes through a lot of the CultureInfo machinery
/// which is not low level enough for the type loader purposes.
/// </summary>
internal static class LowLevelStringConverter
{
private const string HexDigits = "0123456789ABCDEF";
public static string LowLevelToString(this int arg)
{
return ((uint)arg).LowLevelToString();
}
public static string LowLevelToString(this uint arg)
{
StringBuilder sb = new StringBuilder(8);
int shift = 4 * 8;
while (shift > 0)
{
shift -= 4;
int digit = (int)((arg >> shift) & 0xF);
sb.Append(HexDigits[digit]);
}
return sb.ToString();
}
public static string LowLevelToString(this IntPtr arg)
{
StringBuilder sb = new StringBuilder(IntPtr.Size * 4);
ulong num = (ulong)arg;
int shift = IntPtr.Size * 8;
while (shift > 0)
{
shift -= 4;
int digit = (int)((num >> shift) & 0xF);
sb.Append(HexDigits[digit]);
}
return sb.ToString();
}
}
}
| mit | C# |
ca580e9212c6a5ee0370c5a9b40e5fac2329a286 | Remove Comment | Codeer-Software/LambdicSql.SqlServer | Project/LambdicSql.SqlServer.Shared/CdcSymbols.cs | Project/LambdicSql.SqlServer.Shared/CdcSymbols.cs | using LambdicSql.ConverterServices;
using LambdicSql.ConverterServices.SymbolConverters;
namespace LambdicSql.SqlServer
{
/// <summary>
/// Change data capture records insert, update, and delete activity applied to SQL Server tables, supplying the details of the changes in an easily consumed relational format
/// </summary>
public class CdcSymbols
{
/// <summary>
/// sys.fn_cdc_get_all_changes_capture_instance
/// https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/cdc-fn-cdc-get-all-changes-capture-instance-transact-sql
/// </summary>
/// <param name="capture_instance_name">capture instance name</param>
/// <param name="from_lsn">The LSN value that represents the low endpoint of the LSN range to include in the result set. from_lsn is binary(10).</param>
/// <param name="to_lsn">The LSN value that represents the high endpoint of the LSN range to include in the result set. to_lsn is binary(10).</param>
/// <param name="row_filter_option">An option that governs the content of the metadata columns as well as the rows returned in the result set</param>
/// <returns>Type of destination.</returns>
[MethodFormatConverter(Format = "cdc.fn_cdc_get_all_changes_[0]([1], [2], [3])")]
public object fn_cdc_get_all_changes_capture_instance(string capture_instance_name, byte[] from_lsn, byte[] to_lsn, string row_filter_option) => throw new InvalitContextException(nameof(fn_cdc_get_all_changes_capture_instance));
/// <summary>
/// sys.fn_cdc_get_net_changes_capture_instance
/// https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/cdc-fn-cdc-get-net-changes-capture-instance-transact-sql
/// </summary>
/// <param name="capture_instance_name">capture instance name</param>
/// <param name="from_lsn">The LSN that represents the low endpoint of the LSN range to include in the result set. from_lsn is binary(10).</param>
/// <param name="to_lsn">The LSN that represents the high endpoint of the LSN range to include in the result set. to_lsn is binary(10).</param>
/// <param name="row_filter_option">An option that governs the content of the metadata columns as well as the rows returned in the result set. Can be one of the following options</param>
/// <returns>Type of destination.</returns>
[MethodFormatConverter(Format = "cdc.fn_cdc_get_net_changes_[0]([1], [2], [3])")]
public object fn_cdc_get_net_changes_capture_instance(string capture_instance_name, byte[] from_lsn, byte[] to_lsn, string row_filter_option) => throw new InvalitContextException(nameof(fn_cdc_get_net_changes_capture_instance));
}
}
| using LambdicSql.ConverterServices;
using LambdicSql.ConverterServices.SymbolConverters;
namespace LambdicSql.SqlServer
{
/// <summary>
/// Change data capture records insert, update, and delete activity applied to SQL Server tables, supplying the details of the changes in an easily consumed relational format
/// </summary>
public class CdcSymbols
{
/// <summary>
/// sys.fn_cdc_get_all_changes_capture_instance
/// https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/cdc-fn-cdc-get-all-changes-capture-instance-transact-sql
/// </summary>
/// <typeparam name="TDst">Type of destination.</typeparam>
/// <param name="capture_instance_name">capture instance name</param>
/// <param name="from_lsn">The LSN value that represents the low endpoint of the LSN range to include in the result set. from_lsn is binary(10).</param>
/// <param name="to_lsn">The LSN value that represents the high endpoint of the LSN range to include in the result set. to_lsn is binary(10).</param>
/// <param name="row_filter_option">An option that governs the content of the metadata columns as well as the rows returned in the result set</param>
/// <returns>Type of destination.</returns>
[MethodFormatConverter(Format = "cdc.fn_cdc_get_all_changes_[0]([1], [2], [3])")]
public object fn_cdc_get_all_changes_capture_instance(string capture_instance_name, byte[] from_lsn, byte[] to_lsn, string row_filter_option) => throw new InvalitContextException(nameof(fn_cdc_get_all_changes_capture_instance));
/// <summary>
/// sys.fn_cdc_get_net_changes_capture_instance
/// https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/cdc-fn-cdc-get-net-changes-capture-instance-transact-sql
/// </summary>
/// <typeparam name="TDst">Type of destination.</typeparam>
/// <param name="capture_instance_name">capture instance name</param>
/// <param name="from_lsn">The LSN that represents the low endpoint of the LSN range to include in the result set. from_lsn is binary(10).</param>
/// <param name="to_lsn">The LSN that represents the high endpoint of the LSN range to include in the result set. to_lsn is binary(10).</param>
/// <param name="row_filter_option">An option that governs the content of the metadata columns as well as the rows returned in the result set. Can be one of the following options</param>
/// <returns>Type of destination.</returns>
[MethodFormatConverter(Format = "cdc.fn_cdc_get_net_changes_[0]([1], [2], [3])")]
public object fn_cdc_get_net_changes_capture_instance(string capture_instance_name, byte[] from_lsn, byte[] to_lsn, string row_filter_option) => throw new InvalitContextException(nameof(fn_cdc_get_net_changes_capture_instance));
}
}
| mit | C# |
b231f181530536f331e6e6f360a5b374963e4e18 | fix AssemblyInfo | skybrud/Skybrud.Umbraco.Redirects,skybrud/Skybrud.Umbraco.Redirects,skybrud/Skybrud.Umbraco.Redirects | src/Skybrud.Umbraco.Redirects/Properties/AssemblyInfo.cs | src/Skybrud.Umbraco.Redirects/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("Skybrud.Umbraco.Redirects")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Skybrud.Umbraco.Redirects")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("73d1b9ad-6bcf-474c-98a2-4845c94c3d8c")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 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("Skybrud.Umbraco.Redirects8")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Skybrud.Umbraco.Redirects8")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("73d1b9ad-6bcf-474c-98a2-4845c94c3d8c")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
0997c49c437798b0d3d4dfbf5c3c8b52dd61ab5a | Debug camera move | Chaojincoolbean/Fly | Fly/Assets/_Script/DebugScript.cs | Fly/Assets/_Script/DebugScript.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DebugScript : MonoBehaviour {
public bool DebugCamera;
public bool DebugLeftController;
public bool DebugRightController;
public bool DebugCameraMove;
public GameObject Camera;
public GameObject LeftController;
public GameObject RightController;
// Use this for initialization
void Start () {
InputDebug ();
}
// Update is called once per frame
void Update () {
InputDebug ();
}
void InputDebug(){
if (DebugCamera == true) {
Debug.Log ("startCamera:" + Camera.gameObject.transform.position);
}
if (DebugLeftController == true) {
Debug.Log ("startLeftController:" + LeftController.gameObject.transform.position);
}
if (DebugRightController == true) {
Debug.Log ("startRightController:" + RightController.gameObject.transform.position);
}
}
void CameraMoveDebug(){
if (DebugCameraMove == true) {
Camera.gameObject.transform.position = new Vector3 (Camera.gameObject.transform.position.x,
Camera.gameObject.transform.position.y + 1f,
Camera.gameObject.transform.position.z);
Debug.Log ("CameraPosition:" + Camera.gameObject.transform.position);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DebugScript : MonoBehaviour {
public bool DebugCamera;
public bool DebugLeftController;
public bool DebugRightController;
public GameObject Camera;
public GameObject LeftController;
public GameObject RightController;
// Use this for initialization
void Start () {
InputDebug ();
}
// Update is called once per frame
void Update () {
InputDebug ();
}
void InputDebug(){
if (DebugCamera == true) {
Debug.Log ("startCamera:" + Camera.gameObject.transform.position);
}
if (DebugLeftController == true) {
Debug.Log ("startLeftController:" + LeftController.gameObject.transform.position);
}
if (DebugRightController == true) {
Debug.Log ("startRightController:" + RightController.gameObject.transform.position);
}
}
}
| unlicense | C# |
9e57b09a5b597066fc2efb14b494c881feebe018 | update to HTML 5 | ForNeVeR/fornever.me,ForNeVeR/fornever.me,ForNeVeR/fornever.me | ForneverMind/views/_Layout.cshtml | ForneverMind/views/_Layout.cshtml | <!DOCTYPE html>
@using RazorEngine.Templating
@inherits TemplateBase
<html lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>F. von Never — @ViewBag.Title</title>
<base href="@System.Configuration.ConfigurationManager.AppSettings["BaseUrl"]"/>
<link rel="alternate" type="application/rss+xml" href="./rss.xml" title="RSS Feed"/>
<link rel="stylesheet" type="text/css" href="./css/main.css"/>
<script src="app/app.js" async></script>
</head>
<body>
<div id="header">
<div id="logo">
<a href="./">Инженер, программист, джентльмен</a>
</div>
<div id="navigation">
<a href="./archive.html">Посты</a>
<a href="./contact.html">Контакты</a>
<a href="./plans/index.html">Планы</a>
</div>
</div>
<div id="content">
<h1>@ViewBag.Title</h1>
@RenderBody()
</div>
<footer>
<div>
<a class="tag" href="./rss.xml">RSS</a>
<a class="tag" href="https://github.com/ForNeVeR/fornever.me">GitHub</a>
</div>
<div>
Сайт использует библиотеку
<a href="http://docs.freya.io/en/latest/">Freya</a>
</div>
</footer>
@RenderSection("scripts", false)
</body>
</html>
| @using RazorEngine.Templating
@inherits TemplateBase
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>F. von Never — @ViewBag.Title</title>
<base href="@System.Configuration.ConfigurationManager.AppSettings["BaseUrl"]"/>
<link rel="alternate" type="application/rss+xml" href="./rss.xml" title="RSS Feed"/>
<link rel="stylesheet" type="text/css" href="./css/main.css"/>
<script src="app/app.js" async></script>
</head>
<body>
<div id="header">
<div id="logo">
<a href="./">Инженер, программист, джентльмен</a>
</div>
<div id="navigation">
<a href="./archive.html">Посты</a>
<a href="./contact.html">Контакты</a>
<a href="./plans/index.html">Планы</a>
</div>
</div>
<div id="content">
<h1>@ViewBag.Title</h1>
@RenderBody()
</div>
<footer>
<div>
<a class="tag" href="./rss.xml">RSS</a>
<a class="tag" href="https://github.com/ForNeVeR/fornever.me">GitHub</a>
</div>
<div>
Сайт использует библиотеку
<a href="http://docs.freya.io/en/latest/">Freya</a>
</div>
</footer>
@RenderSection("scripts", false)
</body>
</html>
| mit | C# |
685cc9798a7c66e0fd01860d9e3ec2c1ad3f1e40 | rename root, remove namespaces | KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin | src/Kirkin.Experimental/Serialization/XmlSerializer.cs | src/Kirkin.Experimental/Serialization/XmlSerializer.cs | using System.IO;
using System.Xml.Serialization;
using XSerializer = System.Xml.Serialization.XmlSerializer;
namespace Kirkin.Serialization
{
internal sealed class XmlSerializer : Serializer
{
private static readonly XmlSerializerFactory Factory = new XmlSerializerFactory();
private static readonly XmlSerializerNamespaces DefaultNamespaces = CreateDefaultNamespaces();
public override T Deserialize<T>(Stream stream)
{
XSerializer serializer = CreateSerializer<T>();
return (T)serializer.Deserialize(stream);
}
public override void Serialize<T>(T content, Stream stream)
{
XSerializer serializer = CreateSerializer<T>();
serializer.Serialize(stream, content, DefaultNamespaces);
}
private static XSerializer CreateSerializer<T>()
{
return Factory.CreateSerializer(typeof(T), new XmlRootAttribute("Root"));
}
private static XmlSerializerNamespaces CreateDefaultNamespaces()
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
return namespaces;
}
}
} | using System.IO;
using System.Xml.Serialization;
using XSerializer = System.Xml.Serialization.XmlSerializer;
namespace Kirkin.Serialization
{
internal sealed class XmlSerializer : Serializer
{
private static readonly XmlSerializerFactory Factory = new XmlSerializerFactory();
public override T Deserialize<T>(Stream stream)
{
XSerializer serializer = CreateSerializer<T>();
return (T)serializer.Deserialize(stream);
}
public override void Serialize<T>(T content, Stream stream)
{
XSerializer serializer = CreateSerializer<T>();
serializer.Serialize(stream, content);
}
private static XSerializer CreateSerializer<T>()
{
return Factory.CreateSerializer(typeof(T), new XmlRootAttribute("Cache"));
}
}
} | mit | C# |
1a72f36879dd4242c49aea2a06117a51ff7857c9 | Remove whitespace around app version | smbc-digital/iag-contentapi | src/StockportContentApi/Services/HealthcheckService.cs | src/StockportContentApi/Services/HealthcheckService.cs | using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;
namespace StockportContentApi.Services
{
public interface IHealthcheckService
{
Task<Healthcheck> Get();
}
public class HealthcheckService : IHealthcheckService
{
private readonly string _appVersion;
private readonly string _sha;
private readonly IFileWrapper _fileWrapper;
private readonly string _environment;
private readonly ICache _cacheWrapper;
public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
{
_fileWrapper = fileWrapper;
_appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
_sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
_environment = environment;
_cacheWrapper = cacheWrapper;
}
private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
{
if (_fileWrapper.Exists(filePath))
{
var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
if (!string.IsNullOrEmpty(firstLine))
return firstLine.Trim();
}
return defaultValue.Trim();
}
public async Task<Healthcheck> Get()
{
// Commented out because it was breaking prod.
//var keys = await _cacheWrapper.GetKeys();
return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
}
}
} | using System.Collections.Generic;
using StockportContentApi.Model;
using StockportContentApi.Utils;
using System.Linq;
using System.Threading.Tasks;
namespace StockportContentApi.Services
{
public interface IHealthcheckService
{
Task<Healthcheck> Get();
}
public class HealthcheckService : IHealthcheckService
{
private readonly string _appVersion;
private readonly string _sha;
private readonly IFileWrapper _fileWrapper;
private readonly string _environment;
private readonly ICache _cacheWrapper;
public HealthcheckService(string appVersionPath, string shaPath, IFileWrapper fileWrapper, string environment, ICache cacheWrapper)
{
_fileWrapper = fileWrapper;
_appVersion = GetFirstFileLineOrDefault(appVersionPath, "dev");
_sha = GetFirstFileLineOrDefault(shaPath, string.Empty);
_environment = environment;
_cacheWrapper = cacheWrapper;
}
private string GetFirstFileLineOrDefault(string filePath, string defaultValue)
{
if (_fileWrapper.Exists(filePath))
{
var firstLine = _fileWrapper.ReadAllLines(filePath).FirstOrDefault();
if (!string.IsNullOrEmpty(firstLine))
return firstLine;
}
return defaultValue;
}
public async Task<Healthcheck> Get()
{
// Commented out because it was breaking prod.
//var keys = await _cacheWrapper.GetKeys();
return new Healthcheck(_appVersion, _sha, _environment, new List<RedisValueData>());
}
}
} | mit | C# |
88aa4019c094c02b3ffd90218188e5d0c16a32e2 | fix the typo'd namespace | versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla | VersionOne.Bugzilla.BugzillaAPI.Tests/BugTests.cs | VersionOne.Bugzilla.BugzillaAPI.Tests/BugTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace VersionOne.Bugzilla.BugzillaAPI.Tests
{
[TestClass()]
public class Given_A_Bug
{
private IBug _bug;
private string _expectedReassignToPayload;
[TestInitialize()]
public void SetContext()
{
_bug = new Bug();
_expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}";
}
[TestMethod]
public void it_should_give_appropriate_reassignto_payloads()
{
var integrationUser = "terry.densmore@versionone.com";
_bug.AssignedTo = "denise@denise.com";
Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace VersionOne.Bugzilla.BugzillaAPI.Testss
{
[TestClass()]
public class Given_A_Bug
{
private IBug _bug;
private string _expectedReassignToPayload;
[TestInitialize()]
public void SetContext()
{
_bug = new Bug();
_expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}";
}
[TestMethod]
public void it_should_give_appropriate_reassignto_payloads()
{
var integrationUser = "terry.densmore@versionone.com";
_bug.AssignedTo = "denise@denise.com";
Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
}
}
}
| bsd-3-clause | C# |
45b64f078de8bbbe8013a329795bcd2771892028 | Fix EnumHelper ignoreCase | rsdn/CodeJam,NN---/CodeJam | Main/src/Reflection/EnumHelper.cs | Main/src/Reflection/EnumHelper.cs | using System;
using JetBrains.Annotations;
namespace CodeJam.Reflection
{
/// <summary>
/// Helper methods for enumeration.
/// </summary>
[PublicAPI]
public static class EnumHelper
{
/// <summary>
/// Retrieves an array of the names of the constants in a specified enumeration.
/// </summary>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>A string array of the names of the constants in enumType.</returns>
[NotNull]
[Pure]
public static string[] GetNames<T>() => Enum.GetNames(typeof(T));
/// <summary>
/// Retrieves the name of the constant in the specified enumeration that has the specified value.
/// </summary>
/// <param name="value">The value of a particular enumerated constant in terms of its underlying type.</param>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>
/// A string containing the name of the enumerated constant in enumType whose value is value;
/// or null if no such constant is found.
/// </returns>
[CanBeNull]
[Pure]
public static string GetName<T>(T value) => Enum.GetName(typeof(T), value);
/// <summary>
/// Retrieves an array of the values of the constants in a specified enumeration.
/// </summary>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>An array that contains the values of the constants in enumType.</returns>
[NotNull]
[Pure]
public static T[] GetValues<T>() => (T[])Enum.GetValues(typeof (T));
/// <summary>
/// Returns an indication whether a constant with a specified value exists in a specified enumeration.
/// </summary>
/// <param name="value">The value or name of a constant in <typeparamref name="T"/>.</param>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>true if a constant in enumType has a value equal to value; otherwise, false.</returns>
[Pure]
public static bool IsDefined<T>(T value) => Enum.IsDefined(typeof (T), value);
/// <summary>
/// Converts the string representation of the name or numeric <paramref name="value"/> of one or more
/// enumerated constants to an equivalent enumerated object. A parameter <paramref name="ignoreCase"/> specifies
/// whether the operation is case-insensitive.
/// </summary>
/// <param name="value">A string containing the name or value to convert.</param>
/// <param name="ignoreCase">true to ignore case; false to regard case.</param>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>An object of type enumType whose value is represented by value.</returns>
[Pure]
public static T Parse<T>([NotNull] string value, bool ignoreCase = true) =>
(T)Enum.Parse(typeof (T), value, ignoreCase);
}
} | using System;
using JetBrains.Annotations;
namespace CodeJam.Reflection
{
/// <summary>
/// Helper methods for enumeration.
/// </summary>
[PublicAPI]
public static class EnumHelper
{
/// <summary>
/// Retrieves an array of the names of the constants in a specified enumeration.
/// </summary>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>A string array of the names of the constants in enumType.</returns>
[NotNull]
[Pure]
public static string[] GetNames<T>() => Enum.GetNames(typeof(T));
/// <summary>
/// Retrieves the name of the constant in the specified enumeration that has the specified value.
/// </summary>
/// <param name="value">The value of a particular enumerated constant in terms of its underlying type.</param>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>
/// A string containing the name of the enumerated constant in enumType whose value is value;
/// or null if no such constant is found.
/// </returns>
[CanBeNull]
[Pure]
public static string GetName<T>(T value) => Enum.GetName(typeof(T), value);
/// <summary>
/// Retrieves an array of the values of the constants in a specified enumeration.
/// </summary>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>An array that contains the values of the constants in enumType.</returns>
[NotNull]
[Pure]
public static T[] GetValues<T>() => (T[])Enum.GetValues(typeof (T));
/// <summary>
/// Returns an indication whether a constant with a specified value exists in a specified enumeration.
/// </summary>
/// <param name="value">The value or name of a constant in <typeparamref name="T"/>.</param>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>true if a constant in enumType has a value equal to value; otherwise, false.</returns>
[Pure]
public static bool IsDefined<T>(T value) => Enum.IsDefined(typeof (T), value);
/// <summary>
/// Converts the string representation of the name or numeric <paramref name="value"/> of one or more
/// enumerated constants to an equivalent enumerated object. A parameter <paramref name="ignoreCase"/> specifies
/// whether the operation is case-insensitive.
/// </summary>
/// <param name="value">A string containing the name or value to convert.</param>
/// <param name="ignoreCase">true to ignore case; false to regard case.</param>
/// <typeparam name="T">An enumeration type.</typeparam>
/// <returns>An object of type enumType whose value is represented by value.</returns>
[Pure]
public static T Parse<T>([NotNull] string value, bool ignoreCase = true) => (T)Enum.Parse(typeof (T), value);
}
} | mit | C# |
33fdf39e1930bf0d380a73ba8750857a549cff07 | Add a method to read a GUID from #GUID | Arthur2e5/dnlib,jorik041/dnlib,modulexcite/dnlib,yck1509/dnlib,picrap/dnlib,ZixiangBoy/dnlib,0xd4d/dnlib,kiootic/dnlib,ilkerhalil/dnlib | dot10/dotNET/GuidStream.cs | dot10/dotNET/GuidStream.cs | using System;
using dot10.IO;
namespace dot10.dotNET {
class GuidStream : DotNetStream {
/// <inheritdoc/>
public GuidStream(IImageStream imageStream, StreamHeader streamHeader)
: base(imageStream, streamHeader) {
}
/// <inheritdoc/>
public override bool IsValidIndex(uint index) {
return index == 0 || IsValidOffset((index - 1) * 16, 16);
}
/// <summary>
/// Read a <see cref="Guid"/>
/// </summary>
/// <param name="index">Index into this stream</param>
/// <returns>A <see cref="Guid"/> or null if <paramref name="index"/> is 0 or invalid</returns>
public Guid? Read(uint index) {
if (index == 0 || !IsValidIndex(index))
return null;
imageStream.Position = (index - 1) * 16;
return new Guid(imageStream.ReadBytes(16));
}
}
}
| using dot10.IO;
namespace dot10.dotNET {
class GuidStream : DotNetStream {
/// <inheritdoc/>
public GuidStream(IImageStream imageStream, StreamHeader streamHeader)
: base(imageStream, streamHeader) {
}
}
}
| mit | C# |
82fb0b0e683e4b5997d50d8394d68ce40f56e678 | Fix typo | rosolko/WebDriverManager.Net | WebDriverManager/DriverConfigs/Impl/EdgeConfig.cs | WebDriverManager/DriverConfigs/Impl/EdgeConfig.cs | using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
namespace WebDriverManager.DriverConfigs.Impl
{
public class EdgeConfig : IDriverConfig
{
private const string BaseVersionPatternUrl = "https://msedgedriver.azureedge.net/<version>/";
public virtual string GetName()
{
return "Edge";
}
public virtual string GetUrl32()
{
return $"{BaseVersionPatternUrl}edgedriver_win32.zip";
}
public virtual string GetUrl64()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? $"{BaseVersionPatternUrl}edgedriver_mac64.zip"
: $"{BaseVersionPatternUrl}edgedriver_win64.zip";
}
public virtual string GetBinaryName()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? "msedgedriver"
: "msedgedriver.exe";
}
public virtual string GetLatestVersion()
{
var uri = new Uri("https://msedgedriver.azureedge.net/LATEST_BETA");
var webRequest = WebRequest.Create(uri);
using (var response = webRequest.GetResponse())
{
using (var content = response.GetResponseStream())
{
if (content == null) throw new ArgumentNullException($"Can't get content from URL: {uri}");
using (var reader = new StreamReader(content))
{
var version = reader.ReadToEnd().Trim();
return version;
}
}
}
}
}
}
| using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
namespace WebDriverManager.DriverConfigs.Impl
{
public class EdgeConfig : IDriverConfig
{
private const string BaseVersionPatternUrl = "https://msedgedriver.azureedge.net/<version>/";
public virtual string GetName()
{
return "Edge";
}
public virtual string GetUrl32()
{
return $"{BaseVersionPatternUrl}edgedriver_win32.zip";
}
public virtual string GetUrl64()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? $"{BaseVersionPatternUrl}edgedriver_mac64.zip"
: $"{BaseVersionPatternUrl}edgedriver_win64.zip";
}
public virtual string GetBinaryName()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? "msedgedriver.exe"
: "msedgedriver";
}
public virtual string GetLatestVersion()
{
var uri = new Uri("https://msedgedriver.azureedge.net/LATEST_BETA");
var webRequest = WebRequest.Create(uri);
using (var response = webRequest.GetResponse())
{
using (var content = response.GetResponseStream())
{
if (content == null) throw new ArgumentNullException($"Can't get content from URL: {uri}");
using (var reader = new StreamReader(content))
{
var version = reader.ReadToEnd().Trim();
return version;
}
}
}
}
}
}
| mit | C# |
3c4d8d52caed6272140a125bb0b00075884e7fba | Revert version mtapi (MT5) to 1.0.12 | vdemydiuk/mtapi,vdemydiuk/mtapi,vdemydiuk/mtapi | MtApi5/Properties/AssemblyInfo.cs | MtApi5/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("MtApi5")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MtApi5")]
[assembly: AssemblyCopyright("Copyright © 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("f3256daf-a5c0-422d-9d79-f7156cccb910")]
// 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.12")]
[assembly: AssemblyFileVersion("1.0.12")]
| 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("MtApi5")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MtApi5")]
[assembly: AssemblyCopyright("Copyright © 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("f3256daf-a5c0-422d-9d79-f7156cccb910")]
// 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.13")]
[assembly: AssemblyFileVersion("1.0.13")]
| mit | C# |
94bc781df730b2219c1af081e2e4539f833840d5 | remove debug file output | blackdwarf/cli,EdwardBlair/cli,harshjain2/cli,ravimeda/cli,blackdwarf/cli,harshjain2/cli,dasMulli/cli,EdwardBlair/cli,dasMulli/cli,livarcocc/cli-1,harshjain2/cli,blackdwarf/cli,svick/cli,dasMulli/cli,ravimeda/cli,ravimeda/cli,Faizan2304/cli,svick/cli,Faizan2304/cli,johnbeisner/cli,blackdwarf/cli,johnbeisner/cli,EdwardBlair/cli,Faizan2304/cli,svick/cli,johnbeisner/cli,livarcocc/cli-1,livarcocc/cli-1 | src/dotnet/commands/dotnet-complete/CompleteCommand.cs | src/dotnet/commands/dotnet-complete/CompleteCommand.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Cli
{
public class CompleteCommand
{
public static int Run(string[] args)
{
try
{
DebugHelper.HandleDebugSwitch(ref args);
// get the parser for the current subcommand
var parser = Parser.Instance;
// parse the arguments
var result = parser.ParseFrom("dotnet complete", args);
var complete = result["dotnet"]["complete"];
var suggestions = Suggestions(complete);
foreach (var suggestion in suggestions)
{
Console.WriteLine(suggestion);
}
}
catch (Exception e)
{
return 1;
}
return 0;
}
private static string[] Suggestions(AppliedOption complete)
{
var input = complete.Arguments.SingleOrDefault() ?? "";
var positionOption = complete.AppliedOptions.SingleOrDefault(a => a.Name == "position");
if (positionOption != null)
{
var position = positionOption.Value<int>();
if (position > input.Length)
{
input += " ";
}
}
var result = Parser.Instance.Parse(input);
return result.Suggestions()
.ToArray();
}
}
} | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Cli
{
public class CompleteCommand
{
public static int Run(string[] args)
{
try
{
DebugHelper.HandleDebugSwitch(ref args);
// get the parser for the current subcommand
var parser = Parser.Instance;
// parse the arguments
var result = parser.ParseFrom("dotnet complete", args);
var complete = result["dotnet"]["complete"];
var suggestions = Suggestions(complete);
var log = new StringBuilder();
log.AppendLine($"args: {string.Join(" ", args.Select(a => $"\"{a}\""))}");
log.AppendLine("diagram: " + result.Diagram());
File.WriteAllText("parse.log", log.ToString());
foreach (var suggestion in suggestions)
{
Console.WriteLine(suggestion);
}
}
catch (Exception e)
{
File.WriteAllText("dotnet completion exception.log", e.ToString());
throw;
}
return 0;
}
private static string[] Suggestions(AppliedOption complete)
{
var input = complete.Arguments.SingleOrDefault() ?? "";
var positionOption = complete.AppliedOptions.SingleOrDefault(a => a.Name == "position");
if (positionOption != null)
{
var position = positionOption.Value<int>();
if (position > input.Length)
{
input += " ";
}
}
var result = Parser.Instance.Parse(input);
return result.Suggestions()
.ToArray();
}
}
} | mit | C# |
5743c64abaada6aab0c0a59f149ef92b07a45eee | Add comment | danielmundt/csremote | source/Remoting.Server/Command.cs | source/Remoting.Server/Command.cs | #region Header
// Copyright (C) 2012 Daniel Schubert
//
// 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 Header
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Lifetime;
using System.Text;
using System.Threading;
using Remoting.Service;
namespace Remoting.Server
{
public class Command : MarshalByRefObject, ICommand
{
#region Fields
private Context context;
#endregion Fields
#region Constructors
public Command(Context context)
{
this.context = context;
}
#endregion Constructors
#region Methods
public override object InitializeLifetimeService()
{
// indicate that this lease never expires
return null;
}
public int SendCommand(Remoting.Service.Enums.Command command)
{
string appName = AppDomain.CurrentDomain.FriendlyName;
context.SetLog(string.Format("Received command: {0} ({1})", command, appName));
return Process.GetCurrentProcess().Id;
}
#endregion Methods
}
} | #region Header
// Copyright (C) 2012 Daniel Schubert
//
// 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 Header
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Lifetime;
using System.Text;
using System.Threading;
using Remoting.Service;
namespace Remoting.Server
{
public class Command : MarshalByRefObject, ICommand
{
#region Fields
private Context context;
#endregion Fields
#region Constructors
public Command(Context context)
{
this.context = context;
}
#endregion Constructors
#region Methods
public override object InitializeLifetimeService()
{
return null;
}
public int SendCommand(Remoting.Service.Enums.Command command)
{
string appName = AppDomain.CurrentDomain.FriendlyName;
context.SetLog(string.Format("Received command: {0} ({1})", command, appName));
return Process.GetCurrentProcess().Id;
}
#endregion Methods
}
} | mit | C# |
67e7254a7612051cf839fc06d107db1add36c299 | Create regions | bartlomiejwolk/OnCollisionActivate | GameObjectSlot.cs | GameObjectSlot.cs | // Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com)
//
// This file is part of the GameObjectActivator extension for Unity.
// Licensed under the MIT license. See LICENSE file in the project root folder.
using UnityEngine;
// todo convert comments to xml
namespace GameObjectActivatorEx {
/// Object to enable.
[System.Serializable]
public class GameObjectSlot {
#region FIELDS
/// Select to include or exclude a given tag.
[SerializeField]
private TagOptions _tagOption;
/// On collision with objects with this tag
/// the object won't be enabled.
[SerializeField]
private string _tag;
/// Game object.
[SerializeField]
private GameObject _objToEnable;
#endregion
#region PROPERTIES
public string ExcludeTag {
get { return _tag; }
set { _tag = value; }
}
public GameObject ObjToEnable {
get { return _objToEnable; }
set { _objToEnable = value; }
}
public TagOptions TagOption {
get { return _tagOption; }
}
#endregion
}
} | // Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com)
//
// This file is part of the GameObjectActivator extension for Unity.
// Licensed under the MIT license. See LICENSE file in the project root folder.
using UnityEngine;
// todo convert comments to xml
namespace GameObjectActivatorEx {
/// Object to enable.
[System.Serializable]
public class GameObjectSlot {
/// Game object.
[SerializeField]
private GameObject _objToEnable;
public GameObject ObjToEnable {
get { return _objToEnable; }
set { _objToEnable = value; }
}
/// Select to include or exclude a given tag.
[SerializeField]
private TagOptions _tagOption;
public TagOptions TagOption {
get { return _tagOption; }
}
/// On collision with objects with this tag
/// the object won't be enabled.
[SerializeField]
private string _tag;
public string ExcludeTag {
get { return _tag; }
set { _tag = value; }
}
}
} | mit | C# |
29a4e5b40bed74f730354d92d4e318c7e6b88a27 | Add null-checks to the conparers. | Joe4evr/Discord.Addons | src/Discord.Addons.Core/Comparers.cs | src/Discord.Addons.Core/Comparers.cs | using System;
using System.Collections.Generic;
namespace Discord.Addons.Core
{
internal static class Comparers
{
public static IEqualityComparer<IUser> UserComparer => _userComparer ?? Create<IUser , ulong>(ref _userComparer);
public static IEqualityComparer<IGuild> GuildComparer => _guildComparer ?? Create<IGuild , ulong>(ref _guildComparer);
public static IEqualityComparer<IChannel> ChannelComparer => _channelComparer ?? Create<IChannel, ulong>(ref _channelComparer);
public static IEqualityComparer<IRole> RoleComparer => _roleComparer ?? Create<IRole , ulong>(ref _roleComparer);
private static IEqualityComparer<IUser> _userComparer;
private static IEqualityComparer<IGuild> _guildComparer;
private static IEqualityComparer<IChannel> _channelComparer;
private static IEqualityComparer<IRole> _roleComparer;
private static IEqualityComparer<TEntity> Create<TEntity, TId>(ref IEqualityComparer<TEntity> field)
where TEntity : IEntity<TId>
where TId : IEquatable<TId>
{
return field = new EntityEqualityComparer<TEntity, TId>();
}
private sealed class EntityEqualityComparer<TEntity, TId> : EqualityComparer<TEntity>
where TEntity : IEntity<TId>
where TId : IEquatable<TId>
{
public override bool Equals(TEntity x, TEntity y)
{
bool xNull = x == null;
bool yNull = y == null;
if (xNull && yNull)
return true;
if (xNull ^ yNull)
return false;
return x.Id.Equals(y.Id);
}
public override int GetHashCode(TEntity obj)
{
return obj?.Id.GetHashCode() ?? 0;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
namespace Discord.Addons.Core
{
internal static class Comparers
{
public static IEqualityComparer<IUser> UserComparer => _userComparer ?? Create<IUser , ulong>(ref _userComparer);
public static IEqualityComparer<IGuild> GuildComparer => _guildComparer ?? Create<IGuild , ulong>(ref _guildComparer);
public static IEqualityComparer<IChannel> ChannelComparer => _channelComparer ?? Create<IChannel, ulong>(ref _channelComparer);
public static IEqualityComparer<IRole> RoleComparer => _roleComparer ?? Create<IRole , ulong>(ref _roleComparer);
private static IEqualityComparer<IUser> _userComparer;
private static IEqualityComparer<IGuild> _guildComparer;
private static IEqualityComparer<IChannel> _channelComparer;
private static IEqualityComparer<IRole> _roleComparer;
private static IEqualityComparer<TEntity> Create<TEntity, TId>(ref IEqualityComparer<TEntity> field)
where TEntity : IEntity<TId>
where TId : IEquatable<TId>
{
return field = new EntityEqualityComparer<TEntity, TId>();
//var value = new EntityEqualityComparer<TEntity, TId>();
//return (Interlocked.CompareExchange(ref field, value, null) == null) ? value : field;
}
private sealed class EntityEqualityComparer<TEntity, TId> : EqualityComparer<TEntity>
where TEntity : IEntity<TId>
where TId : IEquatable<TId>
{
public override bool Equals(TEntity x, TEntity y)
{
return x.Id.Equals(y.Id);
}
public override int GetHashCode(TEntity obj)
{
return obj.Id.GetHashCode();
}
}
}
}
| mit | C# |
521a4026d4ed34cd16c9e88f63712cbc6a922171 | remove code with secrete | mkliu/ToDoApp,mkliu/ToDoApp,mkliu/ToDoApp,mkliu/ToDoApp | src/MultiChannelToDo/Models/MultiChannelToDoContext.cs | src/MultiChannelToDo/Models/MultiChannelToDoContext.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MultiChannelToDo.Migrations;
using Microsoft.Azure.KeyVault;
using System.Web.Configuration;
namespace MultiChannelToDo.Models
{
public class MultiChannelToDoContext : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, please use data migrations.
// For more information refer to the documentation:
// http://msdn.microsoft.com/en-us/data/jj591621.aspx
public MultiChannelToDoContext() : base("name=MultiChannelToDoContext")
{
// // I put my GetToken method in a Utils class. Change for wherever you placed your method.
// var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(Util.GetToken));
// var sec = kv.GetSecretAsync(WebConfigurationManager.AppSettings["SecretUri"]).Result.Value;
// //I put a variable in a Utils class to hold the secret for general application use.
// Util.EncryptSecret = sec;
}
public System.Data.Entity.DbSet<MultiChannelToDo.Models.TodoItem> ToDoItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("mobile_service_name"); // change schema to the name of your mobile service,
// replacing dashes with underscore
// mobile-service-name ==> mobile_service_name
Database.SetInitializer<MultiChannelToDoContext>(
new MigrateDatabaseToLatestVersion<MultiChannelToDoContext, Configuration>());
base.OnModelCreating(modelBuilder);
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MultiChannelToDo.Migrations;
using Microsoft.Azure.KeyVault;
using System.Web.Configuration;
namespace MultiChannelToDo.Models
{
public class MultiChannelToDoContext : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, please use data migrations.
// For more information refer to the documentation:
// http://msdn.microsoft.com/en-us/data/jj591621.aspx
public MultiChannelToDoContext() : base("name=MultiChannelToDoContext")
{
// I put my GetToken method in a Utils class. Change for wherever you placed your method.
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(Util.GetToken));
var sec = kv.GetSecretAsync(WebConfigurationManager.AppSettings["SecretUri"]).Result.Value;
//I put a variable in a Utils class to hold the secret for general application use.
Util.EncryptSecret = sec;
}
public System.Data.Entity.DbSet<MultiChannelToDo.Models.TodoItem> ToDoItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("mobile_service_name"); // change schema to the name of your mobile service,
// replacing dashes with underscore
// mobile-service-name ==> mobile_service_name
Database.SetInitializer<MultiChannelToDoContext>(
new MigrateDatabaseToLatestVersion<MultiChannelToDoContext, Configuration>());
base.OnModelCreating(modelBuilder);
}
}
}
| mit | C# |
a5e4c4bd11c73da6ea2a4fb8df666be73d39fc45 | Fix tests | olsh/todoist-net | src/Todoist.Net.Tests/Services/ReminersServiceTests.cs | src/Todoist.Net.Tests/Services/ReminersServiceTests.cs | using System;
using System.Linq;
using Todoist.Net.Models;
using Todoist.Net.Tests.Extensions;
using Xunit;
namespace Todoist.Net.Tests.Services
{
[IntegrationPremium]
public class ReminersServiceTests
{
[Fact]
public void CreateDelete_Success()
{
var client = TodoistClientFactory.Create();
var transaction = client.CreateTransaction();
var itemId = transaction.Items.AddAsync(new Item("Temp")).Result;
var reminderId =
transaction.Reminders.AddAsync(new Reminder(itemId) { DueDateUtc = DateTime.UtcNow.AddDays(1) }).Result;
transaction.CommitAsync().Wait();
var reminders = client.Reminders.GetAsync().Result;
Assert.True(reminders.Count() > 0);
var reminderInfo = client.Reminders.GetAsync(reminderId).Result;
Assert.True(reminderInfo != null);
client.Reminders.DeleteAsync(reminderInfo.Reminder.Id).Wait();
client.Items.DeleteAsync(itemId);
}
}
}
| using System;
using System.Linq;
using Todoist.Net.Models;
using Todoist.Net.Tests.Extensions;
using Xunit;
namespace Todoist.Net.Tests.Services
{
[IntegrationPremium]
public class ReminersServiceTests
{
[Fact]
public void CreateDelete_Success()
{
var client = TodoistClientFactory.Create();
var transaction = client.CreateTransaction();
var itemId = transaction.Items.AddAsync(new Item("Temp")).Result;
var reminderId =
transaction.Reminders.AddAsync(new Reminder(itemId) { DueDateUtc = DateTime.UtcNow.AddDays(1) }).Result;
transaction.CommitAsync().Wait();
var reminderInfo = client.Reminders.GetAsync(reminderId).Result;
client.Reminders.DeleteAsync(reminderInfo.Reminder.Id).Wait();
client.Items.DeleteAsync(itemId);
}
[Fact]
public void GetReminderInfo_Success()
{
var client = TodoistClientFactory.Create();
var filters = client.Reminders.GetAsync().Result;
Assert.True(filters.Count() > 0);
var result = client.Reminders.GetAsync(filters.First().Id).Result;
Assert.True(result != null);
}
}
}
| mit | C# |
290ed0f0f0d150681ff7db14a8e9418b359ee22f | Remove unused field. | mfilippov/vimeo-dot-net | src/VimeoDotNet.Tests/Settings/VimeoApiTestSettings.cs | src/VimeoDotNet.Tests/Settings/VimeoApiTestSettings.cs | namespace VimeoDotNet.Tests.Settings
{
public class VimeoApiTestSettings
{
// API Client Settings
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string AccessToken { get; set; }
// Test Content Settings for Me
public long UserId { get; set; }
public long AlbumId { get; set; }
public long ChannelId { get; set; }
public long VideoId { get; set; }
public long TextTrackId { get; set; }
public long PublicUserId { get; set; }
}
} | namespace VimeoDotNet.Tests.Settings
{
public class VimeoApiTestSettings
{
// API Client Settings
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string AccessToken { get; set; }
// Test Content Settings for Me
public long UserId { get; set; }
public long AlbumId { get; set; }
public long ChannelId { get; set; }
public long VideoId { get; set; }
public long TextTrackId { get; set; }
public long PublicUserId { get; set; }
public long PublicAlbumId { get; set; }
public long PublicChannelId { get; set; }
public long PublicVideoId { get; set; }
}
} | mit | C# |
06a54cd6e2558b39daa046a1fd2e1a917cb7cee5 | Use sample store | peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework | osu.Framework.Tests/Visual/Audio/TestSceneLoopingSample.cs | osu.Framework.Tests/Visual/Audio/TestSceneLoopingSample.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
namespace osu.Framework.Tests.Visual.Audio
{
public class TestSceneLoopingSample : FrameworkTestScene
{
private SampleChannel sampleChannel;
[BackgroundDependencyLoader]
private void load(ISampleStore samples)
{
sampleChannel = samples.Get("tone.wav");
// reduce volume of the tone due to how loud it normally is.
if (sampleChannel != null)
sampleChannel.Volume.Value = 0.05;
}
[Test]
public void TestLooping()
{
AddAssert("not looping", () => !sampleChannel.Looping);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddAssert("is playing", () => sampleChannel.Playing);
AddWaitStep("wait", 1);
AddAssert("is still playing", () => sampleChannel.Playing);
AddStep("stop sample", () => sampleChannel.Stop());
AddAssert("not playing", () => !sampleChannel.Playing);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.IO.Stores;
namespace osu.Framework.Tests.Visual.Audio
{
public class TestSceneLoopingSample : FrameworkTestScene
{
private SampleChannel sampleChannel;
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleChannel = audio.GetSampleStore(new NamespacedResourceStore<byte[]>(new DllResourceStore("osu.Framework.Tests.dll"), "Resources")).Get("Samples.tone.wav");
// reduce volume of the tone due to how loud it normally is.
if (sampleChannel != null)
sampleChannel.Volume.Value = 0.05;
}
[Test]
public void TestLooping()
{
AddAssert("not looping", () => !sampleChannel.Looping);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddAssert("is playing", () => sampleChannel.Playing);
AddWaitStep("wait", 1);
AddAssert("is still playing", () => sampleChannel.Playing);
AddStep("stop sample", () => sampleChannel.Stop());
AddAssert("not playing", () => !sampleChannel.Playing);
}
}
}
| mit | C# |
1874a4bf7014fded77d9cdba7f931a3be29a625a | Add HelloWorld plain text API. | stephentoub/corefxlab,axxu/corefxlab,VSadov/corefxlab,ericstj/corefxlab,jamesqo/corefxlab,benaadams/corefxlab,VSadov/corefxlab,KrzysztofCwalina/corefxlab,VSadov/corefxlab,tarekgh/corefxlab,stephentoub/corefxlab,KrzysztofCwalina/corefxlab,VSadov/corefxlab,ericstj/corefxlab,ahsonkhan/corefxlab,stephentoub/corefxlab,mafiya69/corefxlab,joshfree/corefxlab,shhsu/corefxlab,adamsitnik/corefxlab,dalbanhi/corefxlab,ericstj/corefxlab,hanblee/corefxlab,stephentoub/corefxlab,ahsonkhan/corefxlab,whoisj/corefxlab,ericstj/corefxlab,livarcocc/corefxlab,stephentoub/corefxlab,alexperovich/corefxlab,Vedin/corefxlab,Vedin/corefxlab,adamsitnik/corefxlab,ericstj/corefxlab,VSadov/corefxlab,weshaggard/corefxlab,ericstj/corefxlab,ravimeda/corefxlab,Vedin/corefxlab,whoisj/corefxlab,Vedin/corefxlab,hanblee/corefxlab,Vedin/corefxlab,benaadams/corefxlab,tarekgh/corefxlab,dotnet/corefxlab,t-roblo/corefxlab,VSadov/corefxlab,joshfree/corefxlab,stephentoub/corefxlab,nguerrera/corefxlab,Vedin/corefxlab,dotnet/corefxlab | demos/LowAllocationWebServer/SampleServer.cs | demos/LowAllocationWebServer/SampleServer.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;
using System.Diagnostics;
using System.IO;
using System.IO.Buffers;
using System.Net;
using System.Net.Http.Buffered;
using System.Text.Formatting;
class SampleRestServer : HttpServer
{
public readonly ApiRoutingTable<Api> Apis = new ApiRoutingTable<Api>();
public enum Api
{
HelloWorld = 0,
GetTime = 1,
}
public SampleRestServer(Log log, ushort port, byte address1, byte address2, byte address3, byte address4) : base(log, port, address1, address2, address3, address4)
{
Apis.Add(Api.HelloWorld, HttpMethod.Get, requestUri: "/");
Apis.Add(Api.GetTime, HttpMethod.Get, requestUri: "/time");
}
protected override HttpServerBuffer CreateResponse(HttpRequestLine requestLine, ByteSpan headerAndBody)
{
var api = Apis.Map(requestLine);
switch (api) {
case Api.HelloWorld:
return CreateResponseForHelloWorld();
case Api.GetTime:
return CreateResponseForGetTime();
default:
return CreateResponseFor404(requestLine, headerAndBody);
}
}
private HttpServerBuffer CreateResponseForHelloWorld()
{
var formatter = new BufferFormatter(1024, FormattingData.InvariantUtf8);
formatter.Append(@"HTTP/1.1 200 OK");
formatter.Append(HttpNewline);
formatter.Append("Content-Length: 15");
formatter.Append(HttpNewline);
formatter.Append("Content-Type: text/plain; charset=UTF-8");
formatter.Append(HttpNewline);
formatter.Append("Server: .NET Core Sample Server");
formatter.Append(HttpNewline);
formatter.Append("Date: ");
formatter.Append(DateTime.UtcNow, 'R');
formatter.Append(HttpNewline);
formatter.Append(HttpNewline);
formatter.Append("Hello, World");
return new HttpServerBuffer(formatter.Buffer, formatter.CommitedByteCount, BufferPool.Shared);
}
static HttpServerBuffer CreateResponseForGetTime()
{
var formatter = new BufferFormatter(1024, FormattingData.InvariantUtf8);
WriteCommonHeaders(formatter, @"HTTP/1.1 200 OK");
formatter.Append(HttpNewline);
formatter.Append(@"<html><head><title>Time</title></head><body>");
formatter.Append(DateTime.UtcNow, 'O');
formatter.Append(@"</body></html>");
return new HttpServerBuffer(formatter.Buffer, formatter.CommitedByteCount, BufferPool.Shared);
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Buffers;
using System.Net;
using System.Net.Http.Buffered;
using System.Text.Formatting;
class SampleRestServer : HttpServer
{
public readonly ApiRoutingTable<Api> Apis = new ApiRoutingTable<Api>();
public enum Api
{
GetTime = 1,
}
public SampleRestServer(Log log, ushort port, byte address1, byte address2, byte address3, byte address4) : base(log, port, address1, address2, address3, address4)
{
Apis.Add(Api.GetTime, HttpMethod.Get, requestUri: "/time");
}
protected override HttpServerBuffer CreateResponse(HttpRequestLine requestLine, ByteSpan headerAndBody)
{
var api = Apis.Map(requestLine);
switch (api) {
case Api.GetTime:
return CreateResponseForGetTime();
default:
return CreateResponseFor404(requestLine, headerAndBody);
}
}
static HttpServerBuffer CreateResponseForGetTime()
{
var formatter = new BufferFormatter(1024, FormattingData.InvariantUtf8);
WriteCommonHeaders(formatter, @"HTTP/1.1 200 OK");
formatter.Append(HttpNewline);
formatter.Append(@"<html><head><title>Time</title></head><body>");
formatter.Append(DateTime.UtcNow, 'O');
formatter.Append(@"</body></html>");
return new HttpServerBuffer(formatter.Buffer, formatter.CommitedByteCount, BufferPool.Shared);
}
}
| mit | C# |
e64a3abda68bed7eb7a3e606b670abcbfaa5a6ac | Fix ? | MonsieurTweek/ggj2017-babel-tower | Assets/Damien/WindEffect.cs | Assets/Damien/WindEffect.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WindEffect : EffectBlock
{
public Vector2 direction = Vector2.zero;
public float force = 0f;
public Animator feedbackAnimator;
protected override IEnumerator EffectSequence ()
{
GameBlock[] blocks = GameObject.FindObjectsOfType<GameBlock> ();
AttachBlocks (blocks);
yield return null;
feedbackAnimator.enabled = true;
feedbackAnimator.Play("FeedbackAnimation", -1, 0f);
Game.instance.ToggleVibration(Random.Range(0.5f, 1f), Random.Range(0.5f, 1f));
foreach (GameBlock block in blocks)
{
if (block.family == resistantFamily || block.isAttached == true)
continue;
Vector2 velocity = block.rigidBody2D.velocity;
velocity.x = 0f;
block.rigidBody2D.velocity = velocity;
block.rigidBody2D.AddForce(direction * force, ForceMode2D.Impulse);
}
yield return new WaitForSeconds(0.5f);
Game.instance.ToggleVibration();
DettachBlocks (blocks);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WindEffect : EffectBlock
{
public Vector2 direction = Vector2.zero;
public float force = 0f;
public Animator feedbackAnimator;
protected override IEnumerator EffectSequence ()
{
GameBlock[] blocks = GameObject.FindObjectsOfType<GameBlock> ();
AttachBlocks (blocks);
yield return null;
feedbackAnimator.enabled = true;
feedbackAnimator.Play("FeedbackAnimation", -1, 0f);
Game.instance.ToggleVibration(Random.Range(0.5f, 1f), Random.Range(0.5f, 1f));
foreach (GameBlock block in blocks)
{
if (block.family == resistantFamily || block.isAttached == true)
continue;
Vector2 velocity = block.rigidBody2D.velocity;
velocity.x = 0f;
block.rigidBody2D.velocity = velocity;
block.rigidBody2D.AddForce(direction * force, ForceMode2D.Impulse);
}
yield return new WaitForSeconds(0.5f);
feedbackAnimator.enabled = false;
Game.instance.ToggleVibration();
DettachBlocks (blocks);
}
}
| mit | C# |
468d188edc67510294164db1554b877e7852623f | resolve #609 | rollbar/Rollbar.NET | Samples/RollbarSamplesSettings.cs | Samples/RollbarSamplesSettings.cs | #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace Samples
{
public static class RollbarSamplesSettings
{
public const string AccessToken = "efdc4b85d66045f293a7f9e99c732f61";
public const string Environment = "Rollbar.Net-Samples";
public const string DeploymentsWriteAccessToken = "efdc4b85d66045f293a7f9e99c732f61";
public const string DeploymentsReadAccessToken = "595cbf76b05b45f2b3ef661a2e0078d4";
}
}
| #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace Samples
{
public static class RollbarSamplesSettings
{
public const string AccessToken = "17965fa5041749b6bf7095a190001ded";
public const string Environment = "RollbarNetSamples";
public const string DeploymentsReadAccessToken = "8c2982e875544037b51870d558f51ed3";
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.