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 |
|---|---|---|---|---|---|---|---|---|
cb3af09b197466af0ab8fc8f35ff7cf72e53943b | Add IEndpoint restriction to RegisterEndpointDeliveryService. | justinjstark/Delivered,justinjstark/Verdeler | Verdeler/Distributor.cs | Verdeler/Distributor.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Verdeler
{
public class Distributor<TDistributable> : IDistributor<TDistributable> where TDistributable : IDistributable
{
private readonly List<IEndpointRepository> _endpointRepositories
= new List<IEndpointRepository>();
private readonly Dictionary<Type, IEndpointDeliveryService> _endpointDeliveryServices
= new Dictionary<Type, IEndpointDeliveryService>();
public void RegisterEndpointRepository(IEndpointRepository endpointRepository)
{
if (!_endpointRepositories.Contains(endpointRepository))
{
_endpointRepositories.Add(endpointRepository);
}
}
public void RegisterEndpointDeliveryService<TEndpoint>(IEndpointDeliveryService<TEndpoint> endpointDeliveryService)
where TEndpoint : IEndpoint
{
_endpointDeliveryServices[typeof(TEndpoint)] = endpointDeliveryService;
}
public void Distribute(TDistributable distributable, string recipientName)
{
var endpoints = _endpointRepositories.SelectMany(r => r.GetEndpointsForRecipient(recipientName));
foreach (var endpoint in endpoints)
{
var endpointDeliveryService = _endpointDeliveryServices[endpoint.GetType()];
endpointDeliveryService.Deliver(distributable, endpoint);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Verdeler
{
public class Distributor<TDistributable> : IDistributor<TDistributable> where TDistributable : IDistributable
{
private readonly List<IEndpointRepository> _endpointRepositories
= new List<IEndpointRepository>();
private readonly Dictionary<Type, IEndpointDeliveryService> _endpointDeliveryServices
= new Dictionary<Type, IEndpointDeliveryService>();
public void RegisterEndpointRepository(IEndpointRepository endpointRepository)
{
if (!_endpointRepositories.Contains(endpointRepository))
{
_endpointRepositories.Add(endpointRepository);
}
}
public void RegisterEndpointDeliveryService<TEndpoint>(IEndpointDeliveryService<TEndpoint> endpointDeliveryService)
{
_endpointDeliveryServices[typeof(TEndpoint)] = endpointDeliveryService;
}
public void Distribute(TDistributable distributable, string recipientName)
{
var endpoints = _endpointRepositories.SelectMany(r => r.GetEndpointsForRecipient(recipientName));
foreach (var endpoint in endpoints)
{
var endpointDeliveryService = _endpointDeliveryServices[endpoint.GetType()];
endpointDeliveryService.Deliver(distributable, endpoint);
}
}
}
}
| mit | C# |
6d0723aa7de285b58fa0f723baf1fb0ed841d4a9 | Fix crashes when no arguments or no input | TRex22/Windows-Wifi-Manager,shanselman/Windows-Wifi-Manager | WifiProfiles/Program.cs | WifiProfiles/Program.cs | using NetSh;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WifiProfiles
{
class Program
{
static void Main(string[] args)
{
var profiles = NetShWrapper.GetWifiProfiles();
bool sawBadWifi = false;
foreach (var a in profiles)
{
string warning = NetShWrapper.IsOpenAndAutoWifiProfile(a) ? "Warning: AUTO connect to OPEN WiFi" : String.Empty;
Console.WriteLine(String.Format("{0,-20} {1,10} {2,10} {3,30} ", a.Name, a.ConnectionMode, a.Authentication, warning));
if (!String.IsNullOrWhiteSpace(warning)) sawBadWifi = true;
}
if (sawBadWifi)
{
Console.WriteLine("\r\nDelete WiFi profiles that are OPEN *and* AUTO connect? [y/n]");
if (args.Length > 0 && args[0].ToUpperInvariant() == "/DELETEAUTOOPEN" ||
Console.ReadLine().Trim().ToUpperInvariant().StartsWith("Y"))
{
Console.WriteLine("in here");
foreach (var a in profiles.Where(a => NetShWrapper.IsOpenAndAutoWifiProfile(a)))
{
Console.WriteLine(NetShWrapper.DeleteWifiProfile(a));
}
}
}
else
{
Console.WriteLine("\r\nNo WiFi profiles set to OPEN and AUTO connect were found. \r\nOption: Run with /deleteautoopen to auto delete.");
}
//Console.ReadKey();
}
}
}
| using NetSh;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WifiProfiles
{
class Program
{
static void Main(string[] args)
{
var profiles = NetShWrapper.GetWifiProfiles();
bool sawBadWifi = false;
foreach (var a in profiles)
{
string warning = NetShWrapper.IsOpenAndAutoWifiProfile(a) ? "Warning: AUTO connect to OPEN WiFi" : String.Empty;
Console.WriteLine(String.Format("{0,-20} {1,10} {2,10} {3,30} ", a.Name, a.ConnectionMode, a.Authentication, warning));
if (!String.IsNullOrWhiteSpace(warning)) sawBadWifi = true;
}
if (sawBadWifi)
{
Console.WriteLine("\r\nDelete WiFi profiles that are OPEN *and* AUTO connect? [y/n]");
if (args[0].ToUpperInvariant() == "/DELETEAUTOOPEN" || Console.ReadLine().Trim().ToUpperInvariant()[0] == 'Y')
{
Console.WriteLine("in here");
foreach (var a in profiles.Where(a => NetShWrapper.IsOpenAndAutoWifiProfile(a)))
{
Console.WriteLine(NetShWrapper.DeleteWifiProfile(a));
}
}
}
else
{
Console.WriteLine("\r\nNo WiFi profiles set to OPEN and AUTO connect were found. \r\nOption: Run with /deleteautoopen to auto delete.");
}
//Console.ReadKey();
}
}
}
| mit | C# |
3db53ea3fc4544f67bbd49799222d630e96f3298 | Add some more docs | flagbug/Espera,punker76/Espera | Espera/Espera.Core/Analytics/IAnalyticsEndpoint.cs | Espera/Espera.Core/Analytics/IAnalyticsEndpoint.cs | using System.Globalization;
using System.IO;
using System.Threading.Tasks;
namespace Espera.Core.Analytics
{
public interface IAnalyticsEndpoint
{
Task AuthenticateUserAsync(string analyticsToken);
/// <summary>
/// Creates a new user and returns a unique authentication token.
/// This method also authenticates the with the returned token.
/// </summary>
/// <returns>A unique token used for the next authentication.</returns>
Task<string> CreateUserAsync();
/// <summary>
/// Records runtime information about this device and application.
/// </summary>
Task RecordDeviceInformationAsync();
Task RecordErrorAsync(string message, string logId, string stackTrace = null);
Task RecordMetaDataAsync(string key, string value);
/// <summary>
/// Sends a blob to the analytics endpoint and returns the blob ID.
/// </summary>
Task<string> SendBlobAsync(string name, string mimeType, Stream data);
Task UpdateUserEmailAsync(string email);
}
public static class AnalyticsEndpointMixin
{
public static Task RecordLibrarySizeAsync(this IAnalyticsEndpoint endpoint, int songCount)
{
return endpoint.RecordMetaDataAsync("library-size", songCount.ToString(CultureInfo.InvariantCulture));
}
public static Task RecordMobileUsageAsync(this IAnalyticsEndpoint endpoint)
{
return endpoint.RecordMetaDataAsync("uses-mobile", "true");
}
public static Task<string> SendCrashLogAsync(this IAnalyticsEndpoint endpoint, Stream logFileStream)
{
return endpoint.SendBlobAsync("Crash report log", "application/zip", logFileStream);
}
}
} | using System.Globalization;
using System.IO;
using System.Threading.Tasks;
namespace Espera.Core.Analytics
{
public interface IAnalyticsEndpoint
{
Task AuthenticateUserAsync(string analyticsToken);
Task<string> CreateUserAsync();
/// <summary>
/// Records runtime information about this device and application.
/// </summary>
Task RecordDeviceInformationAsync();
Task RecordErrorAsync(string message, string logId, string stackTrace = null);
Task RecordMetaDataAsync(string key, string value);
/// <summary>
/// Sends a blob to the analytics endpoint and returns the blob ID.
/// </summary>
Task<string> SendBlobAsync(string name, string mimeType, Stream data);
Task UpdateUserEmailAsync(string email);
}
public static class AnalyticsEndpointMixin
{
public static Task RecordLibrarySizeAsync(this IAnalyticsEndpoint endpoint, int songCount)
{
return endpoint.RecordMetaDataAsync("library-size", songCount.ToString(CultureInfo.InvariantCulture));
}
public static Task RecordMobileUsageAsync(this IAnalyticsEndpoint endpoint)
{
return endpoint.RecordMetaDataAsync("uses-mobile", "true");
}
public static Task<string> SendCrashLogAsync(this IAnalyticsEndpoint endpoint, Stream logFileStream)
{
return endpoint.SendBlobAsync("Crash report log", "application/zip", logFileStream);
}
}
} | mit | C# |
1b24539644aaab33aef8581cca93945ca8746f16 | Update version number | markembling/MarkEmbling.PostcodesIO | MarkEmbling.PostcodesIO/Properties/AssemblyInfo.cs | MarkEmbling.PostcodesIO/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("MarkEmbling.PostcodesIO")]
[assembly: AssemblyDescription("Library for interacting with the excellent Postcodes.io service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.PostcodesIO")]
[assembly: AssemblyCopyright("Copyright © Mark Embling & contributors 2015-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("a31ab2d0-733e-4d9e-9e5f-fab2b40dc02e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.2")]
[assembly: AssemblyFileVersion("0.0.2")]
| 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("MarkEmbling.PostcodesIO")]
[assembly: AssemblyDescription("Library for interacting with the excellent Postcodes.io service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.PostcodesIO")]
[assembly: AssemblyCopyright("Copyright © Mark Embling & contributors 2015-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("a31ab2d0-733e-4d9e-9e5f-fab2b40dc02e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
| mit | C# |
ca1edfbf29cb2a184e28cd9e449f366e1edf7549 | Add extensions to store values in the bot state | ObjectivityLtd/Bot.Common.Dialogs | Objectivity.Bot.BaseDialogs/Utils/ContextHelper.cs | Objectivity.Bot.BaseDialogs/Utils/ContextHelper.cs | namespace Objectivity.Bot.BaseDialogs.Utils
{
using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
public static class ContextHelper
{
public static T GetValueFromContext<T>(this IDialogContext context, string key)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
T result;
if (!context.UserData.TryGetValue(key, out result))
{
return default(T);
}
return result;
}
public static bool TryGetValueFromContext<T>(this IDialogContext context, string key, out T value)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.UserData.TryGetValue(key, out value))
{
return true;
}
return false;
}
public static void SetValueIntoContext<T>(this IDialogContext context, string key, T value)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
context.UserData.SetValue(key, value);
}
public static async Task SetValueIntoState<T>(this IDialogContext context, string key, T value)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
using (StateClient stateClient = context.Activity.GetStateClient())
{
IBotState chatbotState = stateClient.BotState;
BotData chatbotData = await chatbotState.GetUserDataAsync(
context.Activity.ChannelId, context.Activity.From.Id);
chatbotData.SetProperty(key, value);
await chatbotState.SetUserDataAsync(context.Activity.ChannelId, context.Activity.From.Id, chatbotData);
}
}
public static async Task<T> GetValueFromState<T>(this IDialogContext context, string key)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
using (StateClient stateClient = context.Activity.GetStateClient())
{
IBotState chatbotState = stateClient.BotState;
BotData chatbotData =
await chatbotState.GetUserDataAsync(context.Activity.ChannelId, context.Activity.From.Id);
return chatbotData.GetProperty<T>(key);
}
}
}
} | namespace Objectivity.Bot.BaseDialogs.Utils
{
using System;
using Microsoft.Bot.Builder.Dialogs;
public static class ContextHelper
{
public static T GetValueFromContext<T>(IDialogContext context, string key)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
T result;
if (!context.UserData.TryGetValue(key, out result))
{
return default(T);
}
return result;
}
public static bool TryGetValueFromContext<T>(IDialogContext context, string key, out T value)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.UserData.TryGetValue(key, out value))
{
return true;
}
return false;
}
public static void SetValueIntoContext<T>(IDialogContext context, string key, T value)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
context.UserData.SetValue(key, value);
}
}
} | mit | C# |
29c5e7dd353007bae2adfccf49562abb72e854d0 | Update to follow dev branch | wangkanai/Detection | src/Services/ResponsiveService.cs | src/Services/ResponsiveService.cs | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Http;
using Wangkanai.Detection.DependencyInjection.Options;
using Wangkanai.Detection.Models;
namespace Wangkanai.Detection.Services
{
public class ResponsiveService : IResponsiveService
{
public Device View { get; }
private readonly HttpContext _context;
private const string ResponsiveContextKey = "Responsive";
public ResponsiveService(IHttpContextAccessor accessor, IDeviceService deviceService, DetectionOptions options)
{
if (accessor is null)
throw new ArgumentNullException(nameof(accessor));
if (deviceService is null)
throw new ArgumentNullException(nameof(deviceService));
if (options is null)
options = new DetectionOptions();
_context = accessor.HttpContext;
View = DefaultView(deviceService.Type, options.Responsive);
View = PreferView(_context, View);
}
public void PreferSet(Device desktop)
=> _context.Session.SetString(ResponsiveContextKey, desktop.ToString());
public void PreferClear()
=> _context.Session.Remove(ResponsiveContextKey);
public bool HasPreferred()
=> _context.SafeSession() != null
&& _context.SafeSession().Keys.Any(k => k == ResponsiveContextKey);
private static Device PreferView(HttpContext context, Device defaultView)
{
if (context.SafeSession() is null)
return defaultView;
if (context.SafeSession().Keys.All(k => k != ResponsiveContextKey))
return defaultView;
context.Session.TryGetValue(ResponsiveContextKey, out var raw);
Enum.TryParse<Device>(Encoding.ASCII.GetString(raw), out var preferView);
if (preferView != Device.Unknown && preferView != defaultView)
return preferView;
return defaultView;
}
private static Device DefaultView(Device device, ResponsiveOptions options)
=> device switch
{
Device.Mobile => options.DefaultMobile,
Device.Tablet => options.DefaultTablet,
Device.Desktop => options.DefaultDesktop,
_ => device
};
}
} | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Http;
using Wangkanai.Detection.DependencyInjection.Options;
using Wangkanai.Detection.Models;
namespace Wangkanai.Detection.Services
{
public class ResponsiveService : IResponsiveService
{
public Device View { get; }
private readonly HttpContext _context;
private const string ResponsiveContextKey = "Responsive";
public ResponsiveService(IHttpContextAccessor accessor, IDeviceService deviceService, DetectionOptions options)
{
if (accessor is null)
throw new ArgumentNullException(nameof(accessor));
if (deviceService is null)
throw new ArgumentNullException(nameof(deviceService));
if (options is null)
options = new DetectionOptions();
_context = accessor.HttpContext;
View = DefaultView(deviceService.Type, options.Responsive);
var preferView = PreferView();
if (preferView != Device.Unknown && preferView != View)
View = PreferView();
}
public void PreferSet(Device desktop)
=> _context.Session.SetString(ResponsiveContextKey, desktop.ToString());
public void PreferClear()
=> _context.Session.Remove(ResponsiveContextKey);
public bool HasPreferred()
=> _context.SafeSession() != null
&& _context.SafeSession().Keys.Any(k => k == ResponsiveContextKey);
private Device PreferView()
{
if (!HasPreferred())
return Device.Unknown;
_context.Session.TryGetValue(ResponsiveContextKey, out var raw);
Enum.TryParse<Device>(Encoding.ASCII.GetString(raw), out var preferred);
return preferred;
}
private static Device DefaultView(Device device, ResponsiveOptions options)
=> device switch
{
Device.Mobile => options.DefaultMobile,
Device.Tablet => options.DefaultTablet,
Device.Desktop => options.DefaultDesktop,
_ => device
};
}
} | apache-2.0 | C# |
402cc0684719059eaa7db03288c42aaa9c789788 | Fix none flag | aritchie/bluetoothle,aritchie/bluetoothle | Plugin.BluetoothLE.Abstractions/AdapterFeatures.cs | Plugin.BluetoothLE.Abstractions/AdapterFeatures.cs | using System;
namespace Plugin.BluetoothLE
{
[Flags]
public enum AdapterFeatures
{
None = -1,
ControlAdapterState = 1,
OpenSettings = 2,
ViewPairedDevices = 4,
LowPoweredScan = 8,
ServerAdvertising = 16,
ServerGatt = 32,
// AdvertiseManufacturerData
AllClient = ViewPairedDevices | LowPoweredScan,
AllServer = ServerAdvertising | ServerGatt,
AllControls = ControlAdapterState | OpenSettings,
All = AllClient | AllServer | AllControls
}
}
| using System;
namespace Plugin.BluetoothLE
{
[Flags]
public enum AdapterFeatures
{
None = 0,
ControlAdapterState = 1,
OpenSettings = 2,
ViewPairedDevices = 4,
LowPoweredScan = 8,
ServerAdvertising = 16,
ServerGatt = 32,
// AdvertiseManufacturerData
AllClient = ViewPairedDevices | LowPoweredScan,
AllServer = ServerAdvertising | ServerGatt,
AllControls = ControlAdapterState | OpenSettings,
All = AllClient | AllServer | AllControls
}
}
| mit | C# |
939c19f72d45867cf072f9cdcf39a6b54ef9c121 | Remove commented out code. | mcneel/RhinoCycles | Settings/OptionsDialogCollapsibleSectionUIPanel.cs | Settings/OptionsDialogCollapsibleSectionUIPanel.cs | /**
Copyright 2014-2017 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System;
using Eto.Forms;
using Rhino.UI.Controls;
namespace RhinoCycles.Settings
{
public class OptionsDialogCollapsibleSectionUIPanel : Panel
{
/// <summary>
/// Returns the ID of this panel.
/// </summary>
public static Guid PanelId
{
get
{
return typeof(OptionsDialogCollapsibleSectionUIPanel).GUID;
}
}
/// <summary>
/// Public constructor
/// </summary>
public OptionsDialogCollapsibleSectionUIPanel()
{
InitializeComponents();
InitializeLayout();
}
private EtoCollapsibleSectionHolder m_holder;
private void InitializeComponents()
{
m_holder = new EtoCollapsibleSectionHolder();
}
ApplicationSection m_applicationSection;
IntegratorSection m_integratorSection;
SessionSection m_sessionSection;
DeviceSection m_deviceSection;
private void InitializeLayout()
{
m_applicationSection = new ApplicationSection(true);
m_integratorSection = new IntegratorSection(true);
m_sessionSection = new SessionSection(true);
m_deviceSection = new DeviceSection(true);
m_holder.Add(m_applicationSection);
m_holder.Add(m_integratorSection);
m_holder.Add(m_sessionSection);
m_holder.Add(m_deviceSection);
UpdateSections();
Content = m_holder;
}
private void ResetAllSection_Reset(object sender, EventArgs e)
{
UpdateSections();
}
public void UpdateSections()
{
m_applicationSection.DisplayData();
m_deviceSection.DisplayData();
m_integratorSection.DisplayData();
m_sessionSection.DisplayData();
}
}
}
| /**
Copyright 2014-2017 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System;
using Eto.Forms;
using Rhino.UI.Controls;
namespace RhinoCycles.Settings
{
public class OptionsDialogCollapsibleSectionUIPanel : Panel
{
/// <summary>
/// Returns the ID of this panel.
/// </summary>
public static Guid PanelId
{
get
{
return typeof(OptionsDialogCollapsibleSectionUIPanel).GUID;
}
}
/// <summary>
/// Public constructor
/// </summary>
public OptionsDialogCollapsibleSectionUIPanel()
{
InitializeComponents();
InitializeLayout();
}
private EtoCollapsibleSectionHolder m_holder;
private void InitializeComponents()
{
m_holder = new EtoCollapsibleSectionHolder();
}
ApplicationSection m_applicationSection;
IntegratorSection m_integratorSection;
SessionSection m_sessionSection;
DeviceSection m_deviceSection;
//ResetAllSection m_resetAllSection;
private void InitializeLayout()
{
m_applicationSection = new ApplicationSection(true);
m_integratorSection = new IntegratorSection(true);
m_sessionSection = new SessionSection(true);
m_deviceSection = new DeviceSection(true);
//m_resetAllSection = new ResetAllSection(true);
//m_resetAllSection.Reset += ResetAllSection_Reset;
//m_applicationSection.DisplayData();
//m_deviceSection.DisplayData();
//m_integratorSection.DisplayData();
//m_sessionSection.DisplayData();
m_holder.Add(m_applicationSection);
m_holder.Add(m_integratorSection);
m_holder.Add(m_sessionSection);
m_holder.Add(m_deviceSection);
UpdateSections();
//m_holder.Add(m_resetAllSection);
Content = m_holder;
}
private void ResetAllSection_Reset(object sender, EventArgs e)
{
UpdateSections();
}
public void UpdateSections()
{
m_applicationSection.DisplayData();
m_deviceSection.DisplayData();
m_integratorSection.DisplayData();
m_sessionSection.DisplayData();
}
}
}
| apache-2.0 | C# |
783d1a7d3866415d888e62e57bf0c90e55fb5e5e | Add copyright info in DLL properties. | nzgeek/ElitePlayerJournal | src/Properties/AssemblyInfo.cs | src/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("ElitePlayerJournal")]
[assembly: AssemblyDescription("A library for reading Elite Dangerous player journal files.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ElitePlayerJournal")]
[assembly: AssemblyCopyright("Copyright © Jamie Anderson 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("195b246a-62a6-4399-944a-4ad55e722994")]
// 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")]
| 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("ElitePlayerJournal")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ElitePlayerJournal")]
[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("195b246a-62a6-4399-944a-4ad55e722994")]
// 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: InternalsVisibleTo("Netwonsoft.Json")]
| mit | C# |
25c7dc9ef0f7716a08878733b9cba18063cfef48 | Revert unnecessary change | ppy/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu | osu.Game/Online/Chat/DrawableLinkCompiler.cs | osu.Game/Online/Chat/DrawableLinkCompiler.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Online.Chat
{
/// <summary>
/// An invisible drawable that brings multiple <see cref="Drawable"/> pieces together to form a consumable clickable link.
/// </summary>
public class DrawableLinkCompiler : OsuHoverContainer
{
/// <summary>
/// Each word part of a chat link (split for word-wrap support).
/// </summary>
public List<Drawable> Parts;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos));
protected override HoverClickSounds CreateHoverClickSounds(HoverSampleSet sampleSet) => new LinkHoverSounds(sampleSet, Parts);
public DrawableLinkCompiler(IEnumerable<Drawable> parts)
{
Parts = parts.ToList();
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
IdleColour = colours.Blue;
}
protected override IEnumerable<Drawable> EffectTargets => Parts;
private class LinkHoverSounds : HoverClickSounds
{
private readonly List<Drawable> parts;
public LinkHoverSounds(HoverSampleSet sampleSet, List<Drawable> parts)
: base(sampleSet)
{
this.parts = parts;
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Online.Chat
{
/// <summary>
/// An invisible drawable that brings multiple <see cref="Drawable"/> pieces together to form a consumable clickable link.
/// </summary>
public class DrawableLinkCompiler : OsuHoverContainer
{
/// <summary>
/// Each word part of a chat link (split for word-wrap support).
/// </summary>
public List<Drawable> Parts;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos));
protected override HoverClickSounds CreateHoverClickSounds(HoverSampleSet sampleSet) => new LinkHoverSounds(sampleSet, Parts);
public DrawableLinkCompiler(IEnumerable<Drawable> parts)
{
Parts = parts.ToList();
}
public DrawableLinkCompiler(Drawable part)
{
Parts = new List<Drawable> { part };
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
IdleColour = colours.Blue;
}
protected override IEnumerable<Drawable> EffectTargets => Parts;
private class LinkHoverSounds : HoverClickSounds
{
private readonly List<Drawable> parts;
public LinkHoverSounds(HoverSampleSet sampleSet, List<Drawable> parts)
: base(sampleSet)
{
this.parts = parts;
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos));
}
}
}
| mit | C# |
0e04260b3c0083e831de9b429eaa4e9d4c964dff | Move ToolbarUserArea initialisation to BDL | smoogipoo/osu,peppy/osu-new,DrabWeb/osu,ppy/osu,naoey/osu,Drezi126/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,Frontear/osuKyzer,UselessToucan/osu,2yangk23/osu,peppy/osu,naoey/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,2yangk23/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,Nabile-Rahmani/osu,johnneijzen/osu,ZLima12/osu,ZLima12/osu,UselessToucan/osu,DrabWeb/osu,peppy/osu,DrabWeb/osu,ppy/osu,EVAST9919/osu,naoey/osu,peppy/osu | osu.Game/Overlays/Toolbar/ToolbarUserArea.cs | osu.Game/Overlays/Toolbar/ToolbarUserArea.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using OpenTK;
namespace osu.Game.Overlays.Toolbar
{
internal class ToolbarUserArea : Container
{
public LoginOverlay LoginOverlay;
private ToolbarUserButton button;
public override RectangleF BoundingBox => button.BoundingBox;
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.Y;
AutoSizeAxes = Axes.X;
Children = new Drawable[] {
button = new ToolbarUserButton
{
Action = () => LoginOverlay.ToggleVisibility(),
},
LoginOverlay = new LoginOverlay
{
BypassAutoSizeAxes = Axes.Both,
Position = new Vector2(0, 1),
RelativePositionAxes = Axes.Y,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
}
};
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using OpenTK;
namespace osu.Game.Overlays.Toolbar
{
internal class ToolbarUserArea : Container
{
public LoginOverlay LoginOverlay;
private readonly ToolbarUserButton button;
public override RectangleF BoundingBox => button.BoundingBox;
public ToolbarUserArea()
{
RelativeSizeAxes = Axes.Y;
AutoSizeAxes = Axes.X;
Children = new Drawable[] {
button = new ToolbarUserButton
{
Action = () => LoginOverlay.ToggleVisibility(),
},
LoginOverlay = new LoginOverlay
{
BypassAutoSizeAxes = Axes.Both,
Position = new Vector2(0, 1),
RelativePositionAxes = Axes.Y,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
}
};
}
}
} | mit | C# |
629b473151cfe27abbfe09e454c9a374fa7ade0e | add logging to AbpDefaultRequestCultureProvider | carldai0106/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,luchaoshuai/aspnetboilerplate | src/Abp.AspNetCore/AspNetCore/Localization/AbpDefaultRequestCultureProvider.cs | src/Abp.AspNetCore/AspNetCore/Localization/AbpDefaultRequestCultureProvider.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.DependencyInjection;
using Abp.Configuration;
using Abp.Extensions;
using Abp.Localization;
using Castle.Core.Logging;
namespace Abp.AspNetCore.Localization
{
public class AbpDefaultRequestCultureProvider : RequestCultureProvider
{
public ILogger Logger { get; set; }
public AbpDefaultRequestCultureProvider()
{
Logger = NullLogger.Instance;
}
public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
var settingManager = httpContext.RequestServices.GetRequiredService<ISettingManager>();
var culture = await settingManager.GetSettingValueAsync(LocalizationSettingNames.DefaultLanguage);
if (culture.IsNullOrEmpty())
{
return null;
}
Logger.DebugFormat("{0} - Using Culture:{1} , UICulture:{2}", nameof(AbpDefaultRequestCultureProvider), culture, culture);
return new ProviderCultureResult(culture, culture);
}
}
}
| using System.Threading.Tasks;
using Abp.Configuration;
using Abp.Extensions;
using Abp.Localization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.DependencyInjection;
namespace Abp.AspNetCore.Localization
{
public class AbpDefaultRequestCultureProvider : RequestCultureProvider
{
public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
var settingManager = httpContext.RequestServices.GetRequiredService<ISettingManager>();
var culture = await settingManager.GetSettingValueAsync(LocalizationSettingNames.DefaultLanguage);
if (culture.IsNullOrEmpty())
{
return null;
}
return new ProviderCultureResult(culture, culture);
}
}
}
| mit | C# |
5541d3ce96ab7f44625d9d29ccadd1833420d19a | Add TabHeaderHeight property. | PenguinF/sandra-three | Eutherion/Win/Controls/GlyphTabControl.cs | Eutherion/Win/Controls/GlyphTabControl.cs | #region License
/*********************************************************************************
* GlyphTabControl.cs
*
* Copyright (c) 2004-2020 Henk Nicolai
*
* 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.
*
**********************************************************************************/
#endregion
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Eutherion.Win.Controls
{
/// <summary>
/// Non-selectable control which displays a set of tab pages, and draws a modified-close glyph in each tab header.
/// </summary>
public partial class GlyphTabControl : ContainerControl
{
/// <summary>
/// Gets the character which represents a modified state.
/// </summary>
public static string ModifiedMarkerCharacter { get; } = "•";
private static int Checked(int value, int minimumValue, string propertyName)
{
if (value < minimumValue) throw new ArgumentOutOfRangeException(propertyName, value, $"{propertyName} must be {minimumValue} or higher.");
return value;
}
/// <summary>
/// Gets or sets the tab header height. The minimum value is 1. The default value is <see cref="DefaultTabHeaderHeight"/> (26).
/// </summary>
[DefaultValue(DefaultTabHeaderHeight)]
public int TabHeaderHeight
{
get => tabHeaderHeight;
set { if (tabHeaderHeight != value) { tabHeaderHeight = Checked(value, 1, nameof(TabHeaderHeight)); PerformLayout(); } }
}
private int tabHeaderHeight = DefaultTabHeaderHeight;
/// <summary>
/// The default value for the <see cref="TabHeaderHeight"/> property.
/// </summary>
public const int DefaultTabHeaderHeight = 26;
}
}
| #region License
/*********************************************************************************
* GlyphTabControl.cs
*
* Copyright (c) 2004-2020 Henk Nicolai
*
* 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.
*
**********************************************************************************/
#endregion
using System.Windows.Forms;
namespace Eutherion.Win.Controls
{
/// <summary>
/// Non-selectable control which displays a set of tab pages, and draws a modified-close glyph in each tab header.
/// </summary>
public partial class GlyphTabControl : ContainerControl
{
/// <summary>
/// Gets the character which represents a modified state.
/// </summary>
public static string ModifiedMarkerCharacter { get; } = "•";
}
}
| apache-2.0 | C# |
6e71026a5761fe1e778c6780910686d970632027 | Update DocumentWindow.xaml.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D/UI/Avalonia/Windows/DocumentWindow.xaml.cs | src/Core2D/UI/Avalonia/Windows/DocumentWindow.xaml.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 Avalonia;
using Avalonia.Markup.Xaml;
using Dock.Avalonia.Controls;
namespace Core2D.UI.Avalonia.Windows
{
/// <summary>
/// Interaction logic for <see cref="DocumentWindow"/> xaml.
/// </summary>
public class DocumentWindow : MetroWindow
{
/// <summary>
/// Initializes a new instance of the <see cref="DocumentWindow"/> class.
/// </summary>
public DocumentWindow()
{
InitializeComponent();
this.AttachDevTools();
App.Selector.EnableThemes(this);
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| // 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 Avalonia;
using Avalonia.Markup.Xaml;
using Avalonia.ThemeManager;
using Dock.Avalonia.Controls;
namespace Core2D.UI.Avalonia.Windows
{
/// <summary>
/// Interaction logic for <see cref="DocumentWindow"/> xaml.
/// </summary>
public class DocumentWindow : MetroWindow
{
/// <summary>
/// Initializes a new instance of the <see cref="DocumentWindow"/> class.
/// </summary>
public DocumentWindow()
{
InitializeComponent();
this.AttachDevTools();
App.Selector.EnableThemes(this);
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| mit | C# |
cb9c7e6ffc8a4cf3e3c1bd517042c868b05bac61 | Support for basic auth in web api & odata | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | src/Server/Bit.WebApi/Implementations/DefaultWebApiGlobalActionFilterProviders.cs | src/Server/Bit.WebApi/Implementations/DefaultWebApiGlobalActionFilterProviders.cs | using System.Web.Http;
using Bit.WebApi.ActionFilters;
using Bit.WebApi.Contracts;
namespace Bit.WebApi.Implementations
{
public class GlobalHostAuthenticationFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));
webApiConfiguration.Filters.Add(new HostAuthenticationFilter("Basic"));
}
}
public class GlobalDefaultExceptionHandlerActionFilterProvider<TExceptionHandlerFilterAttribute> : IWebApiConfigurationCustomizer
where TExceptionHandlerFilterAttribute : ExceptionHandlerFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TExceptionHandlerFilterAttribute());
}
}
public class GlobalDefaultLogOperationArgsActionFilterProvider<TOperationArgsArgs> : IWebApiConfigurationCustomizer
where TOperationArgsArgs : LogOperationArgsFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TOperationArgsArgs());
}
}
public class GlobalDefaultRequestModelStateValidatorActionFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new RequestModelStateValidatorActionFilterAttribute());
}
}
}
| using System.Web.Http;
using Bit.WebApi.ActionFilters;
using Bit.WebApi.Contracts;
namespace Bit.WebApi.Implementations
{
public class GlobalHostAuthenticationFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));
}
}
public class GlobalDefaultExceptionHandlerActionFilterProvider<TExceptionHandlerFilterAttribute> : IWebApiConfigurationCustomizer
where TExceptionHandlerFilterAttribute : ExceptionHandlerFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TExceptionHandlerFilterAttribute());
}
}
public class GlobalDefaultLogOperationArgsActionFilterProvider<TOperationArgsArgs> : IWebApiConfigurationCustomizer
where TOperationArgsArgs : LogOperationArgsFilterAttribute, new()
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new TOperationArgsArgs());
}
}
public class GlobalDefaultRequestModelStateValidatorActionFilterProvider : IWebApiConfigurationCustomizer
{
public virtual void CustomizeWebApiConfiguration(HttpConfiguration webApiConfiguration)
{
webApiConfiguration.Filters.Add(new RequestModelStateValidatorActionFilterAttribute());
}
}
}
| mit | C# |
e950214ceb07da422ef229d26cf928624f4a3b40 | Update AbsolutePositioning.cs | asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/DrawingObjects/Pictures/PositioningPictures/AbsolutePositioning.cs | Examples/CSharp/DrawingObjects/Pictures/PositioningPictures/AbsolutePositioning.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.DrawingObjects.Pictures.PositioningPictures
{
public class AbsolutePositioning
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Adding a new worksheet to the Workbook object
int sheetIndex = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];
//Adding a picture at the location of a cell whose row and column indices
//are 5 in the worksheet. It is "F6" cell
int pictureIndex = worksheet.Pictures.Add(5, 5, dataDir + "logo.jpg");
//Accessing the newly added picture
Aspose.Cells.Drawing.Picture picture = worksheet.Pictures[pictureIndex];
//Absolute positioning of the picture in unit of pixels
picture.Left = 60;
picture.Top = 10;
//Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.DrawingObjects.Pictures.PositioningPictures
{
public class AbsolutePositioning
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Adding a new worksheet to the Workbook object
int sheetIndex = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[sheetIndex];
//Adding a picture at the location of a cell whose row and column indices
//are 5 in the worksheet. It is "F6" cell
int pictureIndex = worksheet.Pictures.Add(5, 5, dataDir + "logo.jpg");
//Accessing the newly added picture
Aspose.Cells.Drawing.Picture picture = worksheet.Pictures[pictureIndex];
//Absolute positioning of the picture in unit of pixels
picture.Left = 60;
picture.Top = 10;
//Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");
}
}
} | mit | C# |
13d6c30da555893d1e09d2f8a2821285c33cd202 | Fix MySQL foreign key stuff | Cyberboss/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server | src/Tgstation.Server.Host/Models/Migrations/20190219042440_MYFixRevInfoIndex.cs | src/Tgstation.Server.Host/Models/Migrations/20190219042440_MYFixRevInfoIndex.cs | using Microsoft.EntityFrameworkCore.Migrations;
namespace Tgstation.Server.Host.Models.Migrations
{
/// <summary>
/// Make commit shas non-unique per Instance for MSSQL
/// </summary>
public partial class MYFixRevInfoIndex : Migration
{
/// <summary>
/// Applies the migration
/// </summary>
/// <param name="migrationBuilder">The <see cref="MigrationBuilder"/> to use</param>
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_RevisionInformations_Instances_InstanceId",
table: "RevisionInformations");
migrationBuilder.DropIndex(
name: "IX_RevisionInformations_CommitSha",
table: "RevisionInformations");
migrationBuilder.DropIndex(
name: "IX_RevisionInformations_InstanceId",
table: "RevisionInformations");
migrationBuilder.CreateIndex(
name: "IX_RevisionInformations_InstanceId_CommitSha",
table: "RevisionInformations",
columns: new[] { "InstanceId", "CommitSha" },
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_RevisionInformations_Instances_InstanceId",
table: "RevisionInformations",
column: "InstanceId",
principalTable: "Instances",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <summary>
/// Unapplies the migration
/// </summary>
/// <param name="migrationBuilder">The <see cref="MigrationBuilder"/> to use</param>
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_RevisionInformations_Instances_InstanceId",
table: "RevisionInformations");
migrationBuilder.DropIndex(
name: "IX_RevisionInformations_InstanceId_CommitSha",
table: "RevisionInformations");
migrationBuilder.CreateIndex(
name: "IX_RevisionInformations_CommitSha",
table: "RevisionInformations",
column: "CommitSha",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_RevisionInformations_InstanceId",
table: "RevisionInformations",
column: "InstanceId");
migrationBuilder.AddForeignKey(
name: "FK_RevisionInformations_Instances_InstanceId",
table: "RevisionInformations",
column: "InstanceId",
principalTable: "Instances",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
| using Microsoft.EntityFrameworkCore.Migrations;
namespace Tgstation.Server.Host.Models.Migrations
{
/// <summary>
/// Make commit shas non-unique per Instance for MSSQL
/// </summary>
public partial class MYFixRevInfoIndex : Migration
{
/// <summary>
/// Applies the migration
/// </summary>
/// <param name="migrationBuilder">The <see cref="MigrationBuilder"/> to use</param>
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_RevisionInformations_CommitSha",
table: "RevisionInformations");
migrationBuilder.DropIndex(
name: "IX_RevisionInformations_InstanceId",
table: "RevisionInformations");
migrationBuilder.CreateIndex(
name: "IX_RevisionInformations_InstanceId_CommitSha",
table: "RevisionInformations",
columns: new[] { "InstanceId", "CommitSha" },
unique: true);
}
/// <summary>
/// Unapplies the migration
/// </summary>
/// <param name="migrationBuilder">The <see cref="MigrationBuilder"/> to use</param>
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_RevisionInformations_InstanceId_CommitSha",
table: "RevisionInformations");
migrationBuilder.CreateIndex(
name: "IX_RevisionInformations_CommitSha",
table: "RevisionInformations",
column: "CommitSha",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_RevisionInformations_InstanceId",
table: "RevisionInformations",
column: "InstanceId");
}
}
}
| agpl-3.0 | C# |
03a207e56ed52946d83890fb81439f2de747a4d2 | Set log level to DEBUG | boumenot/Grobid.NET | test/Grobid.Test/GrobidTest.cs | test/Grobid.Test/GrobidTest.cs | using System;
using System.IO;
using ApprovalTests;
using ApprovalTests.Reporters;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using org.apache.log4j;
using org.grobid.core;
namespace Grobid.Test
{
[UseReporter(typeof(DiffReporter))]
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG);
}
[Fact]
[Trait("Test", "EndToEnd")]
public void ExtractTest()
{
var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE");
org.apache.log4j.Logger.getRootLogger().info("PDFTOXMLEXE=" + binPath);
var factory = new GrobidFactory(
"grobid.zip",
binPath,
Directory.GetCurrentDirectory());
var grobid = factory.Create();
var result = grobid.Extract(@"essence-linq.pdf");
result.Should().NotBeEmpty();
Approvals.Verify(result);
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
| using System;
using System.IO;
using ApprovalTests;
using ApprovalTests.Reporters;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using org.apache.log4j;
using org.grobid.core;
namespace Grobid.Test
{
[UseReporter(typeof(DiffReporter))]
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.INFO);
}
[Fact]
[Trait("Test", "EndToEnd")]
public void ExtractTest()
{
var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE");
var factory = new GrobidFactory(
"grobid.zip",
binPath,
Directory.GetCurrentDirectory());
var grobid = factory.Create();
var result = grobid.Extract(@"essence-linq.pdf");
result.Should().NotBeEmpty();
Approvals.Verify(result);
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
| apache-2.0 | C# |
048ad581547a0aa777462b2fae005009a92f4282 | Refactor broker vars | InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET | src/InEngine.Core/Queuing/Commands/RepublishFailed.cs | src/InEngine.Core/Queuing/Commands/RepublishFailed.cs | using System;
using System.Linq;
using CommandLine;
namespace InEngine.Core.Queuing.Commands
{
public class RepublishFailed : AbstractCommand
{
[Option("limit", DefaultValue = 100, HelpText = "The maximum number of messages to republish.")]
public int Limit { get; set; }
[Option("secondary", DefaultValue = false, HelpText = "Republish failed secondary queue messages.")]
public bool UseSecondaryQueue { get; set; }
public override void Run()
{
var queue = Queue.Make(UseSecondaryQueue);
Enumerable.Range(0, Limit)
.ToList()
.ForEach(x => queue.RepublishFailedMessages());
}
}
}
| using System;
using System.Linq;
using CommandLine;
namespace InEngine.Core.Queuing.Commands
{
public class RepublishFailed : AbstractCommand
{
[Option("limit", DefaultValue = 100, HelpText = "The maximum number of messages to republish.")]
public int Limit { get; set; }
[Option("secondary", DefaultValue = false, HelpText = "Republish failed secondary queue messages.")]
public bool UseSecondaryQueue { get; set; }
public override void Run()
{
var broker = Queue.Make(UseSecondaryQueue);
Enumerable.Range(0, Limit)
.ToList()
.ForEach(x => broker.RepublishFailedMessages());
}
}
}
| mit | C# |
73a8f654bf7e6d0b86d87f6326c3f17cbfaf885a | Fix crash when creating a new project if osu!'s folder could not be found. | Damnae/storybrew | editor/Util/OsuHelper.cs | editor/Util/OsuHelper.cs | using Microsoft.Win32;
using System;
using System.IO;
namespace StorybrewEditor.Util
{
public static class OsuHelper
{
public static string GetOsuPath()
{
using (var registryKey = Registry.ClassesRoot.OpenSubKey("osu\\DefaultIcon"))
{
if (registryKey == null)
return string.Empty;
var value = registryKey.GetValue(null).ToString();
var startIndex = value.IndexOf("\"");
var endIndex = value.LastIndexOf("\"");
return value.Substring(startIndex + 1, endIndex - 1);
}
}
public static string GetOsuFolder()
{
var osuPath = GetOsuPath();
if (osuPath.Length == 0)
return Path.GetPathRoot(Environment.SystemDirectory);
return Path.GetDirectoryName(osuPath);
}
public static string GetOsuSongFolder()
{
var osuPath = GetOsuPath();
if (osuPath.Length == 0)
return Path.GetPathRoot(Environment.SystemDirectory);
var osuFolder = Path.GetDirectoryName(osuPath);
var songsFolder = Path.Combine(osuFolder, "Songs");
return Directory.Exists(songsFolder) ? songsFolder : osuFolder;
}
}
}
| using Microsoft.Win32;
using System.IO;
namespace StorybrewEditor.Util
{
public static class OsuHelper
{
public static string GetOsuPath()
{
using (var registryKey = Registry.ClassesRoot.OpenSubKey("osu\\DefaultIcon"))
{
if (registryKey == null)
return string.Empty;
var value = registryKey.GetValue(null).ToString();
var startIndex = value.IndexOf("\"");
var endIndex = value.LastIndexOf("\"");
return value.Substring(startIndex + 1, endIndex - 1);
}
}
public static string GetOsuFolder()
=> Path.GetDirectoryName(GetOsuPath());
public static string GetOsuSongFolder()
{
var osuFolder = Path.GetDirectoryName(GetOsuPath());
var songsFolder = Path.Combine(osuFolder, "Songs");
return Directory.Exists(songsFolder) ? songsFolder : osuFolder;
}
}
}
| mit | C# |
a723a5f55294d5bfe8348b9317b87f1c434c45ce | replace duplicate short name, with backward compatibility (#23) | esskar/Serialize.Linq | src/Serialize.Linq/Nodes/ConditionalExpressionNode.cs | src/Serialize.Linq/Nodes/ConditionalExpressionNode.cs | using System;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using Serialize.Linq.Interfaces;
namespace Serialize.Linq.Nodes
{
#region DataContract
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataContract]
#else
[DataContract(Name = "IF")]
#endif
#if !SILVERLIGHT
[Serializable]
#endif
#endregion
public class ConditionalExpressionNode : ExpressionNode<ConditionalExpression>
{
public ConditionalExpressionNode() { }
public ConditionalExpressionNode(INodeFactory factory, ConditionalExpression expression)
: base(factory, expression) { }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFF")]
#endif
#endregion
public ExpressionNode IfFalse { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFT")]
#endif
#endregion
public ExpressionNode IfTrue { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
#if SERIALIZE_LINQ_BORKED_VERION
[DataMember(EmitDefaultValue = false, Name = "T")]
#else
[DataMember(EmitDefaultValue = false, Name = "C")]
#endif
#endif
#endregion
public ExpressionNode Test { get; set; }
/// <summary>
/// Initializes the specified expression.
/// </summary>
/// <param name="expression">The expression.</param>
protected override void Initialize(ConditionalExpression expression)
{
this.Test = this.Factory.Create(expression.Test);
this.IfTrue = this.Factory.Create(expression.IfTrue);
this.IfFalse = this.Factory.Create(expression.IfFalse);
}
/// <summary>
/// Converts this instance to an expression.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public override Expression ToExpression(ExpressionContext context)
{
return Expression.Condition(this.Test.ToExpression(context), this.IfTrue.ToExpression(context), this.IfFalse.ToExpression(context));
}
}
}
| using System;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using Serialize.Linq.Interfaces;
namespace Serialize.Linq.Nodes
{
#region DataContract
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataContract]
#else
[DataContract(Name = "IF")]
#endif
#if !SILVERLIGHT
[Serializable]
#endif
#endregion
public class ConditionalExpressionNode : ExpressionNode<ConditionalExpression>
{
public ConditionalExpressionNode() { }
public ConditionalExpressionNode(INodeFactory factory, ConditionalExpression expression)
: base(factory, expression) { }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFF")]
#endif
#endregion
public ExpressionNode IfFalse { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "IFT")]
#endif
#endregion
public ExpressionNode IfTrue { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "C")]
#endif
#endregion
public ExpressionNode Test { get; set; }
/// <summary>
/// Initializes the specified expression.
/// </summary>
/// <param name="expression">The expression.</param>
protected override void Initialize(ConditionalExpression expression)
{
this.Test = this.Factory.Create(expression.Test);
this.IfTrue = this.Factory.Create(expression.IfTrue);
this.IfFalse = this.Factory.Create(expression.IfFalse);
}
/// <summary>
/// Converts this instance to an expression.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public override Expression ToExpression(ExpressionContext context)
{
return Expression.Condition(this.Test.ToExpression(context), this.IfTrue.ToExpression(context), this.IfFalse.ToExpression(context));
}
}
}
| mit | C# |
0e3969794a4278ce81165598a942e53f407760d1 | Clean up LingeringNetworkStream | murador/xsp,murador/xsp,arthot/xsp,arthot/xsp,stormleoxia/xsp,murador/xsp,arthot/xsp,stormleoxia/xsp,stormleoxia/xsp,stormleoxia/xsp,murador/xsp,arthot/xsp | src/Mono.WebServer/LingeringNetworkStream.cs | src/Mono.WebServer/LingeringNetworkStream.cs | //
// Mono.WebServer.LingeringNetworkStream
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) Copyright 2004 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net.Sockets;
namespace Mono.WebServer
{
public class LingeringNetworkStream : NetworkStream
{
const int useconds_to_linger = 2000000;
const int max_useconds_to_linger = 30000000;
// We dont actually use the data from this buffer. So we cache it...
static byte [] buffer;
public LingeringNetworkStream (Socket sock, bool owns) : base (sock, owns)
{
EnableLingering = true;
OwnsSocket = owns;
}
public bool OwnsSocket { get; private set; }
public bool EnableLingering { get; set; }
void LingeringClose ()
{
int waited = 0;
if (!Connected)
return;
try {
Socket.Shutdown (SocketShutdown.Send);
DateTime start = DateTime.UtcNow;
while (waited < max_useconds_to_linger) {
int nread = 0;
try {
if (!Socket.Poll (useconds_to_linger, SelectMode.SelectRead))
break;
if (buffer == null)
buffer = new byte [512];
nread = Socket.Receive (buffer, 0, buffer.Length, 0);
} catch { }
if (nread == 0)
break;
waited += (int) (DateTime.UtcNow - start).TotalMilliseconds * 1000;
}
} catch {
// ignore - we don't care, we're closing anyway
}
}
public override void Close ()
{
if (EnableLingering) {
try {
LingeringClose ();
} finally {
base.Close ();
}
}
else
base.Close ();
}
public bool Connected {
get { return Socket.Connected; }
}
}
}
| //
// Mono.WebServer.LingeringNetworkStream
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) Copyright 2004 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net.Sockets;
namespace Mono.WebServer
{
public class LingeringNetworkStream : NetworkStream
{
const int useconds_to_linger = 2000000;
const int max_useconds_to_linger = 30000000;
bool enableLingering = true;
// We dont actually use the data from this buffer. So we cache it...
static byte [] buffer;
bool owns;
public LingeringNetworkStream (Socket sock, bool owns) : base (sock, owns)
{
this.owns = owns;
}
public bool OwnsSocket {
get { return owns; }
}
public bool EnableLingering
{
get { return enableLingering; }
set { enableLingering = value; }
}
void LingeringClose ()
{
int waited = 0;
if (!Connected)
return;
try {
Socket.Shutdown (SocketShutdown.Send);
DateTime start = DateTime.UtcNow;
while (waited < max_useconds_to_linger) {
int nread = 0;
try {
if (!Socket.Poll (useconds_to_linger, SelectMode.SelectRead))
break;
if (buffer == null)
buffer = new byte [512];
nread = Socket.Receive (buffer, 0, buffer.Length, 0);
} catch { }
if (nread == 0)
break;
waited += (int) (DateTime.UtcNow - start).TotalMilliseconds * 1000;
}
} catch {
// ignore - we don't care, we're closing anyway
}
}
public override void Close ()
{
if (enableLingering) {
try {
LingeringClose ();
} finally {
base.Close ();
}
}
else
base.Close ();
}
public bool Connected {
get { return Socket.Connected; }
}
}
}
| mit | C# |
999bac4c33cd33234972afabdac3ac4c90747237 | Add version information and description to the assembly | Domysee/Pather.CSharp | src/Pather.CSharp/Properties/AssemblyInfo.cs | src/Pather.CSharp/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("Pather.CSharp")]
[assembly: AssemblyDescription("Pather.CSharp - A Path Resolution Library for C#")]
[assembly: AssemblyVersion("0.1")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pather.CSharp")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0ce3a750-ffd7-49d1-a737-204ec60c70a5")]
| 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("Pather.CSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pather.CSharp")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0ce3a750-ffd7-49d1-a737-204ec60c70a5")]
| mit | C# |
65de100acff6a2b2d2556258cc12d02e0f3fbd14 | Fix Repository.Info.IsEmpty | ethomson/libgit2sharp,jorgeamado/libgit2sharp,ethomson/libgit2sharp,Skybladev2/libgit2sharp,AMSadek/libgit2sharp,jeffhostetler/public_libgit2sharp,jamill/libgit2sharp,OidaTiftla/libgit2sharp,whoisj/libgit2sharp,mono/libgit2sharp,AArnott/libgit2sharp,psawey/libgit2sharp,vivekpradhanC/libgit2sharp,AMSadek/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,carlosmn/libgit2sharp,dlsteuer/libgit2sharp,vivekpradhanC/libgit2sharp,Skybladev2/libgit2sharp,OidaTiftla/libgit2sharp,oliver-feng/libgit2sharp,Zoxive/libgit2sharp,xoofx/libgit2sharp,nulltoken/libgit2sharp,oliver-feng/libgit2sharp,rcorre/libgit2sharp,psawey/libgit2sharp,paulcbetts/libgit2sharp,mono/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,sushihangover/libgit2sharp,libgit2/libgit2sharp,vorou/libgit2sharp,dlsteuer/libgit2sharp,paulcbetts/libgit2sharp,shana/libgit2sharp,whoisj/libgit2sharp,jorgeamado/libgit2sharp,AArnott/libgit2sharp,jeffhostetler/public_libgit2sharp,jamill/libgit2sharp,GeertvanHorrik/libgit2sharp,red-gate/libgit2sharp,shana/libgit2sharp,Zoxive/libgit2sharp,vorou/libgit2sharp,nulltoken/libgit2sharp,xoofx/libgit2sharp,carlosmn/libgit2sharp,PKRoma/libgit2sharp,rcorre/libgit2sharp,sushihangover/libgit2sharp,red-gate/libgit2sharp,github/libgit2sharp,GeertvanHorrik/libgit2sharp,github/libgit2sharp | LibGit2Sharp/RepositoryInformation.cs | LibGit2Sharp/RepositoryInformation.cs | using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// Provides high level information about a repository.
/// </summary>
public class RepositoryInformation
{
private readonly Repository repo;
internal RepositoryInformation(Repository repo, string posixPath, string posixWorkingDirectoryPath, bool isBare)
{
this.repo = repo;
Path = PosixPathHelper.ToNative(posixPath);
IsBare = isBare;
WorkingDirectory = PosixPathHelper.ToNative(posixWorkingDirectoryPath);
}
/// <summary>
/// Gets the normalized path to the git repository.
/// </summary>
public string Path { get; private set; }
/// <summary>
/// Gets the normalized path to the working directory.
/// <para>
/// Is the repository is bare, null is returned.
/// </para>
/// </summary>
public string WorkingDirectory { get; private set; }
/// <summary>
/// Indicates whether the repository has a working directory.
/// </summary>
public bool IsBare { get; private set; }
/// <summary>
/// Gets a value indicating whether this repository is empty.
/// </summary>
/// <value>
/// <c>true</c> if this repository is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return NativeMethods.git_repository_is_empty(repo.Handle); }
}
/// <summary>
/// Indicates whether the Head points to an arbitrary commit instead of the tip of a local banch.
/// </summary>
public bool IsHeadDetached
{
get
{
if (repo.Info.IsEmpty) return false; // Detached HEAD doesn't mean anything for an empty repo, just return false
return repo.Head is DirectReference;
}
}
}
} | using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// Provides high level information about a repository.
/// </summary>
public class RepositoryInformation
{
private readonly Repository repo;
internal RepositoryInformation(Repository repo, string posixPath, string posixWorkingDirectoryPath, bool isBare)
{
this.repo = repo;
Path = PosixPathHelper.ToNative(posixPath);
IsBare = isBare;
WorkingDirectory = PosixPathHelper.ToNative(posixWorkingDirectoryPath);
IsEmpty = NativeMethods.git_repository_is_empty(repo.Handle);
}
/// <summary>
/// Gets the normalized path to the git repository.
/// </summary>
public string Path { get; private set; }
/// <summary>
/// Gets the normalized path to the working directory.
/// <para>
/// Is the repository is bare, null is returned.
/// </para>
/// </summary>
public string WorkingDirectory { get; private set; }
/// <summary>
/// Indicates whether the repository has a working directory.
/// </summary>
public bool IsBare { get; private set; }
/// <summary>
/// Gets a value indicating whether this repository is empty.
/// </summary>
/// <value>
/// <c>true</c> if this repository is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty { get; private set; }
/// <summary>
/// Indicates whether the Head points to an arbitrary commit instead of the tip of a local banch.
/// </summary>
public bool IsHeadDetached
{
get
{
if (repo.Info.IsEmpty) return false; // Detached HEAD doesn't mean anything for an empty repo, just return false
return repo.Head is DirectReference;
}
}
}
} | mit | C# |
ccb85ea470fed3f7bc0b8304afaff917a7972c86 | fix (from the comments) | Code-Inside/Samples,Code-Inside/Samples,rlerwill/Samples,rlerwill/Samples,amshen/Samples,Code-Inside/Samples,rlerwill/Samples,Code-Inside/Samples,amshen/Samples,amshen/Samples | 2015/WebApiBasicAuth/WebApiBasicAuth/Filters/IdentityBasicAuthenticationAttribute.cs | 2015/WebApiBasicAuth/WebApiBasicAuth/Filters/IdentityBasicAuthenticationAttribute.cs | using System.Collections.Generic;
using System.Net;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace WebApiBasicAuth.Filters
{
public class IdentityBasicAuthenticationAttribute : BasicAuthenticationAttribute
{
protected override async Task<IPrincipal> AuthenticateAsync(string userName, string password, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (userName != "testuser" || password != "Pass1word")
{
// No user with userName/password exists.
return null;
}
// Create a ClaimsIdentity with all the claims for this user.
Claim nameClaim = new Claim(ClaimTypes.Name, userName);
List<Claim> claims = new List<Claim> { nameClaim };
// important to set the identity this way, otherwise IsAuthenticated will be false
// see: http://leastprivilege.com/2012/09/24/claimsidentity-isauthenticated-and-authenticationtype-in-net-4-5/
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationTypes.Basic);
var principal = new ClaimsPrincipal(identity);
return principal;
}
}
}
| using System.Collections.Generic;
using System.Net;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace WebApiBasicAuth.Filters
{
public class IdentityBasicAuthenticationAttribute : BasicAuthenticationAttribute
{
protected override async Task<IPrincipal> AuthenticateAsync(string userName, string password, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (userName != "testuser" && password != "Pass1word")
{
// No user with userName/password exists.
return null;
}
// Create a ClaimsIdentity with all the claims for this user.
Claim nameClaim = new Claim(ClaimTypes.Name, userName);
List<Claim> claims = new List<Claim> { nameClaim };
// important to set the identity this way, otherwise IsAuthenticated will be false
// see: http://leastprivilege.com/2012/09/24/claimsidentity-isauthenticated-and-authenticationtype-in-net-4-5/
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationTypes.Basic);
var principal = new ClaimsPrincipal(identity);
return principal;
}
}
} | mit | C# |
d420a338ce342ac849dbe547f0dadd68d23db5ea | Update Program.cs | vishipayyallore/CSharp-DotNet-Core-Samples | LearningDesignPatterns/Source/DataStructures/LinkedLists/LinkedList.Demos/Program.cs | LearningDesignPatterns/Source/DataStructures/LinkedLists/LinkedList.Demos/Program.cs | using System;
using static System.Console;
namespace LinkedList.Demos
{
class Program
{
static void Main(string[] args)
{
DisplayMonths();
var node = new Node { Value = 101 };
WriteLine(node);
node.NextNode = new Node { Value = 102 };
WriteLine(node.NextNode);
WriteLine("\n\nPress any key ...");
ReadKey();
}
private static void DisplayMonths()
{
for(var month=1; month <=12; month++)
{
WriteLine($"{month}. {new DateTime(DateTime.Now.Year, month, 1).ToString("MMMM")}");
}
}
}
}
//GCHandle handle = GCHandle.Alloc(node, GCHandleType.WeakTrackResurrection);
//IntPtr address = GCHandle.ToIntPtr(handle);
//WriteLine($"Value: {node.Value} at Address: {address}");
| using System;
using static System.Console;
namespace LinkedList.Demos
{
class Program
{
static void Main(string[] args)
{
DisplayMonths();
var node = new Node { Value = 101 };
WriteLine(node);
node.NextNode = new Node { Value = 102 };
WriteLine(node.NextNode);
//GCHandle handle = GCHandle.Alloc(node, GCHandleType.WeakTrackResurrection);
//IntPtr address = GCHandle.ToIntPtr(handle);
//WriteLine($"Value: {node.Value} at Address: {address}");
WriteLine("\n\nPress any key ...");
ReadKey();
}
private static void DisplayMonths()
{
for(var month=1; month <=12; month++)
{
WriteLine($"{month}. {new DateTime(DateTime.Now.Year, month, 1).ToString("MMMM")}");
}
}
}
}
| apache-2.0 | C# |
f57464c382b09c27e8d6ea9804c4c71694254563 | increase size of offlimits list | ChrisMissal/birthdayclub | Core/Givers.cs | Core/Givers.cs | namespace Core
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Givers
{
private readonly Shuffler _shuffler = new Shuffler();
private readonly IList<Person> _inPlay;
private readonly Queue<Person> _offLimits;
private readonly int _maxNotInPlay;
public Givers(IEnumerable<Person> people, IEnumerable<Person> offLimits)
{
_inPlay = new List<Person>(people);
_offLimits = new Queue<Person>(offLimits ?? new Person[0]);
_maxNotInPlay = (int)(_inPlay.Count / 1.25m);
}
public Person Next(Person receiver)
{
// shuffle the people in play
_shuffler.Shuffle(_inPlay);
// grab the first person that's not in the off limits list and
// is not the receiver to be the gift giver this time.
var person = _inPlay
.Where(x => !_offLimits.Contains(x, new PersonComparer()))
.First(x => x.Name != receiver.Name);
if (_offLimits.Select(x => x.Name).Contains(person.Name))
throw new InvalidOperationException(string.Format("{0} is in the offlimits list!", person.Name));
// that chosen person is no longer in play as a gifter
// for awhile, so add them to the "off limits" queue
_inPlay.Remove(person);
_offLimits.Enqueue(person);
// if the number of people that are off limits is more than
// allowed, pop them off the queue and put them back in play
// to be shuffled and entered back into the mix.
if (_offLimits.Count > _maxNotInPlay)
{
var backInTheGame = _offLimits.Dequeue();
_inPlay.Add(backInTheGame);
}
return person;
}
public Person[] OffLimits
{
get { return _offLimits.ToArray(); }
}
}
} | namespace Core
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Givers
{
private readonly Shuffler _shuffler = new Shuffler();
private readonly IList<Person> _inPlay;
private readonly Queue<Person> _offLimits;
private readonly int _maxNotInPlay;
public Givers(IEnumerable<Person> people, IEnumerable<Person> offLimits)
{
_inPlay = new List<Person>(people);
_offLimits = new Queue<Person>(offLimits ?? new Person[0]);
_maxNotInPlay = _inPlay.Count / 2;
}
public Person Next(Person receiver)
{
// shuffle the people in play
_shuffler.Shuffle(_inPlay);
// grab the first person that's not in the off limits list and
// is not the receiver to be the gift giver this time.
var person = _inPlay
.Where(x => !_offLimits.Contains(x, new PersonComparer()))
.First(x => x.Name != receiver.Name);
if (_offLimits.Select(x => x.Name).Contains(person.Name))
throw new InvalidOperationException(string.Format("{0} is in the offlimits list!", person.Name));
// that chosen person is no longer in play as a gifter
// for awhile, so add them to the "off limits" queue
_inPlay.Remove(person);
_offLimits.Enqueue(person);
// if the number of people that are off limits is more than
// allowed, pop them off the queue and put them back in play
// to be shuffled and entered back into the mix.
if (_offLimits.Count > _maxNotInPlay)
{
var backInTheGame = _offLimits.Dequeue();
_inPlay.Add(backInTheGame);
}
return person;
}
public Person[] OffLimits
{
get { return _offLimits.ToArray(); }
}
}
} | mit | C# |
0ccd01bc78995dc40dd4e5dcecf5f6902fb07c6f | Change color to read to test sub-module. | purple-movies/expanse_bundle_lib | RandomColor.cs | RandomColor.cs | using UnityEngine;
using System.Collections;
public class RandomColor : MonoBehaviour {
void Start () {
// var c = new Color(Random.value, Random.value, Random.value, 1f);
var c = new Color(1f, 0, 0f, 1f);
GetComponent<Renderer>().material.color = c;
}
}
| using UnityEngine;
using System.Collections;
public class RandomColor : MonoBehaviour {
void Start () {
// var c = new Color(Random.value, Random.value, Random.value, 1f);
var c = new Color(0, 0, 1f, 1f);
GetComponent<Renderer>().material.color = c;
}
}
| apache-2.0 | C# |
5b39db85bc4eb0061f3c2574be0135bbe5d72487 | Bump version to 0.31.1 | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.31.1";
}
}
| #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.31.0";
}
}
| mit | C# |
a5499a908d8a7d740fc2873ce16298c08c34deae | remove usings. | jkoritzinsky/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,wieslawsoltes/Perspex | tests/Avalonia.Controls.UnitTests/ApplicationTests.cs | tests/Avalonia.Controls.UnitTests/ApplicationTests.cs | using System;
using Avalonia.Data;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ApplicationTests
{
[Fact]
public void Throws_ArgumentNullException_On_Run_If_MainWindow_Is_Null()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
Assert.Throws<ArgumentNullException>(() => { Application.Current.Run(null); });
}
}
[Fact]
public void Raises_ResourcesChanged_When_Event_Handler_Added_After_Resources_Has_Been_Accessed()
{
// Test for #1765.
using (UnitTestApplication.Start())
{
var resources = Application.Current.Resources;
var raised = false;
Application.Current.ResourcesChanged += (s, e) => raised = true;
resources["foo"] = "bar";
Assert.True(raised);
}
}
[Fact]
public void Can_Bind_To_DataContext()
{
using (UnitTestApplication.Start())
{
var application = Application.Current;
application.DataContext = "Test";
application.Bind(Application.NameProperty, new Binding("."));
Assert.Equal("Test", Application.Current.Name);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using Avalonia.Data;
using Avalonia.Threading;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ApplicationTests
{
[Fact]
public void Throws_ArgumentNullException_On_Run_If_MainWindow_Is_Null()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
Assert.Throws<ArgumentNullException>(() => { Application.Current.Run(null); });
}
}
[Fact]
public void Raises_ResourcesChanged_When_Event_Handler_Added_After_Resources_Has_Been_Accessed()
{
// Test for #1765.
using (UnitTestApplication.Start())
{
var resources = Application.Current.Resources;
var raised = false;
Application.Current.ResourcesChanged += (s, e) => raised = true;
resources["foo"] = "bar";
Assert.True(raised);
}
}
[Fact]
public void Can_Bind_To_DataContext()
{
using (UnitTestApplication.Start())
{
var application = Application.Current;
application.DataContext = "Test";
application.Bind(Application.NameProperty, new Binding("."));
Assert.Equal("Test", Application.Current.Name);
}
}
}
}
| mit | C# |
47864c9dece57fa2d689c8089a62cd23800ce55e | Update XTemplatesTests.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | tests/Core2D.UnitTests/Collections/XTemplatesTests.cs | tests/Core2D.UnitTests/Collections/XTemplatesTests.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 Core2D.Collections;
using Xunit;
namespace Core2D.UnitTests
{
public class XTemplatesTests
{
[Fact]
[Trait("Core2D", "Collections")]
public void Inherits_From_ObservableObject()
{
var target = new XTemplates();
Assert.True(target is ObservableObject);
}
[Fact]
[Trait("Core2D", "Collections")]
public void Children_Not_Null()
{
var target = new XTemplates();
Assert.NotNull(target.Children);
}
}
}
| // 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 Core2D.Collections;
using Xunit;
namespace Core2D.UnitTests
{
public class XTemplatesTests
{
[Fact]
[Trait("Core2D", "Collections")]
public void Inherits_From_ObservableResource()
{
var target = new XTemplates();
Assert.True(target is ObservableResource);
}
[Fact]
[Trait("Core2D", "Collections")]
public void Children_Not_Null()
{
var target = new XTemplates();
Assert.NotNull(target.Children);
}
}
}
| mit | C# |
2fe35090b71598bd14b6fc161e6ad7bb33eba60a | fix broken syntax | AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,skolima/NuKeeper,skolima/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper | NuKeeper/Github/IGithub.cs | NuKeeper/Github/IGithub.cs | using System.Threading.Tasks;
namespace NuKeeper.Github
{
interface IGithub
{
Task<OpenPullRequestResult> OpenPullRequest(OpenPullRequestRequest request);
}
}
| using System.Threading.Tasks;
namespace NuKeeper.Github
{
interface IGithub
{
Task<OpenPullRequestResult> OpenPullRequest(OpenPullRequestRequest);
}
}
| apache-2.0 | C# |
959fa2ef1ac45c783524570a4f98cd8680367290 | Bump version | Naxiz/TeleBotDotNet,LouisMT/TeleBotDotNet | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | 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("TeleBotDotNet")]
[assembly: AssemblyDescription("Telegram Bot API wrapper for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("U5R")]
[assembly: AssemblyProduct("TeleBotDotNet")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdc2c81d-c3e9-40b1-8b21-69796411ad56")]
// 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("2015.10.6.1")]
[assembly: AssemblyFileVersion("2015.10.6.1")] | 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("TeleBotDotNet")]
[assembly: AssemblyDescription("Telegram Bot API wrapper for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("U5R")]
[assembly: AssemblyProduct("TeleBotDotNet")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bdc2c81d-c3e9-40b1-8b21-69796411ad56")]
// 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("2015.10.4.1")]
[assembly: AssemblyFileVersion("2015.10.4.1")] | mit | C# |
c944b38839888c404f959ef5752dbe33958e81a6 | Update AssemblyInfo.cs | splauer1us/IAG-Unity-DataAccess | Properties/AssemblyInfo.cs | 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("Iag.Unity.DataAccess")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Iag.Unity.DataAccess")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bf9a3966-ccdb-4dd2-80e0-2d084a9f0ff9")]
// 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.6.0")]
[assembly: AssemblyFileVersion("1.0.6.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("Iag.Unity.DataAccess")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Iag.Unity.DataAccess")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bf9a3966-ccdb-4dd2-80e0-2d084a9f0ff9")]
// 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.4.0")]
[assembly: AssemblyFileVersion("1.0.4.0")]
| mit | C# |
2eb476a539693e57472a8028950875ffbdd9ad0f | Use resource manager in routable template | DonnotRain/Orchard,LaserSrl/Orchard,SzymonSel/Orchard,fortunearterial/Orchard,OrchardCMS/Orchard-Harvest-Website,m2cms/Orchard,NIKASoftwareDevs/Orchard,KeithRaven/Orchard,geertdoornbos/Orchard,arminkarimi/Orchard,yonglehou/Orchard,xiaobudian/Orchard,OrchardCMS/Orchard-Harvest-Website,MetSystem/Orchard,grapto/Orchard.CloudBust,dmitry-urenev/extended-orchard-cms-v10.1,Serlead/Orchard,qt1/orchard4ibn,qt1/Orchard,jersiovic/Orchard,qt1/orchard4ibn,kouweizhong/Orchard,alejandroaldana/Orchard,Anton-Am/Orchard,jersiovic/Orchard,asabbott/chicagodevnet-website,LaserSrl/Orchard,caoxk/orchard,enspiral-dev-academy/Orchard,jtkech/Orchard,emretiryaki/Orchard,cooclsee/Orchard,bigfont/orchard-continuous-integration-demo,hhland/Orchard,salarvand/orchard,salarvand/orchard,smartnet-developers/Orchard,ericschultz/outercurve-orchard,Fogolan/OrchardForWork,JRKelso/Orchard,openbizgit/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Cphusion/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,qt1/orchard4ibn,vairam-svs/Orchard,fassetar/Orchard,KeithRaven/Orchard,andyshao/Orchard,fortunearterial/Orchard,geertdoornbos/Orchard,IDeliverable/Orchard,MpDzik/Orchard,aaronamm/Orchard,hbulzy/Orchard,vard0/orchard.tan,tobydodds/folklife,omidnasri/Orchard,bigfont/orchard-continuous-integration-demo,luchaoshuai/Orchard,armanforghani/Orchard,aaronamm/Orchard,MetSystem/Orchard,Serlead/Orchard,xkproject/Orchard,neTp9c/Orchard,geertdoornbos/Orchard,jerryshi2007/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard,dozoft/Orchard,yonglehou/Orchard,mvarblow/Orchard,jerryshi2007/Orchard,openbizgit/Orchard,asabbott/chicagodevnet-website,asabbott/chicagodevnet-website,Lombiq/Orchard,angelapper/Orchard,Dolphinsimon/Orchard,fassetar/Orchard,xiaobudian/Orchard,Ermesx/Orchard,Fogolan/OrchardForWork,escofieldnaxos/Orchard,hhland/Orchard,fassetar/Orchard,ericschultz/outercurve-orchard,neTp9c/Orchard,salarvand/Portal,omidnasri/Orchard,geertdoornbos/Orchard,omidnasri/Orchard,AEdmunds/beautiful-springtime,jimasp/Orchard,Lombiq/Orchard,Lombiq/Orchard,bedegaming-aleksej/Orchard,dozoft/Orchard,MetSystem/Orchard,AdvantageCS/Orchard,JRKelso/Orchard,IDeliverable/Orchard,harmony7/Orchard,neTp9c/Orchard,OrchardCMS/Orchard,cryogen/orchard,alejandroaldana/Orchard,Praggie/Orchard,andyshao/Orchard,cryogen/orchard,SeyDutch/Airbrush,bigfont/orchard-continuous-integration-demo,dmitry-urenev/extended-orchard-cms-v10.1,luchaoshuai/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,bedegaming-aleksej/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,escofieldnaxos/Orchard,bedegaming-aleksej/Orchard,hhland/Orchard,TalaveraTechnologySolutions/Orchard,alejandroaldana/Orchard,emretiryaki/Orchard,jerryshi2007/Orchard,enspiral-dev-academy/Orchard,abhishekluv/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,abhishekluv/Orchard,jerryshi2007/Orchard,emretiryaki/Orchard,li0803/Orchard,escofieldnaxos/Orchard,jimasp/Orchard,Morgma/valleyviewknolls,TaiAivaras/Orchard,phillipsj/Orchard,qt1/orchard4ibn,johnnyqian/Orchard,jchenga/Orchard,Codinlab/Orchard,jersiovic/Orchard,oxwanawxo/Orchard,stormleoxia/Orchard,jchenga/Orchard,alejandroaldana/Orchard,NIKASoftwareDevs/Orchard,Morgma/valleyviewknolls,patricmutwiri/Orchard,abhishekluv/Orchard,MpDzik/Orchard,bigfont/orchard-cms-modules-and-themes,smartnet-developers/Orchard,OrchardCMS/Orchard,oxwanawxo/Orchard,caoxk/orchard,abhishekluv/Orchard,hbulzy/Orchard,salarvand/Portal,SouleDesigns/SouleDesigns.Orchard,gcsuk/Orchard,dcinzona/Orchard-Harvest-Website,sfmskywalker/Orchard,planetClaire/Orchard-LETS,austinsc/Orchard,marcoaoteixeira/Orchard,hannan-azam/Orchard,dozoft/Orchard,jchenga/Orchard,spraiin/Orchard,dozoft/Orchard,TalaveraTechnologySolutions/Orchard,ehe888/Orchard,neTp9c/Orchard,planetClaire/Orchard-LETS,Dolphinsimon/Orchard,AEdmunds/beautiful-springtime,geertdoornbos/Orchard,openbizgit/Orchard,LaserSrl/Orchard,TaiAivaras/Orchard,omidnasri/Orchard,patricmutwiri/Orchard,openbizgit/Orchard,Anton-Am/Orchard,Codinlab/Orchard,hannan-azam/Orchard,marcoaoteixeira/Orchard,dcinzona/Orchard,MpDzik/Orchard,yersans/Orchard,armanforghani/Orchard,m2cms/Orchard,ericschultz/outercurve-orchard,oxwanawxo/Orchard,jersiovic/Orchard,dcinzona/Orchard-Harvest-Website,mvarblow/Orchard,SzymonSel/Orchard,hbulzy/Orchard,omidnasri/Orchard,planetClaire/Orchard-LETS,patricmutwiri/Orchard,Inner89/Orchard,Sylapse/Orchard.HttpAuthSample,jchenga/Orchard,Anton-Am/Orchard,infofromca/Orchard,AEdmunds/beautiful-springtime,SeyDutch/Airbrush,angelapper/Orchard,OrchardCMS/Orchard,huoxudong125/Orchard,grapto/Orchard.CloudBust,salarvand/Portal,yonglehou/Orchard,cooclsee/Orchard,hhland/Orchard,KeithRaven/Orchard,salarvand/Portal,hhland/Orchard,kgacova/Orchard,Inner89/Orchard,kouweizhong/Orchard,tobydodds/folklife,planetClaire/Orchard-LETS,stormleoxia/Orchard,abhishekluv/Orchard,KeithRaven/Orchard,Praggie/Orchard,grapto/Orchard.CloudBust,hbulzy/Orchard,Anton-Am/Orchard,tobydodds/folklife,phillipsj/Orchard,Inner89/Orchard,qt1/Orchard,dcinzona/Orchard-Harvest-Website,hannan-azam/Orchard,johnnyqian/Orchard,huoxudong125/Orchard,sfmskywalker/Orchard,xkproject/Orchard,spraiin/Orchard,IDeliverable/Orchard,qt1/Orchard,armanforghani/Orchard,fortunearterial/Orchard,johnnyqian/Orchard,MpDzik/Orchard,brownjordaninternational/OrchardCMS,huoxudong125/Orchard,tobydodds/folklife,SzymonSel/Orchard,Ermesx/Orchard,phillipsj/Orchard,TaiAivaras/Orchard,dburriss/Orchard,Codinlab/Orchard,armanforghani/Orchard,angelapper/Orchard,RoyalVeterinaryCollege/Orchard,RoyalVeterinaryCollege/Orchard,Cphusion/Orchard,SouleDesigns/SouleDesigns.Orchard,Sylapse/Orchard.HttpAuthSample,sfmskywalker/Orchard,SzymonSel/Orchard,jagraz/Orchard,Ermesx/Orchard,Serlead/Orchard,TaiAivaras/Orchard,brownjordaninternational/OrchardCMS,AndreVolksdorf/Orchard,kouweizhong/Orchard,sebastienros/msc,xiaobudian/Orchard,NIKASoftwareDevs/Orchard,asabbott/chicagodevnet-website,li0803/Orchard,rtpHarry/Orchard,omidnasri/Orchard,caoxk/orchard,jchenga/Orchard,cooclsee/Orchard,rtpHarry/Orchard,planetClaire/Orchard-LETS,jtkech/Orchard,oxwanawxo/Orchard,AndreVolksdorf/Orchard,vard0/orchard.tan,jagraz/Orchard,TalaveraTechnologySolutions/Orchard,arminkarimi/Orchard,infofromca/Orchard,jimasp/Orchard,mgrowan/Orchard,fortunearterial/Orchard,marcoaoteixeira/Orchard,kgacova/Orchard,arminkarimi/Orchard,vairam-svs/Orchard,mgrowan/Orchard,oxwanawxo/Orchard,fassetar/Orchard,johnnyqian/Orchard,Cphusion/Orchard,grapto/Orchard.CloudBust,salarvand/orchard,Ermesx/Orchard,RoyalVeterinaryCollege/Orchard,vairam-svs/Orchard,TalaveraTechnologySolutions/Orchard,Ermesx/Orchard,dburriss/Orchard,KeithRaven/Orchard,salarvand/orchard,omidnasri/Orchard,DonnotRain/Orchard,hannan-azam/Orchard,TalaveraTechnologySolutions/Orchard,bigfont/orchard-cms-modules-and-themes,kgacova/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,harmony7/Orchard,AdvantageCS/Orchard,Sylapse/Orchard.HttpAuthSample,SzymonSel/Orchard,arminkarimi/Orchard,caoxk/orchard,andyshao/Orchard,kouweizhong/Orchard,patricmutwiri/Orchard,brownjordaninternational/OrchardCMS,emretiryaki/Orchard,AndreVolksdorf/Orchard,SouleDesigns/SouleDesigns.Orchard,infofromca/Orchard,dcinzona/Orchard,AdvantageCS/Orchard,yonglehou/Orchard,AndreVolksdorf/Orchard,MpDzik/Orchard,AndreVolksdorf/Orchard,bigfont/orchard-cms-modules-and-themes,huoxudong125/Orchard,jerryshi2007/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,mvarblow/Orchard,phillipsj/Orchard,neTp9c/Orchard,Praggie/Orchard,smartnet-developers/Orchard,spraiin/Orchard,patricmutwiri/Orchard,harmony7/Orchard,yersans/Orchard,escofieldnaxos/Orchard,vard0/orchard.tan,gcsuk/Orchard,vairam-svs/Orchard,kgacova/Orchard,Dolphinsimon/Orchard,Morgma/valleyviewknolls,qt1/Orchard,xkproject/Orchard,omidnasri/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,cooclsee/Orchard,jagraz/Orchard,grapto/Orchard.CloudBust,jaraco/orchard,JRKelso/Orchard,kgacova/Orchard,jersiovic/Orchard,cryogen/orchard,JRKelso/Orchard,smartnet-developers/Orchard,mvarblow/Orchard,NIKASoftwareDevs/Orchard,arminkarimi/Orchard,Inner89/Orchard,m2cms/Orchard,armanforghani/Orchard,johnnyqian/Orchard,hbulzy/Orchard,infofromca/Orchard,OrchardCMS/Orchard-Harvest-Website,enspiral-dev-academy/Orchard,dcinzona/Orchard,luchaoshuai/Orchard,stormleoxia/Orchard,gcsuk/Orchard,abhishekluv/Orchard,dburriss/Orchard,LaserSrl/Orchard,Lombiq/Orchard,Fogolan/OrchardForWork,tobydodds/folklife,vard0/orchard.tan,luchaoshuai/Orchard,IDeliverable/Orchard,dcinzona/Orchard-Harvest-Website,aaronamm/Orchard,infofromca/Orchard,escofieldnaxos/Orchard,OrchardCMS/Orchard-Harvest-Website,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,salarvand/orchard,jagraz/Orchard,jaraco/orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,qt1/orchard4ibn,Sylapse/Orchard.HttpAuthSample,ehe888/Orchard,Inner89/Orchard,SouleDesigns/SouleDesigns.Orchard,gcsuk/Orchard,li0803/Orchard,ehe888/Orchard,austinsc/Orchard,OrchardCMS/Orchard,DonnotRain/Orchard,aaronamm/Orchard,TalaveraTechnologySolutions/Orchard,dcinzona/Orchard-Harvest-Website,Cphusion/Orchard,Serlead/Orchard,yonglehou/Orchard,aaronamm/Orchard,smartnet-developers/Orchard,SeyDutch/Airbrush,dburriss/Orchard,li0803/Orchard,li0803/Orchard,jaraco/orchard,MpDzik/Orchard,angelapper/Orchard,dcinzona/Orchard,sfmskywalker/Orchard,Morgma/valleyviewknolls,AdvantageCS/Orchard,bigfont/orchard-cms-modules-and-themes,AdvantageCS/Orchard,fassetar/Orchard,enspiral-dev-academy/Orchard,jimasp/Orchard,andyshao/Orchard,IDeliverable/Orchard,harmony7/Orchard,stormleoxia/Orchard,jagraz/Orchard,SeyDutch/Airbrush,bigfont/orchard-cms-modules-and-themes,AEdmunds/beautiful-springtime,xiaobudian/Orchard,Fogolan/OrchardForWork,tobydodds/folklife,Dolphinsimon/Orchard,qt1/orchard4ibn,alejandroaldana/Orchard,jaraco/orchard,cryogen/orchard,rtpHarry/Orchard,Codinlab/Orchard,fortunearterial/Orchard,sebastienros/msc,vairam-svs/Orchard,gcsuk/Orchard,NIKASoftwareDevs/Orchard,mgrowan/Orchard,jtkech/Orchard,sebastienros/msc,austinsc/Orchard,ericschultz/outercurve-orchard,marcoaoteixeira/Orchard,rtpHarry/Orchard,sebastienros/msc,dmitry-urenev/extended-orchard-cms-v10.1,SouleDesigns/SouleDesigns.Orchard,JRKelso/Orchard,xkproject/Orchard,RoyalVeterinaryCollege/Orchard,dburriss/Orchard,LaserSrl/Orchard,sebastienros/msc,huoxudong125/Orchard,ehe888/Orchard,angelapper/Orchard,RoyalVeterinaryCollege/Orchard,TaiAivaras/Orchard,openbizgit/Orchard,omidnasri/Orchard,jtkech/Orchard,harmony7/Orchard,spraiin/Orchard,spraiin/Orchard,m2cms/Orchard,austinsc/Orchard,Sylapse/Orchard.HttpAuthSample,sfmskywalker/Orchard,OrchardCMS/Orchard-Harvest-Website,Anton-Am/Orchard,OrchardCMS/Orchard,yersans/Orchard,enspiral-dev-academy/Orchard,TalaveraTechnologySolutions/Orchard,xkproject/Orchard,MetSystem/Orchard,Praggie/Orchard,SeyDutch/Airbrush,qt1/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,salarvand/Portal,grapto/Orchard.CloudBust,rtpHarry/Orchard,Dolphinsimon/Orchard,emretiryaki/Orchard,xiaobudian/Orchard,jtkech/Orchard,Lombiq/Orchard,vard0/orchard.tan,dcinzona/Orchard,yersans/Orchard,OrchardCMS/Orchard-Harvest-Website,Morgma/valleyviewknolls,dcinzona/Orchard-Harvest-Website,mvarblow/Orchard,austinsc/Orchard,mgrowan/Orchard,Serlead/Orchard,Praggie/Orchard,ehe888/Orchard,TalaveraTechnologySolutions/Orchard,dozoft/Orchard,DonnotRain/Orchard,DonnotRain/Orchard,mgrowan/Orchard,bigfont/orchard-continuous-integration-demo,marcoaoteixeira/Orchard,bedegaming-aleksej/Orchard,Cphusion/Orchard,kouweizhong/Orchard,vard0/orchard.tan,hannan-azam/Orchard,phillipsj/Orchard,MetSystem/Orchard,luchaoshuai/Orchard,bedegaming-aleksej/Orchard,sfmskywalker/Orchard,andyshao/Orchard,Codinlab/Orchard,cooclsee/Orchard,m2cms/Orchard,brownjordaninternational/OrchardCMS,stormleoxia/Orchard,Fogolan/OrchardForWork,jimasp/Orchard,yersans/Orchard,brownjordaninternational/OrchardCMS | src/Orchard.Web/Core/Routable/Views/EditorTemplates/Parts/Routable.RoutePart.cshtml | src/Orchard.Web/Core/Routable/Views/EditorTemplates/Parts/Routable.RoutePart.cshtml | @model Orchard.Core.Routable.ViewModels.RoutableEditorViewModel
@using Orchard.Utility.Extensions
@Script.Require("Slugify");
<fieldset>
@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title, new { @class = "large text" })
</fieldset>
<fieldset class="permalink">
<label class="sub" for="Slug">@T("Permalink")<br /><span>@Request.ToRootUrlString()/@Model.DisplayLeadingPath</span></label>
<span>@Html.TextBoxFor(m => m.Slug, new { @class = "text" })</span>
@Html.EditorFor(m => m.PromoteToHomePage)
<label for="@ViewData.TemplateInfo.GetFullHtmlFieldId("PromoteToHomePage")" class="forcheckbox">@T("Set as home page")</label>
</fieldset>
@using(Capture(script => WorkContext.Page.Tail.Add(script))){
<script type="text/javascript">
$(function(){
//pull slug input from tab order
$("#@Html.FieldIdFor(m=>m.Slug)").attr("tabindex",-1);
$("#@Html.FieldIdFor(m=>m.Title)").blur(function(){
var slug = $("#@Html.FieldIdFor(m=>m.Slug)");
if (slug.val()) { return true; }
$(this).slugify({
target:slug,
contentType:"@Model.ContentType",
id:"@Model.Id",
@if (Model.ContainerId != null) {<text>containerId:@Model.ContainerId,</text>}
url:"@Url.Action("Slugify","Item",new RouteValueDictionary{{"Area","Routable"}})"
})
})
})
</script>
} | @model Orchard.Core.Routable.ViewModels.RoutableEditorViewModel
@using Orchard.Utility.Extensions
<fieldset>
@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title, new { @class = "large text" })
</fieldset>
<fieldset class="permalink">
<label class="sub" for="Slug">@T("Permalink")<br /><span>@Request.ToRootUrlString()/@Model.DisplayLeadingPath</span></label>
<span>@Html.TextBoxFor(m => m.Slug, new { @class = "text" })</span>
@Html.EditorFor(m => m.PromoteToHomePage)
<label for="@ViewData.TemplateInfo.GetFullHtmlFieldId("PromoteToHomePage")" class="forcheckbox">@T("Set as home page")</label>
</fieldset>
@//todo: IResourceManager -> Html.RegisterFootScript("jquery.slugify.js");
@using(Capture(script => WorkContext.Page.Tail.Add(script))){
<script type="text/javascript">
$(function(){
//pull slug input from tab order
$("#@Html.FieldIdFor(m=>m.Slug)").attr("tabindex",-1);
$("#@Html.FieldIdFor(m=>m.Title)").blur(function(){
var slug = $("#@Html.FieldIdFor(m=>m.Slug)");
if (slug.val()) { return true; }
$(this).slugify({
target:slug,
contentType:"@Model.ContentType",
id:"@Model.Id",
@if (Model.ContainerId != null) {<text>containerId:@Model.ContainerId,</text>}
url:"@Url.Action("Slugify","Item",new RouteValueDictionary{{"Area","Routable"}})"
})
})
})
</script>
} | bsd-3-clause | C# |
4b2ddff6b2182a4e5b40a2467ad99c159881c6e6 | Make church properties read-only | brwml/MatchMakerTool | Reporting/Models/Church.cs | Reporting/Models/Church.cs | namespace MatchMaker.Reporting.Models;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml.Linq;
using Ardalis.GuardClauses;
/// <summary>
/// Defines the <see cref="Church" /> class
/// </summary>
[DataContract]
[DebuggerDisplay("Church {Name} ({Id})")]
public class Church
{
/// <summary>
/// Initializes an instance of the <see cref="Church"/> class.
/// </summary>
/// <param name="id">The identifier</param>
/// <param name="name">The name</param>
public Church(int id, string name)
{
this.Id = id;
this.Name = name;
}
/// <summary>
/// Gets or sets the Id
/// </summary>
[DataMember]
public int Id { get; }
/// <summary>
/// Gets or sets the Name
/// </summary>
[DataMember]
public string Name { get; }
/// <summary>
/// Gets a <see cref="Church"/> instance from an XML element
/// </summary>
/// <param name="xml">The xml element</param>
/// <returns>The <see cref="Church"/></returns>
public static Church FromXml(XElement xml)
{
Guard.Against.Null(xml, nameof(xml));
var id = xml.GetAttribute<int>("id");
var name = xml.Value;
return new Church(id, name);
}
/// <summary>
/// Converts the <see cref="Church"/> instance to XML.
/// </summary>
/// <returns>The <see cref="XElement"/> instance</returns>
public XElement ToXml()
{
return new XElement(
"church",
this.Name,
new XAttribute("id", this.Id));
}
}
| namespace MatchMaker.Reporting.Models;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml.Linq;
using Ardalis.GuardClauses;
/// <summary>
/// Defines the <see cref="Church" /> class
/// </summary>
[DataContract]
[DebuggerDisplay("Church {Name} ({Id})")]
public class Church
{
/// <summary>
/// Initializes an instance of the <see cref="Church"/> class.
/// </summary>
/// <param name="id">The identifier</param>
/// <param name="name">The name</param>
public Church(int id, string name)
{
this.Id = id;
this.Name = name;
}
/// <summary>
/// Gets or sets the Id
/// </summary>
[DataMember]
public int Id { get; set; }
/// <summary>
/// Gets or sets the Name
/// </summary>
[DataMember]
public string Name { get; set; }
/// <summary>
/// Gets a <see cref="Church"/> instance from an XML element
/// </summary>
/// <param name="xml">The xml element</param>
/// <returns>The <see cref="Church"/></returns>
public static Church FromXml(XElement xml)
{
Guard.Against.Null(xml, nameof(xml));
var id = xml.GetAttribute<int>("id");
var name = xml.Value;
return new Church(id, name);
}
/// <summary>
/// Converts the <see cref="Church"/> instance to XML.
/// </summary>
/// <returns>The <see cref="XElement"/> instance</returns>
public XElement ToXml()
{
return new XElement(
"church",
this.Name,
new XAttribute("id", this.Id));
}
}
| mit | C# |
ad70f67e22673d30936c8d82ceff05161ba27285 | fix kill sound thing | hagish/tektix,hagish/tektix,hagish/tektix | taktik/Assets/Scripts/Unit.cs | taktik/Assets/Scripts/Unit.cs | using UnityEngine;
using System.Collections;
public class Unit : MonoBehaviour {
public enum UnitType {
SCISSOR = 0,
ROCK = 1,
PAPER = 2,
}
public int PlayerId;
public UnitType Type;
public int Lives = 2;
void OnTriggerEnter(Collider other)
{
Unit otherUnit = other.gameObject.GetComponent<Unit>();
if (otherUnit != null)
{
if (otherUnit.PlayerId != PlayerId)
{
var result = GameCore.CalculateFightDamage(this, otherUnit);
// if i lost kill me
if (result.a) Kill(true);
// but if the other one loses i get damage
else if (result.b) GetDamage();
}
}
ScoreArea scoreArea = other.gameObject.GetComponent<ScoreArea>();
if (scoreArea != null && scoreArea.PlayerId != PlayerId)
{
AudioController.Instance.PlaySound("score");
GameCore.Instance.Score(PlayerId, 1);
Kill(false);
}
}
public void Kill(bool playSound)
{
GameObject.Destroy(gameObject);
if (playSound) AudioController.Instance.PlaySound("kill");
}
public void GetDamage()
{
Lives--;
if (Lives == 0)
{
Kill(true);
}
}
}
| using UnityEngine;
using System.Collections;
public class Unit : MonoBehaviour {
public enum UnitType {
SCISSOR = 0,
ROCK = 1,
PAPER = 2,
}
public int PlayerId;
public UnitType Type;
public int Lives = 2;
void OnTriggerEnter(Collider other)
{
Unit otherUnit = other.gameObject.GetComponent<Unit>();
if (otherUnit != null)
{
if (otherUnit.PlayerId != PlayerId)
{
var result = GameCore.CalculateFightDamage(this, otherUnit);
// if i lost kill me
if (result.a) Kill();
// but if the other one loses i get damage
else if (result.b) GetDamage();
}
}
ScoreArea scoreArea = other.gameObject.GetComponent<ScoreArea>();
if (scoreArea != null && scoreArea.PlayerId != PlayerId)
{
AudioController.Instance.PlaySound("score");
GameCore.Instance.Score(PlayerId, 1);
Kill();
}
}
public void Kill()
{
GameObject.Destroy(gameObject);
AudioController.Instance.PlaySound("kill");
}
public void GetDamage()
{
Lives--;
if (Lives == 0)
{
Kill();
}
}
}
| mit | C# |
f48bce95303228b6ae039ca181e632b2250d71fc | Tidy ListGameMode up | kerzyte/OWLib,overtools/OWLib | OverTool/List/ListGameMode.cs | OverTool/List/ListGameMode.cs | using System;
using System.Collections.Generic;
using System.IO;
using CASCExplorer;
using OWLib;
using OWLib.Types.STUD;
namespace OverTool.List {
public class ListGameMode : IOvertool {
public string Title => "List Game Modes";
public char Opt => 'E';
public string Help => "No additional arguments";
public uint MinimumArgs => 0;
public ushort[] Track => new ushort[1] { 0xC0 };
public bool Display => true;
public void Parse(Dictionary<ushort, List<ulong>> track, Dictionary<ulong, Record> map, CASCHandler handler, bool quiet, OverToolFlags flags) {
Dictionary<uint, Dictionary<uint, string>> data = new Dictionary<uint, Dictionary<uint, string>>();
foreach (ulong key in track[0xC0]) {
if (!map.ContainsKey(key)) {
continue;
}
using (Stream input = Util.OpenFile(map[key], handler)) {
if (input == null) {
continue;
}
STUD stud = new STUD(input);
if (stud.Instances == null || stud.Instances[0] == null) {
continue;
}
GameMode gm = stud.Instances[0] as GameMode;
if (gm == null) {
continue;
}
string name = Util.GetString(gm.Header.name, map, handler);
if (name != null) {
uint ruleset = GUID.Index(gm.Header.ruleset);
if (!data.ContainsKey(ruleset)) {
data[ruleset] = new Dictionary<uint, string>();
}
data[ruleset].Add(GUID.Index(key), name);
}
}
}
foreach (KeyValuePair<uint, Dictionary<uint, string>> pairs in data) {
Console.Out.WriteLine("{0:X8}:", pairs.Key);
foreach (KeyValuePair<uint, string> kv in pairs.Value) {
Console.Out.WriteLine("\t{0} ({1:X8})", kv.Value, kv.Key);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using CASCExplorer;
using OWLib;
using OWLib.Types.STUD;
namespace OverTool.List {
public class ListGameMode : IOvertool {
public string Title => "List Game Modes";
public char Opt => 'E';
public string Help => "No additional arguments";
public uint MinimumArgs => 0;
public ushort[] Track => new ushort[1] { 0xC0 };
public bool Display => true;
public void Parse(Dictionary<ushort, List<ulong>> track, Dictionary<ulong, Record> map, CASCHandler handler, bool quiet, OverToolFlags flags) {
foreach (ulong key in track[0xC0]) {
if (!map.ContainsKey(key)) {
continue;
}
using (Stream input = Util.OpenFile(map[key], handler)) {
if (input == null) {
continue;
}
STUD stud = new STUD(input);
if (stud.Instances == null || stud.Instances[0] == null) {
continue;
}
GameMode gm = stud.Instances[0] as GameMode;
if (gm == null) {
continue;
}
string name = Util.GetString(gm.Header.name, map, handler);
if (name != null) {
Console.Out.WriteLine("{0:X8}: {1}", GUID.Index(gm.Header.ruleset), name);
}
}
}
}
}
}
| mit | C# |
112287b60948fe8b0d75b3c18f126dc4690ada34 | Make class abstract. | sharpjs/PSql,sharpjs/PSql | PSql.Core/_Commands/Cmdlet.cs | PSql.Core/_Commands/Cmdlet.cs | using System;
using System.Management.Automation;
using System.Management.Automation.Host;
namespace PSql
{
/// <summary>
/// Base class for PSql cmdlets.
/// </summary>
public abstract class Cmdlet : System.Management.Automation.Cmdlet
{
private static readonly string[]
HostTag = { "PSHOST" };
public void WriteHost(string message,
bool newLine = true,
ConsoleColor? foregroundColor = null,
ConsoleColor? backgroundColor = null)
{
// Technique learned from PSv5+ Write-Host implementation, which
// works by sending specially-marked messages to the information
// stream.
//
// https://github.com/PowerShell/PowerShell/blob/v6.1.3/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs
var data = new HostInformationMessage
{
Message = message,
NoNewLine = !newLine
};
if (foregroundColor.HasValue || backgroundColor.HasValue)
{
try
{
data.ForegroundColor = foregroundColor;
data.BackgroundColor = backgroundColor;
}
catch (HostException)
{
// Host is non-interactive or does not support colors.
}
}
WriteInformation(data, HostTag);
}
}
}
| using System;
using System.Management.Automation;
using System.Management.Automation.Host;
namespace PSql
{
public class Cmdlet : System.Management.Automation.Cmdlet
{
private static readonly string[]
HostTag = { "PSHOST" };
public void WriteHost(string message,
bool newLine = true,
ConsoleColor? foregroundColor = null,
ConsoleColor? backgroundColor = null)
{
// Technique learned from PSv5+ Write-Host implementation, which
// works by sending specially-marked messages to the information
// stream.
//
// https://github.com/PowerShell/PowerShell/blob/v6.1.3/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs
var data = new HostInformationMessage
{
Message = message,
NoNewLine = !newLine
};
if (foregroundColor.HasValue || backgroundColor.HasValue)
{
try
{
data.ForegroundColor = foregroundColor;
data.BackgroundColor = backgroundColor;
}
catch (HostException)
{
// Host is non-interactive or does not support colors.
}
}
WriteInformation(data, HostTag);
}
}
}
| isc | C# |
132be5d18652b586e09ffe3069752ede8dda1a78 | Optimize constructor for OriginalBoard. | SaxxonPike/roton,SaxxonPike/roton | Source/Roton/Emulation/Original/OriginalBoard.cs | Source/Roton/Emulation/Original/OriginalBoard.cs | using System.Runtime.CompilerServices;
using Roton.Emulation.Data;
using Roton.Emulation.Data.Impl;
using Roton.Infrastructure.Impl;
namespace Roton.Emulation.Original
{
[Context(Context.Original)]
public sealed class OriginalBoard : IBoard
{
private readonly IMemory _memory;
public OriginalBoard(IMemory memory)
{
_memory = memory;
Entrance = new MemoryLocation(_memory, 0x45A9);
}
public IXyPair Camera { get; } = new Location();
public IXyPair Entrance { get; }
public int ExitEast
{
get => _memory.Read8(0x456C);
set => _memory.Write8(0x456C, value);
}
public int ExitNorth
{
get => _memory.Read8(0x4569);
set => _memory.Write8(0x4569, value);
}
public int ExitSouth
{
get => _memory.Read8(0x456A);
set => _memory.Write8(0x456A, value);
}
public int ExitWest
{
get => _memory.Read8(0x456B);
set => _memory.Write8(0x456B, value);
}
public bool IsDark
{
get => _memory.ReadBool(0x4568);
set => _memory.WriteBool(0x4568, value);
}
public int MaximumShots
{
get => _memory.Read8(0x4567);
set => _memory.Write8(0x4567, value);
}
public string Name
{
get => _memory.ReadString(0x2486);
set => _memory.WriteString(0x2486, value);
}
public bool RestartOnZap
{
get => _memory.ReadBool(0x456D);
set => _memory.WriteBool(0x456D, value);
}
public int TimeLimit
{
get => _memory.Read16(0x45AB);
set => _memory.Write16(0x45AB, value);
}
}
} | using Roton.Emulation.Data;
using Roton.Emulation.Data.Impl;
using Roton.Infrastructure.Impl;
namespace Roton.Emulation.Original
{
[Context(Context.Original)]
public sealed class OriginalBoard : IBoard
{
private readonly IMemory _memory;
public OriginalBoard(IMemory memory)
{
_memory = memory;
}
public IXyPair Camera { get; } = new Location();
public IXyPair Entrance => new MemoryLocation(_memory, 0x45A9);
public int ExitEast
{
get => _memory.Read8(0x456C);
set => _memory.Write8(0x456C, value);
}
public int ExitNorth
{
get => _memory.Read8(0x4569);
set => _memory.Write8(0x4569, value);
}
public int ExitSouth
{
get => _memory.Read8(0x456A);
set => _memory.Write8(0x456A, value);
}
public int ExitWest
{
get => _memory.Read8(0x456B);
set => _memory.Write8(0x456B, value);
}
public bool IsDark
{
get => _memory.ReadBool(0x4568);
set => _memory.WriteBool(0x4568, value);
}
public int MaximumShots
{
get => _memory.Read8(0x4567);
set => _memory.Write8(0x4567, value);
}
public string Name
{
get => _memory.ReadString(0x2486);
set => _memory.WriteString(0x2486, value);
}
public bool RestartOnZap
{
get => _memory.ReadBool(0x456D);
set => _memory.WriteBool(0x456D, value);
}
public int TimeLimit
{
get => _memory.Read16(0x45AB);
set => _memory.Write16(0x45AB, value);
}
}
} | isc | C# |
86e7f138adce9e1a4930257b32146181b8a5a656 | make SendPacket protected | flyrpc/flyrpc-csharp | flyrpc/flyrpc/Client.cs | flyrpc/flyrpc/Client.cs | using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace flyrpc
{
public class Client {
private Protocol protocol;
private Router router;
private byte nextSeq = 0;
private Dictionary<int, Action<Client, int, byte[]>> callbacks;
private Dictionary<int, Timer> timers;
public Client(string host, int port) {
router = new Router();
protocol = new Protocol(host, port);
protocol.OnPacket += HandleOnPacket;
callbacks = new Dictionary<int, Action<Client, int, byte[]>>();
timers = new Dictionary<int, Timer>();
}
void HandleOnPacket (Packet pkt) {
byte subType = (byte)(pkt.flag & Protocol.SubTypeBits);
if(subType == Protocol.TypeRPC &&
(pkt.flag & Protocol.FlagResp) != 0) {
int cbid = (pkt.cmd << 16) | pkt.seq;
if(callbacks[cbid] != null) {
callbacks[cbid](this, 0, pkt.msgBuff);
callbacks.Remove(cbid);
if(timers[cbid] != null) {
timers[cbid].Dispose();
timers.Remove(cbid);
}
}
return;
}
router.emitPacket(this, pkt);
}
public void OnMessage(UInt16 cmd, Action<Client, byte[]> handler) {
router.AddRoute(cmd, handler);
}
protected byte SendPacket(byte flag, UInt16 cmd, byte[] buffer) {
Packet p = new Packet();
p.flag = flag;
p.cmd = cmd;
p.seq = nextSeq ++;
p.msgBuff = buffer;
protocol.SendPacket(p);
return p.seq;
}
public void SendMessage(UInt16 cmd, byte[] buffer) {
this.SendPacket(Protocol.TypeRPC, cmd, buffer);
}
/// <summary>
/// Sends the message.
/// </summary>
/// <param name="cmd">Cmd.</param>
/// <param name="buffer">Buffer.</param>
/// <param name="callback">Callback.</param>
public void SendMessage(UInt16 cmd, byte[] buffer, Action<Client, int, byte[]> callback) {
byte seq = this.SendPacket(Protocol.TypeRPC | Protocol.FlagReq, cmd, buffer);
int cbid = cmd << 16 | seq;
callbacks[cbid] = callback;
timers[cbid] = new Timer(new TimerCallback((object obj) => {
callback(this, 1000, null);
timers[cbid].Dispose();
callbacks.Remove(cbid);
timers.Remove(cbid);
}), cbid, 5000, Timeout.Infinite);
}
}
}
| using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace flyrpc
{
public class Client {
private Protocol protocol;
private Router router;
private byte nextSeq = 0;
private Dictionary<int, Action<Client, int, byte[]>> callbacks;
private Dictionary<int, Timer> timers;
public Client(string host, int port) {
router = new Router();
protocol = new Protocol(host, port);
protocol.OnPacket += HandleOnPacket;
callbacks = new Dictionary<int, Action<Client, int, byte[]>>();
timers = new Dictionary<int, Timer>();
}
void HandleOnPacket (Packet pkt) {
byte subType = (byte)(pkt.flag & Protocol.SubTypeBits);
if(subType == Protocol.TypeRPC &&
(pkt.flag & Protocol.FlagResp) != 0) {
int cbid = (pkt.cmd << 16) | pkt.seq;
if(callbacks[cbid] != null) {
callbacks[cbid](this, 0, pkt.msgBuff);
callbacks.Remove(cbid);
if(timers[cbid] != null) {
timers[cbid].Dispose();
timers.Remove(cbid);
}
}
return;
}
router.emitPacket(this, pkt);
}
public void OnMessage(UInt16 cmd, Action<Client, byte[]> handler) {
router.AddRoute(cmd, handler);
}
public byte SendPacket(byte flag, UInt16 cmd, byte[] buffer) {
Packet p = new Packet();
p.flag = flag;
p.cmd = cmd;
p.seq = nextSeq ++;
p.msgBuff = buffer;
protocol.SendPacket(p);
return p.seq;
}
public void SendMessage(UInt16 cmd, byte[] buffer) {
this.SendPacket(Protocol.TypeRPC, cmd, buffer);
}
/// <summary>
/// Sends the message.
/// </summary>
/// <param name="cmd">Cmd.</param>
/// <param name="buffer">Buffer.</param>
/// <param name="callback">Callback.</param>
public void SendMessage(UInt16 cmd, byte[] buffer, Action<Client, int, byte[]> callback) {
byte seq = this.SendPacket(Protocol.TypeRPC | Protocol.FlagReq, cmd, buffer);
int cbid = cmd << 16 | seq;
callbacks[cbid] = callback;
timers[cbid] = new Timer(new TimerCallback((object obj) => {
callback(this, 1000, null);
timers[cbid].Dispose();
callbacks.Remove(cbid);
timers.Remove(cbid);
}), cbid, 5000, Timeout.Infinite);
}
}
}
| apache-2.0 | C# |
d1065186fa7ac6e1b6b403d06f9a9b6a31af5a67 | Add another integration test. | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | test/IntegrationTest.cs | test/IntegrationTest.cs | using System.Net;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Xunit;
namespace HelloWorldApp
{
public class IntegrationTest
{
private TestServer server;
public IntegrationTest()
{
server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
}
[Fact]
public async void ValidRequestReturnsOkTest()
{
using (var client = server.CreateClient())
{
var response = await client.GetAsync("/api/helloworld/World");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<GetHelloWorldResponse>(content);
data.Should().NotBeNull();
data.Name.Should().Be("Hello World!");
}
}
[Fact]
public async void InvalidRequestReturnsNotFoundTest()
{
using (var client = server.CreateClient())
{
var response = await client.GetAsync("/api/helloworld/");
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
}
}
} | using System.Net;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Xunit;
namespace HelloWorldApp
{
public class IntegrationTest
{
private TestServer server;
public IntegrationTest()
{
server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
}
[Fact]
public async void ValidRequestReturnsOkTest()
{
using (var client = server.CreateClient())
{
var response = await client.GetAsync("/api/helloworld/World");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<GetHelloWorldResponse>(content);
data.Should().NotBeNull();
data.Name.Should().Be("Hello World!");
}
}
}
} | mit | C# |
9b252d71ab114b919aef78683808f117b59b8257 | Add update API to app | jongalloway/aspnetcore-workshop,jongalloway/aspnetcore-workshop,jongalloway/aspnetcore-workshop,jongalloway/aspnetcore-workshop,DamianEdwards/aspnetcore-workshop | App/AttendeeList/Controllers/AttendeesApiController.cs | App/AttendeeList/Controllers/AttendeesApiController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AttendeeList
{
[Route("/api/[controller]")]
public class AttendeesApiController : Controller
{
private readonly WorkshopContext _context;
public AttendeesApiController(WorkshopContext context)
{
_context = context;
}
[HttpGet]
public Task<List<Attendee>> Get()
{
return _context.Attendees.ToListAsync();
}
[HttpGet("{id:int}")]
public Task<Attendee> Get(int id)
{
return _context.Attendees.SingleOrDefaultAsync(a => a.Id == id);
}
[HttpPost]
public async Task<IActionResult> Create([FromBody]Attendee attendee)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Attendees.Add(attendee);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(Get), new { id = attendee.Id }, attendee);
}
[HttpPut("{id:int}")]
public async Task<IActionResult> Update([FromBody]Attendee attendee)
{
if (attendee == null)
{
return NotFound();
}
if (!ModelState.IsValid)
{
BadRequest(ModelState);
}
try
{
_context.Update(attendee);
await _context.SaveChangesAsync();
return Ok(attendee);
}
catch (DbUpdateConcurrencyException)
{
if (!AttendeeExists(attendee.Id))
{
return NotFound();
}
else
{
throw;
}
}
}
[HttpDelete("{id:int}")]
public Task Delete(int id)
{
var attendee = new Attendee
{
Id = id
};
_context.Attach(attendee);
_context.Remove(attendee);
return _context.SaveChangesAsync();
}
private bool AttendeeExists(int id)
{
return _context.Attendees.Any(e => e.Id == id);
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AttendeeList
{
[Route("/api/[controller]")]
public class AttendeesApiController : Controller
{
private readonly WorkshopContext _context;
public AttendeesApiController(WorkshopContext context)
{
_context = context;
}
[HttpGet]
public Task<List<Attendee>> Get()
{
return _context.Attendees.ToListAsync();
}
[HttpGet("{id:int}")]
public Task<Attendee> Get(int id)
{
return _context.Attendees.SingleOrDefaultAsync(a => a.Id == id);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Attendee attendee)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Attendees.Add(attendee);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(Get), new { id = attendee.Id }, attendee);
}
[HttpDelete("{id:int}")]
public Task Delete(int id)
{
var attendee = new Attendee
{
Id = id
};
_context.Attach(attendee);
_context.Remove(attendee);
return _context.SaveChangesAsync();
}
}
}
| mit | C# |
290cec0854c67b923e810a8a440c55151bcb8a85 | Mark SingleInstance.OnDestroy() as virtual so extending scripts have the opportunity to do their own cleanup when Unity calls this function on their behalf. | NeerajW/HoloToolkit-Unity,HattMarris1/HoloToolkit-Unity,paseb/MixedRealityToolkit-Unity,paseb/HoloToolkit-Unity,willcong/HoloToolkit-Unity,out-of-pixel/HoloToolkit-Unity | Assets/HoloToolkit/Utilities/Scripts/SingleInstance.cs | Assets/HoloToolkit/Utilities/Scripts/SingleInstance.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T>
{
private static T _Instance;
public static T Instance
{
get
{
if (_Instance == null)
{
T[] objects = FindObjectsOfType<T>();
if (objects.Length != 1)
{
Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length);
}
else
{
_Instance = objects[0];
}
}
return _Instance;
}
}
/// <summary>
/// Called by Unity when destroying a MonoBehaviour. Scripts that extend
/// SingleInstance should be sure to call base.OnDestroy() to ensure the
/// underlying static _Instance reference is properly cleaned up.
/// </summary>
protected virtual void OnDestroy()
{
_Instance = null;
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T>
{
private static T _Instance;
public static T Instance
{
get
{
if (_Instance == null)
{
T[] objects = FindObjectsOfType<T>();
if (objects.Length != 1)
{
Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length);
}
else
{
_Instance = objects[0];
}
}
return _Instance;
}
}
protected void OnDestroy()
{
_Instance = null;
}
}
} | mit | C# |
c01853d1fdb13e044ecc1985067938bdf45c8f0f | Fix duplicate randomsentience sound | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/StationEvents/Events/RandomSentience.cs | Content.Server/StationEvents/Events/RandomSentience.cs | using System.Linq;
using Content.Server.Chat.Managers;
using Content.Server.Ghost.Roles.Components;
using Content.Server.Mind.Commands;
using Content.Server.StationEvents.Components;
using Robust.Shared.Random;
namespace Content.Server.StationEvents.Events;
public sealed class RandomSentience : StationEvent
{
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IChatManager _chatManager = default!;
public override string Name => "RandomSentience";
public override float Weight => WeightNormal;
protected override float EndAfter => 1.0f;
public override void Startup()
{
base.Startup();
var targetList = _entityManager.EntityQuery<SentienceTargetComponent>().ToList();
_random.Shuffle(targetList);
var toMakeSentient = _random.Next(2, 5);
var groups = new HashSet<string>();
foreach (var target in targetList)
{
if (toMakeSentient-- == 0)
break;
MakeSentientCommand.MakeSentient(target.Owner, _entityManager);
_entityManager.RemoveComponent<SentienceTargetComponent>(target.Owner);
var comp = _entityManager.AddComponent<GhostTakeoverAvailableComponent>(target.Owner);
comp.RoleName = _entityManager.GetComponent<MetaDataComponent>(target.Owner).EntityName;
comp.RoleDescription = Loc.GetString("station-event-random-sentience-role-description", ("name", comp.RoleName));
groups.Add(target.FlavorKind);
}
if (groups.Count == 0)
return;
var groupList = groups.ToList();
var kind1 = groupList.Count > 0 ? groupList[0] : "???";
var kind2 = groupList.Count > 1 ? groupList[1] : "???";
var kind3 = groupList.Count > 2 ? groupList[2] : "???";
_chatManager.DispatchStationAnnouncement(
Loc.GetString("station-event-random-sentience-announcement",
("kind1", kind1), ("kind2", kind2), ("kind3", kind3), ("amount", groupList.Count),
("data", Loc.GetString($"random-sentience-event-data-{_random.Next(1, 6)}")),
("strength", Loc.GetString($"random-sentience-event-strength-{_random.Next(1, 8)}"))),
playDefaultSound: false,
colorOverride: Color.Gold
);
}
}
| using System.Linq;
using Content.Server.Chat.Managers;
using Content.Server.Ghost.Roles.Components;
using Content.Server.Mind.Commands;
using Content.Server.StationEvents.Components;
using Robust.Shared.Random;
namespace Content.Server.StationEvents.Events;
public sealed class RandomSentience : StationEvent
{
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IChatManager _chatManager = default!;
public override string Name => "RandomSentience";
public override float Weight => WeightNormal;
protected override float EndAfter => 1.0f;
public override void Startup()
{
base.Startup();
var targetList = _entityManager.EntityQuery<SentienceTargetComponent>().ToList();
_random.Shuffle(targetList);
var toMakeSentient = _random.Next(2, 5);
var groups = new HashSet<string>();
foreach (var target in targetList)
{
if (toMakeSentient-- == 0)
break;
MakeSentientCommand.MakeSentient(target.Owner, _entityManager);
_entityManager.RemoveComponent<SentienceTargetComponent>(target.Owner);
var comp = _entityManager.AddComponent<GhostTakeoverAvailableComponent>(target.Owner);
comp.RoleName = _entityManager.GetComponent<MetaDataComponent>(target.Owner).EntityName;
comp.RoleDescription = Loc.GetString("station-event-random-sentience-role-description", ("name", comp.RoleName));
groups.Add(target.FlavorKind);
}
if (groups.Count == 0)
return;
var groupList = groups.ToList();
var kind1 = groupList.Count > 0 ? groupList[0] : "???";
var kind2 = groupList.Count > 1 ? groupList[1] : "???";
var kind3 = groupList.Count > 2 ? groupList[2] : "???";
_chatManager.DispatchStationAnnouncement(
Loc.GetString("station-event-random-sentience-announcement",
("kind1", kind1), ("kind2", kind2), ("kind3", kind3), ("amount", groupList.Count),
("data", Loc.GetString($"random-sentience-event-data-{_random.Next(1, 6)}")),
("strength", Loc.GetString($"random-sentience-event-strength-{_random.Next(1, 8)}"))),
colorOverride: Color.Gold
);
}
}
| mit | C# |
ceb99c37aa38a30046920da402fe6976797c07ca | Fix r# nag. | JohanLarsson/Gu.Wpf.ValidationScope | Gu.Wpf.ValidationScope.Ui.Tests/Helpers/WindowTests.cs | Gu.Wpf.ValidationScope.Ui.Tests/Helpers/WindowTests.cs | namespace Gu.Wpf.ValidationScope.Ui.Tests
{
using NUnit.Framework;
using TestStack.White;
using TestStack.White.UIItems.WindowItems;
using TestStack.White.WindowsAPI;
public abstract class WindowTests
{
private Application application;
public static Window StaticWindow { get; private set; }
protected Window Window => StaticWindow;
protected abstract string WindowName { get; }
public void RestartApplication()
{
this.OneTimeTearDown();
this.OneTimeSetUp();
}
[OneTimeSetUp]
public virtual void OneTimeSetUp()
{
this.application = Application.AttachOrLaunch(Info.CreateStartInfo(this.WindowName));
StaticWindow = this.application.GetWindow(this.WindowName);
//this.SaveScreenshotToArtifacsDir("start");
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
this.Window?.Keyboard.PressAndLeaveSpecialKey(KeyboardInput.SpecialKeys.CONTROL);
this.Window?.Keyboard.PressAndLeaveSpecialKey(KeyboardInput.SpecialKeys.SHIFT);
//this.SaveScreenshotToArtifacsDir("finish");
this.application?.Dispose();
StaticWindow = null;
}
protected void PressTab()
{
this.Window.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.TAB);
}
// ReSharper disable once UnusedMember.Local
private void SaveScreenshotToArtifacsDir(string suffix)
{
var fileName = System.IO.Path.Combine(Info.ArtifactsDirectory(), $"{this.WindowName}_{suffix}.png");
using (var image = new TestStack.White.ScreenCapture().CaptureDesktop())
{
image.Save(fileName);
}
}
}
} | namespace Gu.Wpf.ValidationScope.Ui.Tests
{
using NUnit.Framework;
using TestStack.White;
using TestStack.White.UIItems.WindowItems;
using TestStack.White.WindowsAPI;
public abstract class WindowTests
{
private Application application;
public static Window StaticWindow { get; private set; }
protected Window Window => StaticWindow;
protected abstract string WindowName { get; }
public void RestartApplication()
{
this.OneTimeTearDown();
this.OneTimeSetUp();
}
[OneTimeSetUp]
public virtual void OneTimeSetUp()
{
this.application = Application.AttachOrLaunch(Info.CreateStartInfo(this.WindowName));
StaticWindow = this.application.GetWindow(this.WindowName);
//this.SaveScreenshotToArtifacsDir("start");
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
this.Window?.Keyboard.PressAndLeaveSpecialKey(KeyboardInput.SpecialKeys.CONTROL);
this.Window?.Keyboard.PressAndLeaveSpecialKey(KeyboardInput.SpecialKeys.SHIFT);
//this.SaveScreenshotToArtifacsDir("finish");
this.application?.Dispose();
StaticWindow = null;
}
protected void PressTab()
{
this.Window.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.TAB);
}
private void SaveScreenshotToArtifacsDir(string suffix)
{
var fileName = System.IO.Path.Combine(Info.ArtifactsDirectory(), $"{this.WindowName}_{suffix}.png");
using (var image = new TestStack.White.ScreenCapture().CaptureDesktop())
{
image.Save(fileName);
}
}
}
} | mit | C# |
d009bb2b235c3940c1a2c76cd7afed087879f625 | comment back to thread redirect | BCITer/Jabber,BCITer/Jabber,BCITer/Jabber | JabberBCIT/JabberBCIT/Views/Forum/CreateComment.cshtml | JabberBCIT/JabberBCIT/Views/Forum/CreateComment.cshtml | @model JabberBCIT.Models.Comment
@{
ViewBag.Title = "CreateComment";
}
@Styles.Render("~/Content/createForumPost.css")
<div class="container">
<div class="row forum">
<div class="col-md-offset-1 col-md-10">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Submit a comment</h2>
<hr />
<div class="form-group">
@Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Text, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Text, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default submitBtn" />
<button class="btn" onclick="location.href='.';return false;">Back to List</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
| @model JabberBCIT.Models.Comment
@{
ViewBag.Title = "CreateComment";
}
@Styles.Render("~/Content/createForumPost.css")
<div class="container">
<div class="row forum">
<div class="col-md-offset-1 col-md-10">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Submit a comment</h2>
<hr />
<div class="form-group">
@Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Text, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Text, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default submitBtn" />
<button class="btn" onclick="location.href='@Url.Action("Index", "Forum")';return false;">Back to List</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
| mit | C# |
19125fbabdc8406920659402ee4b0ef9069e68c2 | update console to new interface. | Jasily/jasily.frameworks.cli-csharp | Jasily.Frameworks.Cli.NetFramework/IO/ConsoleOutput.cs | Jasily.Frameworks.Cli.NetFramework/IO/ConsoleOutput.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jasily.Frameworks.Cli.IO
{
internal class ConsoleOutput : IOutput
{
private void SetColor(OutputLevel level)
{
switch (level)
{
case OutputLevel.Normal:
Console.ResetColor();
break;
case OutputLevel.Error:
Console.ForegroundColor = ConsoleColor.Red;
break;
case OutputLevel.Usage:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
default:
break;
}
}
public void Write(OutputLevel level, string value)
{
this.SetColor(level);
Console.Write(value);
}
public void WriteLine(OutputLevel level, string value)
{
this.SetColor(level);
Console.WriteLine(value);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jasily.Frameworks.Cli.IO
{
internal class ConsoleOutput : IOutput
{
private void SetColor(OutputLevel level)
{
switch (level)
{
case OutputLevel.Normal:
Console.ResetColor();
break;
case OutputLevel.Error:
Console.ForegroundColor = ConsoleColor.Red;
break;
default:
break;
}
}
public void Write(OutputLevel level, string value)
{
this.SetColor(level);
Console.Write(value);
}
public void WriteLine(OutputLevel level, string value)
{
this.SetColor(level);
Console.WriteLine(value);
}
}
}
| mit | C# |
ae507022d8149414f672297c40e012a909cc8ed6 | Make sure required services are registered | mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Server.Web/GlimpseServerWebServices.cs | src/Glimpse.Server.Web/GlimpseServerWebServices.cs | using Glimpse.Agent;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Glimpse.Server.Web;
using Glimpse.Web;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse
{
public class GlimpseServerWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Common
//
services.AddSingleton<IServerBroker, DefaultServerBroker>();
services.AddSingleton<IStorage, InMemoryStorage>();
services.AddTransient<IResourceManager, ResourceManager>();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseServerWebOptions>, GlimpseServerWebOptionsSetup>();
services.AddTransient<IExtensionProvider<IAllowClientAccess>, DefaultExtensionProvider<IAllowClientAccess>>();
services.AddTransient<IExtensionProvider<IAllowAgentAccess>, DefaultExtensionProvider<IAllowAgentAccess>>();
services.AddTransient<IExtensionProvider<IResource>, DefaultExtensionProvider<IResource>>();
services.AddTransient<IExtensionProvider<IResourceStartup>, DefaultExtensionProvider<IResourceStartup>>();
services.AddSingleton<IAllowRemoteProvider, DefaultAllowRemoteProvider>();
services.AddSingleton<IScriptOptionsProvider, DefaultScriptOptionsProvider>();
services.AddSingleton<IMetadataProvider, DefaultMetadataProvider>();
return services;
}
public static IServiceCollection GetLocalAgentServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IMessagePublisher, InProcessChannel>();
return services;
}
}
} | using Glimpse.Agent;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Framework.OptionsModel;
using Glimpse.Server.Web;
using Glimpse.Web;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse
{
public class GlimpseServerWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Common
//
services.AddSingleton<IServerBroker, DefaultServerBroker>();
services.AddSingleton<IStorage, InMemoryStorage>();
services.AddSingleton<IScriptOptionsProvider, DefaultScriptOptionsProvider>();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseServerWebOptions>, GlimpseServerWebOptionsSetup>();
services.AddTransient<IExtensionProvider<IAllowClientAccess>, DefaultExtensionProvider<IAllowClientAccess>>();
services.AddTransient<IExtensionProvider<IAllowAgentAccess>, DefaultExtensionProvider<IAllowAgentAccess>>();
services.AddTransient<IExtensionProvider<IResource>, DefaultExtensionProvider<IResource>>();
services.AddTransient<IExtensionProvider<IResourceStartup>, DefaultExtensionProvider<IResourceStartup>>();
services.AddSingleton<IAllowRemoteProvider, DefaultAllowRemoteProvider>();
services.AddTransient<IResourceManager, ResourceManager>();
return services;
}
public static IServiceCollection GetLocalAgentServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IMessagePublisher, InProcessChannel>();
return services;
}
}
} | mit | C# |
26b85a75bfe40a976f41dca018b669505fa3c8f5 | Refactor for extensibility | kyubisation/FluentRestBuilder,kyubisation/FluentRestBuilder | src/FluentRestBuilder/Pipes/InputOutputPipe.cs | src/FluentRestBuilder/Pipes/InputOutputPipe.cs | // <copyright file="InputOutputPipe.cs" company="Kyubisation">
// Copyright (c) Kyubisation. All rights reserved.
// </copyright>
namespace FluentRestBuilder.Pipes
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
public abstract class InputOutputPipe<TInput> :
OutputPipe<TInput>,
IInputPipe<TInput>
where TInput : class
{
private readonly IOutputPipe<TInput> parent;
protected InputOutputPipe(IOutputPipe<TInput> parent)
: base(parent)
{
this.parent = parent;
this.parent.Attach(this);
}
async Task<IActionResult> IInputPipe<TInput>.Execute(TInput input)
{
var result = await this.ExecuteAsync(input);
if (result != null)
{
return result;
}
return await this.ExecuteChild(input);
}
protected virtual Task<IActionResult> ExecuteAsync(TInput entity) =>
Task.FromResult(this.Execute(entity));
protected virtual IActionResult Execute(TInput entity) => null;
protected virtual async Task<IActionResult> ExecuteChild(TInput input)
{
NoPipeAttachedException.Check(this.Child);
return await this.Child.Execute(input);
}
protected override Task<IActionResult> Execute() => this.parent.Execute();
}
}
| // <copyright file="InputOutputPipe.cs" company="Kyubisation">
// Copyright (c) Kyubisation. All rights reserved.
// </copyright>
namespace FluentRestBuilder.Pipes
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
public abstract class InputOutputPipe<TInput> :
OutputPipe<TInput>,
IInputPipe<TInput>
where TInput : class
{
private readonly IOutputPipe<TInput> parent;
protected InputOutputPipe(IOutputPipe<TInput> parent)
: base(parent)
{
this.parent = parent;
this.parent.Attach(this);
}
async Task<IActionResult> IInputPipe<TInput>.Execute(TInput input)
{
var result = await this.ExecuteAsync(input);
if (result != null)
{
return result;
}
NoPipeAttachedException.Check(this.Child);
return await this.Child.Execute(input);
}
protected virtual Task<IActionResult> ExecuteAsync(TInput entity) =>
Task.FromResult(this.Execute(entity));
protected virtual IActionResult Execute(TInput entity) => null;
protected override Task<IActionResult> Execute() => this.parent.Execute();
}
}
| mit | C# |
514c624fcff4231b2d7a03526842351076241b0c | Fix InvalidSearchApiTests expected status code and message (#4590) | elastic/elasticsearch-net,elastic/elasticsearch-net | tests/Tests/Search/Search/InvalidSearchApiTests.cs | tests/Tests/Search/Search/InvalidSearchApiTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Nest;
using Tests.Core.Extensions;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.EndpointTests.TestState;
namespace Tests.Search.Search
{
public class InvalidSearchApiTests : SearchApiTests
{
public InvalidSearchApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
/// <summary> This is rather noisy on the console out, we only need to test 1 of our overloads randomly really. </summary>
protected override bool TestOnlyOne => true;
protected override bool ExpectIsValid => false;
protected override object ExpectJson => new
{
from = 10,
size = 20,
aggs = new
{
startDates = new
{
date_range = new
{
ranges = new[]
{
new { from = "-1m" }
}
}
}
}
};
protected override int ExpectStatusCode => 500;
protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s
.From(10)
.Size(20)
.Aggregations(a => a
.DateRange("startDates", t => t
.Ranges(ranges => ranges.From("-1m"))
)
);
protected override SearchRequest<Project> Initializer => new SearchRequest<Project>()
{
From = 10,
Size = 20,
Aggregations = new DateRangeAggregation("startDates")
{
Ranges = new List<DateRangeExpression>
{
new DateRangeExpression { From = "-1m" }
}
}
};
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.ShouldNotBeValid();
var serverError = response.ServerError;
serverError.Should().NotBeNull();
serverError.Status.Should().Be(ExpectStatusCode);
serverError.Error.Reason.Should().Be("all shards failed");
serverError.Error.RootCause.First().Reason.Should().Contain("value source config is invalid");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Nest;
using Tests.Core.Extensions;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.EndpointTests.TestState;
namespace Tests.Search.Search
{
public class InvalidSearchApiTests : SearchApiTests
{
public InvalidSearchApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
/// <summary> This is rather noisy on the console out, we only need to test 1 of our overloads randomly really. </summary>
protected override bool TestOnlyOne => true;
protected override bool ExpectIsValid => false;
protected override object ExpectJson => new
{
from = 10,
size = 20,
aggs = new
{
startDates = new
{
date_range = new
{
ranges = new[]
{
new { from = "-1m" }
}
}
}
}
};
protected override int ExpectStatusCode => 400;
protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s
.From(10)
.Size(20)
.Aggregations(a => a
.DateRange("startDates", t => t
.Ranges(ranges => ranges.From("-1m"))
)
);
protected override SearchRequest<Project> Initializer => new SearchRequest<Project>()
{
From = 10,
Size = 20,
Aggregations = new DateRangeAggregation("startDates")
{
Ranges = new List<DateRangeExpression>
{
new DateRangeExpression { From = "-1m" }
}
}
};
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.ShouldNotBeValid();
var serverError = response.ServerError;
serverError.Should().NotBeNull();
serverError.Status.Should().Be(400);
serverError.Error.Reason.Should().Be("all shards failed");
serverError.Error.RootCause.First().Reason.Should().Contain("[-1m]");
}
}
}
| apache-2.0 | C# |
c951f1aab0818154625dd324797477ba5f0c5b5c | Prueba de subir a GitHub | JuanQuijanoAbad/UniversalSync,JuanQuijanoAbad/UniversalSync | UniversalSync_Client_Console/Program.cs | UniversalSync_Client_Console/Program.cs | using System;
using StorageAzure;
namespace UniversalSync_Client_Console
{
public class Program
{
[STAThread]
public static void Main(string[] args)
{
var filesPaths = SelectFolder.RecursiveAndFiles();
var repository = new Blob(new Configuration());
var resultado = new SendFilesToCloud(repository).PutAllFiles(filesPaths);
Console.WriteLine("Pulsa una teclaaa");
Console.ReadKey();
}
}
}
| using System;
using StorageAzure;
namespace UniversalSync_Client_Console
{
public class Program
{
[STAThread]
public static void Main(string[] args)
{
var filesPaths = SelectFolder.RecursiveAndFiles();
var repository = new Blob(new Configuration());
var resultado = new SendFilesToCloud(repository).PutAllFiles(filesPaths);
Console.WriteLine("Pulsa una tecla");
Console.ReadKey();
}
}
}
| mit | C# |
8b4c45d906abe77ad9e885ebe3bfe0caae2880c6 | Update Create Comment Ajax Form | csyntax/BlogSystem | Source/BlogSystem.Web/Views/Comments/_CreateComment.cshtml | Source/BlogSystem.Web/Views/Comments/_CreateComment.cshtml | @model BlogSystem.Web.ViewModels.Comment.CommentViewModel
<h3>Leave a Comment</h3>
@if (User.Identity.IsAuthenticated)
{
using (Ajax.BeginForm("Create", "Comments", new { id = ViewData["id"].ToString() }, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "comments", OnFailure = "BlogSystem.onCreateCommentFailure", OnSuccess = "BlogSystem.onAddCommentSuccess" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, string.Empty, new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control " } })
@Html.ValidationMessageFor(model => model.Content, string.Empty, new { @class = "text-danger" })
</div>
<button type="submit" class="btn btn-default">Add Comment</button>
}
}
else
{
<p>Only registered users can comment.</p>
} | @model BlogSystem.Web.ViewModels.Comment.CommentViewModel
<h3>Leave a Comment</h3>
@if (User.Identity.IsAuthenticated)
{
using (Ajax.BeginForm("Create", "Comments", new { id = ViewData["id"].ToString() }, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "comments", OnFailure = "BlogSystem.onCreateCommentFailure" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, string.Empty, new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control " } })
@Html.ValidationMessageFor(model => model.Content, string.Empty, new { @class = "text-danger" })
</div>
<button type="submit" class="btn btn-default">Add Comment</button>
}
}
else
{
<p>Only registered users can comment.</p>
} | mit | C# |
9df40e8ccbf1108599401ecc05099bb5938f50fc | Add Program | networm/Unity3dScriptTemplatesTool | Unity3dScriptTemplatesTool/Program.cs | Unity3dScriptTemplatesTool/Program.cs | using Microsoft.Win32;
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Unity3dScriptTemplatesTool
{
class Program
{
static void Main(string[] args)
{
// find reg key
const string userRoot = "HKEY_CURRENT_USER";
const string subkey = @"SOFTWARE\Unity Technologies\Installer\Unity";
const string keyName = userRoot + "\\" + subkey;
// get install path
string installPath = (string)Registry.GetValue(keyName, "Location x64", string.Empty);
if (string.IsNullOrEmpty(installPath))
{
Console.WriteLine("Couldn't find Unity3d install path!");
return;
}
// get script templates path
string scriptTemplatesDir = @"Editor\Data\Resources\ScriptTemplates";
string scriptTemplatesPath = Path.Combine(installPath, scriptTemplatesDir);
// modify script template file
try
{
Console.WriteLine("Modify script templates:");
string[] scriptTemplates = Directory.GetFiles(scriptTemplatesPath, "*.txt", SearchOption.TopDirectoryOnly);
foreach (var file in scriptTemplates)
{
string fileName = Path.GetFileName(file);
Console.WriteLine(fileName);
string text = File.ReadAllText(file);
// remove empty line
// .NET regex engine matches the $ between \r and \n
// so we need to do it before change line breaks
// http://stackoverflow.com/questions/7647716/how-to-remove-empty-lines-from-a-formatted-string
text = Regex.Replace(text, @"^\s+$", string.Empty, RegexOptions.Multiline);
// change line breaks
text = Regex.Replace(text, @"\r\n?|\n", "\r\n");
// change using declaration
if (fileName.Contains("C#"))
{
text = text.Replace("using System.Collections;", "using System.Collections.Generic;");
}
File.WriteAllText(file, text, Encoding.UTF8);
}
Console.WriteLine("Job done!");
}
catch (Exception e)
{
Console.WriteLine("Couldn't modify script templates!");
Console.WriteLine("Exception: " + e.Message);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Unity3dScriptTemplatesTool
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
5e070276e09fee1bad13f416b103e7d4c253eccf | Implement link property and added add link method | lucasbrendel/chain | Chain/Chain.cs | Chain/Chain.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chain
{
public interface IChain
{
IList<ILink> Links { get; }
void ConnectAllLinks();
void LoopLinks(int amountOfLoops);
void RunLinks();
void AddLink(ILink link);
}
public class Chain : IChain
{
private IList<ILink> _Links;
public Chain()
{
_Links = new List<ILink>();
}
public IList<ILink> Links
{
get { return _Links; }
}
public void ConnectAllLinks()
{
throw new NotImplementedException();
}
public void LoopLinks(int amountOfLoops)
{
int i = 0;
while (i < amountOfLoops)
{
i++;
RunLinks();
}
}
public void RunLinks()
{
foreach (ILink link in _Links)
{
if(link.IsEnabled)
{
link.HookBeforeLink();
link.RunLink();
link.HookAfterLink();
}
}
}
public void AddLink(ILink link)
{
_Links.Add(link);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chain
{
public interface IChain
{
IList<ILink> Links { get; }
void ConnectAllLinks();
void LoopLinks(int amountOfLoops);
void RunLinks();
}
public class Chain : IChain
{
private IList<ILink> _Links;
public Chain()
{
}
public IList<ILink> Links
{
get { throw new NotImplementedException(); }
}
public void ConnectAllLinks()
{
throw new NotImplementedException();
}
public void LoopLinks(int amountOfLoops)
{
int i = 0;
while (i < amountOfLoops)
{
i++;
RunLinks();
}
}
public void RunLinks()
{
foreach (ILink link in _Links)
{
if(link.IsEnabled)
{
link.HookBeforeLink();
link.RunLink();
link.HookAfterLink();
}
}
}
}
}
| mit | C# |
4078ca1d228843ae6397e805affa8d7cb1fca9f7 | Update to use fluent API to fix build break. | OmniSharp/omnisharp-scaffolding,OmniSharp/omnisharp-scaffolding | test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs | test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var model = new Model();
var builder = new ModelBuilder(model);
builder.Entity<Product>();
builder.Entity<Category>()
.OneToMany(e => e.CategoryProducts, e => e.ProductCategory)
.ForeignKey(e => e.ProductCategoryId);
return model;
}
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var model = new Model();
var builder = new ModelBuilder(model);
builder.Entity<Product>();
builder.Entity<Category>();
var categoryType = model.GetEntityType(typeof(Category));
var productType = model.GetEntityType(typeof(Product));
var categoryFk = productType.GetOrAddForeignKey(productType.GetProperty("ProductCategoryId"), categoryType.GetPrimaryKey());
categoryType.AddNavigation("CategoryProducts", categoryFk, pointsToPrincipal: false);
productType.AddNavigation("ProductCategory", categoryFk, pointsToPrincipal: true);
return model;
}
}
}
} | mit | C# |
8f386040c0e8b595b36c3002f36edb0037cea6c8 | Add Register*ChatMessage methods to interface | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/ChessVariantsTraining/MemoryRepositories/Variant960/IGameRepoForSocketHandlers.cs | src/ChessVariantsTraining/MemoryRepositories/Variant960/IGameRepoForSocketHandlers.cs | using ChessDotNet;
using ChessVariantsTraining.Models.Variant960;
namespace ChessVariantsTraining.MemoryRepositories.Variant960
{
public interface IGameRepoForSocketHandlers
{
Game Get(string id);
void RegisterMove(Game subject, Move move);
void RegisterGameOutcome(Game subject, string outcome);
void RegisterPlayerChatMessage(Game subject, ChatMessage msg);
void RegisterSpectatorChatMessage(Game subject, ChatMessage msg);
}
}
| using ChessDotNet;
using ChessVariantsTraining.Models.Variant960;
namespace ChessVariantsTraining.MemoryRepositories.Variant960
{
public interface IGameRepoForSocketHandlers
{
Game Get(string id);
void RegisterMove(Game subject, Move move);
void RegisterGameOutcome(Game subject, string outcome);
}
}
| agpl-3.0 | C# |
8296e3dfb9d3f3f7a968bb3e056e1e3354e38d53 | Update WindowAlwaysOnTop.cs | UnityCommunity/UnityLibrary | Assets/Scripts/Helpers/Windows/WindowAlwaysOnTop.cs | Assets/Scripts/Helpers/Windows/WindowAlwaysOnTop.cs | // keep executable window always on top, good for multiplayer testing
using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace UnityLibrary
{
public class WindowAlwaysOnTop : MonoBehaviour
{
#if !UNITY_STANDALONE_LINUX
// https://stackoverflow.com/a/34703664/5452781
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
// https://forum.unity.com/threads/unity-window-handle.115364/#post-1650240
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
public static IntPtr GetWindowHandle()
{
return GetActiveWindow();
}
#endif
void Awake()
{
// TODO save current window pos to player prefs on exit, then can open into same position next time
#if !UNITY_EDITOR && !UNITY_STANDALONE_LINUX
Debug.Log("Make window stay on top");
SetWindowPos(GetActiveWindow(), HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
#endif
}
}
}
| // keep executable window always on top, good for multiplayer testing
using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace UnityLibrary
{
public class WindowAlwaysOnTop : MonoBehaviour
{
// https://stackoverflow.com/a/34703664/5452781
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
// https://forum.unity.com/threads/unity-window-handle.115364/#post-1650240
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
public static IntPtr GetWindowHandle()
{
return GetActiveWindow();
}
void Awake()
{
// TODO save current window pos to player prefs on exit, then can open into same position next time
#if !UNITY_EDITOR
Debug.Log("Make window stay on top");
SetWindowPos(GetActiveWindow(), HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
#endif
}
}
}
| mit | C# |
f237a72cc4016ed2b22c9dd7e1db18f1d284b620 | Update Program.cs | hprose/hprose-dotnet | examples/Limiter/Program.cs | examples/Limiter/Program.cs | using Hprose.RPC;
using Hprose.RPC.Plugins.Limiter;
using System;
using System.Net;
using System.Threading.Tasks;
class MyService {
public int Sum(int x, int y) {
return x + y;
}
}
public interface IMyService {
Task<int> Sum(int x, int y);
}
class Program {
static async Task RunClient() {
var client = new Client("http://127.0.0.1:8080/");
client.Use(new ConcurrentLimiter(64).Handler).Use(new RateLimiter(2000).InvokeHandler);
var begin = DateTime.Now;
var proxy = client.UseService<IMyService>();
var n = 5000;
var tasks = new Task<int>[n];
for (int i = 0; i < n; ++i) {
tasks[i] = proxy.Sum(i, i);
}
await Task.WhenAll(tasks);
var end = DateTime.Now;
Console.WriteLine(end - begin);
}
static void Main(string[] args) {
HttpListener server = new HttpListener();
server.Prefixes.Add("http://127.0.0.1:8080/");
server.Start();
var service = new Service();
service.AddInstanceMethods(new MyService()).Bind(server);
RunClient().Wait();
server.Stop();
}
} | using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Hprose.RPC;
using Hprose.RPC.Plugins.Limiter;
class MyService {
public int Sum(int x, int y) {
return x + y;
}
}
public interface IMyService {
Task<int> Sum(int x, int y);
}
class Program {
static async Task RunClient() {
var client = new Client("tcp4://127.0.0.1:8412");
client.Use(new ConcurrentLimiter(64).Handler).Use(new RateLimiter(10000).InvokeHandler);
var begin = DateTime.Now;
var proxy = client.UseService<IMyService>();
var n = 5000;
var tasks = new Task<int>[n];
for (int i = 0; i < n; ++i) {
tasks[i] = proxy.Sum(i, i);
}
await Task.WhenAll(tasks);
var end = DateTime.Now;
Console.WriteLine(end - begin);
}
static void Main(string[] args) {
IPAddress iPAddress = Dns.GetHostAddresses("127.0.0.1")[0];
TcpListener server = new TcpListener(iPAddress, 8412);
server.Start();
var service = new Service();
service.AddInstanceMethods(new MyService()).Bind(server);
RunClient().Wait();
server.Stop();
}
} | mit | C# |
6d6c5a9d56ecd7f1e3a46da5717eb3681860fc3e | tweak how exceptions are logged | TheTree/branch,TheTree/branch,TheTree/branch | dotnet/Packages/Crpc/Middleware/ExceptionMiddleware.cs | dotnet/Packages/Crpc/Middleware/ExceptionMiddleware.cs | using System;
using System.Threading.Tasks;
using Branch.Packages.Bae;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Sentry;
namespace Branch.Packages.Crpc.Middleware
{
public sealed class ExceptionMiddleware : IMiddleware
{
private readonly ILogger _logger;
private readonly IHub _sentry;
private static JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() },
};
public ExceptionMiddleware(ILoggerFactory loggerFactory, IHub sentry)
{
if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));
_logger = loggerFactory.CreateLogger(nameof(ExceptionMiddleware));
_sentry = sentry;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
_sentry.CaptureException(ex);
var bae = ex as BaeException;
if (!(ex is BaeException))
{
// TODO(0xdeafcafe): How should this be done?
bae = new BaeException(BaeCodes.Unknown);
}
var json = JsonConvert.SerializeObject(bae, _jsonSerializerSettings);
context.Response.StatusCode = bae.StatusCode();
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(json);
}
}
}
}
| using System;
using System.Threading.Tasks;
using Branch.Packages.Bae;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Branch.Packages.Crpc.Middleware
{
public sealed class ExceptionMiddleware : IMiddleware
{
private readonly ILogger _logger;
private static JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() },
};
public ExceptionMiddleware(ILoggerFactory loggerFactory)
{
if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));
_logger = loggerFactory.CreateLogger(nameof(ExceptionMiddleware));
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
catch (Exception ex)
{
var bae = ex as BaeException;
// TODO(0xdeafcafe): How should this be done?
if (!(ex is BaeException))
{
_logger.LogError(ex, ex.Message);
bae = new BaeException(BaeCodes.Unknown);
}
var json = JsonConvert.SerializeObject(bae, _jsonSerializerSettings);
context.Response.StatusCode = bae.StatusCode();
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(json);
}
}
}
}
| mit | C# |
dc6d9824e5289cd5220e70b109b91e76e8ea09e6 | Fix the `SampleTypeEqualityComparer`. | fffej/BobTheBuilder,alastairs/BobTheBuilder | BobTheBuilder.Tests/SampleTypeEqualityComparer.cs | BobTheBuilder.Tests/SampleTypeEqualityComparer.cs | using System.Collections.Generic;
namespace BobTheBuilder.Tests
{
internal class SampleTypeEqualityComparer : IEqualityComparer<SampleType>
{
public bool Equals(SampleType x, SampleType y)
{
if (ReferenceEquals(x, y))
{
return true;
}
var stringsAreEqual = x.StringProperty == y.StringProperty;
var intsAreEqual = x.IntProperty == y.IntProperty;
var complexesAreEqual = x.ComplexProperty == y.ComplexProperty;
return stringsAreEqual && intsAreEqual && complexesAreEqual;
}
public int GetHashCode(SampleType obj)
{
return 1;
}
}
} | using System.Collections.Generic;
namespace BobTheBuilder.Tests
{
internal class SampleTypeEqualityComparer : IEqualityComparer<SampleType>
{
public bool Equals(SampleType x, SampleType y)
{
if (ReferenceEquals(x, y))
{
return true;
}
var stringsAreEqual = x.StringProperty == y.StringProperty;
var complexesAreEqual = x.ComplexProperty == y.ComplexProperty;
return stringsAreEqual && complexesAreEqual;
}
public int GetHashCode(SampleType obj)
{
return 1;
}
}
} | apache-2.0 | C# |
f086d33d1adfa1b53ece2b4788fc0f3c7784db52 | use app config to query any database insteead of using hardcoded sproc | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Controller/Helpers.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Controller/Helpers.cs | using Appleseed.Base.Alerts.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
namespace Appleseed.Base.Alerts.Controller
{
class Helpers
{
#region App Config Values
static IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
#endregion
#region helpers
public static string UppercaseFirst(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
public static List<UserAlert> GetUserAlertSchedules(string scheudle)
{
var userAlerts = db.Query<UserAlert>(Constants.GetUserAlertQuery,
commandType: CommandType.Text).ToList<UserAlert>();
return userAlerts;
}
public static bool UpdateUserSendDate(Guid userID, DateTime date)
{
int rowsAffected = db.Execute("");
if (rowsAffected > 0)
{
return true;
}
return false;
}
#endregion
}
}
| using Appleseed.Base.Alerts.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
namespace Appleseed.Base.Alerts.Controller
{
class Helpers
{
#region App Config Values
static IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
#endregion
#region helpers
public static string UppercaseFirst(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
public static List<UserAlert> GetUserAlertSchedules(string scheudle)
{
var userAlerts = db.Query<UserAlert>("GetPortalUserAlerts", new { alert_schedule = scheudle },
commandType: CommandType.StoredProcedure).ToList<UserAlert>();
return userAlerts;
}
public static bool UpdateUserSendDate(Guid userID, DateTime date)
{
int rowsAffected = db.Execute("");
if (rowsAffected > 0)
{
return true;
}
return false;
}
#endregion
}
}
| apache-2.0 | C# |
9304d6a75f39748f3a6e8d81a790140fc846e50c | Remove unused warnings | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,vladkol/MixedRealityToolkit-Unity,vladkol/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,vladkol/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit.Providers/WindowsMixedReality/WindowsMixedRealityGGVHand.cs | Assets/MixedRealityToolkit.Providers/WindowsMixedReality/WindowsMixedRealityGGVHand.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Utilities;
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input
{
/// <summary>
/// A Windows Mixed Reality Controller Instance.
/// </summary>
[MixedRealityController(
SupportedControllerType.GGVHand,
new[] { Handedness.Left, Handedness.Right })]
public class WindowsMixedRealityGGVHand : WindowsMixedRealityController
{
public WindowsMixedRealityGGVHand(TrackingState trackingState, Handedness controllerHandedness, IMixedRealityInputSource inputSource = null, MixedRealityInteractionMapping[] interactions = null)
: base(trackingState, controllerHandedness, inputSource, interactions)
{
}
/// <summary>
/// The GGV hand default interactions
/// </summary>
/// <remarks>A single interaction mapping works for both left and right controllers.</remarks>
public override MixedRealityInteractionMapping[] DefaultInteractions { get; } = new[]
{
new MixedRealityInteractionMapping(0, "Select", AxisType.Digital, DeviceInputType.Select, MixedRealityInputAction.None),
new MixedRealityInteractionMapping(1, "Grip Pose", AxisType.SixDof, DeviceInputType.SpatialGrip, MixedRealityInputAction.None),
};
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Utilities;
#if UNITY_WSA
using UnityEngine;
using UnityEngine.XR.WSA.Input;
#endif
#if WINDOWS_UWP
using System;
using System.Collections.Generic;
using Windows.Perception;
using Windows.Perception.People;
using Windows.UI.Input.Spatial;
#endif
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input
{
/// <summary>
/// A Windows Mixed Reality Controller Instance.
/// </summary>
[MixedRealityController(
SupportedControllerType.GGVHand,
new[] { Handedness.Left, Handedness.Right })]
public class WindowsMixedRealityGGVHand : WindowsMixedRealityController
{
public WindowsMixedRealityGGVHand(TrackingState trackingState, Handedness controllerHandedness, IMixedRealityInputSource inputSource = null, MixedRealityInteractionMapping[] interactions = null)
: base(trackingState, controllerHandedness, inputSource, interactions)
{
}
/// <summary>
/// The GGV hand default interactions
/// </summary>
/// <remarks>A single interaction mapping works for both left and right controllers.</remarks>
public override MixedRealityInteractionMapping[] DefaultInteractions { get; } = new[]
{
new MixedRealityInteractionMapping(0, "Select", AxisType.Digital, DeviceInputType.Select, MixedRealityInputAction.None),
new MixedRealityInteractionMapping(1, "Grip Pose", AxisType.SixDof, DeviceInputType.SpatialGrip, MixedRealityInputAction.None),
};
}
} | mit | C# |
52ad2a21a7483f40ba065408197f87d4f5b03bf1 | Disable Test CalDavToOutlookToCalDavRoundTrip.KeepsCustomProperties | aluxnimm/outlookcaldavsynchronizer,DoCode/Outlook-CalDav-Synchronizer | CalDavSynchronizerTestAutomation/SynchronizerTests/CalDavToOutlookToCalDavRoundTrip.cs | CalDavSynchronizerTestAutomation/SynchronizerTests/CalDavToOutlookToCalDavRoundTrip.cs | using System;
using CalDavSynchronizerTestAutomation.Infrastructure;
using NUnit.Framework;
namespace CalDavSynchronizerTestAutomation.SynchronizerTests
{
[TestFixture]
public class CalDavToOutlookToCalDavRoundTrip
{
//[Test]
public void KeepsCustomProperties ()
{
var eventData = @"
BEGIN:VCALENDAR
PRODID:-//Inverse inc./SOGo 2.2.16//EN
VERSION:2.0
BEGIN:VEVENT
UID:59E2-55170300-17-5DFC2102
SUMMARY:testmeeting
DTSTART;TZID=Europe/Vienna:20150429T110000
DTEND;TZID=Europe/Vienna:20150429T123000
X-CALDAVSYNCHRONIZER-TEST:This is a test property
END:VEVENT
END:VCALENDAR
";
var roundTrippedData = OutlookTestContext.SyncCalDavToOutlookAndBackToCalDav (eventData);
Assert.That (roundTrippedData, Is.StringContaining ("X-CALDAVSYNCHRONIZER-TEST:This is a test property"));
}
[Test]
public void KeepsUid ()
{
var eventData = @"
BEGIN:VCALENDAR
PRODID:-//Inverse inc./SOGo 2.2.16//EN
VERSION:2.0
BEGIN:VEVENT
UID:59E2-55170300-17-5DFC2102
SUMMARY:testmeeting
DTSTART;TZID=Europe/Vienna:20150429T110000
DTEND;TZID=Europe/Vienna:20150429T123000
X-CALDAVSYNCHRONIZER-TEST:This is a test property
END:VEVENT
END:VCALENDAR
";
var roundTrippedData = OutlookTestContext.SyncCalDavToOutlookAndBackToCalDav (eventData);
Assert.That (roundTrippedData, Is.StringContaining ("UID:59E2-55170300-17-5DFC2102"));
}
}
} | using System;
using CalDavSynchronizerTestAutomation.Infrastructure;
using NUnit.Framework;
namespace CalDavSynchronizerTestAutomation.SynchronizerTests
{
[TestFixture]
public class CalDavToOutlookToCalDavRoundTrip
{
[Test]
public void KeepsCustomProperties ()
{
var eventData = @"
BEGIN:VCALENDAR
PRODID:-//Inverse inc./SOGo 2.2.16//EN
VERSION:2.0
BEGIN:VEVENT
UID:59E2-55170300-17-5DFC2102
SUMMARY:testmeeting
DTSTART;TZID=Europe/Vienna:20150429T110000
DTEND;TZID=Europe/Vienna:20150429T123000
X-CALDAVSYNCHRONIZER-TEST:This is a test property
END:VEVENT
END:VCALENDAR
";
var roundTrippedData = OutlookTestContext.SyncCalDavToOutlookAndBackToCalDav (eventData);
Assert.That (roundTrippedData, Is.StringContaining ("X-CALDAVSYNCHRONIZER-TEST:This is a test property"));
}
[Test]
public void KeepsUid ()
{
var eventData = @"
BEGIN:VCALENDAR
PRODID:-//Inverse inc./SOGo 2.2.16//EN
VERSION:2.0
BEGIN:VEVENT
UID:59E2-55170300-17-5DFC2102
SUMMARY:testmeeting
DTSTART;TZID=Europe/Vienna:20150429T110000
DTEND;TZID=Europe/Vienna:20150429T123000
X-CALDAVSYNCHRONIZER-TEST:This is a test property
END:VEVENT
END:VCALENDAR
";
var roundTrippedData = OutlookTestContext.SyncCalDavToOutlookAndBackToCalDav (eventData);
Assert.That (roundTrippedData, Is.StringContaining ("UID:59E2-55170300-17-5DFC2102"));
}
}
} | agpl-3.0 | C# |
f670f1e84defd720d6607967a1e0c5ead0c0fd2a | Update Result.cs | maximn/google-maps,mklimmasch/google-maps,mklimmasch/google-maps,maximn/google-maps | GoogleMapsApi/Entities/Geocoding/Response/Result.cs | GoogleMapsApi/Entities/Geocoding/Response/Result.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GoogleMapsApi.Entities.Geocoding.Response
{
/// <summary>
/// When the geocoder returns results, it places them within a (JSON) results array. Even if the geocoder returns no results (such as if the address doesn't exist) it still returns an empty results array. (XML responses consist of zero or more result elements.)
/// </summary>
[DataContract]
public class Result
{
/// <summary>
/// The types[] array indicates the type of the returned result. This array contains a set of one or more tags identifying the type of feature returned in the result. For example, a geocode of "Chicago" returns "locality" which indicates that "Chicago" is a city, and also returns "political" which indicates it is a political entity.
/// </summary>
[DataMember(Name = "types")]
public IEnumerable<string> Types { get; set; }
/// <summary>
/// formatted_address is a string containing the human-readable address of this location. Often this address is equivalent to the "postal address," which sometimes differs from country to country. (Note that some countries, such as the United Kingdom, do not allow distribution of true postal addresses due to licensing restrictions.) This address is generally composed of one or more address components. For example, the address "111 8th Avenue, New York, NY" contains separate address components for "111" (the street number, "8th Avenue" (the route), "New York" (the city) and "NY" (the US state). These address components contain additional information as noted below.
/// </summary>
[DataMember(Name = "formatted_address")]
public string FormattedAddress { get; set; }
/// <summary>
/// address_components[] is an array containing the separate address components
/// </summary>
[DataMember(Name = "address_components")]
public IEnumerable<AddressComponent> AddressComponents { get; set; }
/// <summary>
/// geometry contains information such as latitude, longitude, location_type, viewport, bounds
/// </summary>
[DataMember(Name = "geometry")]
public Geometry Geometry { get; set; }
/// <summary>
/// indicates that the geocoder did not return an exact match for the original request, though it did match part of the requested address. You may wish to examine the original request for misspellings and/or an incomplete address. Partial matches most often occur for street addresses that do not exist within the locality you pass in the request.
/// </summary>
[DataMember(Name = "partial_match")]
public bool PartialMatch { get; set; }
/// <summary>
/// provides the Google PlaceId
/// </summary>
[DataMember(Name = "place_id")]
public string PlaceId { get; set; }
}
}
| using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GoogleMapsApi.Entities.Geocoding.Response
{
/// <summary>
/// When the geocoder returns results, it places them within a (JSON) results array. Even if the geocoder returns no results (such as if the address doesn't exist) it still returns an empty results array. (XML responses consist of zero or more result elements.)
/// </summary>
[DataContract]
public class Result
{
/// <summary>
/// The types[] array indicates the type of the returned result. This array contains a set of one or more tags identifying the type of feature returned in the result. For example, a geocode of "Chicago" returns "locality" which indicates that "Chicago" is a city, and also returns "political" which indicates it is a political entity.
/// </summary>
[DataMember(Name = "types")]
public IEnumerable<string> Types { get; set; }
/// <summary>
/// formatted_address is a string containing the human-readable address of this location. Often this address is equivalent to the "postal address," which sometimes differs from country to country. (Note that some countries, such as the United Kingdom, do not allow distribution of true postal addresses due to licensing restrictions.) This address is generally composed of one or more address components. For example, the address "111 8th Avenue, New York, NY" contains separate address components for "111" (the street number, "8th Avenue" (the route), "New York" (the city) and "NY" (the US state). These address components contain additional information as noted below.
/// </summary>
[DataMember(Name = "formatted_address")]
public string FormattedAddress { get; set; }
/// <summary>
/// address_components[] is an array containing the separate address components
/// </summary>
[DataMember(Name = "address_components")]
public IEnumerable<AddressComponent> AddressComponents { get; set; }
/// <summary>
/// geometry contains information such as latitude, longitude, location_type, viewport, bounds
/// </summary>
[DataMember(Name = "geometry")]
public Geometry Geometry { get; set; }
/// <summary>
/// indicates that the geocoder did not return an exact match for the original request, though it did match part of the requested address. You may wish to examine the original request for misspellings and/or an incomplete address. Partial matches most often occur for street addresses that do not exist within the locality you pass in the request.
/// </summary>
[DataMember(Name = "partial_match")]
public bool PartialMatch { get; set; }
}
}
| bsd-2-clause | C# |
8ccc6c9a0cc2b2cd82a7461ae31708b872682483 | Support slashes in slugs | synhershko/NSemble,synhershko/NSemble | NSemble.Web/Modules/ContentPages/ContentPagesModule.cs | NSemble.Web/Modules/ContentPages/ContentPagesModule.cs | using System;
using NSemble.Core.Models;
using NSemble.Core.Nancy;
using NSemble.Modules.ContentPages.Models;
using Raven.Client;
namespace NSemble.Modules.ContentPages
{
public class ContentPagesModule : NSembleModule
{
public static readonly string HomepageSlug = "home";
public ContentPagesModule(IDocumentSession session)
: base("ContentPages")
{
Get["/{slug*}"] = p =>
{
var slug = (string)p.slug;
if (string.IsNullOrWhiteSpace(slug))
slug = HomepageSlug;
// For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably
// much shorter for readability.
var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug));
if (cp == null)
return "<p>The requested content page was not found</p>"; // we will return a 404 instead once the system stabilizes...
Model.ContentPage = cp;
((PageModel) Model.Page).Title = cp.Title;
return View["Read", Model];
};
Get["/error"] = o =>
{
throw new NotSupportedException("foo");
};
}
}
} | using System;
using NSemble.Core.Models;
using NSemble.Core.Nancy;
using NSemble.Modules.ContentPages.Models;
using Raven.Client;
namespace NSemble.Modules.ContentPages
{
public class ContentPagesModule : NSembleModule
{
public static readonly string HomepageSlug = "home";
public ContentPagesModule(IDocumentSession session)
: base("ContentPages")
{
Get["/{slug?" + HomepageSlug + "}"] = p =>
{
var slug = (string)p.slug;
// For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably
// much shorter for readability.
var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug));
if (cp == null)
return "<p>The requested content page was not found</p>"; // we will return a 404 instead once the system stabilizes...
Model.ContentPage = cp;
((PageModel) Model.Page).Title = cp.Title;
return View["Read", Model];
};
Get["/error"] = o =>
{
throw new NotSupportedException("foo");
};
}
}
} | apache-2.0 | C# |
e5b670cd63939f5e39381a12e78d708ad5889ce5 | Fix access denied issue when access process information in RemoteProcessService | jmptrader/SuperSocket,jmptrader/SuperSocket,mdavid/SuperSocket,chucklu/SuperSocket,mdavid/SuperSocket,jmptrader/SuperSocket,fryderykhuang/SuperSocket,memleaks/SuperSocket,chucklu/SuperSocket,chucklu/SuperSocket,kerryjiang/SuperSocket,ZixiangBoy/SuperSocket,ZixiangBoy/SuperSocket,fryderykhuang/SuperSocket,mdavid/SuperSocket,fryderykhuang/SuperSocket,ZixiangBoy/SuperSocket,kerryjiang/SuperSocket | RemoteProcessTool/RemoteProcessService/Command/LIST.cs | RemoteProcessTool/RemoteProcessService/Command/LIST.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}", p.ProcessName, p.Id));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}\t{2}", p.ProcessName, p.Id, p.TotalProcessorTime));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
| apache-2.0 | C# |
e73fdb117d27107cb4a04e7d9014d93c02fe5fd0 | clean up comments | forki/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,michaKFromParis/octokit.net,gabrielweyer/octokit.net,devkhan/octokit.net,thedillonb/octokit.net,geek0r/octokit.net,ivandrofly/octokit.net,chunkychode/octokit.net,rlugojr/octokit.net,octokit/octokit.net,hahmed/octokit.net,alfhenrik/octokit.net,ChrisMissal/octokit.net,cH40z-Lord/octokit.net,fffej/octokit.net,Sarmad93/octokit.net,octokit/octokit.net,bslliw/octokit.net,takumikub/octokit.net,gabrielweyer/octokit.net,M-Zuber/octokit.net,eriawan/octokit.net,shiftkey-tester/octokit.net,kdolan/octokit.net,shana/octokit.net,ivandrofly/octokit.net,Sarmad93/octokit.net,kolbasov/octokit.net,khellang/octokit.net,khellang/octokit.net,nsrnnnnn/octokit.net,brramos/octokit.net,thedillonb/octokit.net,editor-tools/octokit.net,editor-tools/octokit.net,naveensrinivasan/octokit.net,gdziadkiewicz/octokit.net,shana/octokit.net,octokit-net-test-org/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,rlugojr/octokit.net,SLdragon1989/octokit.net,darrelmiller/octokit.net,adamralph/octokit.net,magoswiat/octokit.net,daukantas/octokit.net,mminns/octokit.net,devkhan/octokit.net,octokit-net-test-org/octokit.net,hitesh97/octokit.net,TattsGroup/octokit.net,SmithAndr/octokit.net,dampir/octokit.net,SamTheDev/octokit.net,M-Zuber/octokit.net,alfhenrik/octokit.net,octokit-net-test/octokit.net,fake-organization/octokit.net,nsnnnnrn/octokit.net,eriawan/octokit.net,SamTheDev/octokit.net,dlsteuer/octokit.net,shiftkey-tester/octokit.net,Red-Folder/octokit.net,gdziadkiewicz/octokit.net,mminns/octokit.net,TattsGroup/octokit.net,hahmed/octokit.net,SmithAndr/octokit.net,shiftkey/octokit.net,chunkychode/octokit.net,shiftkey/octokit.net,dampir/octokit.net | Octokit/Models/Request/SearchQualifierOperator.cs | Octokit/Models/Request/SearchQualifierOperator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Octokit
{
public enum SearchQualifierOperator
{
GreaterThan, // >
LessThan, // <
LessThanOrEqualTo, // <=
GreaterThanOrEqualTo// >=
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// Used for date and int comparisions in searches
/// </summary>
public enum SearchQualifierOperator
{
GreaterThan, // >
LessThan, // <
LessThanOrEqualTo, // <=
GreaterThanOrEqualTo// >=
}
}
| mit | C# |
90aa677480ff936e8dc54f6813d56daa01eb2847 | fix version | KleinerHacker/net-effects | net.effects/net.effects/Properties/AssemblyInfo.cs | net.effects/net.effects/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("net.effects")]
[assembly: AssemblyDescription(".NET Library with lot of effects")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("PC-Soft (Pfeiffer C Soft)")]
[assembly: AssemblyProduct("net.effects")]
[assembly: AssemblyCopyright("Copyright © PC-Soft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("0defb689-dcc2-4c55-ae36-71a0b8f22dc3")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.*")]
[assembly: AssemblyFileVersion("0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("net.effects")]
[assembly: AssemblyDescription(".NET Library with lot of effects")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("PC-Soft (Pfeiffer C Soft)")]
[assembly: AssemblyProduct("net.effects")]
[assembly: AssemblyCopyright("Copyright © PC-Soft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("0defb689-dcc2-4c55-ae36-71a0b8f22dc3")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
1d4433b1ae059e93c4c47f92f3605c0aec3f0b24 | Enable LoginTests. | Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving | XamarinApp/MyTrips/MyTrips.UITests/Tests/LoginTests.cs | XamarinApp/MyTrips/MyTrips.UITests/Tests/LoginTests.cs | using System;
using NUnit.Framework;
using Xamarin.UITest;
namespace MyTrips.UITests
{
[TestFixture (Platform.iOS)]
public class LoginTests : AbstractSetup
{
public LoginTests (Platform platform) : base (platform)
{
}
[Test]
public void AppLaunchesSuccessfully()
{
app.Screenshot("App Launch");
}
[Test]
public void SkipAuthentication()
{
ClearKeychain ();
new LoginPage ()
.SkipAuthentication ();
app.Screenshot ("Authentication Skipped");
}
[Test]
public void LoginWithFacebook()
{
ClearKeychain ();
new LoginPage ()
.LoginWithFacebook ();
app.Screenshot ("Facebook Authentication Succeeded");
}
}
} | using System;
using NUnit.Framework;
using Xamarin.UITest;
namespace MyTrips.UITests
{
// [TestFixture (Platform.iOS)]
public class LoginTests : AbstractSetup
{
public LoginTests (Platform platform) : base (platform)
{
}
[Test]
public void AppLaunchesSuccessfully()
{
app.Screenshot("App Launch");
}
[Test]
public void SkipAuthentication()
{
ClearKeychain ();
new LoginPage ()
.SkipAuthentication ();
app.Screenshot ("Authentication Skipped");
}
[Test]
public void LoginWithFacebook()
{
ClearKeychain ();
new LoginPage ()
.LoginWithFacebook ();
app.Screenshot ("Facebook Authentication Succeeded");
}
}
} | mit | C# |
723b4f0749486f11b046d3eca98b40de453c6c34 | Move position input before button input like before | EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework | osu.Framework.Android/Input/AndroidTouchHandler.cs | osu.Framework.Android/Input/AndroidTouchHandler.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Android.Views;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges;
using osu.Framework.Platform;
using osuTK.Input;
namespace osu.Framework.Android.Input
{
public class AndroidTouchHandler : InputHandler
{
private readonly AndroidGameView view;
public AndroidTouchHandler(AndroidGameView view)
{
this.view = view;
view.Touch += handleTouches;
view.Hover += handleHover;
}
private void handleTouches(object sender, View.TouchEventArgs e)
{
handlePointerEvent(e.Event);
switch (e.Event.Action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
case MotionEventActions.Move:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, true));
break;
case MotionEventActions.Up:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, false));
break;
}
}
private void handleHover(object sender, View.HoverEventArgs e)
{
handlePointerEvent(e.Event);
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Right, e.Event.ButtonState == MotionEventButtonState.StylusPrimary));
}
private void handlePointerEvent(MotionEvent e)
{
PendingInputs.Enqueue(new MousePositionAbsoluteInput
{
Position = new osuTK.Vector2(e.GetX() * view.ScaleX, e.GetY() * view.ScaleY)
});
}
protected override void Dispose(bool disposing)
{
view.Touch -= handleTouches;
view.Hover -= handleHover;
base.Dispose(disposing);
}
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host) => true;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Android.Views;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges;
using osu.Framework.Platform;
using osuTK.Input;
namespace osu.Framework.Android.Input
{
public class AndroidTouchHandler : InputHandler
{
private readonly AndroidGameView view;
public AndroidTouchHandler(AndroidGameView view)
{
this.view = view;
view.Touch += handleTouches;
view.Hover += handleHover;
}
private void handleTouches(object sender, View.TouchEventArgs e)
{
switch (e.Event.Action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
case MotionEventActions.Move:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, true));
break;
case MotionEventActions.Up:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, false));
break;
}
handlePointerEvent(e.Event);
}
private void handleHover(object sender, View.HoverEventArgs e)
{
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Right, e.Event.ButtonState == MotionEventButtonState.StylusPrimary));
handlePointerEvent(e.Event);
}
private void handlePointerEvent(MotionEvent e)
{
PendingInputs.Enqueue(new MousePositionAbsoluteInput
{
Position = new osuTK.Vector2(e.GetX() * view.ScaleX, e.GetY() * view.ScaleY)
});
}
protected override void Dispose(bool disposing)
{
view.Touch -= handleTouches;
view.Hover -= handleHover;
base.Dispose(disposing);
}
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host) => true;
}
}
| mit | C# |
5aa1f10d2cde25e4deb4276dfa76808a34201cd4 | Hide row when ColumnFilter is false | mcintyre321/mvc.jquery.datatables,offspringer/mvc.jquery.datatables,offspringer/mvc.jquery.datatables,Sohra/mvc.jquery.datatables,Sohra/mvc.jquery.datatables,mcintyre321/mvc.jquery.datatables,seguemark/mvc.jquery.datatables,seguemark/mvc.jquery.datatables,mcintyre321/mvc.jquery.datatables | Mvc.JQuery.Datatables/Views/Shared/DataTable.cshtml | Mvc.JQuery.Datatables/Views/Shared/DataTable.cshtml | @using Mvc.JQuery.Datatables
@model DataTableVm
<table id="@Model.Id" class="display" >
<thead>
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
@if (Model.ColumnFilter)
{
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
}
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">
Loading data from server
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
var $table = $('#@Model.Id');
var dt = $table.dataTable({
"bProcessing": true,
"bStateSave": true,
"bServerSide": true,
"sAjaxSource": "@Html.Raw(Model.AjaxUrl)",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
@if(Model.ColumnFilter){
@:dt.columnFilter({ sPlaceHolder: "head:before" });
}
});
</script>
| @using Mvc.JQuery.Datatables
@model DataTableVm
<table id="@Model.Id" class="display" >
<thead>
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
<tr>
@foreach (var column in Model.Columns)
{
<th>@column</th>
}
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">
Loading data from server
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
var $table = $('#@Model.Id');
var dt = $table.dataTable({
"bProcessing": true,
"bStateSave": true,
"bServerSide": true,
"sAjaxSource": "@Html.Raw(Model.AjaxUrl)",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
@if(Model.ColumnFilter){
@:dt.columnFilter({ sPlaceHolder: "head:before" });
}
});
</script>
| mit | C# |
6b52f73d3098bebb19e9a9ddbfd86c3a4927ae62 | Optimize BundleConfig | ivantomchev/ImdbLiteSE,ivantomchev/ImdbLiteSE,ivantomchev/ImdbLiteSE | Source/Web/ImdbLite.Web/App_Start/BundleConfig.cs | Source/Web/ImdbLite.Web/App_Start/BundleConfig.cs | using System.Web;
using System.Web.Optimization;
namespace ImdbLite.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
RegisterScriptBundles(bundles);
RegisterStyleBundles(bundles);
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = true;
}
private static void RegisterStyleBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
private static void RegisterScriptBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
}
}
}
| using System.Web;
using System.Web.Optimization;
namespace ImdbLite.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = true;
}
}
}
| mit | C# |
83ad56876c18edd3b1d1cc9cbe119e9fa2be9e39 | Update AssemblyInfo.cs | mcintyre321/Noodles,mcintyre321/Noodles | Noodles.AspMvc.Templates/Properties/AssemblyInfo.cs | Noodles.AspMvc.Templates/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("Noodles.AspMvc.Templates")]
[assembly: AssemblyDescription("Noodles transforms your object model into a web app. Install this library to customise the cshtml template files, or if you don't want to use the EmbeddedResourceVirtualPathProvider to load your views")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Noodles.AspMvc.Templates")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[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("323aabd5-b5dd-490e-9559-d127aee65646")]
// 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")]
| 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("Noodles.AspMvc.Templates")]
[assembly: AssemblyDescription("Noodles transforms your object model into a web app. Install this library to customise the cshtml template files, or if you don't want to use the EmbeddedResourceVirtualPathProvider to load your views")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Noodles.AspMvc.Templates")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[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("323aabd5-b5dd-490e-9559-d127aee65646")]
// 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# |
c11427dfd1efa2229afc971d5c239876900076ba | Remove local variable in test helper | tsqllint/tsqllint,tsqllint/tsqllint | TSQLLint.Tests/UnitTests/Rules/RulesTestHelper.cs | TSQLLint.Tests/UnitTests/Rules/RulesTestHelper.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.SqlServer.TransactSql.ScriptDom;
using NUnit.Framework;
using TSQLLint.Lib.Parser;
using TSQLLint.Lib.Rules.RuleViolations;
using TSQLLint.Tests.Helpers;
namespace TSQLLint.Tests.UnitTests.Rules
{
public static class RulesTestHelper
{
public static void RunRulesTest(string rule, string testFileName, Type ruleType, List<RuleViolation> expectedRuleViolations)
{
// arrange
var path = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, $@"..\..\UnitTests\Rules\{rule}\test-files\{testFileName}.sql"));
var sqlString = File.ReadAllText(path);
var fragmentVisitor = new SqlRuleVisitor(null, null);
var ruleViolations = new List<RuleViolation>();
void ErrorCallback(string ruleName, string ruleText, int startLine, int startColumn)
{
ruleViolations.Add(new RuleViolation(ruleName, startLine, startColumn));
}
var visitor = (TSqlFragmentVisitor)Activator.CreateInstance(ruleType, args: (Action<string, string, int, int>)ErrorCallback);
var textReader = Lib.Utility.ParsingUtility.CreateTextReaderFromString(sqlString);
var compareer = new RuleViolationComparer();
// act
fragmentVisitor.VisitRule(textReader, visitor);
ruleViolations = ruleViolations.OrderBy(o => o.Line).ToList();
expectedRuleViolations = expectedRuleViolations.OrderBy(o => o.Line).ToList();
// assert
CollectionAssert.AreEqual(expectedRuleViolations, ruleViolations, compareer);
Assert.AreEqual(expectedRuleViolations.Count, ruleViolations.Count);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.SqlServer.TransactSql.ScriptDom;
using NUnit.Framework;
using TSQLLint.Lib.Parser;
using TSQLLint.Lib.Rules.RuleViolations;
using TSQLLint.Tests.Helpers;
namespace TSQLLint.Tests.UnitTests.Rules
{
public static class RulesTestHelper
{
public static void RunRulesTest(string rule, string testFileName, Type ruleType, List<RuleViolation> expectedRuleViolations)
{
// arrange
var path = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, $@"..\..\UnitTests\Rules\{rule}\test-files\{testFileName}.sql"));
var sqlString = File.ReadAllText(path);
var fragmentVisitor = new SqlRuleVisitor(null, null);
var ruleViolations = new List<RuleViolation>();
// todo fix
var violations = ruleViolations;
void ErrorCallback(string ruleName, string ruleText, int startLine, int startColumn)
{
violations.Add(new RuleViolation(ruleName, startLine, startColumn));
}
var visitor = (TSqlFragmentVisitor)Activator.CreateInstance(ruleType, args: (Action<string, string, int, int>)ErrorCallback);
var textReader = Lib.Utility.ParsingUtility.CreateTextReaderFromString(sqlString);
var compareer = new RuleViolationComparer();
// act
fragmentVisitor.VisitRule(textReader, visitor);
ruleViolations = ruleViolations.OrderBy(o => o.Line).ToList();
expectedRuleViolations = expectedRuleViolations.OrderBy(o => o.Line).ToList();
// assert
CollectionAssert.AreEqual(expectedRuleViolations, ruleViolations, compareer);
Assert.AreEqual(expectedRuleViolations.Count, ruleViolations.Count);
}
}
}
| mit | C# |
74cc0be142dc9aeb8d6d7ea1b04aa5d9f5e1d22c | Update DeviceInfoImplementation.cs | LostBalloon1/Xamarin.Plugins,tim-hoff/Xamarin.Plugins,labdogg1003/Xamarin.Plugins,monostefan/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins,JC-Chris/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins | DeviceInfo/DeviceInfo/DeviceInfo.Plugin.WindowsPhone81/DeviceInfoImplementation.cs | DeviceInfo/DeviceInfo/DeviceInfo.Plugin.WindowsPhone81/DeviceInfoImplementation.cs | /*
* Ported with permission from: Thomasz Cielecki @Cheesebaron
* AppId: https://github.com/Cheesebaron/Cheesebaron.MvxPlugins
*/
//---------------------------------------------------------------------------------
// Copyright 2013 Tomasz Cielecki (tomasz@ostebaronen.dk)
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
// INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing
// permissions and limitations under the License.
//---------------------------------------------------------------------------------
using DeviceInfo.Plugin.Abstractions;
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration.Pnp;
using Windows.System;
using Windows.System.Profile;
using System.Linq;
using Windows.UI.Xaml.Controls;
using System.Text.RegularExpressions;
using Windows.Security.ExchangeActiveSyncProvisioning;
namespace DeviceInfo.Plugin
{
/// <summary>
/// Implementation for DeviceInfo
/// </summary>
public class DeviceInfoImplementation : IDeviceInfo
{
EasClientDeviceInformation deviceInfo;
public DeviceInfoImplementation()
{
deviceInfo = new EasClientDeviceInformation();
}
public string GenerateAppId(bool usingPhoneId = false, string prefix = null, string suffix = null)
{
var appId = "";
if (!string.IsNullOrEmpty(prefix))
appId += prefix;
appId += Guid.NewGuid().ToString();
if (usingPhoneId)
appId += Id;
if (!string.IsNullOrEmpty(suffix))
appId += suffix;
return appId;
}
public string Id
{
get
{
var token = HardwareIdentification.GetPackageSpecificToken(null);
var hardwareId = token.Id;
var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);
var bytes = new byte[hardwareId.Length];
dataReader.ReadBytes(bytes);
return Convert.ToBase64String(bytes);
}
}
public string Model
{
get { return deviceInfo.SystemProductName; }
}
public string Version
{
get
{
return "8.1";//Fix in future, not real great way to get this info in 8.1
}
}
public Platform Platform
{
get
{
#if WINDOWS_APP
return Platform.Windows;
#else
return Platform.WindowsPhone;
#endif
}
}
}
}
| using DeviceInfo.Plugin.Abstractions;
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration.Pnp;
using Windows.System;
using Windows.System.Profile;
using System.Linq;
using Windows.UI.Xaml.Controls;
using System.Text.RegularExpressions;
using Windows.Security.ExchangeActiveSyncProvisioning;
namespace DeviceInfo.Plugin
{
/// <summary>
/// Implementation for DeviceInfo
/// </summary>
public class DeviceInfoImplementation : IDeviceInfo
{
EasClientDeviceInformation deviceInfo;
public DeviceInfoImplementation()
{
deviceInfo = new EasClientDeviceInformation();
}
public string GenerateAppId(bool usingPhoneId = false, string prefix = null, string suffix = null)
{
var appId = "";
if (!string.IsNullOrEmpty(prefix))
appId += prefix;
appId += Guid.NewGuid().ToString();
if (usingPhoneId)
appId += Id;
if (!string.IsNullOrEmpty(suffix))
appId += suffix;
return appId;
}
public string Id
{
get
{
var token = HardwareIdentification.GetPackageSpecificToken(null);
var hardwareId = token.Id;
var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);
var bytes = new byte[hardwareId.Length];
dataReader.ReadBytes(bytes);
return Convert.ToBase64String(bytes);
}
}
public string Model
{
get { return deviceInfo.SystemProductName; }
}
public string Version
{
get
{
return "8.1";//Fix in future, not real great way to get this info in 8.1
}
}
public Platform Platform
{
get
{
#if WINDOWS_APP
return Platform.Windows;
#else
return Platform.WindowsPhone;
#endif
}
}
}
} | mit | C# |
173ab1adb76fdc7f38d8ced4f0db1e3b2f859fc0 | Update key | jCho23/MobileAzureDevDays,jCho23/MobileAzureDevDays,jCho23/MobileAzureDevDays,jCho23/MobileAzureDevDays,jCho23/MobileAzureDevDays,jCho23/MobileAzureDevDays | Xamarin/MobileAzureDevDays/Services/TextAnalysis.cs | Xamarin/MobileAzureDevDays/Services/TextAnalysis.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.ProjectOxford.Text.Core;
using Microsoft.ProjectOxford.Text.Sentiment;
namespace MobileAzureDevDays.Services
{
static class TextAnalysis
{
const string sentimentAPIKey = "ADD KEY";
readonly static Lazy<SentimentClient> sentimentClientHolder = new Lazy<SentimentClient>(() => new SentimentClient(sentimentAPIKey));
static SentimentClient SentimentClient => sentimentClientHolder.Value;
public static async Task<float?> GetSentiment(string text)
{
var sentimentDocument = new SentimentDocument { Id = "1", Text = text };
var sentimentRequest = new SentimentRequest { Documents = new List<IDocument> { { sentimentDocument } } };
var sentimentResults = await SentimentClient.GetSentimentAsync(sentimentRequest);
var documentResult = sentimentResults.Documents.FirstOrDefault();
return documentResult?.Score;
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.ProjectOxford.Text.Core;
using Microsoft.ProjectOxford.Text.Sentiment;
namespace MobileAzureDevDays.Services
{
static class TextAnalysis
{
const string sentimentAPIKey = "b94d27788b514a33bc6e8029e16fd1d5";
readonly static Lazy<SentimentClient> sentimentClientHolder = new Lazy<SentimentClient>(() => new SentimentClient(sentimentAPIKey));
static SentimentClient SentimentClient => sentimentClientHolder.Value;
public static async Task<float?> GetSentiment(string text)
{
var sentimentDocument = new SentimentDocument { Id = "1", Text = text };
var sentimentRequest = new SentimentRequest { Documents = new List<IDocument> { { sentimentDocument } } };
var sentimentResults = await SentimentClient.GetSentimentAsync(sentimentRequest);
var documentResult = sentimentResults.Documents.FirstOrDefault();
return documentResult?.Score;
}
}
}
| mit | C# |
d1853ea55bfc0ddd04c7785ebb246a9865877389 | Fix incorrect formatting for switch/case | smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,peppy/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu-new,johnneijzen/osu | osu.Game/Overlays/BeatmapSet/Scores/NoScoresPlaceholder.cs | osu.Game/Overlays/BeatmapSet/Scores/NoScoresPlaceholder.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Screens.Select.Leaderboards;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Overlays.BeatmapSet.Scores
{
public class NoScoresPlaceholder : Container
{
private readonly SpriteText text;
public NoScoresPlaceholder()
{
AutoSizeAxes = Axes.Both;
Child = text = new SpriteText
{
Font = OsuFont.GetFont(),
};
}
public void UpdateText(BeatmapLeaderboardScope scope)
{
switch (scope)
{
default:
case BeatmapLeaderboardScope.Global:
text.Text = @"No scores yet. Maybe should try setting some?";
return;
case BeatmapLeaderboardScope.Friend:
text.Text = @"None of your friends has set a score on this map yet!";
return;
case BeatmapLeaderboardScope.Country:
text.Text = @"No one from your country has set a score on this map yet!";
return;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Screens.Select.Leaderboards;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Overlays.BeatmapSet.Scores
{
public class NoScoresPlaceholder : Container
{
private readonly SpriteText text;
public NoScoresPlaceholder()
{
AutoSizeAxes = Axes.Both;
Child = text = new SpriteText
{
Font = OsuFont.GetFont(),
};
}
public void UpdateText(BeatmapLeaderboardScope scope)
{
switch (scope)
{
default:
case BeatmapLeaderboardScope.Global:
text.Text = @"No scores yet. Maybe should try setting some?";
return;
case BeatmapLeaderboardScope.Friend:
text.Text = @"None of your friends has set a score on this map yet!";
return;
case BeatmapLeaderboardScope.Country:
text.Text = @"No one from your country has set a score on this map yet!";
return;
}
}
}
}
| mit | C# |
00178a1d4b6e7d8e73f427105341ae00cdc9107e | Add comments explaining behavior of DependencyContext.Default | serilog/serilog-framework-configuration,serilog/serilog-settings-configuration | src/Serilog.Settings.Configuration/Settings/Configuration/Assemblies/AssemblyFinder.cs | src/Serilog.Settings.Configuration/Settings/Configuration/Assemblies/AssemblyFinder.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
namespace Serilog.Settings.Configuration.Assemblies
{
abstract class AssemblyFinder
{
public abstract IReadOnlyList<AssemblyName> FindAssembliesContainingName(string nameToFind);
protected static bool IsCaseInsensitiveMatch(string text, string textToFind)
{
return text != null && text.ToLowerInvariant().Contains(textToFind.ToLowerInvariant());
}
public static AssemblyFinder Auto()
{
// Need to check `Assembly.GetEntryAssembly()` first because
// `DependencyContext.Default` throws an exception when `Assembly.GetEntryAssembly()` returns null
if (Assembly.GetEntryAssembly() != null && DependencyContext.Default != null)
{
return new DependencyContextAssemblyFinder(DependencyContext.Default);
}
return new DllScanningAssemblyFinder();
}
public static AssemblyFinder ForSource(ConfigurationAssemblySource configurationAssemblySource)
{
switch (configurationAssemblySource)
{
case ConfigurationAssemblySource.UseLoadedAssemblies:
return Auto();
case ConfigurationAssemblySource.AlwaysScanDllFiles:
return new DllScanningAssemblyFinder();
default:
throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null);
}
}
public static AssemblyFinder ForDependencyContext(DependencyContext dependencyContext)
{
return new DependencyContextAssemblyFinder(dependencyContext);
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
namespace Serilog.Settings.Configuration.Assemblies
{
abstract class AssemblyFinder
{
public abstract IReadOnlyList<AssemblyName> FindAssembliesContainingName(string nameToFind);
protected static bool IsCaseInsensitiveMatch(string text, string textToFind)
{
return text != null && text.ToLowerInvariant().Contains(textToFind.ToLowerInvariant());
}
public static AssemblyFinder Auto()
{
if (Assembly.GetEntryAssembly() != null)
{
return new DependencyContextAssemblyFinder(DependencyContext.Default);
}
return new DllScanningAssemblyFinder();
}
public static AssemblyFinder ForSource(ConfigurationAssemblySource configurationAssemblySource)
{
switch (configurationAssemblySource)
{
case ConfigurationAssemblySource.UseLoadedAssemblies:
return Auto();
case ConfigurationAssemblySource.AlwaysScanDllFiles:
return new DllScanningAssemblyFinder();
default:
throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null);
}
}
public static AssemblyFinder ForDependencyContext(DependencyContext dependencyContext)
{
return new DependencyContextAssemblyFinder(dependencyContext);
}
}
}
| apache-2.0 | C# |
dd5eca53442d873092965dc4b7d662dc4b89500b | Remove unused method | ReuseReduceRecycle/HitagiBot | HitagiBot/Services/Geocoder.cs | HitagiBot/Services/Geocoder.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Geocoding.Google;
namespace HitagiBot.Services
{
public static class Geocoder
{
private static readonly GoogleGeocoder GeocoderHandle =
new GoogleGeocoder(Program.Config["Tokens:Google Geocoder"]);
public static async Task<IEnumerable<GoogleAddress>> GetAddresses(string query)
{
return await GeocoderHandle.GeocodeAsync(query);
}
public static bool IsAmerica(this GoogleAddress address)
{
var americaCheck = from component in address.Components
where component.ShortName.Equals("US")
&& component.Types.Contains(GoogleAddressType.Country)
&& component.Types.Contains(GoogleAddressType.Political)
select component;
return americaCheck.Any();
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Geocoding.Google;
namespace HitagiBot.Services
{
public static class Geocoder
{
private static readonly GoogleGeocoder GeocoderHandle =
new GoogleGeocoder(Program.Config["Tokens:Google Geocoder"]);
public static async Task<IEnumerable<GoogleAddress>> GetAddresses(string query)
{
return await GeocoderHandle.GeocodeAsync(query);
}
public static async Task<IEnumerable<GoogleAddress>> GetAddressFromCoordinates(int latitude, int longitude)
{
return await GeocoderHandle.ReverseGeocodeAsync(latitude, longitude);
}
public static bool IsAmerica(this GoogleAddress address)
{
var americaCheck = from component in address.Components
where component.ShortName.Equals("US")
&& component.Types.Contains(GoogleAddressType.Country)
&& component.Types.Contains(GoogleAddressType.Political)
select component;
return americaCheck.Any();
}
}
} | bsd-3-clause | C# |
36d6b722ea325c53e4e31796136fffc1942d9d3e | Fix Call list example for C# | teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets | rest/call/list-get-example-4/list-get-example-4.cs | rest/call/list-get-example-4/list-get-example-4.cs | // Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string AuthToken = "your_auth_token";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var request = new CallListRequest();
request.Status = "in-progress";
request.StartTimeComparison = ComparisonType.GreaterThanOrEqualTo;
request.StartTime = new DateTime(2009, 07, 04);
request.EndTimeComparison = ComparisonType.LessThanOrEqualTo;
request.EndTime = new DateTime(2009, 07, 06);
var calls = twilio.ListCalls(request);
foreach (var call in calls.Calls)
{
Console.WriteLine(call.To);
}
}
} | // Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string AuthToken = "your_auth_token";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var request = new CallListRequest();
request.Status = "in-progress";
request.StartTimeComparison = ComparisonType.GreaterThanOrEqualTo;
request.StartTime = new DateTime(2009, 07, 04);
request.StartTimeComparison = ComparisonType.LessThanOrEqualTo;
request.StartTime = new DateTime(2009, 07, 06);
var calls = twilio.ListCalls(request);
foreach (var call in calls.Calls)
{
Console.WriteLine(call.To);
}
}
} | mit | C# |
73bf4c576d43262ce4f69a8735e066a9e41dcbe5 | fix incorrect property has change logic check | carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ilyhacker/aspnetboilerplate,ilyhacker/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate | src/Abp.Zero.EntityFramework/EntityHistory/Extensions/DbPropertyEntryExtensions.cs | src/Abp.Zero.EntityFramework/EntityHistory/Extensions/DbPropertyEntryExtensions.cs | using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace Abp.EntityHistory.Extensions
{
internal static class DbPropertyEntryExtensions
{
internal static object GetNewValue(this DbPropertyEntry propertyEntry)
{
if (propertyEntry.EntityEntry.State == EntityState.Deleted)
{
return propertyEntry.OriginalValue;
}
return propertyEntry.CurrentValue;
}
internal static object GetOriginalValue(this DbPropertyEntry propertyEntry)
{
if (propertyEntry.EntityEntry.State == EntityState.Added)
{
return propertyEntry.CurrentValue;
}
return propertyEntry.OriginalValue;
}
internal static bool HasChanged(this DbPropertyEntry propertyEntry)
{
if (propertyEntry.EntityEntry.State == EntityState.Added)
{
return propertyEntry.CurrentValue != null;
}
if (propertyEntry.EntityEntry.State == EntityState.Deleted)
{
return propertyEntry.OriginalValue != null;
}
return !(propertyEntry.OriginalValue?.Equals(propertyEntry.CurrentValue) ?? propertyEntry.CurrentValue == null);
}
}
} | using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace Abp.EntityHistory.Extensions
{
internal static class DbPropertyEntryExtensions
{
internal static object GetNewValue(this DbPropertyEntry propertyEntry)
{
if (propertyEntry.EntityEntry.State == EntityState.Deleted)
{
return propertyEntry.OriginalValue;
}
return propertyEntry.CurrentValue;
}
internal static object GetOriginalValue(this DbPropertyEntry propertyEntry)
{
if (propertyEntry.EntityEntry.State == EntityState.Added)
{
return propertyEntry.CurrentValue;
}
return propertyEntry.OriginalValue;
}
internal static bool HasChanged(this DbPropertyEntry propertyEntry)
{
if (propertyEntry.EntityEntry.State == EntityState.Added)
{
return propertyEntry.CurrentValue != null;
}
if (propertyEntry.EntityEntry.State == EntityState.Deleted)
{
return propertyEntry.OriginalValue != null;
}
return !(propertyEntry.OriginalValue?.Equals(propertyEntry.CurrentValue)) ?? propertyEntry.CurrentValue == null;
}
}
} | mit | C# |
1fca41c593113e3b8b0d6fead7c7a876998a16ac | Make UserInputManager test much more simple | smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework | osu.Framework.Tests/Platform/UserInputManagerTest.cs | osu.Framework.Tests/Platform/UserInputManagerTest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Input;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () => new UserInputManager().IsAlive);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () =>
{
using (var client = new TestHeadlessGameHost(@"client", true))
{
return client.CurrentRoot.IsAlive;
}
});
}
private class TestHeadlessGameHost : HeadlessGameHost
{
public Drawable CurrentRoot => Root;
public TestHeadlessGameHost(string hostname, bool bindIPC)
: base(hostname, bindIPC)
{
using (var game = new TestGame())
{
Root = game.CreateUserInputManager();
}
}
}
}
}
| mit | C# |
dc38aeac4392d44b1b99aa3b4a18e47aa5373f21 | Remove unnecessary local definition of colour logic from taiko judgement | ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,peppy/osu | osu.Game.Rulesets.Taiko/UI/DrawableTaikoJudgement.cs | osu.Game.Rulesets.Taiko/UI/DrawableTaikoJudgement.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Rulesets.Taiko.UI
{
/// <summary>
/// Text that is shown as judgement when a hit object is hit or missed.
/// </summary>
public class DrawableTaikoJudgement : DrawableJudgement
{
/// <summary>
/// Creates a new judgement text.
/// </summary>
/// <param name="judgedObject">The object which is being judged.</param>
/// <param name="result">The judgement to visualise.</param>
public DrawableTaikoJudgement(JudgementResult result, DrawableHitObject judgedObject)
: base(result, judgedObject)
{
}
protected override void ApplyHitAnimations()
{
this.MoveToY(-100, 500);
base.ApplyHitAnimations();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Objects.Drawables;
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.UI
{
/// <summary>
/// Text that is shown as judgement when a hit object is hit or missed.
/// </summary>
public class DrawableTaikoJudgement : DrawableJudgement
{
/// <summary>
/// Creates a new judgement text.
/// </summary>
/// <param name="judgedObject">The object which is being judged.</param>
/// <param name="result">The judgement to visualise.</param>
public DrawableTaikoJudgement(JudgementResult result, DrawableHitObject judgedObject)
: base(result, judgedObject)
{
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
switch (Result.Type)
{
case HitResult.Ok:
JudgementBody.Colour = colours.GreenLight;
break;
case HitResult.Great:
JudgementBody.Colour = colours.BlueLight;
break;
}
}
protected override void ApplyHitAnimations()
{
this.MoveToY(-100, 500);
base.ApplyHitAnimations();
}
}
}
| mit | C# |
bf69874737e97872defcbad1b8c86e65557ae2be | Fix against pulled code from someone elses merge. | lambdakris/templating,seancpeters/templating,rschiefer/templating,danroth27/templating,seancpeters/templating,lambdakris/templating,rschiefer/templating,lambdakris/templating,mlorbetske/templating,seancpeters/templating,mlorbetske/templating,danroth27/templating,seancpeters/templating,danroth27/templating,rschiefer/templating | src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacro.cs | src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacro.cs | using System;
using System.Text;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Operations;
using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros.Config;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros
{
internal class EvaluateMacro : IMacro
{
public Guid Id => new Guid("BB625F71-6404-4550-98AF-B2E546F46C5F");
public string Type => "evaluate";
public void EvaluateConfig(IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
{
EvaluateMacroConfig config = rawConfig as EvaluateMacroConfig;
if (config == null)
{
throw new InvalidCastException("Couldn't cast the rawConfig as EvaluateMacroConfig");
}
ConditionEvaluator evaluator = EvaluatorSelector.Select(config.Evaluator);
byte[] data = Encoding.UTF8.GetBytes(config.Action);
int len = data.Length;
int pos = 0;
IProcessorState state = new GlobalRunSpec.ProcessorState(vars, data, Encoding.UTF8);
bool faulted;
bool result = evaluator(state, ref len, ref pos, out faulted);
Parameter p = new Parameter
{
IsVariable = true,
Name = config.VariableName
};
setter(p, result.ToString());
}
public void Evaluate(string variableName, IVariableCollection vars, JObject def, IParameterSet parameters, ParameterSetter setter)
{
string evaluatorName = def.ToString("evaluator");
ConditionEvaluator evaluator = EvaluatorSelector.Select(evaluatorName);
byte[] data = Encoding.UTF8.GetBytes(def.ToString("action"));
int len = data.Length;
int pos = 0;
IProcessorState state = new GlobalRunSpec.ProcessorState(vars, data, Encoding.UTF8);
bool faulted;
bool res = evaluator(state, ref len, ref pos, out faulted);
Parameter p = new Parameter
{
IsVariable = true,
Name = variableName
};
setter(p, res.ToString());
}
}
} | using System;
using System.Text;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Operations;
using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros.Config;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros
{
internal class EvaluateMacro : IMacro
{
public Guid Id => new Guid("BB625F71-6404-4550-98AF-B2E546F46C5F");
public string Type => "evaluate";
public void EvaluateConfig(IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
{
EvaluateMacroConfig config = rawConfig as EvaluateMacroConfig;
if (config == null)
{
throw new InvalidCastException("Couldn't cast the rawConfig as EvaluateMacroConfig");
}
ConditionEvaluator evaluator = EvaluatorSelector.Select(config.Evaluator);
byte[] data = Encoding.UTF8.GetBytes(config.Action);
int len = data.Length;
int pos = 0;
IProcessorState state = new GlobalRunSpec.ProcessorState(vars, data, Encoding.UTF8);
bool result = evaluator(state, ref len, ref pos);
Parameter p = new Parameter
{
IsVariable = true,
Name = config.VariableName
};
setter(p, result.ToString());
}
public void Evaluate(string variableName, IVariableCollection vars, JObject def, IParameterSet parameters, ParameterSetter setter)
{
string evaluatorName = def.ToString("evaluator");
ConditionEvaluator evaluator = EvaluatorSelector.Select(evaluatorName);
byte[] data = Encoding.UTF8.GetBytes(def.ToString("action"));
int len = data.Length;
int pos = 0;
IProcessorState state = new GlobalRunSpec.ProcessorState(vars, data, Encoding.UTF8);
bool faulted;
bool res = evaluator(state, ref len, ref pos, out faulted);
Parameter p = new Parameter
{
IsVariable = true,
Name = variableName
};
setter(p, res.ToString());
}
}
} | mit | C# |
c50590c00ec3af040817760b27ad342b9e99c45f | Fix LockFileCache when SDK and trimming task are using different NuGet dlls | ericstj/standard,ericstj/standard,weshaggard/standard,weshaggard/standard | Microsoft.Packaging.Tools.Trimming/tasks/Microsoft.NET.Build.Tasks/LockFileCache.cs | Microsoft.Packaging.Tools.Trimming/tasks/Microsoft.NET.Build.Tasks/LockFileCache.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Build.Framework;
using NuGet.Common;
using NuGet.ProjectModel;
namespace Microsoft.NET.Build.Tasks
{
internal class LockFileCache
{
private IBuildEngine4 _buildEngine;
private static string taskObjectPrefix = null;
public LockFileCache(IBuildEngine4 buildEngine)
{
_buildEngine = buildEngine;
}
public LockFile GetLockFile(string path)
{
if (!Path.IsPathRooted(path))
{
throw new BuildErrorException("Assets file path '{0}' is not rooted. Only full paths are supported.", path);
}
string lockFileKey = GetTaskObjectKey(path);
LockFile result;
object existingLockFileTaskObject = _buildEngine.GetRegisteredTaskObject(lockFileKey, RegisteredTaskObjectLifetime.Build);
if (existingLockFileTaskObject == null)
{
result = LoadLockFile(path);
_buildEngine.RegisterTaskObject(lockFileKey, result, RegisteredTaskObjectLifetime.Build, true);
}
else
{
result = (LockFile)existingLockFileTaskObject;
}
return result;
}
private static string GetTaskObjectKey(string lockFilePath)
{
if (taskObjectPrefix == null)
{
taskObjectPrefix = typeof(LockFile).AssemblyQualifiedName;
}
return $"{taskObjectPrefix}:{lockFilePath}";
}
private LockFile LoadLockFile(string path)
{
if (!File.Exists(path))
{
throw new BuildErrorException("Assets file '{0}' not found. Run a NuGet package restore to generate this file.", path);
}
// TODO - https://github.com/dotnet/sdk/issues/18 adapt task logger to Nuget Logger
return LockFileUtilities.GetLockFile(path, NullLogger.Instance);
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Build.Framework;
using NuGet.Common;
using NuGet.ProjectModel;
namespace Microsoft.NET.Build.Tasks
{
internal class LockFileCache
{
private IBuildEngine4 _buildEngine;
public LockFileCache(IBuildEngine4 buildEngine)
{
_buildEngine = buildEngine;
}
public LockFile GetLockFile(string path)
{
if (!Path.IsPathRooted(path))
{
throw new BuildErrorException("Assets file path '{0}' is not rooted. Only full paths are supported.", path);
}
string lockFileKey = GetTaskObjectKey(path);
LockFile result;
object existingLockFileTaskObject = _buildEngine.GetRegisteredTaskObject(lockFileKey, RegisteredTaskObjectLifetime.Build);
if (existingLockFileTaskObject == null)
{
result = LoadLockFile(path);
_buildEngine.RegisterTaskObject(lockFileKey, result, RegisteredTaskObjectLifetime.Build, true);
}
else
{
result = (LockFile)existingLockFileTaskObject;
}
return result;
}
private static string GetTaskObjectKey(string lockFilePath)
{
return $"{nameof(LockFileCache)}:{lockFilePath}";
}
private LockFile LoadLockFile(string path)
{
if (!File.Exists(path))
{
throw new BuildErrorException("Assets file '{0}' not found. Run a NuGet package restore to generate this file.", path);
}
// TODO - https://github.com/dotnet/sdk/issues/18 adapt task logger to Nuget Logger
return LockFileUtilities.GetLockFile(path, NullLogger.Instance);
}
}
}
| mit | C# |
0c92a5acadba74cb926ea05932703b16e4266bbf | Move the method to static to avoid calling for an instance of the object. This method is simply to create an asbstration level for the prefix. | GSoft-SharePoint/Dynamite-Components,GSoft-SharePoint/Dynamite-Components,GSoft-SharePoint/Dynamite-Components | Source/GSoft.Dynamite.Publishing.Contracts/Constants/PublishingResultSourceInfos.cs | Source/GSoft.Dynamite.Publishing.Contracts/Constants/PublishingResultSourceInfos.cs | using System.Collections.Generic;
using GSoft.Dynamite.Search;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Query;
namespace GSoft.Dynamite.Publishing.Contracts.Constants
{
/// <summary>
/// Holds the Result Source infos for the Publishing module
/// </summary>
public class PublishingResultSourceInfos
{
private static readonly string SearchKqlprefix = "{?{searchTerms} -ContentClass=urn:content-class:SPSPeople}";
/// <summary>
/// A single Catalog Item result source
/// </summary>
/// <returns>A ResultSourceInfo object</returns>
public ResultSourceInfo SingleCatalogItem()
{
return new ResultSourceInfo()
{
Name = "Single Catalog Item",
Level = SearchObjectLevel.Ssa,
Overwrite = false,
Query = SearchKqlprefix,
SortSettings = new Dictionary<string, SortDirection>()
{
{"ListItemID",SortDirection.Ascending}
}
};
}
/// <summary>
/// A single target item
/// </summary>
/// <returns>A result source info object</returns>
public ResultSourceInfo SingleTargetItem()
{
return new ResultSourceInfo()
{
Name = "Single Target Item",
Level = SearchObjectLevel.Ssa,
Overwrite = false,
Query = SearchKqlprefix
};
}
/// <summary>
/// Method to Append a query to the Search KQL prefix
/// </summary>
/// <param name="queryToAppend"></param>
/// <returns>The string prefixed with the Search KQL</returns>
public static string AppendToSearchKqlPrefix(string queryToAppend)
{
return string.Format("{0} {1}", SearchKqlprefix, queryToAppend);
}
}
}
| using System.Collections.Generic;
using GSoft.Dynamite.Search;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Query;
namespace GSoft.Dynamite.Publishing.Contracts.Constants
{
/// <summary>
/// Holds the Result Source infos for the Publishing module
/// </summary>
public class PublishingResultSourceInfos
{
private readonly string SearchKqlprefix = "{?{searchTerms} -ContentClass=urn:content-class:SPSPeople}";
/// <summary>
/// A single Catalog Item result source
/// </summary>
/// <returns>A ResultSourceInfo object</returns>
public ResultSourceInfo SingleCatalogItem()
{
return new ResultSourceInfo()
{
Name = "Single Catalog Item",
Level = SearchObjectLevel.Ssa,
Overwrite = false,
Query = this.SearchKqlprefix,
SortSettings = new Dictionary<string, SortDirection>()
{
{"ListItemID",SortDirection.Ascending}
}
};
}
/// <summary>
/// A single target item
/// </summary>
/// <returns>A result source info object</returns>
public ResultSourceInfo SingleTargetItem()
{
return new ResultSourceInfo()
{
Name = "Single Target Item",
Level = SearchObjectLevel.Ssa,
Overwrite = false,
Query = this.SearchKqlprefix
};
}
/// <summary>
/// Method to Append a query to the Search KQL prefix
/// </summary>
/// <param name="queryToAppend"></param>
/// <returns>The string prefixed with the Search KQL</returns>
public string AppendToSearchKqlPrefix(string queryToAppend)
{
return string.Format("{0} {1}", this.SearchKqlprefix, queryToAppend);
}
}
}
| mit | C# |
d3a5e3ae23aaec58f857333c4b9dd19110955451 | clarify code | NTumbleBit/NTumbleBit,DanGould/NTumbleBit | NTumbleBit.TumblerServer/Program.cs | NTumbleBit.TumblerServer/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using NBitcoin;
using NTumbleBit.Common;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging;
using NTumbleBit.TumblerServer.Services;
using System.Threading;
using NTumbleBit.Common.Logging;
namespace NTumbleBit.TumblerServer
{
public class Program
{
public static void Main(string[] args)
{
Logs.Configure(new FuncLoggerFactory(i => new ConsoleLogger(i, (a, b) => true, false)));
var configuration = new TumblerConfiguration();
configuration.LoadArgs(args);
try
{
IWebHost host = null;
ExternalServices services = null;
if(!configuration.OnlyMonitor)
{
host = new WebHostBuilder()
.UseKestrel()
.UseAppConfiguration(configuration)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
services = (ExternalServices)host.Services.GetService(typeof(ExternalServices));
}
else
{
services = ExternalServices.CreateFromRPCClient(configuration.RPC.ConfigureRPCClient(configuration.Network), new DBreezeRepository(Path.Combine(configuration.DataDir, "db")));
}
CancellationTokenSource cts = new CancellationTokenSource();
var job = new BroadcasterJob(services, Logs.Main);
job.Start(cts.Token);
Logs.Main.LogInformation("BroadcasterJob started");
if(!configuration.OnlyMonitor)
host.Run();
else
Console.ReadLine();
cts.Cancel();
}
catch(ConfigException ex)
{
if(!string.IsNullOrEmpty(ex.Message))
Logs.Main.LogError(ex.Message);
}
catch(Exception exception)
{
Logs.Main.LogError("Exception thrown while running the server " + exception.Message);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using NBitcoin;
using NTumbleBit.Common;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging;
using NTumbleBit.TumblerServer.Services;
using System.Threading;
using NTumbleBit.Common.Logging;
namespace NTumbleBit.TumblerServer
{
public class Program
{
public static void Main(string[] args)
{
Logs.Configure(new FuncLoggerFactory(i => new ConsoleLogger(i, (a, b) => true, false)));
var configuration = new TumblerConfiguration();
configuration.LoadArgs(args);
try
{
IWebHost host = null;
if(!configuration.OnlyMonitor)
{
host = new WebHostBuilder()
.UseKestrel()
.UseAppConfiguration(configuration)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
var services = host == null ?
ExternalServices.CreateFromRPCClient(configuration.RPC.ConfigureRPCClient(configuration.Network), new DBreezeRepository(Path.Combine(configuration.DataDir, "db")))
: (ExternalServices)host.Services.GetService(typeof(ExternalServices));
CancellationTokenSource cts = new CancellationTokenSource();
var job = new BroadcasterJob(services, Logs.Main);
job.Start(cts.Token);
Logs.Main.LogInformation("BroadcasterJob started");
if(!configuration.OnlyMonitor)
host.Run();
else
Console.ReadLine();
cts.Cancel();
}
catch(ConfigException ex)
{
if(!string.IsNullOrEmpty(ex.Message))
Logs.Main.LogError(ex.Message);
}
catch(Exception exception)
{
Logs.Main.LogError("Exception thrown while running the server " + exception.Message);
}
}
}
}
| mit | C# |
ca2ab48fdbc37ad23a3a904057563ee09e4b5444 | Improve performance when getting a KH2 message | Xeeynamo/KingdomHearts | OpenKh.Engine/Kh2MessageProvider.cs | OpenKh.Engine/Kh2MessageProvider.cs | using OpenKh.Kh2;
using OpenKh.Kh2.Messages;
using System.Collections.Generic;
using System.Linq;
namespace OpenKh.Engine
{
public class Kh2MessageProvider : IMessageProvider
{
private Dictionary<int, byte[]> _messages = new Dictionary<int, byte[]>();
public IMessageEncoder Encoder { get; set; } = Encoders.InternationalSystem;
public byte[] GetMessage(ushort id)
{
if (_messages.TryGetValue(id & 0x7fff, out var data))
return data;
if (_messages.TryGetValue(Msg.FallbackMessage, out data))
return data;
return new byte[0];
}
public string GetString(ushort id) =>
MsgSerializer.SerializeText(Encoder.Decode(GetMessage(id)));
public void SetString(ushort id, string text) =>
_messages[id] = Encoder.Encode(MsgSerializer.DeserializeText(text).ToList());
public void Load(List<Msg.Entry> entries) =>
_messages = entries.ToDictionary(x => x.Id, x => x.Data);
}
}
| using OpenKh.Kh2;
using OpenKh.Kh2.Messages;
using System.Collections.Generic;
using System.Linq;
namespace OpenKh.Engine
{
public class Kh2MessageProvider : IMessageProvider
{
private List<Msg.Entry> _messages;
public IMessageEncoder Encoder { get; set; } = Encoders.InternationalSystem;
public byte[] GetMessage(ushort id)
{
var message = _messages?.FirstOrDefault(x => x.Id == (id & 0x7fff));
if (message == null)
{
if (id == Msg.FallbackMessage)
return new byte[0];
return GetMessage(Msg.FallbackMessage);
}
return message.Data;
}
public string GetString(ushort id) =>
MsgSerializer.SerializeText(Encoder.Decode(GetMessage(id)));
public void SetString(ushort id, string text)
{
var message = _messages?.FirstOrDefault(x => x.Id == (id & 0x7fff));
if (message == null)
return;
message.Data = Encoder.Encode(MsgSerializer.DeserializeText(text).ToList());
}
public void Load(List<Msg.Entry> entries) =>
_messages = entries;
}
}
| mit | C# |
3bee36f6a2faf447cb863984b562013e93436a01 | Add index to Action column | NeoAdonis/osu,ppy/osu,naoey/osu,smoogipoo/osu,Drezi126/osu,EVAST9919/osu,2yangk23/osu,2yangk23/osu,NeoAdonis/osu,Damnae/osu,DrabWeb/osu,NeoAdonis/osu,Nabile-Rahmani/osu,peppy/osu-new,peppy/osu,naoey/osu,UselessToucan/osu,DrabWeb/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,ppy/osu,Frontear/osuKyzer,DrabWeb/osu,smoogipooo/osu,ZLima12/osu,johnneijzen/osu,EVAST9919/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,naoey/osu | osu.Game/Input/Bindings/DatabasedKeyBinding.cs | osu.Game/Input/Bindings/DatabasedKeyBinding.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets;
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
namespace osu.Game.Input.Bindings
{
[Table("KeyBinding")]
public class DatabasedKeyBinding : KeyBinding
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[ForeignKey(typeof(RulesetInfo))]
public int? RulesetID { get; set; }
[Indexed]
public int? Variant { get; set; }
[Column("Keys")]
public string KeysString
{
get { return KeyCombination.ToString(); }
private set { KeyCombination = value; }
}
[Indexed]
[Column("Action")]
public new int Action
{
get { return (int)base.Action; }
set { base.Action = value; }
}
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets;
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
namespace osu.Game.Input.Bindings
{
[Table("KeyBinding")]
public class DatabasedKeyBinding : KeyBinding
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[ForeignKey(typeof(RulesetInfo))]
public int? RulesetID { get; set; }
[Indexed]
public int? Variant { get; set; }
[Column("Keys")]
public string KeysString
{
get { return KeyCombination.ToString(); }
private set { KeyCombination = value; }
}
[Column("Action")]
public new int Action
{
get { return (int)base.Action; }
set { base.Action = value; }
}
}
} | mit | C# |
20c04df658139654c284793d2805060666e32190 | Fix label/input binding in attachment form | dafrito/trac-mirror,moreati/trac-gitsvn,moreati/trac-gitsvn,dokipen/trac,exocad/exotrac,exocad/exotrac,dokipen/trac,dafrito/trac-mirror,dafrito/trac-mirror,moreati/trac-gitsvn,moreati/trac-gitsvn,dokipen/trac,dafrito/trac-mirror,exocad/exotrac,exocad/exotrac | templates/attachment.cs | templates/attachment.cs | <?cs include "header.cs" ?>
<?cs include "macros.cs" ?>
<div id="page-content">
<h3>Add Attachment to
<a href="<?cs var:file.attachment_parent_href?>"><?cs var:file.attachment_parent?></a></h3>
<div id="main">
<div id="main-content">
<fieldset>
<form action="<?cs var:cgi_location ?>" method="post"
enctype="multipart/form-data">
<input type="hidden" name="mode" value="attachment" />
<input type="hidden" name="type" value="<?cs var:attachment.type ?>" />
<input type="hidden" name="id" value="<?cs var:attachment.id ?>" />
<div style="align: right">
<label for="author" class="att-label">Author:</label>
<input type="text" id="author" name="author" class="textwidget" size="40"
value="<?cs var:trac.authname?>" />
<br />
<label for="description" class="att-label">Description:</label>
<input type="text" id="description" name="description" class="textwidget"
size="40" />
<br />
<label for="file" class="att-label">File:</label>
<input type="file" id="file" name="attachment" />
<br />
<br />
<input type="reset" value="Reset" />
<input type="submit" value="Add" />
</div>
</form>
</fieldset>
</div>
</div>
</div>
<?cs include:"footer.cs"?>
| <?cs include "header.cs" ?>
<?cs include "macros.cs" ?>
<div id="page-content">
<h3>Add Attachment to
<a href="<?cs var:file.attachment_parent_href?>"><?cs var:file.attachment_parent?></a></h3>
<div id="main">
<div id="main-content">
<fieldset>
<form action="<?cs var:cgi_location ?>" method="post"
enctype="multipart/form-data">
<input type="hidden" name="mode" value="attachment" />
<input type="hidden" name="type" value="<?cs var:attachment.type ?>" />
<input type="hidden" name="id" value="<?cs var:attachment.id ?>" />
<div style="align: right">
<label for="author" class="att-label">Author:</label>
<input type="text" name="author" class="textwidget" size="40" value="<?cs var:trac.authname?>">
<br />
<label for="description" class="att-label">Description:</label>
<input type="text" name="description" class="textwidget" size="40">
<br />
<label for="file" class="att-label">File:</label>
<input type="file" name="attachment"/>
<br />
<br />
<input type="reset" value="Reset"/>
<input type="submit" value="Add"/>
</div>
</form>
</fieldset>
</div>
</div>
</div>
<?cs include:"footer.cs"?>
| bsd-3-clause | C# |
9b3bb93c7f3610f2b6a4a6396ab92b76b72072ca | Remove unnecessary lock. | chromium/vs-chromium,chromium/vs-chromium,chromium/vs-chromium,chromium/vs-chromium | src/Core/Configuration/ConfigurationFileLocator.cs | src/Core/Configuration/ConfigurationFileLocator.cs | // Copyright 2013 The Chromium 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;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using VsChromium.Core.Files;
using VsChromium.Core.Linq;
using VsChromium.Core.Logging;
namespace VsChromium.Core.Configuration {
[Export(typeof(IConfigurationFileLocator))]
public class ConfigurationFileLocator : IConfigurationFileLocator {
private readonly IFileSystem _fileSystem;
[ImportingConstructor]
public ConfigurationFileLocator(IFileSystem fileSystem) {
_fileSystem = fileSystem;
}
public IEnumerable<string> ReadFile(
RelativePath relativePath,
Func<FullPath, IEnumerable<string>, IEnumerable<string>> postProcessing) {
foreach (var directoryName in PossibleDirectoryNames()) {
var path = directoryName.Combine(relativePath);
if (_fileSystem.FileExists(path)) {
Logger.Log("Using configuration file at \"{0}\"", path);
return postProcessing(path, _fileSystem.ReadAllLines(path)).ToReadOnlyCollection();
}
}
throw new FileLoadException(
string.Format("Could not load configuration file \"{0}\" from the following locations:{1}", relativePath,
PossibleDirectoryNames().Aggregate("", (x, y) => x + "\n" + y)));
}
private IEnumerable<FullPath> PossibleDirectoryNames() {
yield return new FullPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
.Combine(new RelativePath(ConfigurationDirectoryNames.LocalUserConfigurationDirectoryName));
yield return new FullPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
.Combine(new RelativePath(ConfigurationDirectoryNames.LocalInstallConfigurationDirectoryName));
}
}
}
| // Copyright 2013 The Chromium 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;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using VsChromium.Core.Files;
using VsChromium.Core.Linq;
using VsChromium.Core.Logging;
namespace VsChromium.Core.Configuration {
[Export(typeof(IConfigurationFileLocator))]
public class ConfigurationFileLocator : IConfigurationFileLocator {
private readonly IFileSystem _fileSystem;
private readonly Dictionary<RelativePath, IList<string>> _fileLines = new Dictionary<RelativePath, IList<string>>();
private readonly object _lock = new object();
[ImportingConstructor]
public ConfigurationFileLocator(IFileSystem fileSystem) {
_fileSystem = fileSystem;
}
public IEnumerable<string> ReadFile(
RelativePath relativePath,
Func<FullPath, IEnumerable<string>, IEnumerable<string>> postProcessing) {
// TODO(rpaquay): Find way to invalidate cache.
lock (_lock) {
IList<string> result;
if (_fileLines.TryGetValue(relativePath, out result))
return result;
result = ReadFileWorker(relativePath, postProcessing);
_fileLines.Add(relativePath, result);
return result;
}
}
private IList<string> ReadFileWorker(RelativePath relativePath, Func<FullPath, IEnumerable<string>, IEnumerable<string>> postProcessing) {
foreach (var directoryName in PossibleDirectoryNames()) {
var path = directoryName.Combine(relativePath);
if (_fileSystem.FileExists(path)) {
Logger.Log("Using configuration file at \"{0}\"", path);
return postProcessing(path, _fileSystem.ReadAllLines(path)).ToReadOnlyCollection();
}
}
throw new FileLoadException(
string.Format("Could not load configuration file \"{0}\" from the following locations:{1}", relativePath,
PossibleDirectoryNames().Aggregate("", (x, y) => x + "\n" + y)));
}
private IEnumerable<FullPath> PossibleDirectoryNames() {
yield return new FullPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
.Combine(new RelativePath(ConfigurationDirectoryNames.LocalUserConfigurationDirectoryName));
yield return new FullPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
.Combine(new RelativePath(ConfigurationDirectoryNames.LocalInstallConfigurationDirectoryName));
}
}
}
| bsd-3-clause | C# |
f2e606db9905d2afe8ea354acf1285b6e465a561 | Fix for unbind on unbound collection | cybergen/bri-lib | BriLib/Scripts/Collection/TemplateDuplicator.cs | BriLib/Scripts/Collection/TemplateDuplicator.cs | using System.Collections.Generic;
using UnityEngine;
namespace BriLib
{
public class TemplateDuplicator : MonoBehaviour
{
[SerializeField] private GameObject _listEntryTemplate;
[SerializeField] private Transform _listParent;
private Dictionary<object, IView> _viewMap = new Dictionary<object, IView>();
private IObservableCollection _collection;
private bool _bound;
public void BindOnCollection(IObservableCollection collection)
{
if (_bound)
{
Debug.LogWarning("Attempting to bind on collection when already bound");
return;
}
_collection = collection;
SpawnEntries();
_collection.OnAddedNonGeneric += OnAdded;
_collection.OnRemovedNonGeneric += OnRemoved;
_collection.OnReplacedNonGeneric += OnReplaced;
_bound = true;
}
public void UnbindOnCollection()
{
if (!_bound) return;
_collection.OnAddedNonGeneric -= OnAdded;
_collection.OnRemovedNonGeneric -= OnRemoved;
_collection.OnReplacedNonGeneric -= OnReplaced;
CleanupEntries();
_bound = false;
}
private void SpawnEntries()
{
for (int i = 0; i < _collection.Count; i++)
{
SpawnView(_collection[i]);
}
}
private void CleanupEntries()
{
for (var enumerator = _viewMap.GetEnumerator(); enumerator.MoveNext();)
{
GameObject.Destroy(enumerator.Current.Value.GameObject);
}
_viewMap.Clear();
}
private IView SpawnView(object data)
{
var go = GameObject.Instantiate(_listEntryTemplate, _listParent);
var view = go.GetComponent<IView>();
view.ApplyData(data);
_viewMap.Add(data, view);
return view;
}
private void OnAdded(int arg1, object arg2)
{
var view = SpawnView(arg2);
view.GameObject.transform.SetSiblingIndex(arg1);
}
private void OnRemoved(int arg1, object arg2)
{
var view = _viewMap[arg2];
var data = view.Data;
GameObject.Destroy(view.GameObject);
_viewMap.Remove(data);
}
private void OnReplaced(int arg1, object oldItem, object newItem)
{
var view = _viewMap[oldItem];
view.ApplyData(newItem);
_viewMap.Remove(oldItem);
_viewMap.Add(newItem, view);
}
}
}
| using System.Collections.Generic;
using UnityEngine;
namespace BriLib
{
public class TemplateDuplicator : MonoBehaviour
{
[SerializeField] private GameObject _listEntryTemplate;
[SerializeField] private Transform _listParent;
private Dictionary<object, IView> _viewMap = new Dictionary<object, IView>();
private IObservableCollection _collection;
private bool _bound;
public void BindOnCollection(IObservableCollection collection)
{
if (_bound)
{
Debug.LogWarning("Attempting to bind on collection when already bound");
return;
}
_collection = collection;
SpawnEntries();
_collection.OnAddedNonGeneric += OnAdded;
_collection.OnRemovedNonGeneric += OnRemoved;
_collection.OnReplacedNonGeneric += OnReplaced;
}
public void UnbindOnCollection()
{
_collection.OnAddedNonGeneric -= OnAdded;
_collection.OnRemovedNonGeneric -= OnRemoved;
_collection.OnReplacedNonGeneric -= OnReplaced;
CleanupEntries();
_bound = false;
}
private void SpawnEntries()
{
for (int i = 0; i < _collection.Count; i++)
{
SpawnView(_collection[i]);
}
}
private void CleanupEntries()
{
for (var enumerator = _viewMap.GetEnumerator(); enumerator.MoveNext();)
{
GameObject.Destroy(enumerator.Current.Value.GameObject);
}
_viewMap.Clear();
}
private IView SpawnView(object data)
{
var go = GameObject.Instantiate(_listEntryTemplate, _listParent);
var view = go.GetComponent<IView>();
view.ApplyData(data);
_viewMap.Add(data, view);
return view;
}
private void OnAdded(int arg1, object arg2)
{
var view = SpawnView(arg2);
view.GameObject.transform.SetSiblingIndex(arg1);
}
private void OnRemoved(int arg1, object arg2)
{
var view = _viewMap[arg2];
var data = view.Data;
GameObject.Destroy(view.GameObject);
_viewMap.Remove(data);
}
private void OnReplaced(int arg1, object oldItem, object newItem)
{
var view = _viewMap[oldItem];
view.ApplyData(newItem);
_viewMap.Remove(oldItem);
_viewMap.Add(newItem, view);
}
}
}
| mit | C# |
f80f8da989209027a7fac1339077e4c004e5bf8b | Unify common options with CppSharp. | mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000 | binder/Options.cs | binder/Options.cs | using CppSharp;
using CppSharp.Generators;
namespace MonoEmbeddinator4000
{
public enum CompilationTarget
{
SharedLibrary,
StaticLibrary,
Application
}
public class Options : DriverOptions
{
public Options()
{
Project = new Project();
GenerateSupportFiles = true;
}
public Project Project;
// Generator options
public GeneratorKind Language;
public TargetPlatform Platform;
/// <summary>
/// Specifies the VS version.
/// </summary>
/// <remarks>When null, latest is used.</remarks>
public VisualStudioVersion VsVersion;
// If code compilation is enabled, then sets the compilation target.
public CompilationTarget Target;
// If true, will force the generation of debug metadata for the native
// and managed code.
public bool DebugMode;
// If true, will use unmanaged->managed thunks to call managed methods.
// In this mode the JIT will generate specialized wrappers for marshaling
// which will be faster but also lead to higher memory consumption.
public bool UseUnmanagedThunks;
// If true, will generate support files alongside generated binding code.
public bool GenerateSupportFiles;
// If true, will compile the generated as a shared library / DLL.
public bool CompileSharedLibrary => Target == CompilationTarget.SharedLibrary;
}
}
| using CppSharp;
using CppSharp.Generators;
namespace MonoEmbeddinator4000
{
public enum CompilationTarget
{
SharedLibrary,
StaticLibrary,
Application
}
public class Options
{
public Options()
{
Project = new Project();
GenerateSupportFiles = true;
}
public Project Project;
// Generator options
public string LibraryName;
public GeneratorKind Language;
public TargetPlatform Platform;
/// <summary>
/// Specifies the VS version.
/// </summary>
/// <remarks>When null, latest is used.</remarks>
public VisualStudioVersion VsVersion;
// If code compilation is enabled, then sets the compilation target.
public CompilationTarget Target;
public string OutputNamespace;
public string OutputDir;
// If true, will force the generation of debug metadata for the native
// and managed code.
public bool DebugMode;
// If true, will use unmanaged->managed thunks to call managed methods.
// In this mode the JIT will generate specialized wrappers for marshaling
// which will be faster but also lead to higher memory consumption.
public bool UseUnmanagedThunks;
// If true, will generate support files alongside generated binding code.
public bool GenerateSupportFiles;
// If true, will try to compile the generated managed-to-native binding code.
public bool CompileCode;
// If true, will compile the generated as a shared library / DLL.
public bool CompileSharedLibrary => Target == CompilationTarget.SharedLibrary;
}
}
| mit | C# |
18f73d13eff95d6b51b44fdec7e2d043c6d10864 | remove absolute namespace in script | DutchBeastman/ProefBekwaamheidIceCubeGames | Assets/Scripts/Audio/AudioClips.cs | Assets/Scripts/Audio/AudioClips.cs | // Created by: Jeremy Bond
// Date: 27/05/2016
using UnityEngine;
public class AudioClips : MonoBehaviour
{
[SerializeField] private AudioClip[] digSounds;
[SerializeField] private AudioClip[] buttonPushSounds;
[SerializeField] private AudioClip walkingSound;
[SerializeField] private AudioClip LosingLifeSound;
[SerializeField] private AudioClip blockLandingSound;
public static AudioClip digSound;
public static AudioClip buttonSound;
public static AudioClip walkSound;
public static AudioClip lostLifeSound;
public static AudioClip blockLandSound;
protected void Awake ()
{
digSound = digSounds[Random.Range(0, digSounds.Length)];
buttonSound = buttonPushSounds[Random.Range(0, buttonPushSounds.Length)];
walkSound = walkingSound;
lostLifeSound = LosingLifeSound;
blockLandSound = blockLandingSound;
}
}
| // Created by: Jeremy Bond
// Date: 27/05/2016
using UnityEngine;
using System.Collections;
public class AudioClips : MonoBehaviour
{
[SerializeField] private AudioClip[] digSounds;
[SerializeField] private AudioClip[] buttonPushSounds;
[SerializeField] private AudioClip walkingSound;
[SerializeField] private AudioClip LosingLifeSound;
[SerializeField] private AudioClip blockLandingSound;
public static AudioClip digSound;
public static AudioClip buttonSound;
public static AudioClip walkSound;
public static AudioClip lostLifeSound;
public static AudioClip blockLandSound;
protected void Awake ()
{
digSound = digSounds[Random.Range(0, digSounds.Length)];
buttonSound = buttonPushSounds[Random.Range(0, buttonPushSounds.Length)];
walkSound = walkingSound;
lostLifeSound = LosingLifeSound;
blockLandSound = blockLandingSound;
}
}
| mit | C# |
0eb07038575b24cc8f6601397866f87d246d51fc | Add damping multiplier to seperations steps | Saduras/DungeonGenerator | Assets/SourceCode/RoomSeperator.cs | Assets/SourceCode/RoomSeperator.cs | using UnityEngine;
[RequireComponent(typeof(RoomGenerator))]
public class RoomSeperator : MonoBehaviour
{
public int steps = 100;
public float damp = 0.5f;
Room[] _rooms;
public void Run()
{
int stepCount = 0;
var generator = this.GetComponent<RoomGenerator> ();
_rooms = generator.generatedRooms;
if (_rooms.Length <= 0) {
Debug.LogWarning ("No rooms found");
}
float maxVelocity = 0f;
do {
stepCount++;
maxVelocity = 0f;
foreach (var room in _rooms) {
var velocity = ComputeVelocity (room);
maxVelocity = Mathf.Max (velocity.magnitude, maxVelocity);
velocity *= damp;
velocity.x = Mathf.Ceil(velocity.x);
velocity.y = 0f;
velocity.z = Mathf.Ceil(velocity.z);
room.transform.localPosition += velocity;
}
} while(maxVelocity > 0.1f && stepCount < steps);
Debug.Log (string.Format ("Seperation finished after {0} steps. MaxVelocity left {1}", stepCount, maxVelocity));
}
Vector3 ComputeVelocity(Room currentRoom)
{
Vector3 velocity = Vector3.zero;
foreach (var otherRoom in _rooms) {
if (currentRoom != otherRoom) {
var overlap = ComputeOverlapWithSign (currentRoom, otherRoom);
velocity += overlap;
}
}
return velocity;
}
Vector3 ComputeOverlapWithSign(Room firstRoom, Room secondRoom)
{
float xOverlap = Mathf.Max (0, Mathf.Min (firstRoom.right, secondRoom.right) - Mathf.Max (firstRoom.left, secondRoom.left));
float zOverlap = Mathf.Max (0, Mathf.Min (firstRoom.top, secondRoom.top) - Mathf.Max (firstRoom.bottom, secondRoom.bottom));
if (xOverlap > 0f && zOverlap > 0f) {
float xDirection = Mathf.Sign (firstRoom.transform.localPosition.x - secondRoom.transform.localPosition.x);
float zDirection = Mathf.Sign (firstRoom.transform.localPosition.z - secondRoom.transform.localPosition.z);
return new Vector3 (xOverlap * xDirection, 0f, zOverlap * zDirection);
} else {
return Vector3.zero;
}
}
}
| using UnityEngine;
[RequireComponent(typeof(RoomGenerator))]
public class RoomSeperator : MonoBehaviour
{
public int steps = 100;
Room[] _rooms;
public void Run()
{
int stepCount = 0;
var generator = this.GetComponent<RoomGenerator> ();
_rooms = generator.generatedRooms;
if (_rooms.Length <= 0) {
Debug.LogWarning ("No rooms found");
}
float maxVelocity = 0f;
do {
stepCount++;
maxVelocity = 0f;
foreach (var room in _rooms) {
var velocity = ComputeVelocity (room);
maxVelocity = Mathf.Max (velocity.magnitude, maxVelocity);
velocity.x = Mathf.Ceil(velocity.x);
velocity.y = 0f;
velocity.z = Mathf.Ceil(velocity.z);
room.transform.localPosition += velocity;
}
} while(maxVelocity > 0.1f && stepCount < steps);
Debug.Log (string.Format ("Seperation finished after {0} steps. MaxVelocity left {1}", stepCount, maxVelocity));
}
Vector3 ComputeVelocity(Room currentRoom)
{
Vector3 velocity = Vector3.zero;
foreach (var otherRoom in _rooms) {
if (currentRoom != otherRoom) {
var overlap = ComputeOverlapWithSign (currentRoom, otherRoom);
velocity += overlap;
}
}
return velocity;
}
Vector3 ComputeOverlapWithSign(Room firstRoom, Room secondRoom)
{
float xOverlap = Mathf.Max (0, Mathf.Min (firstRoom.right, secondRoom.right) - Mathf.Max (firstRoom.left, secondRoom.left));
float zOverlap = Mathf.Max (0, Mathf.Min (firstRoom.top, secondRoom.top) - Mathf.Max (firstRoom.bottom, secondRoom.bottom));
if (xOverlap > 0f && zOverlap > 0f) {
float xDirection = Mathf.Sign (firstRoom.transform.localPosition.x - secondRoom.transform.localPosition.x);
float zDirection = Mathf.Sign (firstRoom.transform.localPosition.z - secondRoom.transform.localPosition.z);
return new Vector3 (xOverlap * xDirection, 0f, zOverlap * zDirection);
} else {
return Vector3.zero;
}
}
}
| mit | C# |
76fcff3a26a16379b5e2a59ab6a2ca234879a887 | Update HtmlWebViewExtender.cs (#96) | randigtroja/Flashback | Flashback.Uwp/Extensions/HtmlWebViewExtender.cs | Flashback.Uwp/Extensions/HtmlWebViewExtender.cs | using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace FlashbackUwp.Extensions
{
/// <summary>
/// Så vi kan binda direkt till "html" från vymodellen
/// </summary>
public class HtmlWebViewExtender
{
public static string GetHTML(DependencyObject obj) => (string)obj.GetValue(HTMLProperty);
public static void SetHTML(DependencyObject obj, string value) => obj.SetValue(HTMLProperty, value);
public static readonly DependencyProperty HTMLProperty = DependencyProperty.RegisterAttached("HTML", typeof(string), typeof(HtmlWebViewExtender), new PropertyMetadata("", new PropertyChangedCallback(OnHTMLChanged)));
private static void OnHTMLChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is WebView wv)
{
wv.NavigateToString((string)e.NewValue);
}
}
}
}
| using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace FlashbackUwp.Extensions
{
/// <summary>
/// Så vi kan binda direkt till "html" från vymodellen
/// </summary>
public class HtmlWebViewExtender
{
public static string GetHTML(DependencyObject obj)
{
return (string)obj.GetValue(HTMLProperty);
}
public static void SetHTML(DependencyObject obj, string value)
{
obj.SetValue(HTMLProperty, value);
}
public static readonly DependencyProperty HTMLProperty = DependencyProperty.RegisterAttached("HTML", typeof(string), typeof(HtmlWebViewExtender), new PropertyMetadata("", new PropertyChangedCallback(OnHTMLChanged)));
private static void OnHTMLChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
WebView wv = d as WebView;
if (wv != null)
{
wv.NavigateToString((string)e.NewValue);
}
}
}
}
| mit | C# |
31f1d15cc3222dbc34bbc0700f04eec56670c492 | Use empty array of the specified type | civicsource/http,civicsource/webapi-utils | Core/CsvArrayConverterAttribute.cs | Core/CsvArrayConverterAttribute.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;
namespace Archon.WebApi
{
public class CsvArrayConverterAttribute : ActionFilterAttribute
{
readonly string name;
readonly Type type;
public CsvArrayConverterAttribute(string name, Type type)
{
this.name = name;
this.type = type;
}
public override void OnActionExecuting(HttpActionContext context)
{
string csv = ExtractCommaSeparatedValue(context);
if (!String.IsNullOrWhiteSpace(csv))
{
context.ActionArguments[name] = csv.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => ConvertString(s.Trim())).ToArray();
}
else
{
context.ActionArguments[name] = Array.CreateInstance(type, 0);
}
}
object ConvertString(string str)
{
if (type == typeof(Guid))
{
return new Guid(str);
}
else
{
return Convert.ChangeType(str, this.type);
}
}
string ExtractCommaSeparatedValue(HttpActionContext context)
{
if (!context.ActionArguments.ContainsKey(name))
return null;
if (context.ControllerContext.RouteData.Values.ContainsKey(this.name))
return (string)context.ControllerContext.RouteData.Values[this.name];
var qs = context.ControllerContext.Request.RequestUri.ParseQueryString();
return qs[name];
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;
namespace Archon.WebApi
{
public class CsvArrayConverterAttribute : ActionFilterAttribute
{
readonly string name;
readonly Type type;
public CsvArrayConverterAttribute(string name, Type type)
{
this.name = name;
this.type = type;
}
public override void OnActionExecuting(HttpActionContext context)
{
string csv = ExtractCommaSeparatedValue(context);
if (!String.IsNullOrWhiteSpace(csv))
{
context.ActionArguments[name] = csv.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => ConvertString(s.Trim())).ToArray();
}
else
{
context.ActionArguments[name] = new object[0];
}
}
object ConvertString(string str)
{
if (type == typeof(Guid))
{
return new Guid(str);
}
else
{
return Convert.ChangeType(str, this.type);
}
}
string ExtractCommaSeparatedValue(HttpActionContext context)
{
if (!context.ActionArguments.ContainsKey(name))
return null;
if (context.ControllerContext.RouteData.Values.ContainsKey(this.name))
return (string)context.ControllerContext.RouteData.Values[this.name];
var qs = context.ControllerContext.Request.RequestUri.ParseQueryString();
return qs[name];
}
}
}
| mit | C# |
240e95f3b99da92f896a7c3c723cad39ec3425ce | Allow name to be over ridden | m0wo/ucreate,nicbell/ucreate,nicbell/ucreate,m0wo/ucreate,m0wo/ucreate,nicbell/ucreate | NicBell.UCreate/Attributes/PropertyAttribute.cs | NicBell.UCreate/Attributes/PropertyAttribute.cs | using NicBell.UCreate.Helpers;
using NicBell.UCreate.Interfaces;
using System;
using System.Runtime.CompilerServices;
using Umbraco.Core.Models;
namespace NicBell.UCreate.Attributes
{
/// <summary>
/// Makes property as part of the generated type
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class PropertyAttribute : Attribute
{
public string Alias { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Mandatory { get; set; }
public string ValidationRegExp { get; set; }
//public object DefaultValue { get; set; }
/// <summary>
/// Property Type. Tip: for standard types use constants in "NicBell.UCreate.Constants.PropertyTypes"
/// </summary>
public string TypeName { get; set; }
/// <summary>
/// If you want to convert the stored value to a custom type
/// </summary>
public Type TypeConverter { get; set; }
public string TabName { get; set; }
/// <summary>
/// Set default values
/// </summary>
public PropertyAttribute([CallerMemberName]string name = null)
{
this.Mandatory = false;
this.ValidationRegExp = "";
this.Description = "";
//this.DefaultValue = null;
this.Alias = "";
this.TypeName = "Textstring";
this.Name = name;
this.TypeConverter = null;
}
public PropertyType GetPropertyType()
{
var propType = new PropertyType(new DataTypeHelper().GetDataType(TypeName))
{
Alias = Alias,
Name = Name,
Description = Description,
Mandatory = Mandatory,
ValidationRegExp = ValidationRegExp
};
return propType;
}
}
}
| using NicBell.UCreate.Helpers;
using NicBell.UCreate.Interfaces;
using System;
using System.Runtime.CompilerServices;
using Umbraco.Core.Models;
namespace NicBell.UCreate.Attributes
{
/// <summary>
/// Makes property as part of the generated type
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class PropertyAttribute : Attribute
{
public string Alias { get; set; }
public string Name { get; private set; }
public string Description { get; set; }
public bool Mandatory { get; set; }
public string ValidationRegExp { get; set; }
//public object DefaultValue { get; set; }
/// <summary>
/// Property Type. Tip: for standard types use constants in "NicBell.UCreate.Constants.PropertyTypes"
/// </summary>
public string TypeName { get; set; }
/// <summary>
/// If you want to convert the stored value to a custom type
/// </summary>
public Type TypeConverter { get; set; }
public string TabName { get; set; }
/// <summary>
/// Set default values
/// </summary>
public PropertyAttribute([CallerMemberName]string name = null)
{
this.Mandatory = false;
this.ValidationRegExp = "";
this.Description = "";
//this.DefaultValue = null;
this.Alias = "";
this.TypeName = "Textstring";
this.Name = name;
this.TypeConverter = null;
}
public PropertyType GetPropertyType()
{
var propType = new PropertyType(new DataTypeHelper().GetDataType(TypeName))
{
Alias = Alias,
Name = Name,
Description = Description,
Mandatory = Mandatory,
ValidationRegExp = ValidationRegExp
};
return propType;
}
}
}
| unlicense | C# |
8f5ab4a0540b20e4f2892e8873218c4b8918133d | change universal version to 1.0.0.9 | poumason/Mixpanel.Net.Client,poumason/MixpanelClientDotNet | Library/MixpanelClientDotNet.UWP/Properties/AssemblyInfo.cs | Library/MixpanelClientDotNet.UWP/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("MixpanelDotNet.UWP")]
[assembly: AssemblyDescription("This project provides basic API integration for using Mixpanel from .NET applications.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pou")]
[assembly: AssemblyProduct("MixpanelDotNet.UWP")]
[assembly: AssemblyCopyright("Copyright © Pou 2016")]
[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.0.9")]
[assembly: AssemblyFileVersion("1.0.0.9")]
[assembly: ComVisible(false)] | 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("MixpanelDotNet.UWP")]
[assembly: AssemblyDescription("This project provides basic API integration for using Mixpanel from .NET applications.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pou")]
[assembly: AssemblyProduct("MixpanelDotNet.UWP")]
[assembly: AssemblyCopyright("Copyright © Pou 2016")]
[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.0.8")]
[assembly: AssemblyFileVersion("1.0.0.8")]
[assembly: ComVisible(false)] | apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.