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
6d8a9b49ab990c3c6298d5c5c761429725d1f5dd
Comment out some Windows-only code on Linux with #if (20211202)
StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork
src/BloomExe/MiscUI/BloomFolderChooser.cs
src/BloomExe/MiscUI/BloomFolderChooser.cs
using System.Windows.Forms; #if !__MonoCS__ using System.Linq; using Microsoft.WindowsAPICodePack.Dialogs; #endif namespace Bloom.MiscUI { /// <summary> /// Static class for launching a folder chooser dialog. This launches the modern Windows /// file chooser dialog as a folder chooser on Windows. Using DialogAdapters.FolderBrowser /// would launch an old fashioned dialog chooser on Windows. /// Linux sticks with the tried and true means of selecting folders through the GUI. /// </summary> public static class BloomFolderChooser { public static string ChooseFolder(string initialFolderPath) { if (SIL.PlatformUtilities.Platform.IsWindows) { // Split into a separate method to prevent the Mono runtime from trying to // reference Windows-only assemblies on Linux. return SelectFolderOnWindows(initialFolderPath); } else { var dialog = new DialogAdapters.FolderBrowserDialogAdapter(); dialog.SelectedPath = initialFolderPath; if (dialog.ShowDialog() == DialogResult.OK) return dialog.SelectedPath; } return null; } private static string SelectFolderOnWindows(string initialFolderPath) { #if !__MonoCS__ // Note, this is Windows only. CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = initialFolderPath, IsFolderPicker = true }; // If we can find Bloom's main window, bring the dialog up on that screen. var rootForm = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f is Shell); var result = rootForm == null ? dialog.ShowDialog() : dialog.ShowDialog(rootForm.Handle); if (result == CommonFileDialogResult.Ok) return dialog.FileName; #endif return null; } } }
using System.Linq; using System.Windows.Forms; using Microsoft.WindowsAPICodePack.Dialogs; namespace Bloom.MiscUI { /// <summary> /// Static class for launching a folder chooser dialog. This launches the modern Windows /// file chooser dialog as a folder chooser on Windows. Using DialogAdapters.FolderBrowser /// would launch an old fashioned dialog chooser on Windows. /// Linux sticks with the tried and true means of selecting folders through the GUI. /// </summary> public static class BloomFolderChooser { public static string ChooseFolder(string initialFolderPath) { if (SIL.PlatformUtilities.Platform.IsWindows) { // Split into a separate method to prevent the Mono runtime from trying to // reference Windows-only assemblies on Linux. return SelectFolderOnWindows(initialFolderPath); } else { var dialog = new DialogAdapters.FolderBrowserDialogAdapter(); dialog.SelectedPath = initialFolderPath; if (dialog.ShowDialog() == DialogResult.OK) return dialog.SelectedPath; } return null; } private static string SelectFolderOnWindows(string initialFolderPath) { // Note, this is Windows only. CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = initialFolderPath, IsFolderPicker = true }; // If we can find Bloom's main window, bring the dialog up on that screen. var rootForm = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f is Shell); var result = rootForm == null ? dialog.ShowDialog() : dialog.ShowDialog(rootForm.Handle); if (result == CommonFileDialogResult.Ok) return dialog.FileName; return null; } } }
mit
C#
7b6787534836ec522547885f8f00f239df022f70
Update FrancisSetash.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/FrancisSetash.cs
src/Firehose.Web/Authors/FrancisSetash.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class FrancisSetash : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Francis"; public string LastName => "Setash"; public string ShortBioOrTagLine => "Infrastructure and DevOps Engineer. Lots of working with Chef, and PowerShell DSC"; public string StateOrRegion => "Arnold, MD"; public string EmailAddress => "francis@i-py.com"; public string TwitterHandle => ""; public string GravatarHash => ""; public Uri WebSite => new Uri("https://i-py.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://i-py.com/feed.xml"); } } public string GitHubHandle => "walked"; public bool Filter(SyndicationItem item) { return item.Title.Text.ToLowerInvariant().Contains("powershell"); } public GeoPosition Position => new GeoPosition(39.0589050,-76.49100906); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class FrancisSetash : IAmACommunityMember { public string FirstName => "Francis"; public string LastName => "Setash"; public string ShortBioOrTagLine => "i-py.com"; public string StateOrRegion => "Arnold, MD"; public string EmailAddress => "Francis@i-py.com"; public string TwitterHandle => ""; public string GravatarHash => ""; public string GitHubHandle => "walked"; public GeoPosition Position => new GeoPosition(39.0589050,-76.4910090); public Uri WebSite => new Uri("https://i-py.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://i-py.com/feed.xml"); } } } public bool Filter(SyndicationItem item) { return item.Title.Text.ToLowerInvariant().Contains("powershell"); } }
mit
C#
e33098d258e9deb4c5d873e8239045f8ebfc526d
fix reading uri value
wikibus/JsonLD.Entities
src/JsonLD.Entities/StringUriConverter.cs
src/JsonLD.Entities/StringUriConverter.cs
using System; using Newtonsoft.Json; using NullGuard; namespace JsonLD.Entities { /// <summary> /// Converter, which ensures that Uris are serialized as strings /// </summary> public class StringUriConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the Uri. /// </summary> public override void WriteJson(JsonWriter writer, [AllowNull] object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } /// <summary> /// Reads the JSON representation of the Uri. /// </summary> [return: AllowNull] public override object ReadJson(JsonReader reader, Type objectType, [AllowNull] object existingValue, JsonSerializer serializer) { return new Uri(reader.Value.ToString(), UriKind.RelativeOrAbsolute); } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> public override bool CanConvert(Type objectType) { return objectType == typeof(Uri); } } }
using System; using Newtonsoft.Json; namespace JsonLD.Entities { /// <summary> /// Converter, which ensures that Uris are serialized as strings /// </summary> public class StringUriConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the Uri. /// </summary> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } /// <summary> /// Reads the JSON representation of the Uri. /// </summary> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return new Uri(reader.ReadAsString(), UriKind.RelativeOrAbsolute); } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> public override bool CanConvert(Type objectType) { return objectType == typeof(Uri); } } }
mit
C#
2cd0cb9805ad2c3be7114cad16d447af17483471
remove useless achievement debug log
solfen/Rogue_Cadet
Assets/Scripts/Achievements/BaseAchievement.cs
Assets/Scripts/Achievements/BaseAchievement.cs
using UnityEngine; using System.Collections; public abstract class BaseAchievement : MonoBehaviour { [SerializeField] private int achievementIndex; [SerializeField] private int shipToUnlock = -1; // Use this for initialization protected virtual void Start () { EventDispatcher.DispatchEvent(Events.ACHIEVMENT_CREATED, achievementIndex); if(GlobalData.instance.saveData.achievementsUnlocked.Contains(achievementIndex)) { Destroy(this); return; } } protected virtual void Unlock() { SaveData data = FileSaveLoad.Load(); data.achievementsUnlocked.Add(achievementIndex); if (shipToUnlock != -1) data.shipsInfo[shipToUnlock].isUnlocked = true; FileSaveLoad.Save(data); EventDispatcher.DispatchEvent(Events.ACHIEVMENT_UNLOCKED, achievementIndex); Destroy(this); } }
using UnityEngine; using System.Collections; public abstract class BaseAchievement : MonoBehaviour { [SerializeField] private int achievementIndex; [SerializeField] private int shipToUnlock = -1; // Use this for initialization protected virtual void Start () { EventDispatcher.DispatchEvent(Events.ACHIEVMENT_CREATED, achievementIndex); if(GlobalData.instance.saveData.achievementsUnlocked.Contains(achievementIndex)) { Destroy(this); return; } } protected virtual void Unlock() { SaveData data = FileSaveLoad.Load(); data.achievementsUnlocked.Add(achievementIndex); if (shipToUnlock != -1) data.shipsInfo[shipToUnlock].isUnlocked = true; FileSaveLoad.Save(data); EventDispatcher.DispatchEvent(Events.ACHIEVMENT_UNLOCKED, achievementIndex); Debug.Log("ACHIEVEMENT: " + achievementIndex + " UNLOCKED!"); Destroy(this); } }
mit
C#
ca845648e734219daab33b835766a070e8196610
Fix negative numbers
robertmuehsig/ExpensiveMeeting,Code-Inside/ExpensiveMeeting
ExpensiveMeeting.WinApp/Views/MainPage.xaml.cs
ExpensiveMeeting.WinApp/Views/MainPage.xaml.cs
using System; using ExpensiveMeeting.WinApp.ViewModels; using Windows.UI.Xaml.Controls; namespace ExpensiveMeeting.WinApp.Views { public sealed partial class MainPage : Page { public MainPage() { InitializeComponent(); NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Disabled; } // strongly-typed view models enable x:bind public MainPageViewModel ViewModel => this.DataContext as MainPageViewModel; private void NumberOfPeopleTextBox_OnTextChanged(object sender, TextChangedEventArgs e) { ValidateInputs(); } private void ValidateInputs() { bool averageSaleryIsInvalid = false; bool numberOfPeopleIsInvalid = false; double salery; if (!double.TryParse(AverageSalery.Text, out salery)) { averageSaleryIsInvalid = true; } else if (salery < 0) { averageSaleryIsInvalid = true; } int numberOfPeople; if (!int.TryParse(NumberOfPeople.Text, out numberOfPeople)) { numberOfPeopleIsInvalid = true; } else if (numberOfPeople < 0) { numberOfPeopleIsInvalid = true; } if (numberOfPeopleIsInvalid || averageSaleryIsInvalid) { ViewModel.HasValidationErrors = true; } else { ViewModel.HasValidationErrors = false; } } private void SaleryTextBox_OnTextChanged(object sender, TextChangedEventArgs e) { ValidateInputs(); } } }
using System; using ExpensiveMeeting.WinApp.ViewModels; using Windows.UI.Xaml.Controls; namespace ExpensiveMeeting.WinApp.Views { public sealed partial class MainPage : Page { public MainPage() { InitializeComponent(); NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Disabled; } // strongly-typed view models enable x:bind public MainPageViewModel ViewModel => this.DataContext as MainPageViewModel; private void NumberOfPeopleTextBox_OnTextChanged(object sender, TextChangedEventArgs e) { ValidateInputs(); } private void ValidateInputs() { bool averageSaleryIsInvalid = false; bool numberOfPeopleIsInvalid = false; double salery; if (!double.TryParse(AverageSalery.Text, out salery)) { averageSaleryIsInvalid = true; } int numberOfPeople; if (!int.TryParse(NumberOfPeople.Text, out numberOfPeople)) { numberOfPeopleIsInvalid = true; } if (numberOfPeopleIsInvalid || averageSaleryIsInvalid) { ViewModel.HasValidationErrors = true; } else { ViewModel.HasValidationErrors = false; } } private void SaleryTextBox_OnTextChanged(object sender, TextChangedEventArgs e) { ValidateInputs(); } } }
mit
C#
6b6a90b63fc9e537c50dd47396ba79eb5f37d117
Throw unexpected value
heejaechang/roslyn,gafter/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,mavasani/roslyn,brettfo/roslyn,nguerrera/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,genlu/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,abock/roslyn,brettfo/roslyn,gafter/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,abock/roslyn,brettfo/roslyn,weltkante/roslyn,sharwell/roslyn,jmarolf/roslyn,physhi/roslyn,sharwell/roslyn,agocke/roslyn,nguerrera/roslyn,AmadeusW/roslyn,davkean/roslyn,panopticoncentral/roslyn,agocke/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,stephentoub/roslyn,abock/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,KevinRansom/roslyn,heejaechang/roslyn,jmarolf/roslyn,dotnet/roslyn,davkean/roslyn,KevinRansom/roslyn,physhi/roslyn,bartdesmet/roslyn,stephentoub/roslyn,nguerrera/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,genlu/roslyn,reaction1989/roslyn,wvdd007/roslyn,physhi/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,agocke/roslyn,stephentoub/roslyn,eriawan/roslyn,dotnet/roslyn,reaction1989/roslyn,tmat/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,tmat/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,genlu/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,mavasani/roslyn,eriawan/roslyn,aelij/roslyn,jmarolf/roslyn,gafter/roslyn,aelij/roslyn,diryboy/roslyn
src/Workspaces/Core/Portable/Extensions/NotificationOptionExtensions.cs
src/Workspaces/Core/Portable/Extensions/NotificationOptionExtensions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class NotificationOptionExtensions { public static string ToEditorConfigString(this NotificationOption notificationOption) { return notificationOption.Severity switch { ReportDiagnostic.Suppress => EditorConfigSeverityStrings.None, ReportDiagnostic.Hidden => EditorConfigSeverityStrings.Silent, ReportDiagnostic.Info => EditorConfigSeverityStrings.Suggestion, ReportDiagnostic.Warn => EditorConfigSeverityStrings.Warning, ReportDiagnostic.Error => EditorConfigSeverityStrings.Error, _ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity) }; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class NotificationOptionExtensions { public static string ToEditorConfigString(this NotificationOption notificationOption) { return notificationOption.Severity switch { ReportDiagnostic.Suppress => EditorConfigSeverityStrings.None, ReportDiagnostic.Hidden => EditorConfigSeverityStrings.Silent, ReportDiagnostic.Info => EditorConfigSeverityStrings.Suggestion, ReportDiagnostic.Warn => EditorConfigSeverityStrings.Warning, ReportDiagnostic.Error => EditorConfigSeverityStrings.Error, _ => throw ExceptionUtilities.Unreachable }; } } }
mit
C#
16f8b4ec8d2113f0dc8513c74b196476e19603e0
Fix the build warning
NickCraver/StackExchange.Exceptional,NickCraver/StackExchange.Exceptional
samples/Samples.MVC4/Controllers/TestController.cs
samples/Samples.MVC4/Controllers/TestController.cs
using System; using System.Transactions; using System.Web.Mvc; namespace Samples.MVC4.Controllers { public class TestController : Controller { public ActionResult Form() { Response.SetCookie(new System.Web.HttpCookie("authToken", "test value")); Response.SetCookie(new System.Web.HttpCookie("notAnAuthToken", "Turnip.")); ViewBag.Message = "This is a sample with a form which has filtered logging (e.g. password is ommitted)."; return View(); } public ActionResult FormSubmit(FormCollection fc) { throw new Exception("Check out the log to see that this exception didn't log the password."); } public ActionResult TransactionScope() { using (var t = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {IsolationLevel = IsolationLevel.ReadCommitted})) { try { throw new Exception("Transaction killing exception of doom!"); //t.Complete(); } catch (Exception e) { MvcApplication.LogException(e); // this still gets logged, because Exceptional ignores transaction scopes } } return RedirectToAction("Exceptions", "Home"); } public ActionResult Throw() { var ex = new Exception("This is an exception throw from the Samples project! - Check out the log to see this exception."); // here's how your catch/throw might can add more info, for example SQL is special cased and shown in the UI: ex.Data["SQL"] = "Select * From FUBAR -- This is a SQL command!"; ex.Data["Redis-Server"] = "REDIS01"; ex.Data["Not-Included"] = "This key is skipped, because it's not in the web.config pattern"; throw ex; } } }
using System; using System.Transactions; using System.Web.Mvc; namespace Samples.MVC4.Controllers { public class TestController : Controller { public ActionResult Form() { Response.SetCookie(new System.Web.HttpCookie("authToken", "test value")); Response.SetCookie(new System.Web.HttpCookie("notAnAuthToken", "Turnip.")); ViewBag.Message = "This is a sample with a form which has filtered logging (e.g. password is ommitted)."; return View(); } public ActionResult FormSubmit(FormCollection fc) { throw new Exception("Check out the log to see that this exception didn't log the password."); } public ActionResult TransactionScope() { using (var t = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {IsolationLevel = IsolationLevel.ReadCommitted})) { try { throw new Exception("Transaction killing exception of doom!"); t.Complete(); } catch (Exception e) { MvcApplication.LogException(e); // this still gets logged, because Exceptional ignores transaction scopes } } return RedirectToAction("Exceptions", "Home"); } public ActionResult Throw() { var ex = new Exception("This is an exception throw from the Samples project! - Check out the log to see this exception."); // here's how your catch/throw might can add more info, for example SQL is special cased and shown in the UI: ex.Data["SQL"] = "Select * From FUBAR -- This is a SQL command!"; ex.Data["Redis-Server"] = "REDIS01"; ex.Data["Not-Included"] = "This key is skipped, because it's not in the web.config pattern"; throw ex; } } }
apache-2.0
C#
d847af7a63eaae8840ae8f622fff407a64da5b05
Enable the content type to be editable when there is no result appearing based on the chosen keywords
sdl/dxa-modules,sdl/dxa-modules,sdl/dxa-modules,sdl/dxa-modules,sdl/dxa-modules
webapp-net/TridionDocsMashup/Areas/TridionDocsMashup/Views/TridionDocsMashup/StaticWidget.cshtml
webapp-net/TridionDocsMashup/Areas/TridionDocsMashup/Views/TridionDocsMashup/StaticWidget.cshtml
@model StaticWidget <div class="rich-text @Model.HtmlClasses" @Html.DxaEntityMarkup()> @if (Model.TridionDocsItems != null && Model.TridionDocsItems.Any()) { foreach (TridionDocsItem item in Model.TridionDocsItems) { if (Model.DisplayContentAs.ToLower() == "embedded content") { <div class="content"> <div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)> @Html.Raw(@item.Body) </div> </div> <br /> } else { <div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)> <a href="@item.Link">@item.Title</a> </div> <br /> } } } else { <span>&nbsp;</span> } </div>
@model StaticWidget <div class="rich-text @Model.HtmlClasses" @Html.DxaEntityMarkup()> @if (Model.TridionDocsItems != null) { foreach (TridionDocsItem item in Model.TridionDocsItems) { if (Model.DisplayContentAs.ToLower() == "embedded content") { <div class="content"> <div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)> @Html.Raw(@item.Body) </div> </div> <br /> } else { <div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)> <a href="@item.Link">@item.Title</a> </div> <br /> } } } </div>
apache-2.0
C#
0b50b46c2cddb53b42502bee1afb19de2208f185
Put in a border color for the color display
mmoening/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl
MatterControlLib/PartPreviewWindow/ItemColorButton.cs
MatterControlLib/PartPreviewWindow/ItemColorButton.cs
/* Copyright (c) 2018, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Linq; using MatterHackers.Agg; using MatterHackers.Agg.Image; using MatterHackers.Agg.UI; using MatterHackers.DataConverters3D; using MatterHackers.Localizations; namespace MatterHackers.MatterControl.PartPreviewWindow { public class ItemColorButton : PopupButton { private ColorButton colorButton; public ItemColorButton(InteractiveScene scene, ThemeConfig theme) { this.ToolTipText = "Color".Localize(); this.DynamicPopupContent = () => { return new ColorSwatchSelector(scene, theme, buttonSize: 16, buttonSpacing: new BorderDouble(1, 1, 0, 0), colorNotifier: (newColor) => colorButton.BackgroundColor = newColor) { Padding = theme.DefaultContainerPadding, BackgroundColor = this.HoverColor }; }; var scaledButtonSize = 14 * GuiWidget.DeviceScale; colorButton = new ColorButton(scene.SelectedItem?.Color ?? theme.SlightShade) { Width = scaledButtonSize, Height = scaledButtonSize, HAnchor = HAnchor.Center, VAnchor = VAnchor.Center, DisabledColor = theme.MinimalShade, Border = new BorderDouble(1), BorderColor = theme.GetBorderColor(200) }; this.AddChild(colorButton); } public override void OnLoad(EventArgs args) { var firstBackgroundColor = this.Parents<GuiWidget>().Where(p => p.BackgroundColor.Alpha0To1 == 1).FirstOrDefault()?.BackgroundColor; if (firstBackgroundColor != null) { // Resolve alpha this.HoverColor = new BlenderRGBA().Blend(firstBackgroundColor.Value, this.HoverColor); } base.OnLoad(args); } public Color Color { get => colorButton.BackgroundColor; set => colorButton.BackgroundColor = value; } } }
/* Copyright (c) 2018, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Linq; using MatterHackers.Agg; using MatterHackers.Agg.Image; using MatterHackers.Agg.UI; using MatterHackers.DataConverters3D; using MatterHackers.Localizations; namespace MatterHackers.MatterControl.PartPreviewWindow { public class ItemColorButton : PopupButton { private ColorButton colorButton; public ItemColorButton(InteractiveScene scene, ThemeConfig theme) { this.ToolTipText = "Color".Localize(); this.DynamicPopupContent = () => { return new ColorSwatchSelector(scene, theme, buttonSize: 16, buttonSpacing: new BorderDouble(1, 1, 0, 0), colorNotifier: (newColor) => colorButton.BackgroundColor = newColor) { Padding = theme.DefaultContainerPadding, BackgroundColor = this.HoverColor }; }; var scaledButtonSize = 14 * GuiWidget.DeviceScale; colorButton = new ColorButton(scene.SelectedItem?.Color ?? theme.SlightShade) { Width = scaledButtonSize, Height = scaledButtonSize, HAnchor = HAnchor.Center, VAnchor = VAnchor.Center, DisabledColor = theme.MinimalShade }; this.AddChild(colorButton); } public override void OnLoad(EventArgs args) { var firstBackgroundColor = this.Parents<GuiWidget>().Where(p => p.BackgroundColor.Alpha0To1 == 1).FirstOrDefault()?.BackgroundColor; if (firstBackgroundColor != null) { // Resolve alpha this.HoverColor = new BlenderRGBA().Blend(firstBackgroundColor.Value, this.HoverColor); } base.OnLoad(args); } public Color Color { get => colorButton.BackgroundColor; set => colorButton.BackgroundColor = value; } } }
bsd-2-clause
C#
028c72c4ff13870643f10724ff552ff8d2d7b6a4
Add call to Configure() and clean up comments.
andrerav/NHibernate.Spatial.MySql.Demo,andrerav/NHibernate.Spatial.MySql.Demo,andrerav/NHibernate.Spatial.MySql.Demo
DemoQueryUtil/Program.cs
DemoQueryUtil/Program.cs
using DemoDataAccess; using DemoDataAccess.Entity; using NHibernate.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoQueryUtil { class Program { static void Main(string[] args) { FluentConfiguration.Configure(); // Works, but Area is always null var county = SessionManager.Session.Query<County>().First(); // Crashes with the error "No persister for: GeoAPI.Geometries.IGeometry" var municipalities = SessionManager.Session.Query<Municipality>() .Where(m => m.Area.Within(county.Area)).ToList(); } } }
using DemoDataAccess; using DemoDataAccess.Entity; using NHibernate.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoQueryUtil { class Program { static void Main(string[] args) { // Works, but Area is null var county = SessionManager.Session.Query<County>().First(); // Crashes var municipalities = SessionManager.Session.Query<Municipality>() .Where(m => m.Area.Within(county.Area)).ToList(); } } }
mit
C#
29d83e3579d1348004123a111ff2ab47a9156211
Tweak fatal exception handler
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
stdlib/corlib/Environment.cs
stdlib/corlib/Environment.cs
using System.Runtime.InteropServices; using System.Primitives.IO; namespace System { /// <summary> /// Defines logic that allows an application to interact with its environment. /// </summary> public static unsafe class Environment { /// <summary> /// Initializes the environment. /// </summary> /// <param name="argc"> /// The number of command-line arguments. /// </param> /// <param name="argv"> /// An array of command-line arguments, each represented as a C-style string. /// </param> /// <returns>An array of strings that can be passed to an entry point.</returns> /// <remarks> /// Only code generated by the compiler should touch this method; it is inaccessible to user code. /// </remarks> [#builtin_hidden] public static string[] Initialize(int argc, byte* * argv) { int newArgc = Math.Max(0, argc - 1); var stringArray = new string[newArgc]; for (int i = 1; i < argc; i++) { stringArray[i - 1] = String.FromCString(argv[i]); } return stringArray; } /// <summary> /// Handles a fatal exception. /// </summary> /// <param name="ex">The exception to handle.</param> [#builtin_hidden] public static void HandleFatalException(Exception ex) { // We can't use the Console class here (because it is // defined in a library that depends on this one). // Instead, we'll use IO primitives, which have the // added advantage of being leaner. var errorMessage = Marshal.StringToHGlobalAnsi( "error: a fatal exception was thrown." + NewLine + "Exception message: " + ex.Message + NewLine); IOPrimitives.WriteCStringToFile( (byte*)errorMessage.ToPointer(), IOPrimitives.StandardErrorFile); Marshal.FreeHGlobal(errorMessage); } /// <summary> /// Gets the newline string. /// </summary> public static string NewLine => "\n"; } }
using System.Runtime.InteropServices; using System.Primitives.IO; namespace System { /// <summary> /// Defines logic that allows an application to interact with its environment. /// </summary> public static unsafe class Environment { /// <summary> /// Initializes the environment. /// </summary> /// <param name="argc"> /// The number of command-line arguments. /// </param> /// <param name="argv"> /// An array of command-line arguments, each represented as a C-style string. /// </param> /// <returns>An array of strings that can be passed to an entry point.</returns> /// <remarks> /// Only code generated by the compiler should touch this method; it is inaccessible to user code. /// </remarks> [#builtin_hidden] public static string[] Initialize(int argc, byte* * argv) { int newArgc = Math.Max(0, argc - 1); var stringArray = new string[newArgc]; for (int i = 1; i < argc; i++) { stringArray[i - 1] = String.FromCString(argv[i]); } return stringArray; } /// <summary> /// Handles a fatal exception. /// </summary> /// <param name="ex">The exception to handle.</param> [#builtin_hidden] public static void HandleFatalException(Exception ex) { // We can't use the Console class here (because it is // defined in a library that depends on this one). // Instead, we'll use IO primitives, which have the // added advantage of being leaner. var errorMessage = Marshal.StringToHGlobalAnsi( "A fatal exception was thrown.\n" + ex.Message); IOPrimitives.WriteCStringToFile( (byte*)errorMessage.ToPointer(), IOPrimitives.StandardErrorFile); Marshal.FreeHGlobal(errorMessage); } /// <summary> /// Gets the newline string. /// </summary> public static string NewLine => "\n"; } }
mit
C#
58f8f9e25c733da3a89932ffefdb8de513af8635
Make TestLogger thread-safe
sebastienros/yessql
test/YesSql.Tests/TestLogger.cs
test/YesSql.Tests/TestLogger.cs
using Microsoft.Extensions.Logging; using System; using System.Text; namespace YesSql.Tests { public class TestLogger : ILogger { private object _lockObj = new object(); private readonly StringBuilder _builder; public TestLogger(StringBuilder builder = null) { _builder = builder ?? new StringBuilder(); } public IDisposable BeginScope<TState>(TState state) { return new FakeScope(); } public bool IsEnabled(LogLevel logLevel) { return IsLevelEnabled(logLevel); } public bool IsLevelEnabled(LogLevel logLevel) { return true; } public void Log(LogLevel logLevel, string log) { lock (_lockObj) { _builder.AppendLine(logLevel.ToString().ToUpper() + ": " + log); } } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { Log(logLevel, formatter(state, exception)); } public override string ToString() { lock (_lockObj) { return _builder.ToString(); } } } public class FakeScope : IDisposable { public void Dispose() { } } }
using Microsoft.Extensions.Logging; using System; using System.Text; namespace YesSql.Tests { public class TestLogger : ILogger { private readonly StringBuilder _builder; public TestLogger(StringBuilder builder = null) { _builder = builder ?? new StringBuilder(); } public IDisposable BeginScope<TState>(TState state) { return new FakeScope(); } public bool IsEnabled(LogLevel logLevel) { return IsLevelEnabled(logLevel); } public bool IsLevelEnabled(LogLevel logLevel) { return true; } public void Log(LogLevel logLevel, string log) { _builder.AppendLine(logLevel.ToString().ToUpper() + ": " + log); } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { Log(logLevel, formatter(state, exception)); } public override string ToString() { return _builder.ToString(); } } public class FakeScope : IDisposable { public void Dispose() { } } }
mit
C#
6c9f0c23726af85e611eeefda82703f8503ef005
use development connection
corker/estuite
Estuite/Estuite.Example/ProgramConfiguration.cs
Estuite/Estuite.Example/ProgramConfiguration.cs
using Estuite.AzureEventStore; using Estuite.Example.Configuration; namespace Estuite.Example { public class ProgramConfiguration : IEventStoreConfiguration, ICloudStorageAccountConfiguration { public string ConnectionString => "UseDevelopmentStorage=true"; public string StreamTableName => "esStreams"; public string EventTableName => "esEvents"; } }
using Estuite.AzureEventStore; using Estuite.Example.Configuration; namespace Estuite.Example { public class ProgramConfiguration : IEventStoreConfiguration, ICloudStorageAccountConfiguration { //public string ConnectionString => "UseDevelopmentStorage=true"; public string ConnectionString => "DefaultEndpointsProtocol=https;AccountName=estuite;AccountKey=WqombaM2u/Tx41EJnT1LDuholL7Y2JbB2DoYzrdlUVYJSaX1ilLt+9r2I06YOtw+GdLqNuBsNdB+873kdKFItg==;TableEndpoint=https://estuite.table.core.windows.net/;"; public string StreamTableName => "esStreams"; public string EventTableName => "esEvents"; } }
mit
C#
c30cf2ac2d763176be251bda1625d6d775cf2cb0
fix crash when datatable serialization has incorrect values
underwater/qdms,underwater/qdms,qusma/qdms,qusma/qdms
QDMSApp/ExtensionMethods/DataGridExtensions.cs
QDMSApp/ExtensionMethods/DataGridExtensions.cs
// ----------------------------------------------------------------------- // <copyright file="DataGridSettingsSerializer.cs" company=""> // Copyright 2014 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Controls; using System.Xml.Serialization; namespace QDMSApp { public static class DataGridExtensions { public static void SerializeLayout(this DataGrid grid, StreamWriter sw) { var allSettings = grid.Columns.Select(c => new ColumnOptions { DisplayIndex = c.DisplayIndex, Width = c.ActualWidth, SortDirection = c.SortDirection }).ToList(); var serializer = new XmlSerializer(typeof(List<ColumnOptions>)); serializer.Serialize(sw, allSettings); } public static void DeserializeLayout(this DataGrid grid, string settings) { List<ColumnOptions> allSettings; var serializer = new XmlSerializer(typeof(List<ColumnOptions>)); using (var sw = new StringReader(settings)) { allSettings = (List<ColumnOptions>)serializer.Deserialize(sw); } for (int i = 0; i < allSettings.Count; i++) { ColumnOptions co = allSettings[i]; grid.Columns[i].Width = co.Width; grid.Columns[i].SortDirection = co.SortDirection; if (co.DisplayIndex >= 0) grid.Columns[i].DisplayIndex = co.DisplayIndex; } } } }
// ----------------------------------------------------------------------- // <copyright file="DataGridSettingsSerializer.cs" company=""> // Copyright 2014 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Controls; using System.Xml.Serialization; namespace QDMSApp { public static class DataGridExtensions { public static void SerializeLayout(this DataGrid grid, StreamWriter sw) { var allSettings = grid.Columns.Select(c => new ColumnOptions { DisplayIndex = c.DisplayIndex, Width = c.ActualWidth, SortDirection = c.SortDirection }).ToList(); var serializer = new XmlSerializer(typeof(List<ColumnOptions>)); serializer.Serialize(sw, allSettings); } public static void DeserializeLayout(this DataGrid grid, string settings) { List<ColumnOptions> allSettings; var serializer = new XmlSerializer(typeof(List<ColumnOptions>)); using (var sw = new StringReader(settings)) { allSettings = (List<ColumnOptions>)serializer.Deserialize(sw); } for (int i = 0; i < allSettings.Count; i++) { ColumnOptions co = allSettings[i]; grid.Columns[i].Width = co.Width; grid.Columns[i].SortDirection = co.SortDirection; grid.Columns[i].DisplayIndex = co.DisplayIndex; } } } }
bsd-3-clause
C#
f609be3e810b67287faf4e8116dfd3b36938ce71
Sort the usings
martijn00/MvvmCross-Plugins
Json/MvvmCross.Plugins.Json/MvxJsonConverter.cs
Json/MvvmCross.Plugins.Json/MvxJsonConverter.cs
// MvxJsonConverter.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using System; using System.Collections.Generic; using System.IO; using MvvmCross.Platform.Platform; using Newtonsoft.Json; namespace MvvmCross.Plugins.Json { public class MvxJsonConverter : IMvxJsonConverter { private static readonly JsonSerializerSettings Settings; static MvxJsonConverter() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize, Converters = new List<JsonConverter> { new MvxEnumJsonConverter() }, DateFormatHandling = DateFormatHandling.IsoDateFormat }; } public T DeserializeObject<T>(string inputText) { return JsonConvert.DeserializeObject<T>(inputText, Settings); } public string SerializeObject(object toSerialise) { return JsonConvert.SerializeObject(toSerialise, Formatting.None, Settings); } public object DeserializeObject(Type type, string inputText) { return JsonConvert.DeserializeObject(inputText, type, Settings); } public T DeserializeObject<T>(Stream stream) { var serializer = JsonSerializer.Create(Settings); using (var sr = new StreamReader(stream)) using (var jsonTextReader = new JsonTextReader(sr)) { return serializer.Deserialize<T>(jsonTextReader); } } } }
// MvxJsonConverter.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using MvvmCross.Platform.Platform; namespace MvvmCross.Plugins.Json { public class MvxJsonConverter : IMvxJsonConverter { private static readonly JsonSerializerSettings Settings; static MvxJsonConverter() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize, Converters = new List<JsonConverter> { new MvxEnumJsonConverter() }, DateFormatHandling = DateFormatHandling.IsoDateFormat }; } public T DeserializeObject<T>(string inputText) { return JsonConvert.DeserializeObject<T>(inputText, Settings); } public string SerializeObject(object toSerialise) { return JsonConvert.SerializeObject(toSerialise, Formatting.None, Settings); } public object DeserializeObject(Type type, string inputText) { return JsonConvert.DeserializeObject(inputText, type, Settings); } public T DeserializeObject<T>(Stream stream) { var serializer = JsonSerializer.Create(Settings); using (var sr = new StreamReader(stream)) using (var jsonTextReader = new JsonTextReader(sr)) { return serializer.Deserialize<T>(jsonTextReader); } } } }
mit
C#
62d31839d45a28b18418dfa3426c226ccdfa6b26
Refactor CompareExpression to use IComparable
ajlopez/Mass
Src/Mass.Core/Expressions/CompareExpression.cs
Src/Mass.Core/Expressions/CompareExpression.cs
namespace Mass.Core.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class CompareExpression : BinaryExpression { private static IDictionary<CompareOperator, Func<object, object, object>> functions = new Dictionary<CompareOperator, Func<object, object, object>>(); private CompareOperator @operator; static CompareExpression() { functions[CompareOperator.Equal] = CompareEqual; functions[CompareOperator.NotEqual] = CompareNotEqual; functions[CompareOperator.Less] = (left, right) => Compare(left, right) < 0; functions[CompareOperator.Greater] = (left, right) => Compare(left, right) > 0; functions[CompareOperator.LessOrEqual] = (left, right) => Compare(left, right) <= 0; functions[CompareOperator.GreaterOrEqual] = (left, right) => Compare(left, right) >= 0; } public CompareExpression(IExpression left, IExpression right, CompareOperator @operator) : base(left, right) { this.@operator = @operator; } public override object Apply(object leftvalue, object rightvalue) { return functions[this.@operator](leftvalue, rightvalue); } public override bool Equals(object obj) { if (!base.Equals(obj)) return false; return this.@operator == ((CompareExpression)obj).@operator; } public override int GetHashCode() { return base.GetHashCode() + (int)this.@operator; } private static int Compare(object left, object right) { var cleft = (IComparable)left; return cleft.CompareTo(right); } private static object CompareEqual(object left, object right) { if (left == null) return right == null; return left.Equals(right); } private static object CompareNotEqual(object left, object right) { if (left == null) return right != null; return !left.Equals(right); } } }
namespace Mass.Core.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class CompareExpression : BinaryExpression { private static IDictionary<CompareOperator, Func<object, object, object>> functions = new Dictionary<CompareOperator, Func<object, object, object>>(); private CompareOperator @operator; static CompareExpression() { functions[CompareOperator.Equal] = CompareEqual; functions[CompareOperator.NotEqual] = CompareNotEqual; functions[CompareOperator.Less] = (left, right) => Operators.LessObject(left, right); functions[CompareOperator.Greater] = (left, right) => Operators.GreaterObject(left, right); functions[CompareOperator.LessOrEqual] = (left, right) => Operators.LessEqualObject(left, right); functions[CompareOperator.GreaterOrEqual] = (left, right) => Operators.GreaterEqualObject(left, right); } public CompareExpression(IExpression left, IExpression right, CompareOperator @operator) : base(left, right) { this.@operator = @operator; } public override object Apply(object leftvalue, object rightvalue) { return functions[this.@operator](leftvalue, rightvalue); } public override bool Equals(object obj) { if (!base.Equals(obj)) return false; return this.@operator == ((CompareExpression)obj).@operator; } public override int GetHashCode() { return base.GetHashCode() + (int)this.@operator; } private static object CompareEqual(object left, object right) { if (left == null) return right == null; return left.Equals(right); } private static object CompareNotEqual(object left, object right) { if (left == null) return right != null; return !left.Equals(right); } } }
mit
C#
c5728c1b58a74dca1f2db2c154ef4687f22c7477
Revise unit tests for Actions.Win32Window
y-iihoshi/ThScoreFileConverter,y-iihoshi/ThScoreFileConverter
ThScoreFileConverterTests/Actions/Win32WindowTests.cs
ThScoreFileConverterTests/Actions/Win32WindowTests.cs
using System; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using ThScoreFileConverter.Actions; using ThScoreFileConverterTests.Models; namespace ThScoreFileConverterTests.Actions { [TestClass] public class Win32WindowTests { [TestMethod] public void Win32WindowTest() { var window = new Window(); var helper = new WindowInteropHelper(window); var handle = helper.EnsureHandle(); var win32window = new Win32Window(window); Assert.AreEqual(handle, win32window.Handle); } [TestMethod] public void Win32WindowTestDefault() { var window = new Window(); var win32window = new Win32Window(window); Assert.AreEqual(IntPtr.Zero, win32window.Handle); } [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "win32window")] [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Win32WindowTestNull() { var win32window = new Win32Window(null); Assert.Fail(TestUtils.Unreachable); } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Windows; using Microsoft.VisualStudio.TestTools.UnitTesting; using ThScoreFileConverter.Actions; using ThScoreFileConverterTests.Models; namespace ThScoreFileConverterTests.Actions { [TestClass] public class Win32WindowTests { [TestMethod] public void Win32WindowTest() { var window = new Window(); var win32window = new Win32Window(window); Assert.IsNotNull(win32window); Assert.AreNotEqual(0, win32window.Handle); } [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "win32window")] [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Win32WindowTestNull() { var win32window = new Win32Window(null); Assert.Fail(TestUtils.Unreachable); } } }
bsd-2-clause
C#
46003716501596a337cde2919966aff79a6df6f5
update version comment
yasokada/unity-150905-dynamicDisplay
Assets/PanelDisplayControl.cs
Assets/PanelDisplayControl.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; /* * v0.2 2015/09/06 * - add sample UI components in each panel * v0.1 2015/09/05 * - show/hide panels */ public class PanelDisplayControl : MonoBehaviour { public GameObject PageSelect; public GameObject PanelGroup; private Vector2[] orgSize; void Start() { orgSize = new Vector2[4]; int idx=0; foreach (Transform child in PanelGroup.transform) { orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width; orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height; bool isOn = getIsOn (idx + 1); DisplayPanel (idx + 1, isOn); idx++; } } bool getIsOn(int idx_st1) { Toggle selected = null; string name; foreach (Transform child in PageSelect.transform) { name = child.gameObject.name; if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"... selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle; break; } } return selected.isOn; } void DisplayPanel(int idx_st1, bool doShow) { GameObject panel = GameObject.Find ("Panel" + idx_st1.ToString ()); if (panel == null) { return; } RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform; Vector2 size = rect.sizeDelta; if (doShow) { size.x = orgSize[idx_st1 - 1].x; size.y = orgSize[idx_st1 - 1].y; } else { size.x = 0; size.y = 0; } rect.sizeDelta = size; } public void ToggleValueChanged(int idx_st1) { bool isOn = getIsOn (idx_st1); DisplayPanel (idx_st1, isOn); Debug.Log (isOn.ToString ()); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; /* * v0.1 2015/09/05 * - show/hide panels */ public class PanelDisplayControl : MonoBehaviour { public GameObject PageSelect; public GameObject PanelGroup; private Vector2[] orgSize; void Start() { orgSize = new Vector2[4]; int idx=0; foreach (Transform child in PanelGroup.transform) { orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width; orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height; bool isOn = getIsOn (idx + 1); DisplayPanel (idx + 1, isOn); idx++; } } bool getIsOn(int idx_st1) { Toggle selected = null; string name; foreach (Transform child in PageSelect.transform) { name = child.gameObject.name; if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"... selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle; break; } } return selected.isOn; } void DisplayPanel(int idx_st1, bool doShow) { GameObject panel = GameObject.Find ("Panel" + idx_st1.ToString ()); if (panel == null) { return; } RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform; Vector2 size = rect.sizeDelta; if (doShow) { size.x = orgSize[idx_st1 - 1].x; size.y = orgSize[idx_st1 - 1].y; } else { size.x = 0; size.y = 0; } rect.sizeDelta = size; } public void ToggleValueChanged(int idx_st1) { bool isOn = getIsOn (idx_st1); DisplayPanel (idx_st1, isOn); Debug.Log (isOn.ToString ()); } }
mit
C#
36b604996a7b2d43c1b37a15e973054675f2b204
Update Character2D: hitGround
bunashibu/kikan
Assets/Scripts/Character2D.cs
Assets/Scripts/Character2D.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(BoxCollider2D))] public class Character2D : MonoBehaviour { void Update() { UpdateRaycast(); } private void UpdateRaycast() { Vector2 footRayOrigin = new Vector2(_character.Collider.bounds.center.x, _character.Collider.bounds.min.y); RaycastHit2D hitGround = Physics2D.Raycast(footRayOrigin, Vector2.down, Mathf.Abs(_character.Rigid.velocity.y), _groundMask); if (hitGround.collider != null) { Debug.DrawRay(footRayOrigin, Vector2.down * Mathf.Abs(_character.Rigid.velocity.y), Color.red); CalculateGroundDistance(hitGround); } else { _character.Rigid.gravityScale = 1; } } private void CalculateGroundDistance(RaycastHit2D hitGround) { if (hitGround.distance == 0) { _character.Rigid.velocity = new Vector2(_character.Rigid.velocity.x, 0); _character.Rigid.gravityScale = 0; transform.position = new Vector3(transform.position.x, hitGround.collider.bounds.max.y + _character.Collider.bounds.extents.y, 0); } else { _character.Rigid.gravityScale = 1; } } [SerializeField] private ICharacter _character; [SerializeField] private LayerMask _groundMask; [Range(0, 1)] [SerializeField] private float _friction; }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(BoxCollider2D))] public class Character2D : MonoBehaviour { void Update() { UpdateRaycast(); } private void UpdateRaycast() { Vector2 footRayOrigin = new Vector2(_character.Collider.bounds.center.x, _character.Collider.bounds.min.y); RaycastHit2D hit = Physics2D.Raycast(footRayOrigin, Vector2.down, Mathf.Abs(_character.Rigid.velocity.y), _groundMask); } [SerializeField] private ICharacter _character; [SerializeField] private LayerMask _groundMask; [Range(0, 1)] [SerializeField] private float _friction; }
mit
C#
14d572891deb1989944580377b070aa5d3a06545
use ObservableBatchCollection instead
milleniumbug/Taxonomy
TaxonomyMobile/TaxonomyMobile/FileListModel.cs
TaxonomyMobile/TaxonomyMobile/FileListModel.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Common; using TaxonomyLib; namespace TaxonomyMobile { class FileListModel : INotifyPropertyChanged { private readonly ObservableBatchCollection<FileItem> files = new ObservableBatchCollection<FileItem>(); public ICollection<FileItem> Files => files; private string path; private Taxonomy managedTaxonomy; public void ChangeDirectory(string path) { var dir = new DirectoryInfo(path); IEnumerable<FileSystemInfo> directories = dir.EnumerateDirectories(); IEnumerable<FileSystemInfo> files = dir.EnumerateFiles(); var entries = directories .Concat(files) .Select(fileInfo => new FileItem(fileInfo.FullName)); this.files.Clear(); this.files.AddRange(entries); } public string TaxonomyShortName => ManagedTaxonomy?.ShortName ?? "Files"; public Taxonomy ManagedTaxonomy { get { return managedTaxonomy; } set { if(managedTaxonomy == value) return; managedTaxonomy = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public FileListModel() { //ChangeDirectory(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath); ChangeDirectory(AppCompat.GetExternalSdCardLocation()); } } internal class FileItem { public FileItem(string path) { Path = path; } public bool IsDirectory => Directory.Exists(Path); public string Path { get; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Common; using TaxonomyLib; namespace TaxonomyMobile { class FileListModel : INotifyPropertyChanged { public ICollection<FileItem> Files { get; } = new ObservableCollection<FileItem>(); private string path; private Taxonomy managedTaxonomy; public void ChangeDirectory(string path) { var dir = new DirectoryInfo(path); IEnumerable<FileSystemInfo> directories = dir.EnumerateDirectories(); IEnumerable<FileSystemInfo> files = dir.EnumerateFiles(); var entries = directories .Concat(files) .Select(fileInfo => new FileItem(fileInfo.FullName)); Files.Clear(); foreach(var fileItem in entries) { Files.Add(fileItem); } } public string TaxonomyShortName => ManagedTaxonomy?.ShortName ?? "Files"; public Taxonomy ManagedTaxonomy { get { return managedTaxonomy; } set { if(managedTaxonomy == value) return; managedTaxonomy = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public FileListModel() { //ChangeDirectory(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath); ChangeDirectory(AppCompat.GetExternalSdCardLocation()); } } internal class FileItem { public FileItem(string path) { Path = path; } public bool IsDirectory => Directory.Exists(Path); public string Path { get; } } }
mit
C#
f36c78fc9cee5dbb596166430be0cacac361b445
Change copyright string
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/Properties/AssemblyInfo.cs
SteamAccountSwitcher/Properties/AssemblyInfo.cs
#region using System.Reflection; using System.Runtime.InteropServices; using System.Windows; #endregion // 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("Steam Account Switcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniel Chalmers Software")] [assembly: AssemblyProduct("Steam Account Switcher")] [assembly: AssemblyCopyright("\u00A9 2015 Daniel Chalmers")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
#region using System.Reflection; using System.Runtime.InteropServices; using System.Windows; #endregion // 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("Steam Account Switcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniel Chalmers Software")] [assembly: AssemblyProduct("Steam Account Switcher")] [assembly: AssemblyCopyright("Copyright Daniel Chalmers \u00A9 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
318e62cdd90a172052b001c55e858d847d815372
Change extension methods to use constant from IndexAnnotation for annotation name
TheOtherTimDuncan/TOTD
TOTD.EntityFramework/ConfigurationExtensions.cs
TOTD.EntityFramework/ConfigurationExtensions.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.ModelConfiguration.Configuration; using System.Linq; namespace TOTD.EntityFramework { public static class ConfigurationExtensions { public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration) { return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute())); } public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name) { return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name))); } public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration) { return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute() { IsUnique = true })); } public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name) { return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name) { IsUnique = true })); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.ModelConfiguration.Configuration; using System.Linq; namespace TOTD.EntityFramework { public static class ConfigurationExtensions { public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration) { return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute())); } public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name) { return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute(name))); } public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration) { return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = true })); } public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name) { return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute(name) { IsUnique = true })); } } }
mit
C#
9ef1143dcd47d8629fa7bddb5b7eb0a2deac6574
fix context update to support jsonvalue properly
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
Tweek.ApiService/Modules/ContextUpdateModule.cs
Tweek.ApiService/Modules/ContextUpdateModule.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using Engine.DataTypes; using Engine.Drivers.Context; using FSharp.Data; using Nancy; using Nancy.ModelBinding; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Tweek.Utils; namespace Tweek.ApiService.Modules { public class ContextUpdateModule : NancyModule { private static readonly string PREFIX = "/context"; public ContextUpdateModule(IContextDriver driver) : base(PREFIX) { Post["/{identityType}/{identityId*}", runAsync: true] = async (@params, ct) => { string identityType = @params.identityType; string identityId = @params.identityId; var identity = new Identity(identityType, identityId); Dictionary<string, JsonValue> data; using (var reader = new StreamReader(Request.Body)) { data = JsonConvert.DeserializeObject<Dictionary<string,JsonValue>>(await reader.ReadToEndAsync(), new JsonValueConverter()) .Where(x=>x.Value != JsonValue.Null) .ToDictionary(x => x.Key, x => x.Value); } await driver.AppendContext(identity, data); return 200; }; Delete["/{identityType}/{identityId}/{key*}", runAsync: true] = async (@params, ct) => { string identityType = @params.identityType; string identityId = @params.identityId; string key = @params.key; var identity = new Identity(identityType, identityId); await driver.RemoveFromContext(identity, key); return 200; }; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using Engine.DataTypes; using Engine.Drivers.Context; using FSharp.Data; using Nancy; using Nancy.ModelBinding; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Tweek.ApiService.Modules { public class ContextUpdateModule : NancyModule { private static readonly string PREFIX = "/context"; public ContextUpdateModule(IContextDriver driver) : base(PREFIX) { Post["/{identityType}/{identityId*}", runAsync: true] = async (@params, ct) => { string identityType = @params.identityType; string identityId = @params.identityId; var identity = new Identity(identityType, identityId); Dictionary<string, JsonValue> data; using (var reader = new StreamReader(Request.Body)) { data = JsonConvert.DeserializeObject<JObject>(await reader.ReadToEndAsync()) .Properties() .Where(x => x.HasValues && x.Value.Type != JTokenType.Null) .ToDictionary(x => x.Name, x => x.Value.Value<JsonValue>()); } await driver.AppendContext(identity, data); return 200; }; Delete["/{identityType}/{identityId}/{key*}", runAsync: true] = async (@params, ct) => { string identityType = @params.identityType; string identityId = @params.identityId; string key = @params.key; var identity = new Identity(identityType, identityId); await driver.RemoveFromContext(identity, key); return 200; }; } } }
mit
C#
f4d354a2358106de02c7774c65386c4e55599a8d
Update IPrimitiveObjectValue.cs
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
main/Smartsheet/Api/Models/IPrimitiveObjectValue.cs
main/Smartsheet/Api/Models/IPrimitiveObjectValue.cs
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2018 SmartsheetClient // %% // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Smartsheet.Api.Models { public interface IPrimitiveObjectValue<T> : ObjectValue { T Value {get; set;} void Serialize(JsonWriter writer); } }
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2018 SmartsheetClient // %% // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed To in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Smartsheet.Api.Models { public interface IPrimitiveObjectValue<T> : ObjectValue { T Value {get; set;} void Serialize(JsonWriter writer); } }
apache-2.0
C#
5c3bb9c44ccddd7602bd200dcc281bf2d4512943
Add ShouldSerializeDirectives to pass test ensuring it's only serialized when non-empty
timheuer/alexa-skills-dotnet,stoiveyp/alexa-skills-dotnet
Alexa.NET/Response/Response.cs
Alexa.NET/Response/Response.cs
using Newtonsoft.Json; using System.Collections.Generic; namespace Alexa.NET.Response { public class ResponseBody { [JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)] public IOutputSpeech OutputSpeech { get; set; } [JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)] public ICard Card { get; set; } [JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)] public Reprompt Reprompt { get; set; } [JsonProperty("shouldEndSession")] [JsonRequired] public bool ShouldEndSession { get; set; } [JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)] public IList<IDirective> Directives { get; set; } = new List<IDirective>(); public bool ShouldSerializeDirectives() { return Directives.Count > 0; } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace Alexa.NET.Response { public class ResponseBody { [JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)] public IOutputSpeech OutputSpeech { get; set; } [JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)] public ICard Card { get; set; } [JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)] public Reprompt Reprompt { get; set; } [JsonProperty("shouldEndSession")] [JsonRequired] public bool ShouldEndSession { get; set; } [JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)] public IList<IDirective> Directives { get; set; } = new List<IDirective>(); } }
mit
C#
a15f9c60b0c52c583f44a6258b4025a124de38b5
Store car value on grid when car is moved via byte array
wrightg42/tron,It423/tron
Tron/Networking/Extensions/NetGameExtension.cs
Tron/Networking/Extensions/NetGameExtension.cs
// NetGameExtension.cs // <copyright file="NetGameExtension.cs"> This code is protected under the MIT License. </copyright> using Tron; namespace Networking.Extensions { /// <summary> /// An extension class for the game containing useful tools for a networked game of tron. /// </summary> public static class NetGameExtension { /// <summary> /// Adjusts a car in the game accordingly to a byte array. /// </summary> /// <param name="g"> The game. </param> /// <param name="byteArray"> The byte array. </param> public static void SetCarPosFromByteArray(this TronGame g, byte[] byteArray) { // Get the index of the car int index = byteArray[0]; // Store the value on the grid g.Grid[g.Cars[index].X][g.Cars[index].Y] = g.Cars[index].Colour; // Adjust the car g.Cars[index].PosFromByteArray(byteArray); } public static void SetCarScoreFromByteArray(this TronGame g, byte[] byteArray) { // Get the index of the car int index = byteArray[0]; // Adjust the car g.Cars[index].ScoreFromByteArray(byteArray); } } }
// NetGameExtension.cs // <copyright file="NetGameExtension.cs"> This code is protected under the MIT License. </copyright> using Tron; namespace Networking.Extensions { /// <summary> /// An extension class for the game containing useful tools for a networked game of tron. /// </summary> public static class NetGameExtension { /// <summary> /// Adjusts a car in the game accordingly to a byte array. /// </summary> /// <param name="g"> The game. </param> /// <param name="byteArray"> The byte array. </param> public static void SetCarPosFromByteArray(this TronGame g, byte[] byteArray) { // Get the index of the car int index = byteArray[0]; // Adjust the car g.Cars[index].PosFromByteArray(byteArray); } public static void SetCarScoreFromByteArray(this TronGame g, byte[] byteArray) { // Get the index of the car int index = byteArray[0]; // Adjust the car g.Cars[index].ScoreFromByteArray(byteArray); } } }
mit
C#
03a127309b3e8bcc41fc6742e2f07cf49089d803
Update assembly information
arthurrump/Zermelo.API
Zermelo/Zermelo.API/Properties/AssemblyInfo.cs
Zermelo/Zermelo.API/Properties/AssemblyInfo.cs
using System.Resources; 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("Zermelo.API")] [assembly: AssemblyDescription("An API for Zermelo's zPortal scheduling program for schools.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.API")] [assembly: AssemblyCopyright("Copyright © 2016 Arthur Rump")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")]
using System.Resources; 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("Zermelo.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.Library")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")]
mit
C#
219e8c730de749924d6cfa418649a642a3f41611
Add inline null checks as requested
NikRimington/Umbraco-CMS,madsoulswe/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tompipe/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,lars-erik/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,WebCentrum/Umbraco-CMS,tompipe/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,tompipe/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,lars-erik/Umbraco-CMS,abryukhov/Umbraco-CMS,lars-erik/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,WebCentrum/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS
src/Umbraco.Web/WebApi/UnhandledExceptionLogger.cs
src/Umbraco.Web/WebApi/UnhandledExceptionLogger.cs
using System.Web.Http.ExceptionHandling; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Logging; namespace Umbraco.Web.WebApi { /// <summary> /// Used to log unhandled exceptions in webapi controllers /// </summary> public class UnhandledExceptionLogger : ExceptionLogger { private readonly ILogger _logger; public UnhandledExceptionLogger() : this(Current.Logger) { } public UnhandledExceptionLogger(ILogger logger) { _logger = logger; } public override void Log(ExceptionLoggerContext context) { if (context != null && context.Exception != null) { var requestUrl = context.ExceptionContext?.ControllerContext?.Request?.RequestUri?.AbsoluteUri; var controllerType = context.ExceptionContext?.ActionContext?.ControllerContext?.Controller?.GetType(); _logger.Error(controllerType, context.Exception, "Unhandled controller exception occurred for request '{RequestUrl}'", requestUrl); } } } }
using System.Web.Http.ExceptionHandling; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Logging; namespace Umbraco.Web.WebApi { /// <summary> /// Used to log unhandled exceptions in webapi controllers /// </summary> public class UnhandledExceptionLogger : ExceptionLogger { private readonly ILogger _logger; public UnhandledExceptionLogger() : this(Current.Logger) { } public UnhandledExceptionLogger(ILogger logger) { _logger = logger; } public override void Log(ExceptionLoggerContext context) { if (context != null && context.ExceptionContext != null && context.ExceptionContext.ActionContext != null && context.ExceptionContext.ActionContext.ControllerContext != null && context.ExceptionContext.ActionContext.ControllerContext.Controller != null && context.Exception != null) { var requestUrl = context.ExceptionContext.ControllerContext.Request.RequestUri.AbsoluteUri; var controllerType = context.ExceptionContext.ActionContext.ControllerContext.Controller.GetType(); _logger.Error(controllerType, context.Exception, "Unhandled controller exception occurred for request '{RequestUrl}'", requestUrl); } } } }
mit
C#
13471245380c092fc2a5c1722c875e499c0c6633
fix bug in "x"
joycode/LibNVim
LibNVim/Editions/EditionDeleteChar.cs
LibNVim/Editions/EditionDeleteChar.cs
using System; using System.Collections.Generic; using System.Text; using LibNVim.Interfaces; namespace LibNVim.Editions { class EditionDeleteChar : AbstractVimEditionRedoable { public EditionDeleteChar(Interfaces.IVimHost host, int repeat) : base(host, repeat) { } public override bool Apply(Interfaces.IVimHost host) { if (host.IsCurrentPositionAtEndOfLine()) { return true; } VimPoint from = host.CurrentPosition; VimPoint to = new VimPoint(from.X, Math.Min(from.Y + this.Repeat - 1, host.CurrentLineEndPosition.Y - 1)); VimSpan span = new VimSpan(from, to).GetClosedEnd(); VimRegister.YankRangeToDefaultRegister(host, span); host.DeleteRange(span); return true; } } }
using System; using System.Collections.Generic; using System.Text; using LibNVim.Interfaces; namespace LibNVim.Editions { class EditionDeleteChar : AbstractVimEditionRedoable { public EditionDeleteChar(Interfaces.IVimHost host, int repeat) : base(host, repeat) { } public override bool Apply(Interfaces.IVimHost host) { if (host.IsCurrentPositionAtEndOfLine()) { return true; } VimPoint from = host.CurrentPosition; VimPoint to = new VimPoint(from.X, Math.Min(from.Y + this.Repeat - 1, host.CurrentLineEndPosition.Y - 1)); VimSpan span = new VimSpan(from, to); VimRegister.YankRangeToDefaultRegister(host, span); host.DeleteRange(span); return true; } } }
bsd-3-clause
C#
4bceda894a463647078b4d1fe7f6497a4db3e425
Update RectangleHitTest.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D.Editor/Bounds/Shapes/RectangleHitTest.cs
src/Draw2D.Editor/Bounds/Shapes/RectangleHitTest.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Draw2D.Core; using Draw2D.Core.Shapes; using Draw2D.Spatial; namespace Draw2D.Editor.Bounds.Shapes { public class RectangleHitTest : BoxHitTest { public override Type TargetType => typeof(RectangleShape); } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Draw2D.Core; using Draw2D.Core.Shapes; using Draw2D.Spatial; namespace Draw2D.Editor.Bounds.Shapes { public class RectangleHitTest : HitTestBase { public override Type TargetType => typeof(RectangleShape); public override PointShape TryToGetPoint(ShapeObject shape, Point2 target, double radius, IHitTest hitTest) { var rectangle = shape as RectangleShape; if (rectangle == null) throw new ArgumentNullException("shape"); var pointHitTest = hitTest.Registered[typeof(PointShape)]; if (pointHitTest.TryToGetPoint(rectangle.TopLeft, target, radius, hitTest) != null) { return rectangle.TopLeft; } if (pointHitTest.TryToGetPoint(rectangle.BottomRight, target, radius, hitTest) != null) { return rectangle.BottomRight; } foreach (var point in rectangle.Points) { if (pointHitTest.TryToGetPoint(point, target, radius, hitTest) != null) { return point; } } return null; } public override ShapeObject Contains(ShapeObject shape, Point2 target, double radius, IHitTest hitTest) { var rectangle = shape as RectangleShape; if (rectangle == null) throw new ArgumentNullException("shape"); return Rect2.FromPoints( rectangle.TopLeft.X, rectangle.TopLeft.Y, rectangle.BottomRight.X, rectangle.BottomRight.Y).Contains(target) ? shape : null; } public override ShapeObject Overlaps(ShapeObject shape, Rect2 target, double radius, IHitTest hitTest) { var rectangle = shape as RectangleShape; if (rectangle == null) throw new ArgumentNullException("shape"); return Rect2.FromPoints( rectangle.TopLeft.X, rectangle.TopLeft.Y, rectangle.BottomRight.X, rectangle.BottomRight.Y).IntersectsWith(target) ? shape : null; } } }
mit
C#
3167016b608b1a1afe4f1ffdb052838c4291feae
Remove test for "DisableColorCompression" flag.
dotless/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,dotless/dotless,rytmis/dotless,rytmis/dotless
src/dotless.Test/Specs/Compression/ColorsFixture.cs
src/dotless.Test/Specs/Compression/ColorsFixture.cs
using System; using dotless.Core.Parser; using dotless.Core.Parser.Infrastructure; namespace dotless.Test.Specs.Compression { using NUnit.Framework; public class ColorsFixture : CompressedSpecFixtureBase { [Test] public void Colors() { AssertExpression("#fea", "#fea"); AssertExpression("#0000ff", "#0000ff"); AssertExpression("blue", "blue"); } [Test] public void Should_not_compress_IE_ARGB() { AssertExpressionUnchanged("#ffaabbcc"); AssertExpressionUnchanged("#aabbccdd"); } [Test] public void Overflow() { AssertExpression("#000", "#111111 - #444444"); AssertExpression("#fff", "#eee + #fff"); AssertExpression("#fff", "#aaa * 3"); AssertExpression("lime", "#00ee00 + #009900"); AssertExpression("red", "#ee0000 + #990000"); } [Test] public void Gray() { AssertExpression("#888", "rgb(136, 136, 136)"); AssertExpression("gray", "hsl(50, 0, 50)"); } } }
using System; using dotless.Core.Parser; using dotless.Core.Parser.Infrastructure; namespace dotless.Test.Specs.Compression { using NUnit.Framework; public class ColorsFixture : CompressedSpecFixtureBase { [Test] public void Colors() { AssertExpression("#fea", "#fea"); AssertExpression("#0000ff", "#0000ff"); AssertExpression("blue", "blue"); } [Test] public void Should_not_compress_IE_ARGB() { AssertExpressionUnchanged("#ffaabbcc"); AssertExpressionUnchanged("#aabbccdd"); } [Test] public void Overflow() { AssertExpression("#000", "#111111 - #444444"); AssertExpression("#fff", "#eee + #fff"); AssertExpression("#fff", "#aaa * 3"); AssertExpression("lime", "#00ee00 + #009900"); AssertExpression("red", "#ee0000 + #990000"); } [Test] public void Gray() { AssertExpression("#888", "rgb(136, 136, 136)"); AssertExpression("gray", "hsl(50, 0, 50)"); } [Test] public void DisableColorCompression() { var oldEnv = DefaultEnv(); DefaultEnv = () => new Env(null) { Compress = true, DisableColorCompression = false }; AssertExpression("#111", "#111111"); DefaultEnv = () => new Env(null) { Compress = true, DisableColorCompression = true }; AssertExpression("#111111", "#111111"); DefaultEnv = () => oldEnv; } } }
apache-2.0
C#
6cd8aadfe93201b5435a53715854b11768c7d6fe
remove comment
modulexcite/xbehave.net,hitesh97/xbehave.net,mvalipour/xbehave.net,mvalipour/xbehave.net,xbehave/xbehave.net,modulexcite/xbehave.net,adamralph/xbehave.net,hitesh97/xbehave.net
src/issues/Xbehave.Issues/MultipleGivensAndWhens.cs
src/issues/Xbehave.Issues/MultipleGivensAndWhens.cs
// <copyright file="MultipleGivensAndWhens.cs" company="Adam Ralph"> // Copyright (c) Adam Ralph. All rights reserved. // </copyright> namespace Xbehave.Issues { using System; using FluentAssertions; public class MultipleGivensAndWhens { [Scenario] public static void MultipleWithActionDisposables() { var disposable0 = default(Disposable); var disposable1 = default(Disposable); "Given a disposable," .Given( () => disposable0 = new Disposable(), () => disposable0.Dispose()); "and another disposable" .Given( () => disposable1 = new Disposable(), () => disposable1.Dispose()); "when using the first disposable" .When(() => disposable0.Use()); "and using the second disposable" .When(() => disposable1.Use()); _.ThenInIsolation(() => true.Should().Be(false)); _.ThenInIsolation(() => true.Should().Be(false)); } public sealed class Disposable : IDisposable { public Disposable() { Console.WriteLine("CREATED"); } public void Use() { Console.WriteLine("USED"); } public void Dispose() { Console.WriteLine("DISPOSED"); } } } }
// <copyright file="MultipleGivensAndWhens.cs" company="Adam Ralph"> // Copyright (c) Adam Ralph. All rights reserved. // </copyright> namespace Xbehave.Issues { using System; using FluentAssertions; public class MultipleGivensAndWhens { // 2 failures with 1 x 1 disposal [Scenario] public static void MultipleWithActionDisposables() { var disposable0 = default(Disposable); var disposable1 = default(Disposable); "Given a disposable," .Given( () => disposable0 = new Disposable(), () => disposable0.Dispose()); "and another disposable" .Given( () => disposable1 = new Disposable(), () => disposable1.Dispose()); "when using the first disposable" .When(() => disposable0.Use()); "and using the second disposable" .When(() => disposable1.Use()); _.ThenInIsolation(() => true.Should().Be(false)); _.ThenInIsolation(() => true.Should().Be(false)); } public sealed class Disposable : IDisposable { public Disposable() { Console.WriteLine("CREATED"); } public void Use() { Console.WriteLine("USED"); } public void Dispose() { Console.WriteLine("DISPOSED"); } } } }
mit
C#
7e54cf205ea42bebc659ce13bfe123fbb2d5a69e
fix assembly resolver in NuGet plugin
JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,stormleoxia/teamcity-nuget-support
nuget-extensions/nuget-commands/src/CredentialsSetter.cs
nuget-extensions/nuget-commands/src/CredentialsSetter.cs
using System; using System.ComponentModel.Composition; using System.IO; using System.Linq; using JetBrains.TeamCity.NuGet.ExtendedCommands.Data; using JetBrains.TeamCity.NuGetRunner; namespace JetBrains.TeamCity.NuGet.ExtendedCommands { [Export] [ComponentOrder(Index = "J")] public partial class CredentialsSetter : ICreatableComponent { private String myState = "not initialized"; public void Initialize() { var path = Environment.GetEnvironmentVariable("TEAMCITY_NUGET_FEEDS"); if (string.IsNullOrWhiteSpace(path)) return; if (!File.Exists(path)) { Console.Out.WriteLine("Failed to load NuGet feed credentials file: " + path); return; } new AssemblyResolver(GetType().Assembly.GetAssemblyDirectory()); var sources = XmlSerializerHelper.Load<NuGetSources>(path); var actual = sources.Sources.Where(x => x.HasCredentials).ToArray(); if (actual.Any()) { myState = actual.Aggregate("ENABLED:", (acc, next) => acc + "feed=" + next.Source + ",user=" + (next.Username ?? "<null>") + "; "); UpdateCredentials(actual); } } public string Describe() { return "State: " + myState; } } }
using System; using System.ComponentModel.Composition; using System.IO; using System.Linq; using JetBrains.TeamCity.NuGet.ExtendedCommands.Data; namespace JetBrains.TeamCity.NuGet.ExtendedCommands { [Export] [ComponentOrder(Index = "J")] public partial class CredentialsSetter : ICreatableComponent { private String myState = "not initialized"; public void Initialize() { var path = Environment.GetEnvironmentVariable("TEAMCITY_NUGET_FEEDS"); if (string.IsNullOrWhiteSpace(path)) return; if (!File.Exists(path)) { Console.Out.WriteLine("Failed to load NuGet feed credentials file: " + path); return; } var sources = XmlSerializerHelper.Load<NuGetSources>(path); var actual = sources.Sources.Where(x => x.HasCredentials).ToArray(); if (actual.Any()) { myState = actual.Aggregate("ENABLED:", (acc, next) => acc + "feed=" + next.Source + ",user=" + (next.Username ?? "<null>") + "; "); UpdateCredentials(actual); } } public string Describe() { return "State: " + myState; } } }
apache-2.0
C#
677c0bb1a53b8ea29464046a088b04aebd5579e8
test commit
Theliahh/parallelsorting
ParallelSorting/Program.cs
ParallelSorting/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParallelSorting { class Program { static void Main(string[] args) { test; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParallelSorting { class Program { static void Main(string[] args) { } } }
mit
C#
115a99a924b78ffdc88262de4d729083d80fcca6
Bump Assembly Version
dasgarner/xibo-dotnetclient,xibosignage/xibo-dotnetclient
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Xibo Open Source Digital Signage")] [assembly: AssemblyDescription("Digital Signage Player")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xibo Digital Signage")] [assembly: AssemblyProduct("Xibo")] [assembly: AssemblyCopyright("Copyright Dan Garner © 2008-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3bd467a4-4ef9-466a-b156-a79c13a863f7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("10.8.1.0")] [assembly: AssemblyFileVersion("10.8.1.0")] [assembly: NeutralResourcesLanguageAttribute("en-GB")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Xibo Open Source Digital Signage")] [assembly: AssemblyDescription("Digital Signage Player")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xibo Digital Signage")] [assembly: AssemblyProduct("Xibo")] [assembly: AssemblyCopyright("Copyright Dan Garner © 2008-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3bd467a4-4ef9-466a-b156-a79c13a863f7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("10.8.0.4")] [assembly: AssemblyFileVersion("10.8.0.4")] [assembly: NeutralResourcesLanguageAttribute("en-GB")]
agpl-3.0
C#
7bae4e1219a448a818633b3ed8e243aea5274869
Improve validation exception
kotorihq/kotori-core
KotoriCore/Exceptions/KotoriValidationException.cs
KotoriCore/Exceptions/KotoriValidationException.cs
using System.Collections.Generic; using System.Linq; using KotoriCore.Helpers; using Sushi2; namespace KotoriCore.Exceptions { /// <summary> /// Kotori validation exception. /// </summary> public class KotoriValidationException : KotoriException { const string UnknownErrorMessage = "Unknown error."; /// <summary> /// Gets the messages. /// </summary> /// <value>The messages.</value> public IEnumerable<string> Messages { get; } /// <summary> /// Initializes a new instance of the <see cref="T:KotoriCore.Exceptions.KotoriValidationException"/> class. /// </summary> /// <param name="validationResults">Validation results.</param> public KotoriValidationException(IEnumerable<ValidationResult> validationResults) : base(validationResults?.Where(vr => vr != null && !vr.IsValid).Select(vr2 => vr2.Message).ToImplodedString(" ") ?? UnknownErrorMessage) { var messages = validationResults?.Where(vr => vr != null && !vr.IsValid).Select(vr2 => vr2.Message); if (!messages.Any()) Messages = new List<string> { UnknownErrorMessage }; else Messages = messages; } /// <summary> /// Initializes a new instance of the <see cref="T:KotoriCore.Exceptions.KotoriValidationException"/> class. /// </summary> /// <param name="message">Message.</param> public KotoriValidationException(string message) : base(message) { Messages = new List<string> { message ?? UnknownErrorMessage }; } } }
using System.Collections.Generic; using System.Linq; using KotoriCore.Helpers; using Sushi2; namespace KotoriCore.Exceptions { /// <summary> /// Kotori validation exception. /// </summary> public class KotoriValidationException : KotoriException { /// <summary> /// Initializes a new instance of the <see cref="T:KotoriCore.Exceptions.KotoriValidationException"/> class. /// </summary> /// <param name="validationResults">Validation results.</param> public KotoriValidationException(IEnumerable<ValidationResult> validationResults) : base(validationResults?.Where(vr => vr != null && !vr.IsValid).Select(vr2 => vr2.Message).ToImplodedString(" ") ?? "Unknown error.") { } /// <summary> /// Initializes a new instance of the <see cref="T:KotoriCore.Exceptions.KotoriValidationException"/> class. /// </summary> /// <param name="message">Message.</param> public KotoriValidationException(string message) : base(message) { } } }
mit
C#
98d33c701b5133f76502218a772fbfa30416201b
Use RaisePropertyChanged
manupstairs/Notepad
Notepad/MvvmLightSample/ViewModel/MainViewModel.cs
Notepad/MvvmLightSample/ViewModel/MainViewModel.cs
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using System.Windows.Input; namespace MvvmLightSample.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { private string title; public string Title { get { return title; } set { Set(ref title, value); } } private string text; public string Text { get { return text; } set { text = value; RaisePropertyChanged("Text"); RaisePropertyChanged("TitleAndText"); } } public string TitleAndText { get { return title + text; } } public ICommand ChangeTitleCommand { get; set; } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { Title = "Hello World"; ChangeTitleCommand = new RelayCommand(ChangeTitle); } private void ChangeTitle() { Title = "Hello MvvmLight"; } } }
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using System.Windows.Input; namespace MvvmLightSample.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { private string title; public string Title { get { return title; } set { Set(ref title, value); } } public ICommand ChangeTitleCommand { get; set; } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { Title = "Hello World"; ChangeTitleCommand = new RelayCommand(ChangeTitle); } private void ChangeTitle() { Title = "Hello MvvmLight"; } } }
mit
C#
a29cb2f488018de5b88d6f37459fa0794708920d
Remove theory from test
luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,andmattia/aspnetboilerplate,zclmoon/aspnetboilerplate,ryancyq/aspnetboilerplate,Nongzhsh/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,oceanho/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,zclmoon/aspnetboilerplate,ilyhacker/aspnetboilerplate,Nongzhsh/aspnetboilerplate,verdentk/aspnetboilerplate,fengyeju/aspnetboilerplate,virtualcca/aspnetboilerplate,AlexGeller/aspnetboilerplate,oceanho/aspnetboilerplate,zclmoon/aspnetboilerplate,fengyeju/aspnetboilerplate,ryancyq/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,fengyeju/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,andmattia/aspnetboilerplate,beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,AlexGeller/aspnetboilerplate,verdentk/aspnetboilerplate,AlexGeller/aspnetboilerplate,oceanho/aspnetboilerplate,beratcarsi/aspnetboilerplate,virtualcca/aspnetboilerplate,beratcarsi/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ilyhacker/aspnetboilerplate,virtualcca/aspnetboilerplate,andmattia/aspnetboilerplate
test/Abp.RedisCache.Tests/RedisCacheManager_Test.cs
test/Abp.RedisCache.Tests/RedisCacheManager_Test.cs
using System; using Abp.Configuration.Startup; using Abp.Runtime.Caching; using Abp.Runtime.Caching.Configuration; using Abp.Runtime.Caching.Redis; using Abp.Tests; using Castle.MicroKernel.Registration; using NSubstitute; using Xunit; using Shouldly; namespace Abp.RedisCache.Tests { public class RedisCacheManager_Test : TestBaseWithLocalIocManager { private readonly ITypedCache<string, MyCacheItem> _cache; public RedisCacheManager_Test() { LocalIocManager.Register<AbpRedisCacheOptions>(); LocalIocManager.Register<ICachingConfiguration, CachingConfiguration>(); LocalIocManager.Register<IAbpRedisCacheDatabaseProvider, AbpRedisCacheDatabaseProvider>(); LocalIocManager.Register<ICacheManager, AbpRedisCacheManager>(); LocalIocManager.Register<IRedisCacheSerializer,DefaultRedisCacheSerializer>(); LocalIocManager.IocContainer.Register(Component.For<IAbpStartupConfiguration>().UsingFactoryMethod(() => Substitute.For<IAbpStartupConfiguration>())); var defaultSlidingExpireTime = TimeSpan.FromHours(24); LocalIocManager.Resolve<ICachingConfiguration>().Configure("MyTestCacheItems", cache => { cache.DefaultSlidingExpireTime = defaultSlidingExpireTime; }); _cache = LocalIocManager.Resolve<ICacheManager>().GetCache<string, MyCacheItem>("MyTestCacheItems"); _cache.DefaultSlidingExpireTime.ShouldBe(defaultSlidingExpireTime); } //[Theory] //[InlineData("A", 42)] //[InlineData("B", 43)] public void Simple_Get_Set_Test(string cacheKey, int cacheValue) { var item = _cache.Get(cacheKey, () => new MyCacheItem { Value = cacheValue }); item.ShouldNotBe(null); item.Value.ShouldBe(cacheValue); _cache.GetOrDefault(cacheKey).Value.ShouldBe(cacheValue); } [Serializable] public class MyCacheItem { public int Value { get; set; } } } }
using System; using Abp.Configuration.Startup; using Abp.Runtime.Caching; using Abp.Runtime.Caching.Configuration; using Abp.Runtime.Caching.Redis; using Abp.Tests; using Castle.MicroKernel.Registration; using NSubstitute; using Xunit; using Shouldly; namespace Abp.RedisCache.Tests { public class RedisCacheManager_Test : TestBaseWithLocalIocManager { private readonly ITypedCache<string, MyCacheItem> _cache; public RedisCacheManager_Test() { LocalIocManager.Register<AbpRedisCacheOptions>(); LocalIocManager.Register<ICachingConfiguration, CachingConfiguration>(); LocalIocManager.Register<IAbpRedisCacheDatabaseProvider, AbpRedisCacheDatabaseProvider>(); LocalIocManager.Register<ICacheManager, AbpRedisCacheManager>(); LocalIocManager.Register<IRedisCacheSerializer,DefaultRedisCacheSerializer>(); LocalIocManager.IocContainer.Register(Component.For<IAbpStartupConfiguration>().UsingFactoryMethod(() => Substitute.For<IAbpStartupConfiguration>())); var defaultSlidingExpireTime = TimeSpan.FromHours(24); LocalIocManager.Resolve<ICachingConfiguration>().Configure("MyTestCacheItems", cache => { cache.DefaultSlidingExpireTime = defaultSlidingExpireTime; }); _cache = LocalIocManager.Resolve<ICacheManager>().GetCache<string, MyCacheItem>("MyTestCacheItems"); _cache.DefaultSlidingExpireTime.ShouldBe(defaultSlidingExpireTime); } [Theory] [InlineData("A", 42)] [InlineData("B", 43)] public void Simple_Get_Set_Test(string cacheKey, int cacheValue) { var item = _cache.Get(cacheKey, () => new MyCacheItem { Value = cacheValue }); item.ShouldNotBe(null); item.Value.ShouldBe(cacheValue); _cache.GetOrDefault(cacheKey).Value.ShouldBe(cacheValue); } [Serializable] public class MyCacheItem { public int Value { get; set; } } } }
mit
C#
ec7dbe41fbdaa5eb229f4ab2baa30ae777c47495
Call ToString() instead of Enum.GetName
mavasani/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,bartdesmet/roslyn,dotnet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn
src/EditorFeatures/Core/Logging/FunctionIdOptions.cs
src/EditorFeatures/Core/Logging/FunctionIdOptions.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.Linq; using System.Collections.Concurrent; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Internal.Log { internal static class FunctionIdOptions { private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options = new(); private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption; private static Option2<bool> CreateOption(FunctionId id) { var name = id.ToString(); return new(nameof(FunctionIdOptions), name, defaultValue: false, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name)); } private static IEnumerable<FunctionId> GetFunctionIds() => Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>(); public static IEnumerable<IOption> GetOptions() => GetFunctionIds().Select(GetOption); public static Option2<bool> GetOption(FunctionId id) => s_options.GetOrAdd(id, s_optionCreator); public static Func<FunctionId, bool> CreateFunctionIsEnabledPredicate(IGlobalOptionService globalOptions) { var functionIdOptions = GetFunctionIds().ToDictionary(id => id, id => globalOptions.GetOption(GetOption(id))); return functionId => functionIdOptions[functionId]; } } }
// 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.Linq; using System.Collections.Concurrent; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Internal.Log { internal static class FunctionIdOptions { private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options = new(); private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption; private static Option2<bool> CreateOption(FunctionId id) { var name = Enum.GetName(typeof(FunctionId), id) ?? throw ExceptionUtilities.UnexpectedValue(id); return new(nameof(FunctionIdOptions), name, defaultValue: false, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name)); } private static IEnumerable<FunctionId> GetFunctionIds() => Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>(); public static IEnumerable<IOption> GetOptions() => GetFunctionIds().Select(GetOption); public static Option2<bool> GetOption(FunctionId id) => s_options.GetOrAdd(id, s_optionCreator); public static Func<FunctionId, bool> CreateFunctionIsEnabledPredicate(IGlobalOptionService globalOptions) { var functionIdOptions = GetFunctionIds().ToDictionary(id => id, id => globalOptions.GetOption(GetOption(id))); return functionId => functionIdOptions[functionId]; } } }
mit
C#
b3eb733bb1635d274615148a55d8555405fb384b
Fix incorrect implementation of executor
zebraxxl/Winium.Desktop,jorik041/Winium.Desktop,2gis/Winium.Desktop
src/Winium.Desktop.Driver/CommandExecutors/IsComboBoxExpandedExecutor.cs
src/Winium.Desktop.Driver/CommandExecutors/IsComboBoxExpandedExecutor.cs
namespace Winium.Desktop.Driver.CommandExecutors { #region using using Winium.Cruciatus.Extensions; using Winium.StoreApps.Common; #endregion internal class IsComboBoxExpandedExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var element = this.Automator.ElementsRegistry.GetRegisteredElement(registeredKey); return this.JsonResponse(ResponseStatus.Success, element.ToComboBox().IsExpanded); } #endregion } }
namespace Winium.Desktop.Driver.CommandExecutors { #region using using Winium.StoreApps.Common; #endregion internal class IsComboBoxExpandedExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var element = this.Automator.ElementsRegistry.GetRegisteredElement(registeredKey); return this.JsonResponse(ResponseStatus.Success, element.Properties.IsEnabled); } #endregion } }
mpl-2.0
C#
d4c29d7ff183313fcbc6ca703a0e555354ffc578
Make it work also for ODBC - especially useful since ODBC seems more challenging for the transaction handling.
nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH2420/Fixture.cs
src/NHibernate.Test/NHSpecificTest/NH2420/Fixture.cs
using System; using System.Data; using System.Data.Odbc; using System.Data.SqlClient; using System.Transactions; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH2420 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH2420"; } } protected override bool AppliesTo(Dialect.Dialect dialect) { return (dialect is MsSql2005Dialect); } [Test] public void ShouldBeAbleToReleaseSuppliedConnectionAfterDistributedTransaction() { string connectionString = cfg.GetProperty("connection.connection_string"); ISession s; using (var ts = new TransactionScope()) { // Enlisting DummyEnlistment as a durable resource manager will start // a DTC transaction System.Transactions.Transaction.Current.EnlistDurable( DummyEnlistment.Id, new DummyEnlistment(), EnlistmentOptions.None); IDbConnection connection; if (sessions.ConnectionProvider.Driver.GetType() == typeof(OdbcDriver)) connection = new OdbcConnection(connectionString); else connection = new SqlConnection(connectionString); using (connection) { connection.Open(); using (s = Sfi.OpenSession(connection)) { s.Save(new MyTable { String = "hello!" }); } connection.Close(); } ts.Complete(); } // Prior to the patch, an InvalidOperationException exception would occur in the // TransactionCompleted delegate at this point with the message, "Disconnect cannot // be called while a transaction is in progress". Although the exception can be // seen reported in the IDE, NUnit fails to see it. The TransactionCompleted event // fires *after* the transaction is committed and so it doesn't affect the success // of the transaction. Assert.That(s.IsConnected, Is.False); Assert.That(((ISessionImplementor)s).ConnectionManager.IsConnected, Is.False); Assert.That(((ISessionImplementor)s).IsClosed, Is.True); } protected override void OnTearDown() { using (ISession s = OpenSession()) { s.Delete("from MyTable"); s.Flush(); } } } }
using System; using System.Data; using System.Data.SqlClient; using System.Transactions; using NHibernate.Dialect; using NHibernate.Engine; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH2420 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH2420"; } } protected override bool AppliesTo(Dialect.Dialect dialect) { return (dialect is MsSql2005Dialect); } [Test] public void ShouldBeAbleToReleaseSuppliedConnectionAfterDistributedTransaction() { string connectionString = cfg.GetProperty("connection.connection_string"); ISession s; using (var ts = new TransactionScope()) { // Enlisting DummyEnlistment as a durable resource manager will start // a DTC transaction System.Transactions.Transaction.Current.EnlistDurable( DummyEnlistment.Id, new DummyEnlistment(), EnlistmentOptions.None); using (IDbConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (s = Sfi.OpenSession(connection)) { s.Save(new MyTable() { String = "hello!" }); } connection.Close(); } ts.Complete(); } // Prior to the patch, an InvalidOperationException exception would occur in the // TransactionCompleted delegate at this point with the message, "Disconnect cannot // be called while a transaction is in progress". Although the exception can be // seen reported in the IDE, NUnit fails to see it. The TransactionCompleted event // fires *after* the transaction is committed and so it doesn't affect the success // of the transaction. Assert.That(s.IsConnected, Is.False); Assert.That(((ISessionImplementor)s).ConnectionManager.IsConnected, Is.False); Assert.That(((ISessionImplementor)s).IsClosed, Is.True); } protected override void OnTearDown() { using (ISession s = OpenSession()) { s.Delete("from MyTable"); s.Flush(); } } } }
lgpl-2.1
C#
eb5b2c662343ba8bcdcc6b1bbd21a3f9b20d0af6
Fix namespace issue after refactor of startup
Hammerstad/Moya
Moya.Runner.Console/Program.cs
Moya.Runner.Console/Program.cs
namespace Moya.Runner.Console { using System; using Extensions; class Program { private static void Main(string[] args) { try { new Startup.Startup().Run(args); } catch(Exception e) { Console.Error.WriteLine("Error: {0}".FormatWith(e.Message)); Environment.Exit(1); } } } }
namespace Moya.Runner.Console { using System; using Extensions; class Program { private static void Main(string[] args) { try { new Startup().Run(args); } catch(Exception e) { Console.Error.WriteLine("Error: {0}".FormatWith(e.Message)); Environment.Exit(1); } } } }
mit
C#
7f277b130822e08b32ee10b746e4d47015783112
replace return code
kheiakiyama/speech-eng-functions
SentenceScraping/run.csx
SentenceScraping/run.csx
#r "System.Configuration" #r "System.Collections" #r "System.Linq.Expressions" #load "../QuestionEntity.csx" using System.Net; using System.Net.Http; using System.Configuration; using System.Linq; using Newtonsoft.Json; using Microsoft.Azure; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using LinqToTwitter; public static async Task Run(TimerInfo myTimer, TraceWriter log) { log.Info("function processed a request."); var auth = new LinqToTwitter.SingleUserAuthorizer { CredentialStore = new LinqToTwitter.SingleUserInMemoryCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["Twitter_ConsumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["Twitter_ConsumerSecret"], AccessToken = ConfigurationManager.AppSettings["Twitter_AccessToken"], AccessTokenSecret = ConfigurationManager.AppSettings["Twitter_AccessTokenSecret"] } }; var twitter = new TwitterContext(auth); var dic = await EigoMeigen_bot(twitter, log); foreach (var key in dic.Keys) { log.Info(key.ToString()); var existEntity = QuestionEntity.GetEntity(key.ToString()); if (existEntity != null) continue; var entity = new QuestionEntity(key) { Sentence = dic[key], }; entity.Insert(); } } private static async Task<Dictionary<ulong, string>> EigoMeigen_bot(TwitterContext context, TraceWriter log) { var tweets = await context.Status .Where(tweet => tweet.Type == StatusType.User && tweet.ScreenName == "EigoMeigen_bot") .ToListAsync(); Dictionary<ulong, string> dic = new Dictionary<ulong, string>(); tweets.ForEach((obj) => { var english = obj.Text.Split(new string[] { "\n" }, StringSplitOptions.None).FirstOrDefault(); dic.Add(obj.StatusID, english); log.Info(english); }); return dic; }
#r "System.Configuration" #r "System.Collections" #r "System.Linq.Expressions" #load "../QuestionEntity.csx" using System.Net; using System.Net.Http; using System.Configuration; using System.Linq; using Newtonsoft.Json; using Microsoft.Azure; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using LinqToTwitter; public static async Task Run(TimerInfo myTimer, TraceWriter log) { log.Info("function processed a request."); var auth = new LinqToTwitter.SingleUserAuthorizer { CredentialStore = new LinqToTwitter.SingleUserInMemoryCredentialStore { ConsumerKey = ConfigurationManager.AppSettings["Twitter_ConsumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["Twitter_ConsumerSecret"], AccessToken = ConfigurationManager.AppSettings["Twitter_AccessToken"], AccessTokenSecret = ConfigurationManager.AppSettings["Twitter_AccessTokenSecret"] } }; var twitter = new TwitterContext(auth); var dic = await EigoMeigen_bot(twitter, log); foreach (var key in dic.Keys) { log.Info(key.ToString()); var existEntity = QuestionEntity.GetEntity(key.ToString()); if (existEntity != null) continue; var entity = new QuestionEntity(key) { Sentence = dic[key], }; entity.Insert(); } } private static async Task<Dictionary<ulong, string>> EigoMeigen_bot(TwitterContext context, TraceWriter log) { var tweets = await context.Status .Where(tweet => tweet.Type == StatusType.User && tweet.ScreenName == "EigoMeigen_bot") .ToListAsync(); Dictionary<ulong, string> dic = new Dictionary<ulong, string>(); tweets.ForEach((obj) => { log.Info(obj.Text); var english = obj.Text.Split(new string[] { "¥r¥n", "¥n" }, StringSplitOptions.None).FirstOrDefault(); dic.Add(obj.StatusID, english); log.Info(english); }); return dic; }
mit
C#
1ef71a7017c0ce6c70926921f161a8a6f8f3e9b7
Remove unnecessary enum
kcotugno/OpenARLog
OpenARLog.Data/BandsManager.cs
OpenARLog.Data/BandsManager.cs
/* * Copyright (C) 2015-2016 kcotugno * All rights reserved * * Distributed under the terms of the BSD 2 Clause software license. See the * accompanying LICENSE file or http://www.opensource.org/licenses/BSD-2-Clause. * * Author: kcotugno * Date: 4/6/2016 */ using System.Collections.Generic; using System.Data; namespace OpenARLog.Data { public class BandsManager : TypeDataManager { public List<BandModel> Bands { get { return _bands; } } private List<BandModel> _bands; public BandsManager(TypeDataDb db) : base(db, Constants.TYPES.BANDS) { // Do Nothing } public override void PopulateList() { if (_bands == null) _bands = new List<BandModel>(); _bands.Clear(); foreach (DataRow row in _dataTable.Rows) { BandModel band = new BandModel() { Band = row.Field<string>("Band"), LowerFrequency = row.Field<double?>("Lower_Freq_MHz"), UpperFrequency = row.Field<double?>("Upper_Freq_MHz") }; _bands.Add(band); } } public bool IsValidBand(string text) { // TODO return true; } } }
/* * Copyright (C) 2015-2016 kcotugno * All rights reserved * * Distributed under the terms of the BSD 2 Clause software license. See the * accompanying LICENSE file or http://www.opensource.org/licenses/BSD-2-Clause. * * Author: kcotugno * Date: 4/6/2016 */ using System.Collections.Generic; using System.Data; namespace OpenARLog.Data { public class BandsManager : TypeDataManager { // Varibles cannot have a number as the first character. So we reverse the meter position. public enum BANDS { NONE = 0, M2190, M630, M560, M160, M80, M60, M40, M30, M20, M17, M15, M12, M10, M6, M4, M2, M1_25, CM70, CM33, CM23, CM13, CM9, CM6, CM3, CM1_25, MM6, MM4, MM2_5, MM2, MM1 }; public List<BandModel> Bands { get { return _bands; } } private List<BandModel> _bands; public BandsManager(TypeDataDb db) : base(db, Constants.TYPES.BANDS) { // Do Nothing } public override void PopulateList() { if (_bands == null) _bands = new List<BandModel>(); _bands.Clear(); foreach (DataRow row in _dataTable.Rows) { BandModel band = new BandModel() { Band = row.Field<string>("Band"), LowerFrequency = row.Field<double?>("Lower_Freq_MHz"), UpperFrequency = row.Field<double?>("Upper_Freq_MHz") }; _bands.Add(band); } } public bool IsValidBand(string text) { // TODO return true; } } }
mit
C#
874be8b1f49ac023e9a016801dd81ae90ffc8f30
remove inflation from the base page
MiniProfiler/dotnet,MiniProfiler/dotnet
samples/Samples.AspNetCore/Controllers/HomeController.cs
samples/Samples.AspNetCore/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc; using StackExchange.Profiling; namespace Samples.AspNetCore.Controllers { public class HomeController : Controller { public IActionResult Index() { using (MiniProfiler.Current.Step("Example Step")) { using (MiniProfiler.Current.Step("Sub timing")) { // Not trying to delay the page load here, only serve as an example } using (MiniProfiler.Current.Step("Sub timing 2")) { // Not trying to delay the page load here, only serve as an example } } return View(); } public IActionResult Error() => View(); } }
using Microsoft.AspNetCore.Mvc; using StackExchange.Profiling; using System.Threading; namespace Samples.AspNetCore.Controllers { public class HomeController : Controller { public IActionResult Index() { using (MiniProfiler.Current.Step("Delay Step")) { Thread.Sleep(50); using (MiniProfiler.Current.Step("Sub timing")) { Thread.Sleep(65); } } return View(); } public IActionResult Error() => View(); } }
mit
C#
076fc74d00f212843942801ffe5e2109de0d9f62
test keep this one
MatthewKapteyn/SubmoduleTest
SubmoduleTest/Program.cs
SubmoduleTest/Program.cs
using System; //using Huawei_Unlock; namespace SubmoduleTest { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); //Test.HW_ALGO_SELECTOR("This_is_a_15_digit_imei_jk"); Console.WriteLine("Made second change to SubmoduleTest"); Console.WriteLine("Made third change to SubmoduleTest"); // I've got a lovely bunch of cocnuts - we don't want this line - its terrible - but we don't know that yet // oh boy, what now? i really like this commit, it looks amazeballs } } }
using System; //using Huawei_Unlock; namespace SubmoduleTest { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); //Test.HW_ALGO_SELECTOR("This_is_a_15_digit_imei_jk"); Console.WriteLine("Made second change to SubmoduleTest"); Console.WriteLine("Made third change to SubmoduleTest"); // I've got a lovely bunch of cocnuts - we don't want this line - its terrible - but we don't know that yet } } }
unlicense
C#
b88cf6e515d9b678ebdb61f90dbb61b59b723ad9
Update AssemblyInfo.cs
apimatic/unirest-net
unirest-net/unirest-net/Properties/AssemblyInfo.cs
unirest-net/unirest-net/Properties/AssemblyInfo.cs
using System.Reflection; // 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("unirest-net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("APIMATIC")] [assembly: AssemblyProduct("unirest-net")] [assembly: AssemblyCopyright("Copyright © APIMATIC 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.27")] [assembly: AssemblyFileVersion("1.0.1.27")]
using System.Reflection; // 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("unirest-net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("APIMATIC")] [assembly: AssemblyProduct("unirest-net")] [assembly: AssemblyCopyright("Copyright © APIMATIC 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.26")] [assembly: AssemblyFileVersion("1.0.1.26")]
mit
C#
b1f70234b1f1e735ca36343b136195f2f2f8bcca
Remove "Equals" and "GetHashCode" methods of "SeasonDataModel"
InfiniteSoul/Azuria
Azuria/Api/v1/DataModels/Info/SeasonDataModel.cs
Azuria/Api/v1/DataModels/Info/SeasonDataModel.cs
using Azuria.Enums.Info; using Newtonsoft.Json; namespace Azuria.Api.v1.DataModels.Info { /// <summary> /// </summary> public class SeasonDataModel : IDataModel { /// <summary> /// </summary> [JsonProperty("id")] public int Id { get; set; } /// <summary> /// </summary> [JsonProperty("season")] public Season Season { get; set; } /// <summary> /// </summary> [JsonProperty("year")] public int Year { get; set; } } }
using Azuria.Enums.Info; using Newtonsoft.Json; namespace Azuria.Api.v1.DataModels.Info { /// <summary> /// </summary> public class SeasonDataModel : IDataModel { /// <summary> /// </summary> [JsonProperty("id")] public int Id { get; set; } /// <summary> /// </summary> [JsonProperty("season")] public Season Season { get; set; } /// <summary> /// </summary> [JsonProperty("year")] public int Year { get; set; } /// <inheritdoc /> public bool Equals(SeasonDataModel other) { return this.Id == other.Id && this.Season == other.Season && this.Year == other.Year; } /// <inheritdoc /> public override int GetHashCode() { unchecked { int hashCode = this.Id; hashCode = hashCode * 397 ^ (int) this.Season; hashCode = hashCode * 397 ^ this.Year; return hashCode; } } } }
mit
C#
588551f8f7babcc160041882a9d7444ca7c86911
Fix typo
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/AirTableSettings.cs
Battery-Commander.Web/Models/AirTableSettings.cs
namespace BatteryCommander.Web.Models { public class AirTableSettings { public string BaseId { get; set; } public string AppKey { get; set; } } }
namespace BatteryCommander.Web.Models { public class AirTableSettings { public string BaseId { get; set; } public string AppKey { get; set; } }
mit
C#
b34f5a52f412d60fb98e6c7ca217f8bf2cab04e4
Remove legacy code
alfredosegundo/BudgetMVC,alfredosegundo/BudgetMVC
BudgetMVC.Model/Business/ContributionBusiness.cs
BudgetMVC.Model/Business/ContributionBusiness.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BudgetMVC.Model.EntityFramework; using BudgetMVC.Model.Entity; namespace BudgetMVC.Model.Business { public class ContributionBusiness : PersistentBusiness<Contribution> { public ContributionBusiness(BudgetContext db) : base(db) { } public IEnumerable<Contribution> GetCurrentContributions(int month, int year) { var query = from contributions in db.Contributions where contributions.InitialDate <= new DateTime(year, month, 1) group contributions by contributions.Contributor into g select g.OrderByDescending(c => c.InitialDate).FirstOrDefault(); return query.ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BudgetMVC.Model.EntityFramework; using BudgetMVC.Model.Entity; namespace BudgetMVC.Model.Business { public class ContributionBusiness : PersistentBusiness<Contribution> { public ContributionBusiness(BudgetContext db) : base(db) { } public IEnumerable<Contribution> GetCurrentContributions(int month, int year) { var query = from contributions in db.Contributions where contributions.InitialDate <= new DateTime(year, month, 1) group contributions by contributions.Contributor into g select g.OrderByDescending(c => c.InitialDate).FirstOrDefault(); return query.ToList(); } } class ContributorComparer : IEqualityComparer<Contribution> { public bool Equals(Contribution x, Contribution y) { return x.ID.Equals(y.ID); } public int GetHashCode(Contribution obj) { return obj.ID.GetHashCode(); } } }
mit
C#
49a789f01e414e7cc356067b009c93456abeb929
implement authentication for user/maininfo
ismaelbelghiti/Tigwi,ismaelbelghiti/Tigwi
Core/Tigwi.API/Controllers/InfoUserController.cs
Core/Tigwi.API/Controllers/InfoUserController.cs
using System.Web.Mvc; using Tigwi.API.Models; using Tigwi.Auth; using Tigwi.Storage.Library; namespace Tigwi.API.Controllers { public class InfoUserController : ApiController { // // GET : /user/maininfo // The user you get the info depend on who you are according to authentication public ActionResult MainInfo() { Answer output; try { // Key must be sent in a cookie var keyCookie = Request.Cookies.Get("key"); if (keyCookie == null) output = new Answer(new Error("No key cookie was sent")); else { var userId = (new ApiKeyAuth(Storage, keyCookie.Value)).Authenticate(); var userInfo = Storage.User.GetInfo(userId); var userToReturn = new User(userInfo, userId); output = new Answer(userToReturn); } } catch (StorageLibException exception) { // Result is an non-empty error XML element output = new Answer(new Error(exception.Code.ToString())); } catch (AuthFailedException) { output = new Answer(new Error("Authentication failed")); } return Serialize(output); } } }
using System; using System.Web.Mvc; using Tigwi.API.Models; using Tigwi.Storage.Library; namespace Tigwi.API.Controllers { public class InfoUserController : ApiController { // TODO : add "need authentication" in specs // TODO : add authentication // // GET : /user/maininfo // The user you get the info depend on who you are according to authentication /* public ActionResult MainInfo() { Answer output; try { var userId = ; var userInfo = Storage.User.GetInfo(userId); var userToReturn = new User(userInfo, userId); output = new Answer(userToReturn); } catch (StorageLibException exception) { // Result is an non-empty error XML element output = new Answer(new Error(exception.Code.ToString())); } return Serialize(output); }*/ } }
bsd-3-clause
C#
fc931daca8f89865c234c79a3df648432ec580fd
Make the caller check the CanExecute state
punker76/Espera,flagbug/Espera
Espera.View/ViewModels/DirectYoutubeViewModel.cs
Espera.View/ViewModels/DirectYoutubeViewModel.cs
using System; using System.Reactive; using System.Reactive.Linq; using System.Threading.Tasks; using Akavache; using Espera.Core; using Espera.Core.Management; using Espera.Core.Settings; using Rareform.Validation; using ReactiveUI; using Splat; namespace Espera.View.ViewModels { /// <summary> /// This ViewModel is used as proxy to add links from YouTube directly /// </summary> public class DirectYoutubeViewModel : SongSourceViewModel<YoutubeSongViewModel> { private readonly IYoutubeSongFinder youtubeSongFinder; public DirectYoutubeViewModel(Library library, CoreSettings coreSettings, Guid accessToken, IYoutubeSongFinder youtubeSongFinder = null) : base(library, coreSettings, accessToken) { this.youtubeSongFinder = youtubeSongFinder ?? new YoutubeSongFinder(Locator.Current.GetService<IBlobCache>(BlobCacheKeys.RequestCacheContract)); } public override DefaultPlaybackAction DefaultPlaybackAction { get { return DefaultPlaybackAction.AddToPlaylist; } } public override ReactiveCommand<Unit> PlayNowCommand { get { throw new NotImplementedException(); } } /// <summary> /// Resolves the given YouTube URL and adds the song to the playlist. /// /// This method will only execute successfuly if the <see cref="SongSourceViewModel{T}.AddToPlaylistCommand"/> command can execute. /// </summary> public async Task AddDirectYoutubeUrlToPlaylist(Uri url, int? targetIndex) { if (url == null) Throw.ArgumentNullException(() => url); YoutubeSong song = await this.youtubeSongFinder.ResolveYoutubeSongFromUrl(url); if (song == null) { this.Log().Error("Could not register direct YouTube url {0}", url.OriginalString); return; } this.SelectedSongs = new[] { new YoutubeSongViewModel(song, () => { throw new NotImplementedException(); }) }; await this.AddToPlaylistCommand.ExecuteAsync(targetIndex); } } }
using System; using System.Reactive; using System.Reactive.Linq; using System.Threading.Tasks; using Akavache; using Espera.Core; using Espera.Core.Management; using Espera.Core.Settings; using Rareform.Validation; using ReactiveUI; using Splat; namespace Espera.View.ViewModels { /// <summary> /// This ViewModel is used as proxy to add links from YouTube directly /// </summary> public class DirectYoutubeViewModel : SongSourceViewModel<YoutubeSongViewModel> { private readonly IYoutubeSongFinder youtubeSongFinder; public DirectYoutubeViewModel(Library library, CoreSettings coreSettings, Guid accessToken, IYoutubeSongFinder youtubeSongFinder = null) : base(library, coreSettings, accessToken) { this.youtubeSongFinder = youtubeSongFinder ?? new YoutubeSongFinder(Locator.Current.GetService<IBlobCache>(BlobCacheKeys.RequestCacheContract)); } public override DefaultPlaybackAction DefaultPlaybackAction { get { return DefaultPlaybackAction.AddToPlaylist; } } public override ReactiveCommand<Unit> PlayNowCommand { get { throw new NotImplementedException(); } } /// <summary> /// Resolves the given YouTube URL and adds the song to the playlist. /// /// This method will only execute if the <see cref="SongSourceViewModel{T}.AddToPlaylistCommand"/> command can execute. /// </summary> public async Task AddDirectYoutubeUrlToPlaylist(Uri url, int? targetIndex) { if (url == null) Throw.ArgumentNullException(() => url); if (!this.AddToPlaylistCommand.CanExecute(null)) return; YoutubeSong song = await this.youtubeSongFinder.ResolveYoutubeSongFromUrl(url); if (song == null) { this.Log().Error("Could not register direct YouTube url {0}", url.OriginalString); return; } this.SelectedSongs = new[] { new YoutubeSongViewModel(song, () => { throw new NotImplementedException(); }) }; await this.AddToPlaylistCommand.ExecuteAsync(targetIndex); } } }
mit
C#
f292ce3757d8cb19d969f119428508582c0ccbe4
Add return time
CVBDL/RALibraryServer
RaLibrary/Models/BorrowLog.cs
RaLibrary/Models/BorrowLog.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace RaLibrary.Models { public class BorrowLog { public int Id { get; set; } public int F_BookID { get; set; } [ForeignKey("F_BookID")] public virtual Book Book { get; set; } [Required] [MaxLength(50)] public string Borrower { get; set; } [Required] public DateTime BorrowTime { get; set; } public DateTime ReturnTime { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace RaLibrary.Models { public class BorrowLog { public int Id { get; set; } public int F_BookID { get; set; } [ForeignKey("F_BookID")] public virtual Book Book { get; set; } [Required] public string Borrower { get; set; } [Required] public DateTime BorrowTime { get; set; } } }
mit
C#
5cf9e10efd1664f4ec986d8d5e6e3c13ef8814bc
Update CustomCollectionListFilter.cs
clement911/ShopifySharp,nozzlegear/ShopifySharp
ShopifySharp/Filters/CustomCollectionListFilter.cs
ShopifySharp/Filters/CustomCollectionListFilter.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace ShopifySharp.Filters { /// <summary> /// Options for filtering custom collection lists. /// </summary> public class CustomCollectionListFilter : ListFilter<CustomCollection> { /// <summary> /// Restrict results to after the specified ID. /// </summary> [JsonProperty("since_id")] public long? SinceId { get; set; } /// <summary> /// Show smart collections with given title /// </summary> [JsonProperty("title")] public string Title { get; set; } /// <summary> /// Show smart collections that includes given product /// </summary> [JsonProperty("product_id")] public long? ProductId { get; set; } /// <summary> /// Filter by smart collection handle /// </summary> [JsonProperty("handle")] public string Handle { get; set; } [JsonProperty("ids")] public IEnumerable<long> Ids { get; set; } [JsonProperty("updated_at_min")] public DateTimeOffset? UpdatedAtMin { get; set; } [JsonProperty("updated_at_max")] public DateTimeOffset? UpdatedAtMax { get; set; } [JsonProperty("published_at_min")] public DateTimeOffset? PublishedAtMin { get; set; } [JsonProperty("published_at_max")] public DateTimeOffset? PublishedAtMax { get; set; } [JsonProperty("published_status")] public string PublishedStatus { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace ShopifySharp.Filters { /// <summary> /// Options for filtering custom collection lists. /// </summary> public class CustomCollectionListFilter : ListFilter<CustomCollection> { /// <summary> /// Restrict results to after the specified ID. /// </summary> [JsonProperty("since_id")] public long? SinceId { get; set; } /// <summary> /// Show smart collections with given title /// </summary> [JsonProperty("title")] public string Title { get; set; } /// <summary> /// Show smart collections that includes given product /// </summary> [JsonProperty("product_id")] public long? ProductId { get; set; } /// <summary> /// Filter by smart collection handle /// </summary> [JsonProperty("handle")] public string Handle { get; set; } [JsonProperty("ids")] public IEnumerable<long> Ids { get; set; } [JsonProperty("updated_at_min")] public DateTimeOffset? UpdatedAtMin { get; set; } [JsonProperty("updated_at_min")] public DateTimeOffset? UpdatedAtMax { get; set; } [JsonProperty("published_at_min")] public DateTimeOffset? PublishedAtMin { get; set; } [JsonProperty("published_at_min")] public DateTimeOffset? PublishedAtMax { get; set; } [JsonProperty("published_status")] public string PublishedStatus { get; set; } } }
mit
C#
06d01e46cd28556e7a5354787098e1c698ed062b
Include the update event
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Commands/UpdateSUTARequest.cs
Battery-Commander.Web/Commands/UpdateSUTARequest.cs
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using BatteryCommander.Web.Queries; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Commands { public class UpdateSUTARequest : IRequest { [FromRoute] public int Id { get; set; } [FromForm] public Detail Body { get; set; } public class Detail { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public String Reasoning { get; set; } public String MitigationPlan { get; set; } } private class Handler : AsyncRequestHandler<UpdateSUTARequest> { private readonly Database db; private readonly IMediator dispatcher; public Handler(Database db, IMediator dispatcher) { this.db = db; this.dispatcher = dispatcher; } protected override async Task Handle(UpdateSUTARequest request, CancellationToken cancellationToken) { var current_user = await dispatcher.Send(new GetCurrentUser { }); var suta = await db .SUTAs .Where(s => s.Id == request.Id) .SingleOrDefaultAsync(cancellationToken); suta.StartDate = request.Body.StartDate; suta.EndDate = request.Body.EndDate; suta.Reasoning = request.Body.Reasoning; suta.MitigationPlan = request.Body.MitigationPlan; suta.Events.Add(new SUTA.Event { Author = $"{current_user}", Message = "Request Updated" }); await db.SaveChangesAsync(cancellationToken); } } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Commands { public class UpdateSUTARequest : IRequest { [FromRoute] public int Id { get; set; } [FromForm] public Detail Body { get; set; } public class Detail { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public String Reasoning { get; set; } public String MitigationPlan { get; set; } } private class Handler : AsyncRequestHandler<UpdateSUTARequest> { private readonly Database db; public Handler(Database db) { this.db = db; } protected override async Task Handle(UpdateSUTARequest request, CancellationToken cancellationToken) { var suta = await db .SUTAs .Where(s => s.Id == request.Id) .SingleOrDefaultAsync(cancellationToken); suta.StartDate = request.Body.StartDate; suta.EndDate = request.Body.EndDate; suta.Reasoning = request.Body.Reasoning; suta.MitigationPlan = request.Body.MitigationPlan; await db.SaveChangesAsync(cancellationToken); } } } }
mit
C#
0a84b75fd9036ab824c7a93f0c895da77cb6cae7
Add Apache 2.0 license header.
douglaswth/ssh-handler
ssh-handler/ssh-handler.cs
ssh-handler/ssh-handler.cs
// SSH Handler // // Douglas Thrift // // ssh-handler.cs /* Copyright 2013 Douglas Thrift * * 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.Diagnostics; using System.Text; public class SshHandler { public static void Main(string[] args) { foreach (string arg in args) Ssh(arg); } private static void Ssh(string arg) { System.Uri uri = new System.Uri(arg); string user = null, password = null; if (uri.UserInfo.Length != 0) { string[] userInfo = uri.UserInfo.Split(new char[] { ':' }, 2); user = userInfo[0]; if (userInfo.Length == 2) password = userInfo[1]; } StringBuilder args = new StringBuilder(); if (password != null) args.Append("-pw ").Append(password).Append(' '); if (user != null) args.Append(user).Append('@'); args.Append(uri.Host); if (uri.Port != -1) args.Append(':').Append(uri.Port); Process.Start(@"C:\Program Files (x86)\PuTTY\putty.exe", args.ToString()); } }
// SSH Handler // // Douglas Thrift // // ssh-handler using System.Diagnostics; using System.Text; public class SshHandler { public static void Main(string[] args) { foreach (string arg in args) Ssh(arg); } private static void Ssh(string arg) { System.Uri uri = new System.Uri(arg); string user = null, password = null; if (uri.UserInfo.Length != 0) { string[] userInfo = uri.UserInfo.Split(new char[] { ':' }, 2); user = userInfo[0]; if (userInfo.Length == 2) password = userInfo[1]; } StringBuilder args = new StringBuilder(); if (password != null) args.Append("-pw ").Append(password).Append(' '); if (user != null) args.Append(user).Append('@'); args.Append(uri.Host); if (uri.Port != -1) args.Append(':').Append(uri.Port); Process.Start(@"C:\Program Files (x86)\PuTTY\putty.exe", args.ToString()); } }
apache-2.0
C#
ff5150a14d152242026cdd6be462088f2a15ad03
Fix typo in IMultiplayerClient xmldoc
peppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu
osu.Game/Online/RealtimeMultiplayer/IMultiplayerClient.cs
osu.Game/Online/RealtimeMultiplayer/IMultiplayerClient.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 a multiplayer client instance. /// </summary> public interface IMultiplayerClient { /// <summary> /// Signals that the room has changed state. /// </summary> /// <param name="state">The state of the room.</param> Task RoomStateChanged(MultiplayerRoomState state); /// <summary> /// Signals that a user has joined the room. /// </summary> /// <param name="user">The user.</param> Task UserJoined(MultiplayerRoomUser user); /// <summary> /// Signals that a user has left the room. /// </summary> /// <param name="user">The user.</param> Task UserLeft(MultiplayerRoomUser user); /// <summary> /// Signal that the host of the room has changed. /// </summary> /// <param name="userId">The user ID of the new host.</param> Task HostChanged(long userId); /// <summary> /// Signals that the settings for this room have changed. /// </summary> /// <param name="newSettings">The updated room settings.</param> Task SettingsChanged(MultiplayerRoomSettings newSettings); /// <summary> /// Signals that a user in this room changed their state. /// </summary> /// <param name="userId">The ID of the user performing a state change.</param> /// <param name="state">The new state of the user.</param> Task UserStateChanged(long userId, MultiplayerUserState state); /// <summary> /// Signals that a match is to be started. This will *only* be sent to clients which are to begin loading at this point. /// </summary> Task LoadRequested(); /// <summary> /// Signals that a match has started. All users in the <see cref="MultiplayerUserState.Loaded"/> state should begin gameplay as soon as possible. /// </summary> Task MatchStarted(); /// <summary> /// Signals that the match has ended, all players have finished and results are ready to be displayed. /// </summary> Task ResultsReady(); } }
// 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 a multiplayer client instance. /// </summary> public interface IMultiplayerClient { /// <summary> /// Signals that the room has changed state. /// </summary> /// <param name="state">The state of the room.</param> Task RoomStateChanged(MultiplayerRoomState state); /// <summary> /// Signals that a user has joined the room. /// </summary> /// <param name="user">The user.</param> Task UserJoined(MultiplayerRoomUser user); /// <summary> /// Signals that a user has left the room. /// </summary> /// <param name="user">The user.</param> Task UserLeft(MultiplayerRoomUser user); /// <summary> /// Signal that the host of the room has changed. /// </summary> /// <param name="userId">The user ID of the new host.</param> Task HostChanged(long userId); /// <summary> /// Signals that the settings for this room have changed. /// </summary> /// <param name="newSettings">The updated room settings.</param> Task SettingsChanged(MultiplayerRoomSettings newSettings); /// <summary> /// Signals that a user in this room changed their state. /// </summary> /// <param name="userId">The ID of the user performing a state change.</param> /// <param name="state">The new state of the user.</param> Task UserStateChanged(long userId, MultiplayerUserState state); /// <summary> /// Signals that a match is to be started. This will *only* be sent to clients which are to begin loading at this point. /// </summary> Task LoadRequested(); /// <summary> /// Signals that a match has started. All user in the <see cref="MultiplayerUserState.Loaded"/> state should begin gameplay as soon as possible. /// </summary> Task MatchStarted(); /// <summary> /// Signals that the match has ended, all players have finished and results are ready to be displayed. /// </summary> Task ResultsReady(); } }
mit
C#
3d98faad3c7a8527fed6efc948fdef8089ceb412
Update JobOpportunityController.cs
ncarrasco/empleo-dot-net,luis-ramirez/empleo-dot-net,ncarrasco/empleo-dot-net,claudiosanchez/empleo-dot-net,luis-ramirez/empleo-dot-net,eatskolnikov/empleo-dot-net,ncarrasco/empleo-dot-net,RaulMonteroC/empleo-dot-net,claudiosanchez/empleo-dot-net,eatskolnikov/empleo-dot-net,luis-ramirez/empleo-dot-net,developersdo/empleo-dot-net,EfrainReyes/empleo-dot-net,Ronald2/empleo-dot-net,developersdo/empleo-dot-net,developersdo/empleo-dot-net,RaulMonteroC/empleo-dot-net,RaulMonteroC/empleo-dot-net,eatskolnikov/empleo-dot-net,EfrainReyes/empleo-dot-net,Ronald2/empleo-dot-net,EfrainReyes/empleo-dot-net,claudiosanchez/empleo-dot-net,Ronald2/empleo-dot-net
EmpleoDotNet/Controllers/JobOpportunityController.cs
EmpleoDotNet/Controllers/JobOpportunityController.cs
using System.Linq; using System.Web.Mvc; using EmpleoDotNet.Models; using Microsoft.Owin.Security.Provider; namespace EmpleoDotNet.Controllers { public class JobOpportunityController : Controller { private readonly Database _databaseContext; public JobOpportunityController() { _databaseContext = new Database(); } // GET: Vacantes public ActionResult Index() { var vmJobList = _databaseContext.JobOpportunities .OrderByDescending(e => e.Created) .ToList(); if (!vmJobList.Any()) return RedirectToAction("Index", "Home"); return View(vmJobList); } public ActionResult Detail(int? id) { if (!id.HasValue) return View("Index"); var vm = _databaseContext.JobOpportunities .FirstOrDefault(d => d.Id == id); return vm == null ? View("Index") : View("Detail", vm); } } }
using System.Linq; using System.Web.Mvc; using EmpleoDotNet.Models; using Microsoft.Owin.Security.Provider; namespace EmpleoDotNet.Controllers { public class JobOpportunityController : Controller { private readonly Database _databaseContext; public JobOpportunityController() { _databaseContext = new Database(); } // GET: Vacantes public ActionResult Index() { var vmJobList = _databaseContext.JobOpportunities .OrderByDescending(e => e.Created) .ToList(); if (!vmJobList.Any()) return RedirectToAction("Index", "Home"); return View(vmJobList.ToList()); } public ActionResult Detail(int? id) { if (!id.HasValue) return View("Index"); var vm = _databaseContext.JobOpportunities .FirstOrDefault(d => d.Id == id); return vm == null ? View("Index") : View("Detail", vm); } } }
unlicense
C#
ba1593d15133616f02fbf14f387204be46a58c6a
Fix faulting CurrentBeatsTime calculation
HelloKitty/Booma.Proxy
src/Booma.Proxy.Client.Unity.Common/Services/Time/TimeService.cs
src/Booma.Proxy.Client.Unity.Common/Services/Time/TimeService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// Static time functions and features. /// </summary> public static class TimeService { private static double _startBeatsTime; private static float unitySecondsStartTime; private static readonly object syncObj = new object(); /// <summary> /// The starting beats time. /// </summary> public static double StartBeatsTime { get { lock(syncObj) return _startBeatsTime; } set { lock(syncObj) { unitySecondsStartTime = UnityEngine.Time.realtimeSinceStartup; _startBeatsTime = value; } } } //See: https://en.wikipedia.org/wiki/Swatch_Internet_Time#Calculation_from_UTC.2B1 /// <summary> /// The current time in Beats. /// (The start time + time since) /// </summary> public static double CurrentBeatsTime => StartBeatsTime + ((UnityEngine.Time.realtimeSinceStartup - unitySecondsStartTime) / 86.4f); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// Static time functions and features. /// </summary> public static class TimeService { private static double _startBeatsTime; private static float unitySecondsStartTime; private static readonly object syncObj = new object(); /// <summary> /// The starting beats time. /// </summary> public static double StartBeatsTime { get { lock(syncObj) return _startBeatsTime; } set { lock(syncObj) { unitySecondsStartTime = UnityEngine.Time.realtimeSinceStartup; _startBeatsTime = value; } } } //See: https://en.wikipedia.org/wiki/Swatch_Internet_Time#Calculation_from_UTC.2B1 /// <summary> /// The current time in Beats. /// (The start time + time since) /// </summary> public static double CurrentBeatsTime => StartBeatsTime + ((UnityEngine.Time.realtimeSinceStartup - unitySecondsStartTime) / 84.6f); } }
agpl-3.0
C#
e639d5c275f264a7b325a0f68268b8545b52973f
Update to deal with breaking Features change in httpabstraction
Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype
src/Glimpse.Server.Web/Framework/RequestAuthorizerAllowRemote.cs
src/Glimpse.Server.Web/Framework/RequestAuthorizerAllowRemote.cs
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Features; namespace Glimpse.Server.Web { public class RequestAuthorizerAllowRemote : IRequestAuthorizer { private readonly IAllowRemoteProvider _allowRemoteProvider; public RequestAuthorizerAllowRemote(IAllowRemoteProvider allowRemoteProvider) { _allowRemoteProvider = allowRemoteProvider; } public bool AllowUser(HttpContext context) { var connectionFeature = context.Features.Get<IHttpConnectionFeature>(); return _allowRemoteProvider.AllowRemote || (connectionFeature != null && connectionFeature.IsLocal); } } }
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Features; namespace Glimpse.Server.Web { public class RequestAuthorizerAllowRemote : IRequestAuthorizer { private readonly IAllowRemoteProvider _allowRemoteProvider; public RequestAuthorizerAllowRemote(IAllowRemoteProvider allowRemoteProvider) { _allowRemoteProvider = allowRemoteProvider; } public bool AllowUser(HttpContext context) { var connectionFeature = context.GetFeature<IHttpConnectionFeature>(); return _allowRemoteProvider.AllowRemote || (connectionFeature != null && connectionFeature.IsLocal); } } }
mit
C#
946b30ec6d6dea18343da5b692a5e3ae41aa498c
Hide Android navigation bar.
Noxalus/Xmas-Hell
Xmas-Hell/Xmas-Hell-Android/XmasHellActivity.cs
Xmas-Hell/Xmas-Hell-Android/XmasHellActivity.cs
using Android.App; using Android.Content.PM; using Android.OS; using Android.Views; namespace Xmas_Hell_Android { [Activity(Label = "Xmas Hell" , MainLauncher = true , Icon = "@drawable/icon" , Theme = "@style/Theme.Splash" , AlwaysRetainTaskState = true , LaunchMode = Android.Content.PM.LaunchMode.SingleInstance , ScreenOrientation = ScreenOrientation.SensorPortrait , ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden | ConfigChanges.ScreenSize)] public class XmasHellActivity : Microsoft.Xna.Framework.AndroidGameActivity, View.IOnSystemUiVisibilityChangeListener { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); var g = new XmasHell.XmasHell(this); View vw = (View)g.Services.GetService(typeof(View)); SetContentView(vw); g.Run(); vw.SetOnSystemUiVisibilityChangeListener(this); HideSystemUi(); } public void OnSystemUiVisibilityChange(StatusBarVisibility visibility) { HideSystemUi(); } private void HideSystemUi() { SystemUiFlags flags = SystemUiFlags.HideNavigation | SystemUiFlags.Fullscreen | SystemUiFlags.ImmersiveSticky; this.Window.DecorView.SystemUiVisibility = (StatusBarVisibility)flags; } } }
using Android.App; using Android.Content.PM; using Android.OS; using Android.Views; namespace Xmas_Hell_Android { [Activity(Label = "Xmas Hell" , MainLauncher = true , Icon = "@drawable/icon" , Theme = "@style/Theme.Splash" , AlwaysRetainTaskState = true , LaunchMode = Android.Content.PM.LaunchMode.SingleInstance , ScreenOrientation = ScreenOrientation.SensorPortrait , ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden | ConfigChanges.ScreenSize)] public class XmasHellActivity : Microsoft.Xna.Framework.AndroidGameActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); var g = new XmasHell.XmasHell(this); SetContentView((View)g.Services.GetService(typeof(View))); g.Run(); } } }
mit
C#
f9c41f99e36f90db81938db72e7b5a67ffd27ab9
Allow for changing the weight of built-in and 3rd party dashboards (#8628)
umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS
src/Umbraco.Web/Dashboards/DashboardCollectionBuilder.cs
src/Umbraco.Web/Dashboards/DashboardCollectionBuilder.cs
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Dashboards; using Umbraco.Core.Manifest; namespace Umbraco.Web.Dashboards { public class DashboardCollectionBuilder : WeightedCollectionBuilderBase<DashboardCollectionBuilder, DashboardCollection, IDashboard> { private Dictionary<Type, int> _customWeights = new Dictionary<Type, int>(); protected override DashboardCollectionBuilder This => this; /// <summary> /// Changes the default weight of a dashboard /// </summary> /// <typeparam name="T">The type of dashboard</typeparam> /// <param name="weight">The new dashboard weight</param> /// <returns></returns> public DashboardCollectionBuilder SetWeight<T>(int weight) where T : IDashboard { _customWeights[typeof(T)] = weight; return this; } protected override IEnumerable<IDashboard> CreateItems(IFactory factory) { // get the manifest parser just-in-time - injecting it in the ctor would mean that // simply getting the builder in order to configure the collection, would require // its dependencies too, and that can create cycles or other oddities var manifestParser = factory.GetInstance<ManifestParser>(); var dashboardSections = Merge(base.CreateItems(factory), manifestParser.Manifest.Dashboards); return dashboardSections; } private IEnumerable<IDashboard> Merge(IEnumerable<IDashboard> dashboardsFromCode, IReadOnlyList<ManifestDashboard> dashboardFromManifest) { return dashboardsFromCode.Concat(dashboardFromManifest) .Where(x => !string.IsNullOrEmpty(x.Alias)) .OrderBy(GetWeight); } private int GetWeight(IDashboard dashboard) { var typeOfDashboard = dashboard.GetType(); if(_customWeights.ContainsKey(typeOfDashboard)) { return _customWeights[typeOfDashboard]; } switch (dashboard) { case ManifestDashboard manifestDashboardDefinition: return manifestDashboardDefinition.Weight; default: var weightAttribute = dashboard.GetType().GetCustomAttribute<WeightAttribute>(false); return weightAttribute?.Weight ?? DefaultWeight; } } } }
using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Dashboards; using Umbraco.Core.Manifest; namespace Umbraco.Web.Dashboards { public class DashboardCollectionBuilder : WeightedCollectionBuilderBase<DashboardCollectionBuilder, DashboardCollection, IDashboard> { protected override DashboardCollectionBuilder This => this; protected override IEnumerable<IDashboard> CreateItems(IFactory factory) { // get the manifest parser just-in-time - injecting it in the ctor would mean that // simply getting the builder in order to configure the collection, would require // its dependencies too, and that can create cycles or other oddities var manifestParser = factory.GetInstance<ManifestParser>(); var dashboardSections = Merge(base.CreateItems(factory), manifestParser.Manifest.Dashboards); return dashboardSections; } private IEnumerable<IDashboard> Merge(IEnumerable<IDashboard> dashboardsFromCode, IReadOnlyList<ManifestDashboard> dashboardFromManifest) { return dashboardsFromCode.Concat(dashboardFromManifest) .Where(x => !string.IsNullOrEmpty(x.Alias)) .OrderBy(GetWeight); } private int GetWeight(IDashboard dashboard) { switch (dashboard) { case ManifestDashboard manifestDashboardDefinition: return manifestDashboardDefinition.Weight; default: var weightAttribute = dashboard.GetType().GetCustomAttribute<WeightAttribute>(false); return weightAttribute?.Weight ?? DefaultWeight; } } } }
mit
C#
ac59384537e8f670437307f450771b58dfb1e751
Make a little section of code easier to debug
Vector241-Eric/ZBuildLights,mhinze/ZBuildLights,mhinze/ZBuildLights,Vector241-Eric/ZBuildLights,Vector241-Eric/ZBuildLights,mhinze/ZBuildLights
src/ZBuildLights.Core/Services/UnassignedLightService.cs
src/ZBuildLights.Core/Services/UnassignedLightService.cs
using System.Linq; using ZBuildLights.Core.Models; namespace ZBuildLights.Core.Services { public class UnassignedLightService : IUnassignedLightService { private readonly IZWaveNetwork _network; public UnassignedLightService(IZWaveNetwork network) { _network = network; } public void SetUnassignedLights(MasterModel masterModel) { var allLights = masterModel.AllLights; var allSwitches = _network.GetAllSwitches(); var switchesAlreadyInAProject = allSwitches .Where(sw => allLights.Any(l => { var lightIdentity = l.ZWaveIdentity; var switchIdentity = sw.ZWaveIdentity; return lightIdentity.Equals(switchIdentity); }) ).ToArray(); var newSwitches = allSwitches.Except(switchesAlreadyInAProject); var newLights = newSwitches.Select(x => new Light(x.ZWaveIdentity)).ToArray(); masterModel.AddUnassignedLights(newLights); } } }
using System.Linq; using ZBuildLights.Core.Models; namespace ZBuildLights.Core.Services { public class UnassignedLightService : IUnassignedLightService { private readonly IZWaveNetwork _network; public UnassignedLightService(IZWaveNetwork network) { _network = network; } public void SetUnassignedLights(MasterModel masterModel) { var allLights = masterModel.AllLights; var allSwitches = _network.GetAllSwitches(); var switchesAlreadyInAProject = allSwitches .Where(sw => allLights.Any(l =>l.ZWaveIdentity.Equals(sw.ZWaveIdentity)) ).ToArray(); var newSwitches = allSwitches.Except(switchesAlreadyInAProject); var newLights = newSwitches.Select(x => new Light(x.ZWaveIdentity)).ToArray(); masterModel.AddUnassignedLights(newLights); } } }
mit
C#
c6e2fb393eac9e9eb1d96cb3f6136b0382e1429b
clean up
asipe/SupaCharge
src/SupaCharge.Core/ConfigurationWrapper/ConfigurationWrapper.cs
src/SupaCharge.Core/ConfigurationWrapper/ConfigurationWrapper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using SupaCharge.Core.Converter; namespace SupaCharge.Core.ConfigurationWrapper { public class ConfigurationWrapper { public bool Contains(string key) { return (ConfigurationManager.AppSettings[key] != null); } public T Get<T>(string key) { return _Converter.Get<T>(ConfigurationManager.AppSettings[key]); } public T Get<T>(string key, T defValue) { return ConfigurationManager.AppSettings[key] == null ? defValue : _Converter.Get<T>(ConfigurationManager.AppSettings[key]); } private static readonly ValueConverter _Converter = new ValueConverter(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using SupaCharge.Core.Converter; namespace SupaCharge.Core.ConfigurationWrapper { public class ConfigurationWrapper { public bool Contains(string key) { return (ConfigurationManager.AppSettings[key] != null); } public T Get<T>(string key) { return _Converter.Get<T>(ConfigurationManager.AppSettings[key]); } public T Get<T>(string key, T defValue) { return ConfigurationManager.AppSettings[key] == null ? defValue : _Converter.Get<T>(ConfigurationManager.AppSettings[key]); } private static readonly ValueConverter _Converter = new ValueConverter(); } }
mit
C#
393e79084d48eaa5de1925e6fd9d8229c14da049
Add FromString method for loading ResourceHandler from string
Octopus-ITSM/CefSharp,rover886/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,NumbersInternational/CefSharp,illfang/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,dga711/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,jamespearce2006/CefSharp,illfang/CefSharp,battewr/CefSharp,ITGlobal/CefSharp,twxstar/CefSharp,rlmcneary2/CefSharp,Octopus-ITSM/CefSharp,dga711/CefSharp,haozhouxu/CefSharp,NumbersInternational/CefSharp,AJDev77/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,battewr/CefSharp,joshvera/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,AJDev77/CefSharp,zhangjingpu/CefSharp,Octopus-ITSM/CefSharp,windygu/CefSharp,zhangjingpu/CefSharp,illfang/CefSharp,twxstar/CefSharp,yoder/CefSharp,joshvera/CefSharp,dga711/CefSharp,joshvera/CefSharp,haozhouxu/CefSharp,jamespearce2006/CefSharp,wangzheng888520/CefSharp,AJDev77/CefSharp,VioletLife/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,windygu/CefSharp,gregmartinhtc/CefSharp,windygu/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,ruisebastiao/CefSharp,Haraguroicha/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,dga711/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,rover886/CefSharp,rover886/CefSharp,Livit/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,NumbersInternational/CefSharp,battewr/CefSharp,Livit/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,yoder/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,yoder/CefSharp,wangzheng888520/CefSharp
CefSharp/ResourceHandler.cs
CefSharp/ResourceHandler.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; using System.IO; using System.Text; namespace CefSharp { public class ResourceHandler { public string MimeType { get; set; } public Stream Stream { get; set; } public int StatusCode { get; set; } public string StatusText { get; set; } public NameValueCollection Headers { get; set; } public ResourceHandler() { StatusCode = 200; StatusText = "OK"; } public static ResourceHandler FromFileName(string fileName) { return new ResourceHandler { Stream = File.OpenRead(fileName) }; } public static ResourceHandler FromString(string text) { return new ResourceHandler { Stream = new MemoryStream(Encoding.UTF8.GetBytes(text)) }; } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; using System.IO; namespace CefSharp { public class ResourceHandler { public string MimeType { get; set; } public Stream Stream { get; set; } public int StatusCode { get; set; } public string StatusText { get; set; } public NameValueCollection Headers { get; set; } public ResourceHandler() { StatusCode = 200; StatusText = "OK"; } public static ResourceHandler FromFileName(string fileName) { return new ResourceHandler { Stream = File.OpenRead(fileName) }; } } }
bsd-3-clause
C#
955027f531a3ae1987395206c09e989bbe00d40f
Resolve #1156 -- Fix Mislabeled PrimaryAbilityResourceTypes (#1150)
LeagueSandbox/GameServer
GameServerCore/Enums/PrimaryAbilityResourceType.cs
GameServerCore/Enums/PrimaryAbilityResourceType.cs
namespace GameServerCore.Enums { public enum PrimaryAbilityResourceType : byte { MANA = 0, Energy = 1, None = 2, Shield = 3, Battlefury = 4, Dragonfury = 5, Rage = 6, Heat = 7, Ferocity = 8, BloodWell = 9, Wind = 10, Gnarfury = 11 } }
namespace GameServerCore.Enums { public enum PrimaryAbilityResourceType : byte { MANA = 0, ENERGY = 1, NONE = 2, SHIELD = 3, BATTLE_FURY = 4, DRAGON_FURY = 5, RAGE = 6, HEAT = 7, FEROCITY = 8, BLOOD_WELL = 9, WIND = 10, OTHER = 11 } }
agpl-3.0
C#
5e1e89115bb59ebc68f4c1127019304f275dbe3d
comment out debug borders for results
Pathoschild/StardewMods
LookupAnything/Components/SearchResultComponent.cs
LookupAnything/Components/SearchResultComponent.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; using StardewValley.Menus; namespace Pathoschild.LookupAnything.Components { class SearchResultComponent { public SearchResult Result { get; private set; } private ClickableComponent panel; private int Width = 500; private int Height = 70; public SearchResultComponent(SearchResult result) { this.panel = new ClickableComponent(new Rectangle(0, 0, this.Width, this.Height), result.Name); this.Result = result; } public bool containsPoint(int x, int y) { return this.panel.containsPoint(x, y); } public Vector2 draw(SpriteBatch contentBatch, Vector2 position, float width) { contentBatch.DrawTextBlock(Game1.smallFont, $"({this.Result.TargetType}) {this.Result.Name}", position + new Vector2(70, this.Height / 2), width); contentBatch.DrawLine(position.X, position.Y, new Vector2(Width, 1), Color.Black); //contentBatch.DrawLine(position.X, position.Y, new Vector2(1, Height), Color.Red); //contentBatch.DrawLine(position.X + Width, position.Y, new Vector2(1, Height), Color.Pink); //contentBatch.DrawLine(position.X, position.Y + Height, new Vector2(Width, 1), Color.Green); this.panel = new ClickableComponent(new Rectangle((int)position.X, (int)position.Y, this.Width, this.Height), this.Result.Name); return new Vector2(this.Width, this.Height); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; using StardewValley.Menus; namespace Pathoschild.LookupAnything.Components { class SearchResultComponent { public SearchResult Result { get; private set; } private ClickableComponent panel; private int Width = 500; private int Height = 70; public SearchResultComponent(SearchResult result) { this.panel = new ClickableComponent(new Rectangle(0, 0, this.Width, this.Height), result.Name); this.Result = result; } public bool containsPoint(int x, int y) { return this.panel.containsPoint(x, y); } public Vector2 draw(SpriteBatch contentBatch, Vector2 position, float width) { contentBatch.DrawTextBlock(Game1.smallFont, $"({this.Result.TargetType}) {this.Result.Name}", position + new Vector2(70, this.Height / 2), width); contentBatch.DrawLine(position.X, position.Y, new Vector2(Width, 1), Color.Blue); contentBatch.DrawLine(position.X, position.Y, new Vector2(1, Height), Color.Red); contentBatch.DrawLine(position.X + Width, position.Y, new Vector2(1, Height), Color.Pink); contentBatch.DrawLine(position.X, position.Y + Height, new Vector2(Width, 1), Color.Green); this.panel = new ClickableComponent(new Rectangle((int)position.X, (int)position.Y, this.Width, this.Height), this.Result.Name); return new Vector2(this.Width, this.Height); } } }
mit
C#
3fbf4bafaf3e143ff2f2480221336c3d4ec46575
Bump version to 0.4
mganss/XmlSchemaClassGenerator,mganss/XmlSchemaClassGenerator
XmlSchemaClassGenerator/Properties/AssemblyInfo.cs
XmlSchemaClassGenerator/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("XmlSchemaClassGenerator")] [assembly: AssemblyDescription("A console program and library to generate XmlSerializer compatible C# classes from XML Schema files.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Ganss")] [assembly: AssemblyProduct("XmlSchemaClassGenerator")] [assembly: AssemblyCopyright("Copyright © 2013-2014 Michael Ganss")] [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("de5a48df-c5c0-4efc-9516-264d4e76d2a9")] // 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.4.*")]
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("XmlSchemaClassGenerator")] [assembly: AssemblyDescription("A console program and library to generate XmlSerializer compatible C# classes from XML Schema files.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Ganss")] [assembly: AssemblyProduct("XmlSchemaClassGenerator")] [assembly: AssemblyCopyright("Copyright © 2013-2014 Michael Ganss")] [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("de5a48df-c5c0-4efc-9516-264d4e76d2a9")] // 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.3.*")]
apache-2.0
C#
f943d8debdbd3adb4d926901dbebc5ddbee98499
add dir to ex message
vorou/play.NET,vorou/play.NET
Src/playNET/FileLocator.cs
Src/playNET/FileLocator.cs
using System.Collections.Generic; using System.IO; using System.Linq; namespace playNET { public class FileLocator : IFileLocator { private readonly string directory; public FileLocator(string directory) { if (!Directory.EnumerateFiles(directory, "*.mp3").Any()) throw new FileNotFoundException("Directory contains no mp3s: " + directory); this.directory = directory; } public IEnumerable<string> FindTracks() { return Directory.GetFiles(directory, "*.mp3"); } } }
using System.Collections.Generic; using System.IO; using System.Linq; namespace playNET { public class FileLocator : IFileLocator { private readonly string directory; public FileLocator(string directory) { if (!Directory.EnumerateFiles(directory, "*.mp3").Any()) throw new FileNotFoundException(); this.directory = directory; } public IEnumerable<string> FindTracks() { return Directory.GetFiles(directory, "*.mp3"); } } }
mit
C#
fe8e405362f826afccb318d7db90b586f864e4a8
clean up code
IUMDPI/IUMediaHelperApps
Packager.Test/Extensions/StringExtensionTests.cs
Packager.Test/Extensions/StringExtensionTests.cs
using NUnit.Framework; using Packager.Extensions; namespace Packager.Test.Extensions { [TestFixture] public class StringExtensionTests { [TestCase(@"testing """, @"testing \""")] public void NormalizeForCommandLineShouldEscapeQuotesCorrectly(string original, string expected) { var result = original.NormalizeForCommandLine(); Assert.That(result, Is.EqualTo(expected)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Packager.Extensions; namespace Packager.Test.Extensions { [TestFixture] public class StringExtensionTests { [TestCase(@"testing """, @"testing \""")] public void NormalizeForCommandLineShouldEscapeQuotesCorrectly(string original, string expected) { var result = original.NormalizeForCommandLine(); Assert.That(result, Is.EqualTo(expected)); } } }
apache-2.0
C#
54b0d9026c055e9397d5c11c8bb2fb369d687fe8
Remove unused namespaces
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
Modix.Services/StackExchange/StackExchangeService.cs
Modix.Services/StackExchange/StackExchangeService.cs
using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Modix.Services.StackExchange { public class StackExchangeService { private string _ApiReferenceUrl = $"http://api.stackexchange.com/2.2/search/advanced" + "?key={0}" + $"&order=desc" + $"&sort=votes" + $"&filter=default"; public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags) { _ApiReferenceUrl = string.Format(_ApiReferenceUrl, token); phrase = Uri.EscapeDataString(phrase); site = Uri.EscapeDataString(site); tags = Uri.EscapeDataString(tags); var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}"; var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); var response = await client.GetAsync(query); if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while querying the Stack Exchange API."); } var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<StackExchangeResponse>(json); } } }
using Newtonsoft.Json; using System; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Modix.Services.StackExchange { public class StackExchangeService { private string _ApiReferenceUrl = $"http://api.stackexchange.com/2.2/search/advanced" + "?key={0}" + $"&order=desc" + $"&sort=votes" + $"&filter=default"; public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags) { _ApiReferenceUrl = string.Format(_ApiReferenceUrl, token); phrase = Uri.EscapeDataString(phrase); site = Uri.EscapeDataString(site); tags = Uri.EscapeDataString(tags); var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}"; var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); var response = await client.GetAsync(query); if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while querying the Stack Exchange API."); } var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<StackExchangeResponse>(json); } } }
mit
C#
05a359c61e7c635b0fbb3ef937106c5120641218
Initialise GType
mono-soc-2011/banshee,petejohanson/banshee,babycaseny/banshee,dufoli/banshee,arfbtwn/banshee,Dynalon/banshee-osx,directhex/banshee-hacks,dufoli/banshee,dufoli/banshee,arfbtwn/banshee,stsundermann/banshee,ixfalia/banshee,GNOME/banshee,Dynalon/banshee-osx,lamalex/Banshee,GNOME/banshee,lamalex/Banshee,Dynalon/banshee-osx,petejohanson/banshee,stsundermann/banshee,dufoli/banshee,allquixotic/banshee-gst-sharp-work,babycaseny/banshee,directhex/banshee-hacks,Carbenium/banshee,Carbenium/banshee,babycaseny/banshee,mono-soc-2011/banshee,ixfalia/banshee,GNOME/banshee,lamalex/Banshee,Dynalon/banshee-osx,petejohanson/banshee,Carbenium/banshee,Dynalon/banshee-osx,babycaseny/banshee,allquixotic/banshee-gst-sharp-work,arfbtwn/banshee,petejohanson/banshee,directhex/banshee-hacks,ixfalia/banshee,arfbtwn/banshee,stsundermann/banshee,mono-soc-2011/banshee,lamalex/Banshee,dufoli/banshee,dufoli/banshee,ixfalia/banshee,stsundermann/banshee,ixfalia/banshee,Carbenium/banshee,babycaseny/banshee,lamalex/Banshee,ixfalia/banshee,GNOME/banshee,directhex/banshee-hacks,allquixotic/banshee-gst-sharp-work,Carbenium/banshee,stsundermann/banshee,mono-soc-2011/banshee,Dynalon/banshee-osx,GNOME/banshee,lamalex/Banshee,arfbtwn/banshee,Dynalon/banshee-osx,GNOME/banshee,allquixotic/banshee-gst-sharp-work,GNOME/banshee,allquixotic/banshee-gst-sharp-work,Dynalon/banshee-osx,babycaseny/banshee,stsundermann/banshee,mono-soc-2011/banshee,GNOME/banshee,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,mono-soc-2011/banshee,ixfalia/banshee,mono-soc-2011/banshee,babycaseny/banshee,ixfalia/banshee,Carbenium/banshee,stsundermann/banshee,arfbtwn/banshee,arfbtwn/banshee,directhex/banshee-hacks,dufoli/banshee,arfbtwn/banshee,babycaseny/banshee,petejohanson/banshee,directhex/banshee-hacks,dufoli/banshee,petejohanson/banshee
src/Backends/Banshee.Gio/Banshee.IO.Gio/Provider.cs
src/Backends/Banshee.Gio/Banshee.IO.Gio/Provider.cs
// // Provider.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Banshee.IO.Gio { public class Provider : Banshee.IO.IProvider { static Provider () { GLib.GType.Init (); } public Type FileProvider { get { return typeof (File); } } public Type DirectoryProvider { get { return typeof (Directory); } } public Type DemuxVfsProvider { get { return typeof (DemuxVfs); } } public bool LocalOnly { get { return false; } } } }
// // Provider.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Banshee.IO.Gio { public class Provider : Banshee.IO.IProvider { public Type FileProvider { get { return typeof (File); } } public Type DirectoryProvider { get { return typeof (Directory); } } public Type DemuxVfsProvider { get { return typeof (DemuxVfs); } } public bool LocalOnly { get { return false; } } } }
mit
C#
8347100adb075e43485439b9acc0d1e9ad9b383d
Add new DTO fields for pool information
IWBWbiz/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner
MultiMiner.Remoting.Server/Data/Transfer/Device.cs
MultiMiner.Remoting.Server/Data/Transfer/Device.cs
using MultiMiner.Engine; using MultiMiner.Xgminer; using System; namespace MultiMiner.Remoting.Server.Data.Transfer { public class Device : DeviceDescriptor { //device info public bool Enabled { get; set; } public string Name { get; set; } public DevicePlatform Platform { get; set; } public int ProcessorCount { get; set; } //coin info public CryptoCoin Coin { get; set; } public double Difficulty { get; set; } public double Price { get; set; } public double Profitability { get; set; } public double AdjustedProfitability { get; set; } public double AverageProfitability { get; set; } //calculated public string Pool { get; set; } public double Exchange { get; set; } public double EffectiveHashRate { get; set; } //device stats public double Temperature { get; set; } public int FanPercent { get; set; } public double AverageHashrate { get; set; } public double CurrentHashrate { get; set; } public int AcceptedShares { get; set; } public int RejectedShares { get; set; } public int HardwareErrors { get; set; } public double Utility { get; set; } public double WorkUtility { get; set; } public string Intensity { get; set; } //string, might be D public int PoolIndex { get; set; } public double RejectedSharesPercent { get; set; } public double HardwareErrorsPercent { get; set; } //pool info public double LastShareDifficulty { get; set; } public DateTime? LastShareTime { get; set; } public string Url { get; set; } public int BestShare { get; set; } public double PoolStalePercent { get; set; } } }
using MultiMiner.Engine; using MultiMiner.Xgminer; namespace MultiMiner.Remoting.Server.Data.Transfer { public class Device : DeviceDescriptor { //device info public bool Enabled { get; set; } public string Name { get; set; } public DevicePlatform Platform { get; set; } public int ProcessorCount { get; set; } //coin info public CryptoCoin Coin { get; set; } public double Difficulty { get; set; } public double Price { get; set; } public double Profitability { get; set; } public double AdjustedProfitability { get; set; } public double AverageProfitability { get; set; } //calculated public string Pool { get; set; } public double Exchange { get; set; } public double EffectiveHashRate { get; set; } //device stats public double Temperature { get; set; } public int FanPercent { get; set; } public double AverageHashrate { get; set; } public double CurrentHashrate { get; set; } public int AcceptedShares { get; set; } public int RejectedShares { get; set; } public int HardwareErrors { get; set; } public double Utility { get; set; } public double WorkUtility { get; set; } public string Intensity { get; set; } //string, might be D public int PoolIndex { get; set; } public double RejectedSharesPercent { get; set; } public double HardwareErrorsPercent { get; set; } } }
mit
C#
eeeda65cd477a9a51ea9b33b19f4f166e9a68ad6
Remove char[] allocation from GetDrives (#31114)
shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,wtgodbe/corefx,ViktorHofer/corefx,ptoonen/corefx,mmitche/corefx,Jiayili1/corefx,shimingsg/corefx,ericstj/corefx,BrennanConroy/corefx,Jiayili1/corefx,BrennanConroy/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,ptoonen/corefx,wtgodbe/corefx,BrennanConroy/corefx,ptoonen/corefx,Jiayili1/corefx,ericstj/corefx,shimingsg/corefx,Jiayili1/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx,mmitche/corefx,Jiayili1/corefx,ptoonen/corefx,wtgodbe/corefx,ViktorHofer/corefx,mmitche/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,mmitche/corefx,wtgodbe/corefx,mmitche/corefx,ericstj/corefx,ptoonen/corefx,shimingsg/corefx,ericstj/corefx,shimingsg/corefx,mmitche/corefx,Jiayili1/corefx,ericstj/corefx,ptoonen/corefx,wtgodbe/corefx
src/Common/src/System/IO/DriveInfoInternal.Win32.cs
src/Common/src/System/IO/DriveInfoInternal.Win32.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.Diagnostics; using System.Text; namespace System.IO { /// <summary>Contains internal volume helpers that are shared between many projects.</summary> internal static partial class DriveInfoInternal { public static string[] GetLogicalDrives() { int drives = Interop.Kernel32.GetLogicalDrives(); if (drives == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); // GetLogicalDrives returns a bitmask starting from // position 0 "A" indicating whether a drive is present. // Loop over each bit, creating a string for each one // that is set. uint d = (uint)drives; int count = 0; while (d != 0) { if (((int)d & 1) != 0) count++; d >>= 1; } string[] result = new string[count]; Span<char> root = stackalloc char[] { 'A', ':', '\\' }; d = (uint)drives; count = 0; while (d != 0) { if (((int)d & 1) != 0) { result[count++] = new string(root); } d >>= 1; root[0]++; } return result; } } }
// 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.Diagnostics; using System.Text; namespace System.IO { /// <summary>Contains internal volume helpers that are shared between many projects.</summary> internal static partial class DriveInfoInternal { public static string[] GetLogicalDrives() { int drives = Interop.Kernel32.GetLogicalDrives(); if (drives == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); // GetLogicalDrives returns a bitmask starting from // position 0 "A" indicating whether a drive is present. // Loop over each bit, creating a string for each one // that is set. uint d = (uint)drives; int count = 0; while (d != 0) { if (((int)d & 1) != 0) count++; d >>= 1; } string[] result = new string[count]; char[] root = new char[] { 'A', ':', '\\' }; d = (uint)drives; count = 0; while (d != 0) { if (((int)d & 1) != 0) { result[count++] = new string(root); } d >>= 1; root[0]++; } return result; } } }
mit
C#
5456648f8864bfbe2d3cf93aacceba81f922fc1d
Increment version to 1.4.3
ascendedguard/sc2replay-csharp,evilz/sc2replay-csharp
Starcraft2.ReplayParser/Properties/AssemblyInfo.cs
Starcraft2.ReplayParser/Properties/AssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Ascend"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- 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("Starcraft2.ReplayParser")] [assembly: AssemblyDescription("Library for parsing information from a Starcraft 2 replay file.")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCompany("Ascend")] [assembly: AssemblyProduct("Starcraft2.ReplayParser")] [assembly: AssemblyCopyright("Copyright © Ascend 2010")] [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("ab85402d-b34a-42ed-b74e-02c2656896d8")] // 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.4.3.*")] [assembly: AssemblyFileVersion("1.4.3.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Ascend"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- 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("Starcraft2.ReplayParser")] [assembly: AssemblyDescription("Library for parsing information from a Starcraft 2 replay file.")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCompany("Ascend")] [assembly: AssemblyProduct("Starcraft2.ReplayParser")] [assembly: AssemblyCopyright("Copyright © Ascend 2010")] [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("ab85402d-b34a-42ed-b74e-02c2656896d8")] // 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.4.2.*")] [assembly: AssemblyFileVersion("1.4.2.0")]
mit
C#
dbfcedf92db5e0f23ccdf8eb4cfe03a1245113c7
Update OperaConfig.cs
rosolko/WebDriverManager.Net
WebDriverManager/DriverConfigs/Impl/OperaConfig.cs
WebDriverManager/DriverConfigs/Impl/OperaConfig.cs
using System; using System.Linq; using System.Net; using AngleSharp.Html.Parser; namespace WebDriverManager.DriverConfigs.Impl { public class OperaConfig : IDriverConfig { public virtual string GetName() { return "Opera"; } public virtual string GetUrl32() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win32.zip"; } public virtual string GetUrl64() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win64.zip"; } public virtual string GetBinaryName() { return "operadriver.exe"; } public virtual string GetLatestVersion() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var client = new WebClient()) { var htmlCode = client.DownloadString("https://github.com/operasoftware/operachromiumdriver/releases"); var parser = new HtmlParser(); var document = parser.ParseDocument(htmlCode); var version = document.QuerySelectorAll(".Link--primary") .Select(element => element.TextContent) .FirstOrDefault(); return version; } } public virtual string GetMatchingBrowserVersion() { throw new NotImplementedException(); } } }
using System; using System.Linq; using System.Net; using AngleSharp.Html.Parser; namespace WebDriverManager.DriverConfigs.Impl { public class OperaConfig : IDriverConfig { public virtual string GetName() { return "Opera"; } public virtual string GetUrl32() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win32.zip"; } public virtual string GetUrl64() { return "https://github.com/operasoftware/operachromiumdriver/releases/download/v.<version>/operadriver_win64.zip"; } public virtual string GetBinaryName() { return "operadriver.exe"; } public virtual string GetLatestVersion() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var client = new WebClient()) { var htmlCode = client.DownloadString("https://github.com/operasoftware/operachromiumdriver/releases"); var parser = new HtmlParser(); var document = parser.ParseDocument(htmlCode); var version = document.QuerySelectorAll(".release-header .f1 a") .Select(element => element.TextContent) .FirstOrDefault(); return version; } } public virtual string GetMatchingBrowserVersion() { throw new NotImplementedException(); } } }
mit
C#
e5454b19eb5fd4ce4ab0fc502b75cc31df6c6ee1
fix bug in subset sum dp
justcoding121/Advanced-Algorithms,justcoding121/Algorithm-Sandbox
Algorithm.Sandbox/DynamicProgramming/Sum/SubSetSum.cs
Algorithm.Sandbox/DynamicProgramming/Sum/SubSetSum.cs
using System.Collections.Generic; namespace Algorithm.Sandbox.DynamicProgramming.Sum { /// <summary> /// Problem statement /// http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/ /// </summary> public class SubSetSum { public static bool HasSubSet(int[] input, int sum) { return SubSetSumR(input, input.Length - 1, sum, new Dictionary<string, bool>()); } private static bool SubSetSumR(int[] input, int i, int sum, Dictionary<string, bool> cache) { if (i < 0) { return false; } //found sequence if (input[i] == sum) { return true; } var cacheKey = $"{i}-{sum}"; if (cache.ContainsKey(cacheKey)) { return cache[cacheKey]; } bool result; //skip if (input[i] > sum) { result = SubSetSumR(input, i - 1, sum, cache); cache.Add(cacheKey, result); return result; } //skip or pick result = SubSetSumR(input, i - 1, sum, cache) || SubSetSumR(input, i - 1, sum - input[i], cache); if (!cache.ContainsKey(cacheKey)) { cache.Add(cacheKey, result); } return result; } } }
using System.Collections.Generic; namespace Algorithm.Sandbox.DynamicProgramming.Sum { /// <summary> /// Problem statement /// http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/ /// </summary> public class SubSetSum { public static bool HasSubSet(int[] input, int sum) { return SubSetSumR(input, input.Length - 1, sum, new Dictionary<int, bool>()); } private static bool SubSetSumR(int[] input, int i, int sum, Dictionary<int, bool> cache) { if (i < 0) { return false; } //found sequence if (input[i] == sum) { return true; } if(cache.ContainsKey(i)) { return cache[i]; } bool result; //skip if (input[i] > sum) { result = SubSetSumR(input, i - 1, sum, cache); cache.Add(i, result); return result; } //skip or pick result = SubSetSumR(input, i - 1, sum, cache) || SubSetSumR(input, i, sum - input[i], cache); if (!cache.ContainsKey(i)) { cache.Add(i, result); } return result; } } }
mit
C#
ae472bd6d33eac66e311de7a4e91e9aac55065b2
Add `using System` to fix this file being detected as Smalltalk
SteamDatabase/ValveResourceFormat
ValveResourceFormat/Resource/Enums/VTexFormat.cs
ValveResourceFormat/Resource/Enums/VTexFormat.cs
using System; namespace ValveResourceFormat { public enum VTexFormat { #pragma warning disable 1591 UNKNOWN = 0, DXT1 = 1, DXT5 = 2, I8 = 3, // TODO: Not used in dota RGBA8888 = 4, R16 = 5, // TODO: Not used in dota RG1616 = 6, // TODO: Not used in dota RGBA16161616 = 7, // TODO: Not used in dota R16F = 8, // TODO: Not used in dota RG1616F = 9, // TODO: Not used in dota RGBA16161616F = 10, // TODO: Not used in dota R32F = 11, // TODO: Not used in dota RG3232F = 12, // TODO: Not used in dota RGB323232F = 13, // TODO: Not used in dota RGBA32323232F = 14, // TODO: Not used in dota PNG = 16 // TODO: resourceinfo doesn't know about this #pragma warning restore 1591 } }
namespace ValveResourceFormat { public enum VTexFormat { #pragma warning disable 1591 UNKNOWN = 0, DXT1 = 1, DXT5 = 2, I8 = 3, // TODO: Not used in dota RGBA8888 = 4, R16 = 5, // TODO: Not used in dota RG1616 = 6, // TODO: Not used in dota RGBA16161616 = 7, // TODO: Not used in dota R16F = 8, // TODO: Not used in dota RG1616F = 9, // TODO: Not used in dota RGBA16161616F = 10, // TODO: Not used in dota R32F = 11, // TODO: Not used in dota RG3232F = 12, // TODO: Not used in dota RGB323232F = 13, // TODO: Not used in dota RGBA32323232F = 14, // TODO: Not used in dota PNG = 16 // TODO: resourceinfo doesn't know about this #pragma warning restore 1591 } }
mit
C#
cca3ad2fc0aebe8cee5607efad9442386c79e3f6
throw in Auth0 since we named it?
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/API/ApiController.cs
Battery-Commander.Web/Controllers/API/ApiController.cs
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]"), Authorize(AuthenticationSchemes = "Auth0,Bearer,Cookies")] public class ApiController : Controller { protected readonly Database db; public ApiController(Database db) { this.db = db; } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]"), Authorize(AuthenticationSchemes = "Bearer,Cookies")] public class ApiController : Controller { protected readonly Database db; public ApiController(Database db) { this.db = db; } } }
mit
C#
d9371b92a09babc98321d366711b1e3894f0bfd9
Update assembly info informational version
SkyKick/datadogcsharp
DataDogCSharp/DataDogCSharp/Properties/AssemblyInfo.cs
DataDogCSharp/DataDogCSharp/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("DataDogCSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataDogCSharp")] [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("bdc14997-0981-470e-9497-e0fd00289ad6")] // 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")] [assembly: AssemblyInformationalVersion("0.0.2-beta")]
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("DataDogCSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataDogCSharp")] [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("bdc14997-0981-470e-9497-e0fd00289ad6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
aa6135a392142e271255299abebfd6e3754320d4
Migrate Buddy to the new backend
flagbug/Espera,punker76/Espera
Espera/Espera.Core/Analytics/BuddyAnalyticsEndpoint.cs
Espera/Espera.Core/Analytics/BuddyAnalyticsEndpoint.cs
using System; using System.Globalization; using System.IO; using System.Reflection; using System.Threading.Tasks; using Buddy; namespace Espera.Core.Analytics { public class BuddyAnalyticsEndpoint : IAnalyticsEndpoint { private readonly BuddyClient client; private AuthenticatedUser storedUser; public BuddyAnalyticsEndpoint() { this.client = new BuddyClient("bbbbbc.mhbbbxjLrKNl", "83585740-AE7A-4F68-828D-5E6A8825A0EE", autoRecordDeviceInfo: false); } public async Task AuthenticateUserAsync(string analyticsToken) { this.storedUser = await this.client.LoginAsync(analyticsToken); } public async Task<string> CreateUserAsync() { string throwAwayToken = Guid.NewGuid().ToString(); AuthenticatedUser user = await this.client.CreateUserAsync(throwAwayToken, throwAwayToken); this.storedUser = user; return user.Token; } public async Task RecordDeviceInformationAsync() { string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); await this.client.Device.RecordInformationAsync(Environment.OSVersion.VersionString, "Desktop", this.storedUser, version); await this.RecordLanguageAsync(); } public Task RecordErrorAsync(string message, string logId, string stackTrace = null) { string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); return this.client.Device.RecordCrashAsync(message, Environment.OSVersion.VersionString, "Desktop", this.storedUser, stackTrace, version, metadata: logId); } public Task RecordMetaDataAsync(string key, string value) { return this.storedUser.Metadata.SetAsync(key, value); } public async Task<string> SendBlobAsync(string name, string mimeType, Stream data) { Blob blob = await this.storedUser.Blobs.AddAsync(name, mimeType, String.Empty, 0, 0, data); return blob.BlobID.ToString(CultureInfo.InvariantCulture); } public Task UpdateUserEmailAsync(string email) { AuthenticatedUser user = this.storedUser; return user.UpdateAsync(user.Email, String.Empty, user.Gender, user.Age, email, // email is the only field we change here user.Status, user.LocationFuzzing, user.CelebrityMode, user.ApplicationTag); } } }
using System; using System.Globalization; using System.IO; using System.Reflection; using System.Threading.Tasks; using Buddy; namespace Espera.Core.Analytics { public class BuddyAnalyticsEndpoint : IAnalyticsEndpoint { private readonly BuddyClient client; private AuthenticatedUser storedUser; public BuddyAnalyticsEndpoint() { this.client = new BuddyClient("Espera", "EC60C045-B432-44A6-A4E0-15B4BF607105", autoRecordDeviceInfo: false); } public async Task AuthenticateUserAsync(string analyticsToken) { this.storedUser = await this.client.LoginAsync(analyticsToken); } public async Task<string> CreateUserAsync() { string throwAwayToken = Guid.NewGuid().ToString(); AuthenticatedUser user = await this.client.CreateUserAsync(throwAwayToken, throwAwayToken); this.storedUser = user; return user.Token; } public async Task RecordDeviceInformationAsync() { string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); await this.client.Device.RecordInformationAsync(Environment.OSVersion.VersionString, "Desktop", this.storedUser, version); await this.RecordLanguageAsync(); } public Task RecordErrorAsync(string message, string logId, string stackTrace = null) { string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); return this.client.Device.RecordCrashAsync(message, Environment.OSVersion.VersionString, "Desktop", this.storedUser, stackTrace, version, metadata: logId); } public Task RecordMetaDataAsync(string key, string value) { return this.storedUser.Metadata.SetAsync(key, value); } public async Task<string> SendBlobAsync(string name, string mimeType, Stream data) { Blob blob = await this.storedUser.Blobs.AddAsync(name, mimeType, String.Empty, 0, 0, data); return blob.BlobID.ToString(CultureInfo.InvariantCulture); } public Task UpdateUserEmailAsync(string email) { AuthenticatedUser user = this.storedUser; return user.UpdateAsync(user.Email, String.Empty, user.Gender, user.Age, email, // email is the only field we change here user.Status, user.LocationFuzzing, user.CelebrityMode, user.ApplicationTag); } } }
mit
C#
1e6c5dece6aceb9e133aa6c5d0f42c3af4e93b85
Append and Prepend extension
theraot/Theraot
Framework.Core/Theraot/Collections/Extensions.extra.cs
Framework.Core/Theraot/Collections/Extensions.extra.cs
using System; using System.Collections.Generic; using Theraot.Collections.Specialized; namespace Theraot.Collections { public static partial class Extensions { public static IEnumerable<T> Append<T>(this IEnumerable<T> target, IEnumerable<T> append) { return new ExtendedEnumerable<T>(target, append); } public static IEnumerable<T> Append<T>(this IEnumerable<T> target, T append) { return new ExtendedEnumerable<T>(target, AsUnaryEnumerable(append)); } public static IEnumerable<T> Prepend<T>(this IEnumerable<T> target, IEnumerable<T> prepend) { return new ExtendedEnumerable<T>(prepend, target); } public static IEnumerable<T> Prepend<T>(this IEnumerable<T> target, T prepend) { return new ExtendedEnumerable<T>(AsUnaryEnumerable(prepend), target); } #if FAT public static IEnumerable<T> Cycle<T>(this IEnumerable<T> source) { if (source == null) { throw new ArgumentNullException("source"); } var progressive = new ProgressiveCollection<T>(source); while (true) { foreach (var item in progressive) { yield return item; } } // Infinite Loop - This method creates an endless IEnumerable<T> } #endif } }
#if FAT using System; using System.Collections.Generic; using Theraot.Collections.Specialized; namespace Theraot.Collections { public static partial class Extensions { public static IEnumerable<T> Append<T>(this IEnumerable<T> target, IEnumerable<T> append) { return new ExtendedEnumerable<T>(target, append); } public static IEnumerable<T> Append<T>(this IEnumerable<T> target, T append) { return new ExtendedEnumerable<T>(target, AsUnaryEnumerable(append)); } public static IEnumerable<T> Cycle<T>(this IEnumerable<T> source) { if (source == null) { throw new ArgumentNullException("source"); } var progressive = new ProgressiveCollection<T>(source); while (true) { foreach (var item in progressive) { yield return item; } } // Infinite Loop - This method creates an endless IEnumerable<T> } public static IEnumerable<T> Prepend<T>(this IEnumerable<T> target, IEnumerable<T> prepend) { return new ExtendedEnumerable<T>(prepend, target); } public static IEnumerable<T> Prepend<T>(this IEnumerable<T> target, T prepend) { return new ExtendedEnumerable<T>(AsUnaryEnumerable(prepend), target); } } } #endif
mit
C#
840f88a7018778bd7f56116d1fd93d100c36c64d
remove commented, old configuration
cvent/Metrics.NET,Liwoj/Metrics.NET,huoxudong125/Metrics.NET,etishor/Metrics.NET,mnadel/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,ntent-ad/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET
Samples/Owin.Sample/Startup.cs
Samples/Owin.Sample/Startup.cs
using Metrics; using Microsoft.Owin.Cors; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Owin.Metrics; using System; using System.Web.Http; namespace Owin.Sample { public class Startup { public void Configuration(IAppBuilder app) { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; app.UseCors(CorsOptions.AllowAll); Metric.Config .WithAllCounters() .WithReporting(r => r.WithConsoleReport(TimeSpan.FromSeconds(30))) .WithOwin(middleware => app.Use(middleware), config => config .WithRequestMetricsConfig(c => c.RegisterAllMetrics()) .WithMetricsEndpoint() ); var httpConfig = new HttpConfiguration(); httpConfig.MapHttpAttributeRoutes(); app.UseWebApi(httpConfig); } } }
using Metrics; using Microsoft.Owin.Cors; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Owin.Metrics; using System; using System.Web.Http; namespace Owin.Sample { public class Startup { public void Configuration(IAppBuilder app) { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; app.UseCors(CorsOptions.AllowAll); Metric.Config .WithAllCounters() .WithReporting(r => r.WithConsoleReport(TimeSpan.FromSeconds(30))) .WithOwin(middleware => app.Use(middleware), config => config .WithRequestMetricsConfig(c => c.RegisterAllMetrics()) .WithMetricsEndpoint() ); //app.UseMetrics(Metric.Config.WithAllCounters() // .WithReporting(r => r.WithConsoleReport(TimeSpan.FromSeconds(30))), // owinMetrics => owinMetrics.RegisterAllMetrics()); var httpConfig = new HttpConfiguration(); httpConfig.MapHttpAttributeRoutes(); app.UseWebApi(httpConfig); } } }
apache-2.0
C#
6a4a907ed67e6a82fa25fa54fb81eb9a4eb481f6
Compress only the vessel proto. TEST
DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
LmpCommon/Message/Data/Vessel/VesselProtoMsgData.cs
LmpCommon/Message/Data/Vessel/VesselProtoMsgData.cs
using Lidgren.Network; using LmpCommon.Message.Types; namespace LmpCommon.Message.Data.Vessel { public class VesselProtoMsgData : VesselBaseMsgData { internal VesselProtoMsgData() { } public override bool CompressCondition => true; public int NumBytes; public byte[] Data = new byte[0]; public override VesselMessageType VesselMessageType => VesselMessageType.Proto; public override string ClassName { get; } = nameof(VesselProtoMsgData); internal override void InternalSerialize(NetOutgoingMessage lidgrenMsg) { base.InternalSerialize(lidgrenMsg); if (CompressCondition) { var compressedData = CachedQuickLz.CachedQlz.Compress(Data, NumBytes, out NumBytes); CachedQuickLz.ArrayPool<byte>.Recycle(Data); Data = compressedData; } lidgrenMsg.Write(NumBytes); lidgrenMsg.Write(Data, 0, NumBytes); if (CompressCondition) { CachedQuickLz.ArrayPool<byte>.Recycle(Data); } } internal override void InternalDeserialize(NetIncomingMessage lidgrenMsg) { base.InternalDeserialize(lidgrenMsg); NumBytes = lidgrenMsg.ReadInt32(); if (Data.Length < NumBytes) Data = new byte[NumBytes]; lidgrenMsg.ReadBytes(Data, 0, NumBytes); if (Compressed) { var decompressedData = CachedQuickLz.CachedQlz.Decompress(Data, out NumBytes); CachedQuickLz.ArrayPool<byte>.Recycle(Data); Data = decompressedData; } } internal override int InternalGetMessageSize() { return base.InternalGetMessageSize() + sizeof(int) + sizeof(byte) * NumBytes; } } }
using Lidgren.Network; using LmpCommon.Message.Types; namespace LmpCommon.Message.Data.Vessel { public class VesselProtoMsgData : VesselBaseMsgData { internal VesselProtoMsgData() { } public int NumBytes; public byte[] Data = new byte[0]; public override VesselMessageType VesselMessageType => VesselMessageType.Proto; public override string ClassName { get; } = nameof(VesselProtoMsgData); internal override void InternalSerialize(NetOutgoingMessage lidgrenMsg) { base.InternalSerialize(lidgrenMsg); lidgrenMsg.Write(NumBytes); lidgrenMsg.Write(Data, 0, NumBytes); } internal override void InternalDeserialize(NetIncomingMessage lidgrenMsg) { base.InternalDeserialize(lidgrenMsg); NumBytes = lidgrenMsg.ReadInt32(); if (Data.Length < NumBytes) Data = new byte[NumBytes]; lidgrenMsg.ReadBytes(Data, 0, NumBytes); } internal override int InternalGetMessageSize() { return base.InternalGetMessageSize() + sizeof(int) + sizeof(byte) * NumBytes; } } }
mit
C#
520ff5dc46c96a7cf9d82136b62966f202260383
Revert "Fix for an odd crash we were experiencing"
Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms
Xamarin.Forms.Xaml/MarkupExtensions/TypeExtension.cs
Xamarin.Forms.Xaml/MarkupExtensions/TypeExtension.cs
using System; namespace Xamarin.Forms.Xaml { [ContentProperty("TypeName")] public class TypeExtension : IMarkupExtension<Type> { public string TypeName { get; set; } public Type ProvideValue(IServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); var typeResolver = serviceProvider.GetService(typeof (IXamlTypeResolver)) as IXamlTypeResolver; if (typeResolver == null) throw new ArgumentException("No IXamlTypeResolver in IServiceProvider"); return typeResolver.Resolve(TypeName, serviceProvider); } object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) { return (this as IMarkupExtension<Type>).ProvideValue(serviceProvider); } } }
using System; namespace Xamarin.Forms.Xaml { [ContentProperty("TypeName")] public class TypeExtension : IMarkupExtension<Type> { public string TypeName { get; set; } public Type ProvideValue(IServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); var typeResolver = serviceProvider.GetService(typeof (IXamlTypeResolver)) as IXamlTypeResolver; if (typeResolver == null) throw new ArgumentException("No IXamlTypeResolver in IServiceProvider"); //HACK: this fixes an extreme case in our app where we had our version of ItemsView in a ListView header, just taking this out for now and seeing what this will break if (string.IsNullOrEmpty(TypeName)) return null; return typeResolver.Resolve(TypeName, serviceProvider); } object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) { return (this as IMarkupExtension<Type>).ProvideValue(serviceProvider); } } }
mit
C#
81bb961326c0fe1e0845163e6d8d35e682cccc2e
Update assembly version
nexussays/Xamarin.Mobile,xamarin/Xamarin.Mobile,xamarin/Xamarin.Mobile,moljac/Xamarin.Mobile,orand/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile
MonoDroid/Xamarin.Mobile/Properties/AssemblyInfo.cs
MonoDroid/Xamarin.Mobile/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("Xamarin.Mobile")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xamarin Inc.")] [assembly: AssemblyProduct("Xamarin.Mobile")] [assembly: AssemblyCopyright("Copyright 2011-2012 Xamarin Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // 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.5.1.0")] [assembly: AssemblyFileVersion("0.5.1.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("Xamarin.Mobile")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xamarin Inc.")] [assembly: AssemblyProduct("Xamarin.Mobile")] [assembly: AssemblyCopyright("Copyright 2011-2012 Xamarin Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // 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.5.0.0")] [assembly: AssemblyFileVersion("0.5.0.0")]
apache-2.0
C#
d31dc896f19fd4dfbefa794b44c0cfaf588e2d70
add comment for SecurityContractAttribute
SignalGo/SignalGo-full-net
SignalGo.Server/DataTypes/SecurityContractAttribute.cs
SignalGo.Server/DataTypes/SecurityContractAttribute.cs
using SignalGo.Server.Models; using SignalGo.Shared.Http; using SignalGo.Shared.Models; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace SignalGo.Server.DataTypes { /// <summary> /// Security contract attribute for using check permission before call methods /// </summary> public abstract class SecurityContractAttribute : Attribute { /// <summary> /// call your security method for http calls /// </summary> /// <param name="client">client if that called method</param> /// <param name="controller">controller if available</param> /// <param name="serviceName">service name</param> /// <param name="methodName">method name</param> /// <param name="address">address</param> /// <param name="parameters">parameters</param> /// <returns></returns> public abstract bool CheckHttpPermission(ClientInfo client, IHttpClientInfo controller, string serviceName, string methodName, string address, List<object> parameters); /// <summary> /// result of your security method for http calls when access dined /// </summary> /// <param name="client">client if that called method</param> /// <param name="controller">controller if available</param> /// <param name="serviceName">service name</param> /// <param name="methodName">method name</param> /// <param name="address">address</param> /// <param name="parameters">parameters</param> /// <returns></returns> public abstract object GetHttpValueWhenDenyPermission(ClientInfo client, IHttpClientInfo controller, string serviceName, string methodName, string address, List<object> parameters); /// <summary> /// call your check security method /// </summary> /// <param name="client">who client is calling your method</param> /// <param name="service">your service instance class that used this attribute</param> /// <param name="method"></param> /// <param name="parameters"></param> /// <returns>if client have permission return true else false</returns> public abstract bool CheckPermission(ClientInfo client, object service, MethodInfo method, List<object> parameters); /// <summary> /// after return false when calling CheckPermission server call this method for send data to client /// </summary> /// <param name="client">who client is calling your method</param> /// <param name="service">your service instance class that used this attribute</param> /// <param name="method"></param> /// <param name="parameters"></param> /// <returns>if your method is not void you can return a value to client</returns> public abstract object GetValueWhenDenyPermission(ClientInfo client, object service, MethodInfo method, List<object> parameters); } }
using SignalGo.Server.Models; using SignalGo.Shared.Http; using SignalGo.Shared.Models; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace SignalGo.Server.DataTypes { /// <summary> /// Security contract attribute for using check permission before call methods /// </summary> public abstract class SecurityContractAttribute : Attribute { public abstract bool CheckHttpPermission(ClientInfo client, IHttpClientInfo controller, string serviceName, string methodName, string address, List<object> parameters); public abstract object GetHttpValueWhenDenyPermission(ClientInfo client, IHttpClientInfo controller, string serviceName, string methodName, string address, List<object> parameters); /// <summary> /// call your check security method /// </summary> /// <param name="client">who client is calling your method</param> /// <param name="service">your service instance class that used this attribute</param> /// <returns>if client have permission return true else false</returns> public abstract bool CheckPermission(ClientInfo client, object service, MethodInfo method, List<object> parameters); /// <summary> /// after return false when calling CheckPermission server call this method for send data to client /// </summary> /// <param name="client">who client is calling your method</param> /// <param name="service">your service instance class that used this attribute</param> /// <returns>if your method is not void you can return a value to client</returns> public abstract object GetValueWhenDenyPermission(ClientInfo client, object service, MethodInfo method, List<object> parameters); } }
mit
C#
5640e2262480a84bc00f82c6b366396e1b4630c2
add Telerik.JustMock.MSTest2.Test.Elevated to InternalsVisible in DemoLibS
telerik/JustMockLite
Telerik.JustMock.DemoLib/Properties/AssemblyInfo.cs
Telerik.JustMock.DemoLib/Properties/AssemblyInfo.cs
/* JustMock Lite Copyright © 2010-2014 Telerik AD 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.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("Telerik.JustMock.DemoLib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Telerik.JustMock.DemoLib")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany("Telerik AD")] [assembly: AssemblyCopyright("Copyright © 2010-2014 Telerik AD")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("60f21ed4-498b-4cdf-b16c-05f1ea3e4f60")] // 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: InternalsVisibleTo("Telerik.JustMock.Nunit.Tests")] [assembly: InternalsVisibleTo("Telerik.JustMock.Tests")] [assembly: InternalsVisibleTo(Telerik.JustMock.DemoLib.JustMock.FullyQualifiedAssemblyName)] [assembly: InternalsVisibleTo("Telerik.JustMock.Tests.Elevated")] [assembly: InternalsVisibleTo("Telerik.JustMock.MSTest2.Tests")] [assembly: InternalsVisibleTo("Telerik.JustMock.MSTest2.Tests.Elevated")]
/* JustMock Lite Copyright © 2010-2014 Telerik AD 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.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("Telerik.JustMock.DemoLib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Telerik.JustMock.DemoLib")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany("Telerik AD")] [assembly: AssemblyCopyright("Copyright © 2010-2014 Telerik AD")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("60f21ed4-498b-4cdf-b16c-05f1ea3e4f60")] // 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: InternalsVisibleTo("Telerik.JustMock.Nunit.Tests")] [assembly: InternalsVisibleTo("Telerik.JustMock.Tests")] [assembly: InternalsVisibleTo(Telerik.JustMock.DemoLib.JustMock.FullyQualifiedAssemblyName)] [assembly: InternalsVisibleTo("Telerik.JustMock.Tests.Elevated")] [assembly: InternalsVisibleTo("Telerik.JustMock.MSTest2.Tests")]
apache-2.0
C#
7ebd5558aa65454486f2caba94496288bc288ad9
Update FileLoader.cs
mutouzdl/MutCSVLoaderForUnity
Assets/Scripts/CSVLoader/FileLoader.cs
Assets/Scripts/CSVLoader/FileLoader.cs
using UnityEngine; using System.IO; using System; /// <summary> /// 文件读取工具类 /// 作者:笨木头 www.benmutou.com /// 使用本代码时,请保留作者信息 /// </summary> public class FileLoader { /// <summary> /// 读取文件,结果保存到一个string数组,数组的每一行就是文件的每一行 /// (只支持PC和Android,不支持iOS,因为木头不玩iOS) /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static string[] LoadFileLines(string filePath) { string url = Application.streamingAssetsPath + "/" + filePath; #if UNITY_EDITOR return File.ReadAllLines(url); #elif UNITY_ANDROID WWW www = new WWW(url); while (!www.isDone) { } return www.text.Split(new string[] { "\r\n" }, StringSplitOptions.None); #else return File.ReadAllLines(url); #endif } }
using UnityEngine; using System.IO; /// <summary> /// 文件读取工具类 /// 作者:笨木头 www.benmutou.com /// 使用本代码时,请保留作者信息 /// </summary> public class FileLoader { /// <summary> /// 读取文件,结果保存到一个string数组,数组的每一行就是文件的每一行 /// (只支持PC和Android,不支持iOS,因为木头不玩iOS) /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static string[] LoadFileLines(string filePath) { string url = Application.streamingAssetsPath + "/" + filePath; #if UNITY_EDITOR return File.ReadAllLines(url); #elif UNITY_ANDROID WWW www = new WWW(url); while (!www.isDone) { } return www.text.Split(new string[] { "\r\n" }, StringSplitOptions.None); #else return File.ReadAllLines(url); #endif } }
mit
C#
a7ff01114c1e78b88b7c486b6f803bb357df0980
fix bug seedBullet not destroy itself immediately after hit Destroyable
LNWPOR/HamsterRushVR-Client
Assets/Scripts/SeedBulletController.cs
Assets/Scripts/SeedBulletController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SeedBulletController : MonoBehaviour { private float destroyDuration = 3f; private void OnTriggerEnter(Collider other) { //Debug.Log(collision.gameObject.name); if (other.gameObject.tag.Equals("Destroyable")) { Destroy(other.gameObject); Destroy(gameObject); }else { StartCoroutine(DestroyBullet()); } } private IEnumerator DestroyBullet() { yield return new WaitForSeconds(destroyDuration); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SeedBulletController : MonoBehaviour { private float destroyDuration = 3f; private void OnTriggerEnter(Collider other) { //Debug.Log(collision.gameObject.name); if (other.gameObject.tag.Equals("Destroyable")) { Destroy(other.gameObject); } StartCoroutine(DestroyBullet()); } private IEnumerator DestroyBullet() { yield return new WaitForSeconds(destroyDuration); } }
mit
C#
6e7b1273f11e583e270c0624d6d6e228d4af5cf3
Remove pause at the end of generator
ssg/TurkishId
generator/Program.cs
generator/Program.cs
/* Copyright 2014 Sedat Kapanoglu 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; namespace TurkishIdGen { internal class Program { private static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine( @"Generates random and valid Turkish Republic citizen ID Number) <ssg@sourtimes.org> Usage: TurkishIdGen count"); Environment.Exit(1); } int count = int.Parse(args[0]); var rnd = new Random(); for (int n = 0; n < count; n++) { string no = generateRandomId(rnd); Console.WriteLine(no); } } private static string generateRandomId(Random rnd) { int value = rnd.Next(100000000, 1000000000); return generateIdFromValue(value); } private static string generateIdFromValue(int x) { int d1 = x / 100000000; int d2 = (x / 10000000) % 10; int d3 = (x / 1000000) % 10; int d4 = (x / 100000) % 10; int d5 = (x / 10000) % 10; int d6 = (x / 1000) % 10; int d7 = (x / 100) % 10; int d8 = (x / 10) % 10; int d9 = x % 10; int oddSum = d1 + d3 + d5 + d7 + d9; int evenSum = d2 + d4 + d6 + d8; int firstChecksum = ((oddSum * 7) - evenSum) % 10; int secondChecksum = (oddSum + evenSum + firstChecksum) % 10; return String.Format("{0}{1}{2}", x, firstChecksum, secondChecksum); } } }
/* Copyright 2014 Sedat Kapanoglu 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; namespace TurkishIdGen { internal class Program { private static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine( @"Generates random and valid Turkish Republic citizen ID Number) <ssg@sourtimes.org> Usage: TurkishIdGen count"); Environment.Exit(1); } int count = int.Parse(args[0]); var rnd = new Random(); for (int n = 0; n < count; n++) { string no = generateRandomId(rnd); Console.WriteLine(no); } Console.Read(); } private static string generateRandomId(Random rnd) { int value = rnd.Next(100000000, 1000000000); return generateIdFromValue(123456789); } private static string generateIdFromValue(int x) { int d1 = x / 100000000; int d2 = (x / 10000000) % 10; int d3 = (x / 1000000) % 10; int d4 = (x / 100000) % 10; int d5 = (x / 10000) % 10; int d6 = (x / 1000) % 10; int d7 = (x / 100) % 10; int d8 = (x / 10) % 10; int d9 = x % 10; int oddSum = d1 + d3 + d5 + d7 + d9; int evenSum = d2 + d4 + d6 + d8; int firstChecksum = ((oddSum * 7) - evenSum) % 10; int secondChecksum = (oddSum + evenSum + firstChecksum) % 10; return String.Format("{0}{1}{2}", x, firstChecksum, secondChecksum); } } }
apache-2.0
C#
da43e7e14d46673ebcacfbc30b907207ae3550a8
fix version
raml-org/raml-dotnet-parser,raml-org/raml-dotnet-parser
source/AMF.Parser/Properties/AssemblyInfo.cs
source/AMF.Parser/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("AMF.Parser")] [assembly: AssemblyDescription("RAML and OAS (swagger) parser for .Net")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MuleSoft")] [assembly: AssemblyProduct("AMF.Parser")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("af24976e-d021-4aa5-b7d7-1de6574cd6f6")] // 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.9.4")] [assembly: AssemblyFileVersion("0.9.4")]
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("AMF.Parser")] [assembly: AssemblyDescription("RAML and OAS (swagger) parser for .Net")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MuleSoft")] [assembly: AssemblyProduct("AMF.Parser")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("af24976e-d021-4aa5-b7d7-1de6574cd6f6")] // 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.9.5")] [assembly: AssemblyFileVersion("0.9.5")]
apache-2.0
C#
91c34743bc1fe4236c24204ac2cc7a895eb2579d
Improve HyphenatedRoutingConvention
OlsonDev/PersonalWebApp,OlsonDev/PersonalWebApp
Conventions/HyphenatedRoutingConvention.cs
Conventions/HyphenatedRoutingConvention.cs
using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.AspNet.Mvc.ApplicationModels; namespace PersonalWebApp.Conventions { // See https://github.com/aspnet/Routing/issues/186 public class HyphenatedRoutingConvention : IApplicationModelConvention { public string DefaultController { get; set; } public string DefaultAction { get; set; } public HyphenatedRoutingConvention(string defaultController = "home", string defaultAction = "index") { DefaultController = defaultController.ToLower(); DefaultAction = defaultAction.ToLower(); } public void Apply(ApplicationModel application) { foreach (var controller in application.Controllers) { if (controller.AttributeRoutes.Count != 0) continue; var controllerTmpl = Slugify(controller.ControllerName); controller.AttributeRoutes.Add(new AttributeRouteModel { Template = controllerTmpl }); var actionsToAdd = new List<ActionModel>(); foreach (var action in controller.Actions) { if (action.AttributeRouteModel != null) continue; var actionSlug = Slugify(action.ActionName); var actionTmpl = $"{actionSlug}/{{id?}}"; if (actionSlug == DefaultAction) { var defaultActionModel = new ActionModel(action) { AttributeRouteModel = new AttributeRouteModel { Template = "" } }; actionsToAdd.Add(defaultActionModel); if (controllerTmpl == DefaultController) { actionsToAdd.Add(new ActionModel(action) { AttributeRouteModel = new AttributeRouteModel { Template = "/" } }); } } action.AttributeRouteModel = new AttributeRouteModel { Template = actionTmpl }; } // Flaky; contigent on resolution of https://github.com/aspnet/Mvc/issues/4043 foreach (var action in actionsToAdd) { controller.Actions.Add(action); } } } private string Slugify(string pascalString) { return Regex.Replace(pascalString, "([a-z])([A-Z])", "$1-$2").ToLower(); } } }
using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.AspNet.Mvc.ApplicationModels; namespace PersonalWebApp.Conventions { // See https://github.com/aspnet/Routing/issues/186 public class HyphenatedRoutingConvention : IApplicationModelConvention { public string DefaultController { get; set; } public string DefaultAction { get; set; } public HyphenatedRoutingConvention(string defaultController = "home", string defaultAction = "index") { DefaultController = defaultController.ToLower(); DefaultAction = defaultAction.ToLower(); } public void Apply(ApplicationModel application) { foreach (var controller in application.Controllers) { if (controller.AttributeRoutes.Count != 0) continue; var controllerTmpl = Slugify(controller.ControllerName); controller.AttributeRoutes.Add(new AttributeRouteModel { Template = controllerTmpl }); if (controllerTmpl == DefaultController) { controller.AttributeRoutes.Add(new AttributeRouteModel { Template = "" }); } var actionsToAdd = new List<ActionModel>(); foreach (var action in controller.Actions) { if (action.AttributeRouteModel != null) continue; var actionSlug = Slugify(action.ActionName); var actionTmpl = $"{actionSlug}/{{id?}}"; if (actionSlug == DefaultAction) { var defaultActionModel = new ActionModel(action) { AttributeRouteModel = new AttributeRouteModel { Template = "" } }; actionsToAdd.Add(defaultActionModel); } action.AttributeRouteModel = new AttributeRouteModel { Template = actionTmpl }; } // Flaky; contigent on resolution of https://github.com/aspnet/Mvc/issues/4043 foreach (var action in actionsToAdd) { controller.Actions.Add(action); } } } private string Slugify(string pascalString) { return Regex.Replace(pascalString, "([a-z])([A-Z])", "$1-$2").ToLower(); } } }
mit
C#
83dd8a945233e77b3afa298b09f7d4c3ad0bc185
change unused tests
Enigmatrix/Cobalt
Cobalt.Tests/Common/Data/QueryTests.cs
Cobalt.Tests/Common/Data/QueryTests.cs
using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Reactive.Linq; using Cobalt.Common.Data; using Cobalt.Common.Data.Migration.Sqlite; using Cobalt.Common.Data.Repository; using Xunit; namespace Cobalt.Tests.Common.Data { public class QueryTests { public void GetappDurations() { var conn = new SQLiteConnection("Data Source=dat2.db").OpenAndReturn(); var repo = new SqliteRepository(conn, new SqliteMigrator(conn)); var o = repo.GetAppDurations(); var durs = new List<(App, TimeSpan)>(o.ToEnumerable().OrderByDescending(x => x.Duration)); Assert.Contains("chrome", durs.First().Item1.Path); } public void TestGetAppsIncludingTags() { var conn = new SQLiteConnection("Data Source=dat2.db").OpenAndReturn(); var repo = new SqliteRepository(conn, new SqliteMigrator(conn)); var o = repo.GetApps(); var appList = new List<List<Tag>>(o.Select(x => new List<Tag>(x.Tags.ToEnumerable())).ToEnumerable()); Assert.Equal(3, appList.Max(t => t.Count)); } } }
using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Reactive.Linq; using Cobalt.Common.Data; using Cobalt.Common.Data.Migration.Sqlite; using Cobalt.Common.Data.Repository; using Xunit; namespace Cobalt.Tests.Common.Data { public class QueryTests { [Fact] public void GetappDurations() { var conn = new SQLiteConnection("Data Source=dat2.db").OpenAndReturn(); var repo = new SqliteRepository(conn, new SqliteMigrator(conn)); var o = repo.GetAppDurations(); var durs = new List<(App, TimeSpan)>(o.ToEnumerable().OrderByDescending(x => x.Duration)); Assert.Contains("chrome", durs.First().Item1.Path); } [Fact] public void TestGetAppsIncludingTags() { var conn = new SQLiteConnection("Data Source=dat2.db").OpenAndReturn(); var repo = new SqliteRepository(conn, new SqliteMigrator(conn)); var o = repo.GetApps(); var appList = new List<List<Tag>>(o.Select(x => new List<Tag>(x.Tags.ToEnumerable())).ToEnumerable()); Assert.Equal(3, appList.Max(t => t.Count)); } } }
mit
C#
9b866f32a3d94280e16311fe48aa2d44c27f682c
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.10.3")] [assembly: AssemblyInformationalVersion("0.10.3")] /* * Version 0.10.3 * * Renames TargetMembers to TypeMembers to clarify. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.10.2")] [assembly: AssemblyInformationalVersion("0.10.2")] /* * Version 0.10.2 * * Renames CompositeEnumerables to CompositeEnumerable, which fixes the typo. */
mit
C#
6dacc5dbb7cb9c1ed288bd43ff1455bad227ebaf
Test project model color enforcing.
ZhangLeiCharles/mobile,eatskolnikov/mobile,peeedge/mobile,eatskolnikov/mobile,masterrr/mobile,peeedge/mobile,masterrr/mobile,ZhangLeiCharles/mobile,eatskolnikov/mobile
Tests/Data/Models/ProjectModelTest.cs
Tests/Data/Models/ProjectModelTest.cs
using System; using NUnit.Framework; using Toggl.Phoebe.Data.DataObjects; using Toggl.Phoebe.Data.NewModels; namespace Toggl.Phoebe.Tests.Data.Models { [TestFixture] public class ProjectModelTest : ModelTest<ProjectModel> { [Test] public void TestColorEnforcing () { var project = new ProjectModel (new ProjectData () { Id = Guid.NewGuid (), Color = 12345, }); // Make sure that we return the underlying color Assert.AreEqual (12345, project.Color); Assert.That (() => project.GetHexColor (), Throws.Nothing); // And that we enforce to the colors we know of project.Color = 54321; Assert.AreNotEqual (54321, project.Color); Assert.AreEqual (54321 % ProjectModel.HexColors.Length, project.Color); Assert.That (() => project.GetHexColor (), Throws.Nothing); } } }
using System; using NUnit.Framework; using Toggl.Phoebe.Data.NewModels; namespace Toggl.Phoebe.Tests.Data.Models { [TestFixture] public class ProjectModelTest : ModelTest<ProjectModel> { } }
bsd-3-clause
C#
49773a6c649cf36cb58824437c9e695ec32d8296
Exclude 513 for SQLiteMs
LinqToDB4iSeries/linq2db,sdanyliv/linq2db,linq2db/linq2db,jogibear9988/linq2db,AK107/linq2db,inickvel/linq2db,LinqToDB4iSeries/linq2db,ronnyek/linq2db,genusP/linq2db,jogibear9988/linq2db,lvaleriu/linq2db,MaceWindu/linq2db,sdanyliv/linq2db,MaceWindu/linq2db,AK107/linq2db,genusP/linq2db,lvaleriu/linq2db,enginekit/linq2db,linq2db/linq2db
Tests/Linq/UserTests/Issue513Tests.cs
Tests/Linq/UserTests/Issue513Tests.cs
using System.Linq; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; namespace Tests.UserTests { using Model; [TestFixture] public class Issue513Tests : TestBase { [Test, DataContextSource] public void Simple(string context) { using (var db = GetDataContext(context)) { Assert.AreEqual(typeof(InheritanceParentBase), InheritanceParent[0].GetType()); Assert.AreEqual(typeof(InheritanceParent1), InheritanceParent[1].GetType()); Assert.AreEqual(typeof(InheritanceParent2), InheritanceParent[2].GetType()); AreEqual(InheritanceParent, db.InheritanceParent); AreEqual(InheritanceChild, db.InheritanceChild); } } [Test, DataContextSource(TestProvName.SQLiteMs)] public void Test(string context) { using (var semaphore = new Semaphore(0, 10)) { var tasks = new Task[10]; for (var i = 0; i < 10; i++) tasks[i] = new Task(() => TestInternal(context, semaphore)); for (var i = 0; i < 10; i++) tasks[i].Start(); Thread .Sleep(100); semaphore.Release(10); Task.WaitAll(tasks); } } private void TestInternal(string context, Semaphore semaphore) { try { using (var db = GetDataContext(context)) { semaphore.WaitOne(); AreEqual( InheritanceChild.Select(_ => _.Parent).Distinct(), db.InheritanceChild.Select(_ => _.Parent).Distinct()); } } finally { semaphore.Release(); } } } }
using System.Linq; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; namespace Tests.UserTests { using Model; [TestFixture] public class Issue513Tests : TestBase { [Test, DataContextSource] public void Simple(string context) { using (var db = GetDataContext(context)) { Assert.AreEqual(typeof(InheritanceParentBase), InheritanceParent[0].GetType()); Assert.AreEqual(typeof(InheritanceParent1), InheritanceParent[1].GetType()); Assert.AreEqual(typeof(InheritanceParent2), InheritanceParent[2].GetType()); AreEqual(InheritanceParent, db.InheritanceParent); AreEqual(InheritanceChild, db.InheritanceChild); } } [Test, DataContextSource] public void Test(string context) { using (var semaphore = new Semaphore(0, 10)) { var tasks = new Task[10]; for (var i = 0; i < 10; i++) tasks[i] = new Task(() => TestInternal(context, semaphore)); for (var i = 0; i < 10; i++) tasks[i].Start(); Thread .Sleep(100); semaphore.Release(10); Task.WaitAll(tasks); } } private void TestInternal(string context, Semaphore semaphore) { try { using (var db = GetDataContext(context)) { semaphore.WaitOne(); AreEqual( InheritanceChild.Select(_ => _.Parent).Distinct(), db.InheritanceChild.Select(_ => _.Parent).Distinct()); } } finally { semaphore.Release(); } } } }
mit
C#
fe7747da0d7822b72b17b2c3d100c1a765a6b318
Decrease number of operations to run to decrease benchmark duration from few hours to about 30 minutes
Catel/Catel.Benchmarks
src/Catel.Benchmarks.Shared/BenchmarkBase.cs
src/Catel.Benchmarks.Shared/BenchmarkBase.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BenchmarkBase.cs" company="Catel development team"> // Copyright (c) 2008 - 2017 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Benchmarks { using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Engines; // Uncomment to make all benchmarks slower (but probably more accurate) [SimpleJob(RunStrategy.Throughput, launchCount: 1, warmupCount: 3, targetCount: 10, invocationCount: 500)] public abstract class BenchmarkBase { } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BenchmarkBase.cs" company="Catel development team"> // Copyright (c) 2008 - 2017 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Benchmarks { using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Engines; // Uncomment to make all benchmarks slower (but probably more accurate) [SimpleJob(RunStrategy.Throughput, launchCount: 1, warmupCount: 2, targetCount: 10, invocationCount: 10)] public abstract class BenchmarkBase { } }
mit
C#
1c8ebd0f29eec12fd72d5ac782ee9d5549372aec
Change the method of identifying SELECT * to match LiteCore
couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net
src/Couchbase.Lite/API/Query/SelectResult.cs
src/Couchbase.Lite/API/Query/SelectResult.cs
// // SelectResultFactory.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2017 Couchbase, 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 // // 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 Couchbase.Lite.Internal.Query; namespace Couchbase.Lite.Query { /// <summary> /// A class for generating instances of <see cref="ISelectResult"/>. This *will* /// be expanded on in the near future. /// </summary> public static class SelectResult { private static readonly IExpression Star = new QueryTypeExpression("", ExpressionType.KeyPath); /// <summary> /// Creates an instance based on the given expression /// </summary> /// <param name="expression">The expression describing what to select from the /// query (e.g. <see cref="Lite.Query.Expression.Property(string)"/>)</param> /// <returns>The instantiated instance</returns> public static ISelectResultAs Expression(IExpression expression) { return new QuerySelectResult(expression); } /// <summary> /// Creates a select result instance that will return all of the /// data in the retrieved document /// </summary> /// <returns>The instantiated instance</returns> public static ISelectResultFrom All() { return new QuerySelectResult(Star); } } }
// // SelectResultFactory.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2017 Couchbase, 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 // // 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 Couchbase.Lite.Internal.Query; namespace Couchbase.Lite.Query { /// <summary> /// A class for generating instances of <see cref="ISelectResult"/>. This *will* /// be expanded on in the near future. /// </summary> public static class SelectResult { private static readonly IExpression Star = new QueryTypeExpression("*", ExpressionType.KeyPath); /// <summary> /// Creates an instance based on the given expression /// </summary> /// <param name="expression">The expression describing what to select from the /// query (e.g. <see cref="Lite.Query.Expression.Property(string)"/>)</param> /// <returns>The instantiated instance</returns> public static ISelectResultAs Expression(IExpression expression) { return new QuerySelectResult(expression); } /// <summary> /// Creates a select result instance that will return all of the /// data in the retrieved document /// </summary> /// <returns>The instantiated instance</returns> public static ISelectResultFrom All() { return new QuerySelectResult(Star); } } }
apache-2.0
C#
ef817ff2748e9358b48fb7fa0bd51b3f0ce70e32
Make KeyEqualityComparer public.
Faithlife/FaithlifeUtility
src/Faithlife.Utility/KeyEqualityComparer.cs
src/Faithlife.Utility/KeyEqualityComparer.cs
using System; using System.Collections.Generic; namespace Faithlife.Utility { /// <summary> /// An EqualityComparer which tests equality on a key type /// </summary> /// <typeparam name="TSource">The source object type</typeparam> /// <typeparam name="TKey">The key object type</typeparam> public class KeyEqualityComparer<TSource, TKey> : EqualityComparer<TSource> { /// <summary> /// Initializes a new instance of the KeyEqualityComparer class. /// </summary> /// <param name="keySelector">The key selector delegate</param> /// <param name="keyComparer">The IEqualityComparer used for comparison of keys</param> public KeyEqualityComparer(Func<TSource, TKey> keySelector, IEqualityComparer<TKey> keyComparer = null) { m_keySelector = keySelector ?? throw new ArgumentNullException(nameof(keySelector)); m_keyComparer = keyComparer ?? EqualityComparer<TKey>.Default; } /// <summary> /// Determines whether two objects are equal. /// </summary> /// <param name="x">The first object to compare.</param> /// <param name="y">The second object to compare.</param> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> public override bool Equals(TSource x, TSource y) => m_keyComparer.Equals(m_keySelector(x), m_keySelector(y)); /// <summary> /// Serves as a hash function for the specified object for hashing algorithms and data structures, such as a hash table. /// </summary> /// <param name="obj">The object for which to get a hash code.</param> /// <returns>A hash code for the specified object.</returns> /// <exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception> public override int GetHashCode(TSource obj) => obj == null ? 0 : m_keyComparer.GetHashCode(m_keySelector(obj)); readonly Func<TSource, TKey> m_keySelector; readonly IEqualityComparer<TKey> m_keyComparer; } }
using System; using System.Collections.Generic; namespace Faithlife.Utility { /// <summary> /// An EqualityComparer which tests equality on a key type /// </summary> /// <typeparam name="TSource">The source object type</typeparam> /// <typeparam name="TKey">The key object type</typeparam> internal class KeyEqualityComparer<TSource, TKey> : EqualityComparer<TSource> { /// <summary> /// Initializes a new instance of the KeyEqualityComparer class. /// </summary> /// <param name="keySelector">The key selector delegate</param> /// <param name="keyComparer">The IEqualityComparer used for comparison of keys</param> public KeyEqualityComparer(Func<TSource, TKey> keySelector, IEqualityComparer<TKey> keyComparer = null) { m_keySelector = keySelector ?? throw new ArgumentNullException(nameof(keySelector)); m_keyComparer = keyComparer ?? EqualityComparer<TKey>.Default; } /// <summary> /// Determines whether two objects are equal. /// </summary> /// <param name="x">The first object to compare.</param> /// <param name="y">The second object to compare.</param> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> public override bool Equals(TSource x, TSource y) => m_keyComparer.Equals(m_keySelector(x), m_keySelector(y)); /// <summary> /// Serves as a hash function for the specified object for hashing algorithms and data structures, such as a hash table. /// </summary> /// <param name="obj">The object for which to get a hash code.</param> /// <returns>A hash code for the specified object.</returns> /// <exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception> public override int GetHashCode(TSource obj) => obj == null ? 0 : m_keyComparer.GetHashCode(m_keySelector(obj)); readonly Func<TSource, TKey> m_keySelector; readonly IEqualityComparer<TKey> m_keyComparer; } }
mit
C#