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 |
|---|---|---|---|---|---|---|---|---|
33ecae7337fd3c4ead228300e88506be962558ee
|
Add StopAsync method
|
erikipedia/MediaCaptureWPF,erikipedia/MediaCaptureWPF,mmaitre314/MediaCaptureWPF,mmaitre314/MediaCaptureWPF,mmaitre314/MediaCaptureWPF,erikipedia/MediaCaptureWPF
|
MediaCaptureWPF/CapturePreview.cs
|
MediaCaptureWPF/CapturePreview.cs
|
using MediaCaptureWPF.Native;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Media;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
namespace MediaCaptureWPF
{
public class CapturePreview : D3DImage
{
CapturePreviewNative m_preview;
MediaCapture m_capture;
uint m_width;
uint m_height;
public CapturePreview(MediaCapture capture)
{
var props = (VideoEncodingProperties)capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
m_width = props.Width;
m_height = props.Height;
m_preview = new CapturePreviewNative(this, m_width, m_height);
m_capture = capture;
}
public async Task StartAsync()
{
var profile = new MediaEncodingProfile
{
Audio = null,
Video = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.Rgb32, m_width, m_height),
Container = null
};
await m_capture.StartPreviewToCustomSinkAsync(profile, (IMediaExtension)m_preview.MediaSink);
}
public async Task StopAsync()
{
await m_capture.StopPreviewAsync();
}
}
}
|
using MediaCaptureWPF.Native;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Media;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
namespace MediaCaptureWPF
{
public class CapturePreview : D3DImage
{
CapturePreviewNative m_preview;
MediaCapture m_capture;
uint m_width;
uint m_height;
public CapturePreview(MediaCapture capture)
{
var props = (VideoEncodingProperties)capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
m_width = props.Width;
m_height = props.Height;
m_preview = new CapturePreviewNative(this, m_width, m_height);
m_capture = capture;
}
public async Task StartAsync()
{
var profile = new MediaEncodingProfile
{
Audio = null,
Video = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.Rgb32, m_width, m_height),
Container = null
};
await m_capture.StartPreviewToCustomSinkAsync(profile, (IMediaExtension)m_preview.MediaSink);
}
}
}
|
apache-2.0
|
C#
|
10135cb6b52fedc0d076cfaf35e2ce6e7f39524d
|
bump version
|
Fody/InfoOf
|
CommonAssemblyInfo.cs
|
CommonAssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyTitle("InfoOf")]
[assembly: AssemblyProduct("InfoOf")]
[assembly: AssemblyVersion("1.2.0")]
|
using System.Reflection;
[assembly: AssemblyTitle("InfoOf")]
[assembly: AssemblyProduct("InfoOf")]
[assembly: AssemblyVersion("1.1.1")]
|
mit
|
C#
|
4c59925d4b4b11e0797f3c740764f8064ebdb448
|
Make DllImport exclusive to iOS
|
sanukin39/UniVersionManager
|
Assets/UniVersionManager/UniVersionManager.cs
|
Assets/UniVersionManager/UniVersionManager.cs
|
using UnityEngine;
using System;
using System.Runtime.InteropServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class UniVersionManager
{
#if UNITY_IOS
[DllImport("__Internal")]
private static extern string GetVersionName_();
[DllImport("__Internal")]
private static extern string GetBuildVersionName_ ();
#endif
public static string GetVersion ()
{
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<string>("GetVersionName");
#else
return "0";
#endif
}
public static string GetBuildVersion(){
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetBuildVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<int>("GetVersionCode").ToString ();
#else
return "0";
#endif
}
public static bool IsNewVersion (string targetVersion)
{
var current = new Version(GetVersion());
var target = new Version(targetVersion);
return current.CompareTo(target) < 0;
}
}
|
using UnityEngine;
using System;
using System.Runtime.InteropServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
public static class UniVersionManager
{
[DllImport("__Internal")]
private static extern string GetVersionName_();
[DllImport("__Internal")]
private static extern string GetBuildVersionName_ ();
public static string GetVersion ()
{
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<string>("GetVersionName");
#else
return "0";
#endif
}
public static string GetBuildVersion(){
#if UNITY_EDITOR
return PlayerSettings.bundleVersion;
#elif UNITY_IOS
return GetBuildVersionName_();
#elif UNITY_ANDROID
AndroidJavaObject ajo = new AndroidJavaObject("net.sanukin.UniVersionManager");
return ajo.CallStatic<int>("GetVersionCode").ToString ();
#else
return "0";
#endif
}
public static bool IsNewVersion (string targetVersion)
{
var current = new Version(GetVersion());
var target = new Version(targetVersion);
return current.CompareTo(target) < 0;
}
}
|
mit
|
C#
|
a8c09f8e76c06638e00f7bad7c6bcafaa73f00ec
|
Split tests and deduplicated code
|
Wolfolo/DesignPatternsCSharp
|
DesignPatternsExercise/CreationalPatterns/FactoryMethod/FactoryMethodTest.cs
|
DesignPatternsExercise/CreationalPatterns/FactoryMethod/FactoryMethodTest.cs
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DesignPatternsExercise.CreationalPatterns.FactoryMethod.Mocks;
using System.Collections.Generic;
namespace DesignPatternsExercise.CreationalPatterns.FactoryMethod
{
[TestClass]
public class FactoryMethodTest
{
private Dictionary<ProductType, Type> ProductionProvider()
{
var products = new Dictionary<ProductType, Type>();
products.Add(ProductType.Foo, typeof(FooProduct));
products.Add(ProductType.Bar, typeof(BarProduct));
products.Add(ProductType.Baz, typeof(BazProduct));
return products;
}
[TestMethod]
public void TestFactoryProducesProducts()
{
var factory = new CompleteFactory();
foreach (var product in ProductionProvider())
{
Assert.IsInstanceOfType(factory.Build(product.Key), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(product.Key), product.Value);
}
}
[TestMethod]
public void TestIncompleteFactoryThrowsException()
{
IFactoryMethod factory = new IncompleteFactory();
try
{
foreach (var product in ProductionProvider())
{
Assert.IsInstanceOfType(factory.Build(product.Key), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(product.Key), product.Value);
}
// Must not get here
Assert.Fail();
}
catch(Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(NotImplementedException));
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DesignPatternsExercise.CreationalPatterns.FactoryMethod.Mocks;
namespace DesignPatternsExercise.CreationalPatterns.FactoryMethod
{
[TestClass]
public class FactoryMethodTest
{
[TestMethod]
public void TestProduction()
{
IFactoryMethod factory = new IncompleteFactory();
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(FooProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(BarProduct));
try
{
factory.Build(ProductType.Baz);
}
catch(Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(NotImplementedException));
}
// Try again with a complete factory
factory = new CompleteFactory();
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Baz), typeof(IProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Foo), typeof(FooProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Bar), typeof(BarProduct));
Assert.IsInstanceOfType(factory.Build(ProductType.Baz), typeof(BazProduct));
}
}
}
|
unlicense
|
C#
|
cac41997fc2a94b606541fcc0e5a76f5fe6ce6e4
|
Use double checked lock to improve performance.
|
castleproject/Castle.Transactions,castleproject/Castle.Facilities.Wcf-READONLY,codereflection/Castle.Components.Scheduler,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/Castle.Facilities.Wcf-READONLY,carcer/Castle.Components.Validator,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/castle-READONLY-SVN-dump
|
InversionOfControl/Castle.MicroKernel/Lifestyle/SingletonLifestyleManager.cs
|
InversionOfControl/Castle.MicroKernel/Lifestyle/SingletonLifestyleManager.cs
|
// Copyright 2004-2008 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.MicroKernel.Lifestyle
{
using System;
/// <summary>
/// Summary description for SingletonLifestyleManager.
/// </summary>
[Serializable]
public class SingletonLifestyleManager : AbstractLifestyleManager
{
private volatile Object instance;
public override void Dispose()
{
if (instance != null) base.Release( instance );
}
public override object Resolve(CreationContext context)
{
if (instance == null)
{
lock (ComponentActivator)
{
if (instance == null)
{
instance = base.Resolve(context);
}
}
}
return instance;
}
public override void Release( object instance )
{
// Do nothing
}
}
}
|
// Copyright 2004-2008 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.MicroKernel.Lifestyle
{
using System;
/// <summary>
/// Summary description for SingletonLifestyleManager.
/// </summary>
[Serializable]
public class SingletonLifestyleManager : AbstractLifestyleManager
{
private Object instance;
public override void Dispose()
{
if (instance != null) base.Release( instance );
}
public override object Resolve(CreationContext context)
{
lock(ComponentActivator)
{
if (instance == null)
{
instance = base.Resolve(context);
}
}
return instance;
}
public override void Release( object instance )
{
// Do nothing
}
}
}
|
apache-2.0
|
C#
|
05e6c3ef6a0b030234922736c36b4f3cef8f097a
|
Create JSon Reader command is ready
|
olebg/Movie-Theater-Project
|
MovieTheater/MovieTheater.Framework/Core/Commands/CreateJsonReaderCommand.cs
|
MovieTheater/MovieTheater.Framework/Core/Commands/CreateJsonReaderCommand.cs
|
using System.Collections.Generic;
using MovieTheater.Framework.Core.Commands.Contracts;
using MovieTheater.Framework.Core.Providers;
using MovieTheater.Framework.Core.Providers.Contracts;
namespace MovieTheater.Framework.Core.Commands
{
public class CreateJsonReaderCommand : ICommand
{
private IReader reader;
private IWriter writer;
public CreateJsonReaderCommand()
{
this.reader = new ConsoleReader();
this.writer = new ConsoleWriter();
}
public string Execute(List<string> parameters)
{
var jsonReader = new JsonReader(reader, writer);
jsonReader.Read();
return "Successfully read json file!";
}
}
}
|
using System;
using System.Collections.Generic;
using MovieTheater.Framework.Core.Commands.Contracts;
namespace MovieTheater.Framework.Core.Commands
{
public class CreateJsonReaderCommand : ICommand
{
public string Execute(List<string> parameters)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
30ff4990fb05a72b9cbb006c95a1bd2e6220d7ef
|
Fix enum starting value
|
uo-lca/CalRecycleLCA,uo-lca/CalRecycleLCA
|
Database/DataModel/Enum.cs
|
Database/DataModel/Enum.cs
|
namespace LcaDataModel {
using System;
public enum DataProviderEnum {
append=1,
fragments,
scenarios
}
public enum DataTypeEnum {
Flow=1,
FlowProperty,
Process,
UnitGroup,
Source,
LCIAMethod,
Contact,
Fragment
}
public enum DirectionEnum {
Input=1, Output
}
public enum FlowTypeEnum {
IntermediateFlow=1,
ElementaryFlow
}
public enum NodeTypeEnum {
Process=1, Fragment, InputOutput, Background
}
}
|
namespace LcaDataModel {
using System;
public enum DataProviderEnum {
append,
fragments,
scenarios
}
public enum DataTypeEnum {
Flow,
FlowProperty,
Process,
UnitGroup,
Source,
LCIAMethod,
Contact,
Fragment
}
public enum DirectionEnum {
Input, Output
}
public enum FlowTypeEnum {
IntermediateFlow,
ElementaryFlow
}
public enum NodeTypeEnum {
Process, Fragment, InputOutput, Background
}
}
|
bsd-2-clause
|
C#
|
9a4a3b18594c883ed72750a5e0e457bb4f397243
|
Update src/Compilers/Core/Portable/SourceGeneration/GlobalAliases.cs
|
CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,weltkante/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,weltkante/roslyn,mavasani/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,mavasani/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,bartdesmet/roslyn
|
src/Compilers/Core/Portable/SourceGeneration/GlobalAliases.cs
|
src/Compilers/Core/Portable/SourceGeneration/GlobalAliases.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SourceGeneration;
/// <summary>
/// Simple wrapper class around an immutable array so we can have the value-semantics needed for the incremental
/// generator to know when a change actually happened and it should run later transform stages.
/// </summary>
internal sealed class GlobalAliases : IEquatable<GlobalAliases>
{
public static readonly GlobalAliases Empty = new(ImmutableArray<(string aliasName, string symbolName)>.Empty);
public readonly ImmutableArray<(string aliasName, string symbolName)> AliasAndSymbolNames;
private int _hashCode;
private GlobalAliases(ImmutableArray<(string aliasName, string symbolName)> aliasAndSymbolNames)
{
AliasAndSymbolNames = aliasAndSymbolNames;
}
public static GlobalAliases Create(ImmutableArray<(string aliasName, string symbolName)> aliasAndSymbolNames)
{
return aliasAndSymbolNames.IsEmpty ? Empty : new GlobalAliases(aliasAndSymbolNames);
}
public static GlobalAliases Concat(GlobalAliases ga1, GlobalAliases ga2)
{
if (ga1.AliasAndSymbolNames.Length == 0)
return ga2;
if (ga2.AliasAndSymbolNames.Length == 0)
return ga1;
return Create(ga1.AliasAndSymbolNames.Concat(ga2.AliasAndSymbolNames));
}
public override int GetHashCode()
{
if (_hashCode == 0)
{
var hashCode = 0;
foreach (var tuple in this.AliasAndSymbolNames)
hashCode = Hash.Combine(tuple.GetHashCode(), hashCode);
_hashCode = hashCode == 0 ? 1 : hashCode;
}
return _hashCode;
}
public override bool Equals(object? obj)
=> this.Equals(obj as GlobalAliases);
public bool Equals(GlobalAliases? aliases)
{
if (aliases is null)
return false;
if (ReferenceEquals(this, aliases))
return true;
if (this.AliasAndSymbolNames == aliases.AliasAndSymbolNames)
return true;
if (this.AliasAndSymbolNames.Length != aliases.AliasAndSymbolNames.Length)
return false;
for (int i = 0, n = this.AliasAndSymbolNames.Length; i < n; i++)
{
if (this.AliasAndSymbolNames[i] != aliases.AliasAndSymbolNames[i])
return false;
}
return true;
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SourceGeneration;
/// <summary>
/// Simple wrapper class around an immutable array so we can have the value-semantics needed for the incremental
/// generator to know when a change actually happened and it should run later transform stages.
/// </summary>
internal class GlobalAliases : IEquatable<GlobalAliases>
{
public static readonly GlobalAliases Empty = new(ImmutableArray<(string aliasName, string symbolName)>.Empty);
public readonly ImmutableArray<(string aliasName, string symbolName)> AliasAndSymbolNames;
private int _hashCode;
private GlobalAliases(ImmutableArray<(string aliasName, string symbolName)> aliasAndSymbolNames)
{
AliasAndSymbolNames = aliasAndSymbolNames;
}
public static GlobalAliases Create(ImmutableArray<(string aliasName, string symbolName)> aliasAndSymbolNames)
{
return aliasAndSymbolNames.IsEmpty ? Empty : new GlobalAliases(aliasAndSymbolNames);
}
public static GlobalAliases Concat(GlobalAliases ga1, GlobalAliases ga2)
{
if (ga1.AliasAndSymbolNames.Length == 0)
return ga2;
if (ga2.AliasAndSymbolNames.Length == 0)
return ga1;
return Create(ga1.AliasAndSymbolNames.Concat(ga2.AliasAndSymbolNames));
}
public override int GetHashCode()
{
if (_hashCode == 0)
{
var hashCode = 0;
foreach (var tuple in this.AliasAndSymbolNames)
hashCode = Hash.Combine(tuple.GetHashCode(), hashCode);
_hashCode = hashCode == 0 ? 1 : hashCode;
}
return _hashCode;
}
public override bool Equals(object? obj)
=> this.Equals(obj as GlobalAliases);
public bool Equals(GlobalAliases? aliases)
{
if (aliases is null)
return false;
if (ReferenceEquals(this, aliases))
return true;
if (this.AliasAndSymbolNames == aliases.AliasAndSymbolNames)
return true;
if (this.AliasAndSymbolNames.Length != aliases.AliasAndSymbolNames.Length)
return false;
for (int i = 0, n = this.AliasAndSymbolNames.Length; i < n; i++)
{
if (this.AliasAndSymbolNames[i] != aliases.AliasAndSymbolNames[i])
return false;
}
return true;
}
}
|
mit
|
C#
|
b24f568940f37b3b70caf98e4af2a7ce5fceea33
|
Remove unused method
|
OrleansContrib/Orleankka,pkese/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka,mhertis/Orleankka,mhertis/Orleankka,yevhen/Orleankka,pkese/Orleankka
|
Source/Orleankka.Runtime/Actor.cs
|
Source/Orleankka.Runtime/Actor.cs
|
using System;
using System.Threading.Tasks;
namespace Orleankka
{
using Core;
using Behaviors;
using Services;
using Utility;
public abstract class Actor
{
ActorRef self;
protected Actor()
{
Behavior = ActorBehavior.Null(this);
}
protected Actor(string id, IActorRuntime runtime, Dispatcher dispatcher = null) : this()
{
Requires.NotNull(runtime, nameof(runtime));
Requires.NotNullOrWhitespace(id, nameof(id));
Runtime = runtime;
Dispatcher = dispatcher ?? ActorType.Dispatcher(GetType());
Path = GetType().ToActorPath(id);
}
internal void Initialize(ActorEndpoint endpoint, ActorPath path, IActorRuntime runtime, Dispatcher dispatcher)
{
Path = path;
Runtime = runtime;
Dispatcher = Dispatcher ?? dispatcher;
Endpoint = endpoint;
}
public string Id => Path.Id;
internal ActorEndpoint Endpoint {get; private set;}
public ActorPath Path {get; private set;}
public IActorRuntime Runtime {get; private set;}
public ActorBehavior Behavior {get; private set;}
public Dispatcher Dispatcher {get; private set;}
public IActorSystem System => Runtime.System;
public IActivationService Activation => Runtime.Activation;
public IReminderService Reminders => Runtime.Reminders;
public ITimerService Timers => Runtime.Timers;
public ActorRef Self => self ?? (self = System.ActorOf(Path));
public virtual Task OnActivate() => Behavior.HandleActivate();
public virtual Task OnDeactivate() => Behavior.HandleDeactivate();
public virtual Task<object> OnReceive(object message) => Behavior.HandleReceive(message);
public virtual Task OnReminder(string id) => Behavior.HandleReminder(id);
public async Task<TResult> Dispatch<TResult>(object message, Func<object, Task<object>> fallback = null) =>
(TResult)await Dispatch(message, fallback);
public Task<object> Dispatch(object message, Func<object, Task<object>> fallback = null)
{
Requires.NotNull(message, nameof(message));
return Dispatcher.Dispatch(this, message, fallback);
}
}
}
|
using System;
using System.Threading.Tasks;
namespace Orleankka
{
using Core;
using Behaviors;
using Services;
using Utility;
public abstract class Actor
{
ActorRef self;
protected Actor()
{
Behavior = ActorBehavior.Null(this);
}
protected Actor(string id, IActorRuntime runtime, Dispatcher dispatcher = null) : this()
{
Requires.NotNull(runtime, nameof(runtime));
Requires.NotNullOrWhitespace(id, nameof(id));
Runtime = runtime;
Dispatcher = dispatcher ?? ActorType.Dispatcher(GetType());
Path = GetType().ToActorPath(id);
}
internal void Initialize(ActorEndpoint endpoint, ActorPath path, IActorRuntime runtime, Dispatcher dispatcher)
{
Path = path;
Runtime = runtime;
Dispatcher = Dispatcher ?? dispatcher;
Endpoint = endpoint;
}
public string Id => Path.Id;
internal ActorEndpoint Endpoint {get; private set;}
internal bool IsExecutingInsideRuntime() => Endpoint != null;
public ActorPath Path {get; private set;}
public IActorRuntime Runtime {get; private set;}
public ActorBehavior Behavior {get; private set;}
public Dispatcher Dispatcher {get; private set;}
public IActorSystem System => Runtime.System;
public IActivationService Activation => Runtime.Activation;
public IReminderService Reminders => Runtime.Reminders;
public ITimerService Timers => Runtime.Timers;
public ActorRef Self => self ?? (self = System.ActorOf(Path));
public virtual Task OnActivate() => Behavior.HandleActivate();
public virtual Task OnDeactivate() => Behavior.HandleDeactivate();
public virtual Task<object> OnReceive(object message) => Behavior.HandleReceive(message);
public virtual Task OnReminder(string id) => Behavior.HandleReminder(id);
public async Task<TResult> Dispatch<TResult>(object message, Func<object, Task<object>> fallback = null) =>
(TResult)await Dispatch(message, fallback);
public Task<object> Dispatch(object message, Func<object, Task<object>> fallback = null)
{
Requires.NotNull(message, nameof(message));
return Dispatcher.Dispatch(this, message, fallback);
}
}
}
|
apache-2.0
|
C#
|
9859a7ac62bc158cf5a599bdef536f00eec90cb6
|
Update assembly info
|
5andr0/PogoLocationFeeder,5andr0/PogoLocationFeeder
|
PogoLocationFeeder/Properties/AssemblyInfo.cs
|
PogoLocationFeeder/Properties/AssemblyInfo.cs
|
/*
PogoLocationFeeder gathers pokemon data from various sources and serves it to connected clients
Copyright (C) 2016 PogoLocationFeeder Development Team <admin@pokefeeder.live>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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("PogoLocationFeeder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PogoLocationFeeder")]
[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("76f6eeef-e89f-4e43-aa9d-1567cbc1420b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.9.0")]
[assembly: AssemblyFileVersion("0.1.9.0")]
|
/*
PogoLocationFeeder gathers pokemon data from various sources and serves it to connected clients
Copyright (C) 2016 PogoLocationFeeder Development Team <admin@pokefeeder.live>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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("PogoLocationFeeder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PogoLocationFeeder")]
[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("76f6eeef-e89f-4e43-aa9d-1567cbc1420b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.8.0")]
[assembly: AssemblyFileVersion("0.1.8.0")]
|
agpl-3.0
|
C#
|
cd863434be087a72772b4ed2f82feaf5f80b0796
|
Fix TreeDataTemplate.
|
AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,OronDF343/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,MrDaedra/Avalonia,wieslawsoltes/Perspex,susloparovdenis/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,MrDaedra/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,punker76/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,susloparovdenis/Perspex,Perspex/Perspex,OronDF343/Avalonia,susloparovdenis/Avalonia,jkoritzinsky/Avalonia,jazzay/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,susloparovdenis/Avalonia,wieslawsoltes/Perspex
|
src/Markup/Avalonia.Markup.Xaml/Templates/TreeDataTemplate.cs
|
src/Markup/Avalonia.Markup.Xaml/Templates/TreeDataTemplate.cs
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections;
using System.Reactive.Linq;
using System.Reflection;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Markup.Data;
using Avalonia.Markup.Xaml.Data;
using Avalonia.Metadata;
namespace Avalonia.Markup.Xaml.Templates
{
public class TreeDataTemplate : ITreeDataTemplate
{
public Type DataType { get; set; }
[Content]
public TemplateContent Content { get; set; }
[AssignBinding]
public Binding ItemsSource { get; set; }
public bool SupportsRecycling => true;
public bool Match(object data)
{
if (DataType == null)
{
return true;
}
else
{
return DataType.GetTypeInfo().IsAssignableFrom(data.GetType().GetTypeInfo());
}
}
public InstancedBinding ItemsSelector(object item)
{
if (ItemsSource != null)
{
var obs = new ExpressionObserver(item, ItemsSource.Path);
return new InstancedBinding(obs, BindingMode.OneWay, BindingPriority.Style);
}
return null;
}
public bool IsExpanded(object item)
{
return true;
}
public IControl Build(object data)
{
var visualTreeForItem = Content.Load();
visualTreeForItem.DataContext = data;
return visualTreeForItem;
}
}
}
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections;
using System.Reactive.Linq;
using System.Reflection;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Markup.Data;
using Avalonia.Markup.Xaml.Data;
using Avalonia.Metadata;
namespace Avalonia.Markup.Xaml.Templates
{
public class TreeDataTemplate : ITreeDataTemplate
{
public Type DataType { get; set; }
[Content]
public TemplateContent Content { get; set; }
[AssignBinding]
public Binding ItemsSource { get; set; }
public bool SupportsRecycling => true;
public bool Match(object data)
{
if (DataType == null)
{
return true;
}
else
{
return DataType.GetTypeInfo().IsAssignableFrom(data.GetType().GetTypeInfo());
}
}
public InstancedBinding ItemsSelector(object item)
{
if (ItemsSource != null)
{
var obs = new ExpressionObserver(item, ItemsSource.Path);
return new InstancedBinding(obs, BindingPriority.Style);
}
return null;
}
public bool IsExpanded(object item)
{
return true;
}
public IControl Build(object data)
{
var visualTreeForItem = Content.Load();
visualTreeForItem.DataContext = data;
return visualTreeForItem;
}
}
}
|
mit
|
C#
|
7884c85140f17ea51954bb536c8fb35fda5f24e6
|
Update addin versions
|
cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe
|
Cake.Recipe/Content/addins.cake
|
Cake.Recipe/Content/addins.cake
|
///////////////////////////////////////////////////////////////////////////////
// ADDINS
///////////////////////////////////////////////////////////////////////////////
#addin nuget:?package=Cake.AppVeyor&version=1.1.0.9
#addin nuget:?package=Cake.Coveralls&version=0.4.0
#addin nuget:?package=Cake.Gitter&version=0.5.0
#addin nuget:?package=Cake.ReSharperReports&version=0.6.0
#addin nuget:?package=Cake.Slack&version=0.6.0
#addin nuget:?package=Cake.Twitter&version=0.4.0
#addin nuget:?package=Cake.MicrosoftTeams&version=0.3.0
#addin nuget:?package=Cake.Wyam&version=0.17.1
#addin nuget:?package=Cake.Git&version=0.13.0
#addin nuget:?package=Cake.Kudu&version=0.4.0
#addin nuget:?package=Cake.Incubator&version=1.0.48
#addin nuget:?package=Cake.Figlet&version=0.4.0
|
///////////////////////////////////////////////////////////////////////////////
// ADDINS
///////////////////////////////////////////////////////////////////////////////
#addin nuget:?package=Cake.AppVeyor&version=1.1.0.9
#addin nuget:?package=Cake.Coveralls&version=0.4.0
#addin nuget:?package=Cake.Gitter&version=0.5.0
#addin nuget:?package=Cake.ReSharperReports&version=0.6.0
#addin nuget:?package=Cake.Slack&version=0.6.0
#addin nuget:?package=Cake.Twitter&version=0.4.0
#addin nuget:?package=Cake.MicrosoftTeams&version=0.3.0
#addin nuget:?package=Cake.Wyam&version=0.17.0
#addin nuget:?package=Cake.Git&version=0.13.0
#addin nuget:?package=Cake.Kudu&version=0.4.0
#addin nuget:?package=Cake.Incubator&version=1.0.38
#addin nuget:?package=Cake.Figlet&version=0.4.0
|
mit
|
C#
|
e2339acdad001c9bde4bf125dd53008dfaa27bf4
|
update sinus script
|
jump4r/Outsider
|
Outsider/Assets/Scripts/Sinus.cs
|
Outsider/Assets/Scripts/Sinus.cs
|
using UnityEngine;
using System.Collections;
using System;
public class Sinus : MonoBehaviour {
//unoptimized version
private static System.Random RandomNumber = new System.Random();
public double frequency;
public double frequency2 = 220;
public double gain = 0.02;
public static int[] pitchClass = new int[] {0, 2, 4, 5, 7, 9, 11};
public double skew;
public double swellRate;
private double increment;
private double increment2;
private double increment3;
private double phase;
private double phase2;
private double phase3;
private double sampling_frequency = 44100;
void Awake() {
frequency = Sinus.midiToFreq((UnityEngine.Random.Range(1, 3) * 12) + UnityEngine.Random.Range(0, pitchClass.Length - 1));
skew = (float)Math.Sin((float)RandomNumber.NextDouble()*2.0f*Math.PI) * 2.0f;
swellRate = (float)Mathf.Clamp((float)(RandomNumber.NextDouble()), 0.1f, 1.0f);
//frequency2 = skew + frequency;
phase = 0;
phase2 = 0;
phase3 = 0;
}
void OnAudioFilterRead(float[] data, int channels) {
// update increment in case frequency has changed
increment = (frequency + skew + (100.0 * Math.Sin(phase2))) * 2 * Math.PI / sampling_frequency;
increment2 = frequency2 * 2 * Math.PI / sampling_frequency;
increment3 = swellRate * 2 * Math.PI / sampling_frequency;
for (var i = 0; i < data.Length; i = i + channels) {
phase = phase + increment;
phase2 = phase2 + increment2;
phase3 = phase3 + increment3;
// this is where we copy audio data to make them
// "available" to Unity
data[i] = data[i] * (float)(gain * Math.Sin(phase));
data[i] = data[i] * (float)(Math.Abs(Math.Sin(phase3)) * Math.Abs(Math.Sin(phase3)));
// if we have stero, we copy the mono data to each channel
if (channels == 2) data[i + 1] = data[i];
if (phase > 2 * Math.PI) phase = 0;
if (phase2 > 2 * Math.PI) phase2 = 0;
if (phase3 > 2 * Math.PI) phase3 = 0;
}
}
static float midiToFreq(int midi) {
return Mathf.Pow(2.0f, (float)((midi * 1.0f) / 12.0f)) * 440.0f;
}
}
|
using UnityEngine;
using System.Collections;
using System;
public class Sinus : MonoBehaviour {
//unoptimized version
private static System.Random RandomNumber = new System.Random();
public double frequency = 440;
public double frequency2;
public double gain = 0.02;
public double skew;
private double increment;
private double phase;
private double sampling_frequency = 44100;
void Awake() {
skew = (float)Math.Sin((float)RandomNumber.NextDouble()*2.0f*Math.PI) * 2.0f;
frequency2 = skew + frequency;
}
void OnAudioFilterRead(float[] data, int channels) {
// update increment in case frequency has changed
increment = (frequency + skew) * 2 * Math.PI / sampling_frequency;
for (var i = 0; i < data.Length; i = i + channels) {
phase = phase + increment;
// this is where we copy audio data to make them
// "available" to Unity
data[i] = data[i] * (float)(gain * Math.Sin(phase));
// if we have stero, we copy the mono data to each channel
if (channels == 2) data[i + 1] = data[i];
if (phase > 2 * Math.PI) phase = 0;
}
}
}
|
mit
|
C#
|
3fa53f59c5b1dc0c015945288a7e2b7c3814c4cd
|
Remove old commented code
|
mrahhal/MR.AspNetCore.Jobs,mrahhal/MR.AspNetCore.Jobs
|
src/MR.AspNetCore.Jobs.SqlServer/SqlServerStorage.cs
|
src/MR.AspNetCore.Jobs.SqlServer/SqlServerStorage.cs
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MR.AspNetCore.Jobs.Models;
namespace MR.AspNetCore.Jobs
{
public class SqlServerStorage : IStorage
{
private IServiceProvider _provider;
private ILogger _logger;
public SqlServerStorage(
IServiceProvider provider,
ILogger<SqlServerStorage> logger)
{
_provider = provider;
_logger = logger;
}
public async Task InitializeAsync(CancellationToken cancellationToken)
{
using (var scope = _provider.CreateScope())
{
if (cancellationToken.IsCancellationRequested) return;
var provider = scope.ServiceProvider;
var context = provider.GetRequiredService<JobsDbContext>();
_logger.LogDebug("Ensuring all migrations are applied to Jobs database.");
await context.Database.MigrateAsync(cancellationToken);
}
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MR.AspNetCore.Jobs.Models;
namespace MR.AspNetCore.Jobs
{
public class SqlServerStorage : IStorage
{
private IServiceProvider _provider;
private ILogger _logger;
public SqlServerStorage(
IServiceProvider provider,
ILogger<SqlServerStorage> logger)
{
_provider = provider;
_logger = logger;
}
public async Task InitializeAsync(CancellationToken cancellationToken)
{
using (var scope = _provider.CreateScope())
{
if (cancellationToken.IsCancellationRequested) return;
var provider = scope.ServiceProvider;
var context = provider.GetRequiredService<JobsDbContext>();
_logger.LogDebug("Ensuring all migrations are applied to Jobs database.");
await context.Database.MigrateAsync(cancellationToken);
}
}
//public IStorageConnection GetConnection() => _provider.GetRequiredService<IStorageConnection>();
//internal void UseConnection(Action<SqlConnection> action)
//{
// UseConnection(connection =>
// {
// action(connection);
// return true;
// });
//}
//internal T UseConnection<T>(Func<SqlConnection, T> func)
//{
// SqlConnection connection = null;
// try
// {
// connection = CreateAndOpenConnection();
// return func(connection);
// }
// finally
// {
// ReleaseConnection(connection);
// }
//}
//internal Task UseConnectionAsync(Func<SqlConnection, Task> action)
//{
// return UseConnectionAsync(async connection =>
// {
// await action(connection);
// return true;
// });
//}
//internal async Task<T> UseConnectionAsync<T>(Func<SqlConnection, Task<T>> func)
//{
// SqlConnection connection = null;
// try
// {
// connection = CreateAndOpenConnection();
// return await func(connection);
// }
// finally
// {
// ReleaseConnection(connection);
// }
//}
//internal void UseTransaction(Action<SqlConnection, SqlTransaction> action, IsolationLevel? isolationLevel = null)
//{
// UseTransaction((connection, transaction) =>
// {
// action(connection, transaction);
// return true;
// }, isolationLevel);
//}
//internal Task UseTransactionAsync(Func<SqlConnection, SqlTransaction, Task> func, IsolationLevel? isolationLevel = null)
//{
// return UseTransactionAsync(async (connection, transaction) =>
// {
// await func(connection, transaction);
// return true;
// }, isolationLevel);
//}
//internal T UseTransaction<T>(Func<SqlConnection, SqlTransaction, T> func, IsolationLevel? isolationLevel = null)
//{
// return UseConnection(connection =>
// {
// T result;
// using (var transaction = CreateTransaction(connection, isolationLevel))
// {
// result = func(connection, transaction);
// transaction.Commit();
// }
// return result;
// });
//}
//internal async Task<T> UseTransactionAsync<T>(Func<SqlConnection, SqlTransaction, Task<T>> func, IsolationLevel? isolationLevel = null)
//{
// return await UseConnectionAsync(async connection =>
// {
// T result;
// using (var transaction = CreateTransaction(connection, isolationLevel))
// {
// result = await func(connection, transaction);
// transaction.Commit();
// }
// return result;
// });
//}
//internal SqlConnection CreateAndOpenConnection()
//{
// var connection = new SqlConnection(_connectionString);
// connection.Open();
// return connection;
//}
//internal void ReleaseConnection(IDbConnection connection)
//{
// if (connection == null) throw new ArgumentNullException(nameof(connection));
// connection.Dispose();
//}
//private SqlTransaction CreateTransaction(SqlConnection connection, IsolationLevel? isolationLevel)
//{
// return
// isolationLevel == null ?
// connection.BeginTransaction() :
// connection.BeginTransaction(isolationLevel.Value);
//}
}
}
|
mit
|
C#
|
36fa63e68cb50d4c55e074929a8f0bbc84598173
|
simplify path to sln in compiler test
|
scichelli/Nautilus-Build,scichelli/Nautilus-Build
|
src/Nautilus.Tests/BuildInstructionsCompilerTests.cs
|
src/Nautilus.Tests/BuildInstructionsCompilerTests.cs
|
using Should;
namespace Nautilus.Tests
{
public class BuildInstructionsCompilerTests
{
private readonly BuildInstructionsCompiler _buildInstructionsCompiler;
public BuildInstructionsCompilerTests()
{
_buildInstructionsCompiler = new BuildInstructionsCompiler();
}
public void BaselineCompilerTest()
{
var results = _buildInstructionsCompiler.Compile(Instructions);
results.Errors.HasErrors.ShouldBeFalse();
}
public void ReportingCompilerErrors()
{
var results = _buildInstructionsCompiler.Compile(string.Format("{0} invalid code", Instructions));
results.Errors.HasErrors.ShouldBeTrue();
results.Errors.Count.ShouldEqual(1);
}
private const string Instructions = @"
using Nautilus.Framework;
namespace TestToBuild
{
public class SampleBuildInstructions : BuildInstructions
{
private const string _pathToSolution = @"".\src\HelloNautilus.sln"";
public void Default()
{
CompileSolution(_pathToSolution);
RunUnitTests();
}
}
}
";
}
}
|
using Should;
namespace Nautilus.Tests
{
public class BuildInstructionsCompilerTests
{
private readonly BuildInstructionsCompiler _buildInstructionsCompiler;
public BuildInstructionsCompilerTests()
{
_buildInstructionsCompiler = new BuildInstructionsCompiler();
}
public void BaselineCompilerTest()
{
var results = _buildInstructionsCompiler.Compile(Instructions);
results.Errors.HasErrors.ShouldBeFalse();
}
public void ReportingCompilerErrors()
{
var results = _buildInstructionsCompiler.Compile(string.Format("{0} invalid code", Instructions));
results.Errors.HasErrors.ShouldBeTrue();
results.Errors.Count.ShouldEqual(1);
}
private const string Instructions = @"
using Nautilus.Framework;
namespace TestToBuild
{
public class SampleBuildInstructions : BuildInstructions
{
private const string _pathToSolution = @""C:\play\nautilus\Nautilus-Build\Hello-Nautilus\src\HelloNautilus.sln"";
public void Default()
{
CompileSolution(_pathToSolution);
RunUnitTests();
}
}
}
";
}
}
|
mit
|
C#
|
6df6e07f736ec681deed56c8323c40677d632207
|
Add menu bar
|
pleonex/deblocus,pleonex/deblocus
|
Deblocus/MainWindow.Designer.cs
|
Deblocus/MainWindow.Designer.cs
|
//
// MainWindow.Designer.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Reflection;
using Xwt;
using Xwt.Drawing;
using NHibernate.Type;
namespace Deblocus
{
public partial class MainWindow : Window
{
private static readonly Color LightBlue = Color.FromBytes(149, 167, 185);
private ComboBox comboSubject;
private ComboBox comboLesson;
private Button btnSettings;
private void CreateComponents()
{
Width = 800;
Height = 600;
Version version = Assembly.GetExecutingAssembly().GetName().Version;
Title = string.Format("Deblocus - v{0}.{1}.{2}",
version.Major, version.Minor, version.Build);
CloseRequested += HandleCloseRequested;
var menuPanelDivision = new VBox();
menuPanelDivision.BackgroundColor = LightBlue;
menuPanelDivision.PackStart(MakeMenuBar(), margin: 0);
menuPanelDivision.PackStart(MakePanel(), true, margin: 0);
// Set the content
Padding = new WidgetSpacing();
Content = menuPanelDivision;
}
private Widget MakeMenuBar()
{
var menuBox = new HBox();
menuBox.MinHeight = 30;
menuBox.BackgroundColor = Colors.LightPink;
menuBox.Margin = new WidgetSpacing();
var lblSubject = new Label("Subject:");
lblSubject.MarginLeft = 10;
menuBox.PackStart(lblSubject);
comboSubject = new ComboBox();
menuBox.PackStart(comboSubject, vpos: WidgetPlacement.Center);
var lblLesson = new Label("Lesson:");
lblLesson.MarginLeft = 10;
menuBox.PackStart(lblLesson);
comboLesson = new ComboBox();
menuBox.PackStart(comboLesson, vpos: WidgetPlacement.Center);
btnSettings = new Button(StockIcons.Information);
btnSettings.MarginRight = 10;
btnSettings.Style = ButtonStyle.Borderless;
btnSettings.VerticalPlacement = WidgetPlacement.Center;
menuBox.PackEnd(btnSettings);
return menuBox;
}
private Widget MakePanel()
{
var panelBox = new Table();
panelBox.BackgroundColor = LightBlue;
return panelBox;
}
}
}
|
//
// MainWindow.Designer.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using Xwt;
using System.Reflection;
namespace Deblocus
{
public partial class MainWindow : Window
{
private void CreateComponents()
{
Width = 800;
Height = 600;
Version version = Assembly.GetExecutingAssembly().GetName().Version;
Title = string.Format("Deblocus - v{0}.{1}.{2}",
version.Major, version.Minor, version.Build);
CloseRequested += HandleCloseRequested;
}
}
}
|
agpl-3.0
|
C#
|
3d8f88533593b390831600013d585c5aaceffcb4
|
Add getInbox, fix naming on messagesurl
|
justcool393/RedditSharp-1,ekaralar/RedditSharpWindowsStore,RobThree/RedditSharp,angelotodaro/RedditSharp,Jinivus/RedditSharp,theonlylawislove/RedditSharp,nyanpasudo/RedditSharp,IAmAnubhavSaini/RedditSharp,tomnolan95/RedditSharp,SirCmpwn/RedditSharp,pimanac/RedditSharp,epvanhouten/RedditSharp,chuggafan/RedditSharp-1,CrustyJew/RedditSharp
|
RedditSharp/AuthenticatedUser.cs
|
RedditSharp/AuthenticatedUser.cs
|
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace RedditSharp
{
public class AuthenticatedUser : RedditUser
{
private const string ModeratorUrl = "/reddits/mine/moderator.json";
private const string UnreadMessagesUrl = "/message/unread.json?mark=true&limit=25";
private const string ModQueueUrl = "/r/mod/about/modqueue.json";
private const string UnmoderatedUrl = "/r/mod/about/unmoderated.json";
private const string ModMailUrl = "/message/moderator.json";
private const string MessagesUrl = "/message/messages.json";
private const string InboxUrl = "/message/inbox.json";
public AuthenticatedUser(Reddit reddit, JToken json, IWebAgent webAgent) : base(reddit, json, webAgent)
{
JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings);
}
public Listing<Subreddit> GetModeratorReddits()
{
return new Listing<Subreddit>(Reddit, ModeratorUrl, WebAgent);
}
public Listing<Thing> GetUnreadMessages()
{
return new Listing<Thing>(Reddit, UnreadMessagesUrl, WebAgent);
}
public Listing<VotableThing> GetModerationQueue()
{
return new Listing<VotableThing>(Reddit, ModQueueUrl, WebAgent);
}
public Listing<Post> GetUnmoderatedLinks ()
{
return new Listing<Post>(Reddit, UnmoderatedUrl, WebAgent);
}
public Listing<PrivateMessage> GetModMail()
{
return new Listing<PrivateMessage>(Reddit, ModMailUrl, WebAgent);
}
public Listing<PrivateMessage> GetPrivateMessages()
{
return new Listing<PrivateMessage>(Reddit, MessagesUrl, WebAgent);
}
public Listing<PrivateMessage> GetInbox()
{
return new Listing<PrivateMessage>(Reddit, InboxUrl, WebAgent);
}
[JsonProperty("modhash")]
public string Modhash { get; set; }
[JsonProperty("has_mail")]
public bool HasMail { get; set; }
[JsonProperty("has_mod_mail")]
public bool HasModMail { get; set; }
}
}
|
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace RedditSharp
{
public class AuthenticatedUser : RedditUser
{
private const string ModeratorUrl = "/reddits/mine/moderator.json";
private const string UnreadMessagesUrl = "/message/unread.json?mark=true&limit=25";
private const string ModQueueUrl = "/r/mod/about/modqueue.json";
private const string UnmoderatedUrl = "/r/mod/about/unmoderated.json";
private const string ModMailUrl = "/message/moderator.json";
private const string InboxUrl = "/message/messages.json";
public AuthenticatedUser(Reddit reddit, JToken json, IWebAgent webAgent) : base(reddit, json, webAgent)
{
JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings);
}
public Listing<Subreddit> GetModeratorReddits()
{
return new Listing<Subreddit>(Reddit, ModeratorUrl, WebAgent);
}
public Listing<Thing> GetUnreadMessages()
{
return new Listing<Thing>(Reddit, UnreadMessagesUrl, WebAgent);
}
public Listing<VotableThing> GetModerationQueue()
{
return new Listing<VotableThing>(Reddit, ModQueueUrl, WebAgent);
}
public Listing<Post> GetUnmoderatedLinks ()
{
return new Listing<Post>(Reddit, UnmoderatedUrl, WebAgent);
}
public Listing<PrivateMessage> GetModMail()
{
return new Listing<PrivateMessage>(Reddit, ModMailUrl, WebAgent);
}
public Listing<PrivateMessage> GetPrivateMessages()
{
return new Listing<PrivateMessage>(Reddit, InboxUrl, WebAgent);
}
[JsonProperty("modhash")]
public string Modhash { get; set; }
[JsonProperty("has_mail")]
public bool HasMail { get; set; }
[JsonProperty("has_mod_mail")]
public bool HasModMail { get; set; }
}
}
|
mit
|
C#
|
08b0aedeca04b49ae251681981009d1c06918d6b
|
Simplify out when viewing files with no changes
|
terrajobst/git-istage,terrajobst/git-istage
|
src/git-istage/FileDocument.cs
|
src/git-istage/FileDocument.cs
|
using System.Text;
using LibGit2Sharp;
namespace GitIStage;
internal sealed class FileDocument : Document
{
private readonly int _indexOfFirstFile;
private readonly string[] _lines;
private readonly TreeEntryChanges[] _changes;
private FileDocument(int indexOfFirstFile, string[] lines, TreeChanges changes, int width)
{
_indexOfFirstFile = indexOfFirstFile;
_lines = lines;
_changes = changes.ToArray();
Width = width;
}
public override int Height => _lines.Length;
public override int Width { get; }
public override string GetLine(int index)
{
return _lines[index];
}
public TreeEntryChanges GetChange(int index)
{
var changeIndex = index - _indexOfFirstFile;
if (changeIndex < 0 || changeIndex >= _changes.Length)
return null;
return _changes[changeIndex];
}
public static FileDocument Create(string repositoryPath, TreeChanges changes, bool viewStage)
{
var builder = new StringBuilder();
if (changes.Any())
{
builder.AppendLine();
builder.AppendLine(viewStage ? "Changes to be committed:" : "Changes not staged for commit:");
builder.AppendLine();
var indent = new string(' ', 8);
foreach (var c in changes)
{
var path = Path.GetRelativePath(repositoryPath, c.Path);
var change = (c.Status.ToString().ToLower() + ":").PadRight(12);
builder.Append(indent);
builder.Append(change);
builder.Append(path);
builder.AppendLine();
}
}
var indexOfFirstFile = 3;
var lines = builder.ToString().Split(Environment.NewLine);
var width = lines.Select(l => l.Length)
.DefaultIfEmpty(0)
.Max();
return new FileDocument(indexOfFirstFile, lines, changes, width);
}
}
|
using System.Text;
using LibGit2Sharp;
namespace GitIStage;
internal sealed class FileDocument : Document
{
private readonly int _indexOfFirstFile;
private readonly string[] _lines;
private readonly TreeEntryChanges[] _changes;
private FileDocument(int indexOfFirstFile, string[] lines, TreeChanges changes, int width)
{
_indexOfFirstFile = indexOfFirstFile;
_lines = lines;
_changes = changes.ToArray();
Width = width;
}
public override int Height => _lines.Length;
public override int Width { get; }
public override string GetLine(int index)
{
return _lines[index];
}
public TreeEntryChanges GetChange(int index)
{
var changeIndex = index - _indexOfFirstFile;
if (changeIndex < 0 || changeIndex >= _changes.Length)
return null;
return _changes[changeIndex];
}
public static FileDocument Create(string repositoryPath, TreeChanges changes, bool viewStage)
{
var builder = new StringBuilder();
builder.AppendLine();
if (viewStage)
builder.AppendLine("Changes to be committed:");
else
builder.AppendLine("Changes not staged for commit:");
builder.AppendLine();
var indent = new string(' ', 8);
foreach (var c in changes)
{
var path = Path.GetRelativePath(repositoryPath, c.Path);
var change = (c.Status.ToString().ToLower() + ":").PadRight(12);
builder.Append(indent);
builder.Append(change);
builder.Append(path);
builder.AppendLine();
}
var indexOfFirstFile = 3;
var lines = builder.ToString().Split(Environment.NewLine);
var width = lines.Select(l => l.Length)
.DefaultIfEmpty(0)
.Max();
return new FileDocument(indexOfFirstFile, lines, changes, width);
}
}
|
mit
|
C#
|
559aa797da9d4e2475b85bed2935b30914985c36
|
Simplify dictionary reading code - use iterator block, not linq.
|
EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an
|
WikipediaAvsAnTrieExtractor/RegexTextUtils.cs
|
WikipediaAvsAnTrieExtractor/RegexTextUtils.cs
|
using System.Reflection;
using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.IO;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared between threads because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
const RegexOptions options = RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.CultureInvariant;
static readonly Regex firstLetter = new Regex(@"(?<=^[^\s\w]*)\w", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
static string Capitalize(string word) {
return firstLetter.Replace(word, m => m.Value.ToUpperInvariant());
}
static readonly HashSet<string> dictionary;
static IEnumerable<string> ReadWordsFromDictionary(TextReader reader) {
for (var line = reader.ReadLine(); line != null; line = reader.ReadLine()) {
var word = line.Trim();
yield return word;
yield return Capitalize(word);
}
}
static RegexTextUtils() {
var myType = typeof(RegexTextUtils);
using (var dictStream = myType.Assembly.GetManifestResourceStream(myType.Namespace + ".english.ngl"))
using (var reader = new StreamReader(dictStream))
dictionary = new HashSet<string>(ReadWordsFromDictionary(reader));
}
}
}
|
using System.Reflection;
using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.IO;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared between threads because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
const RegexOptions options = RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.CultureInvariant;
static readonly Regex firstLetter = new Regex(@"(?<=^[^\s\w]*)\w", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
static string Capitalize(string word) {
return firstLetter.Replace(word, m => m.Value.ToUpperInvariant());
}
static HashSet<string> dictionary;
static void LoadDictionary(TextReader reader) {
var dictElems =
ReadLines(reader)
.Select(line => line.Trim())
.SelectMany(word => new[] { word, Capitalize(word) });
dictionary = new HashSet<string>(dictElems);
}
static IEnumerable<string> ReadLines(TextReader reader) {
for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
yield return line;
}
const string dictFileName = "english.ngl";
static RegexTextUtils() {
var assembly = typeof(RegexTextUtils).Assembly;
using (var dictStream = assembly.GetManifestResourceStream(typeof(RegexTextUtils).Namespace + ".english.ngl"))
using (var reader = new StreamReader(dictStream))
LoadDictionary(reader);
}
}
}
|
apache-2.0
|
C#
|
26d6f96c4e2decdba1836a98280a2ba6381c379d
|
Fix LabelledTextBox not correctly forwarding focus to its underlying TextBox component
|
NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu
|
osu.Game/Graphics/UserInterfaceV2/LabelledTextBox.cs
|
osu.Game/Graphics/UserInterfaceV2/LabelledTextBox.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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class LabelledTextBox : LabelledComponent<OsuTextBox, string>
{
public event TextBox.OnCommitHandler OnCommit;
public LabelledTextBox()
: base(false)
{
}
public bool ReadOnly
{
set => Component.ReadOnly = value;
}
public string PlaceholderText
{
set => Component.PlaceholderText = value;
}
public string Text
{
set => Component.Text = value;
}
public Container TabbableContentContainer
{
set => Component.TabbableContentContainer = value;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Component.BorderColour = colours.Blue;
}
protected virtual OsuTextBox CreateTextBox() => new OsuTextBox
{
CommitOnFocusLost = true,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
CornerRadius = CORNER_RADIUS,
};
public override bool AcceptsFocus => true;
protected override void OnFocus(FocusEvent e)
{
base.OnFocus(e);
GetContainingInputManager().ChangeFocus(Component);
}
protected override OsuTextBox CreateComponent() => CreateTextBox().With(t =>
{
t.OnCommit += (sender, newText) => OnCommit?.Invoke(sender, newText);
});
}
}
|
// 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class LabelledTextBox : LabelledComponent<OsuTextBox, string>
{
public event TextBox.OnCommitHandler OnCommit;
public LabelledTextBox()
: base(false)
{
}
public bool ReadOnly
{
set => Component.ReadOnly = value;
}
public string PlaceholderText
{
set => Component.PlaceholderText = value;
}
public string Text
{
set => Component.Text = value;
}
public Container TabbableContentContainer
{
set => Component.TabbableContentContainer = value;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Component.BorderColour = colours.Blue;
}
protected virtual OsuTextBox CreateTextBox() => new OsuTextBox
{
CommitOnFocusLost = true,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
CornerRadius = CORNER_RADIUS,
};
protected override OsuTextBox CreateComponent() => CreateTextBox().With(t =>
{
t.OnCommit += (sender, newText) => OnCommit?.Invoke(sender, newText);
});
}
}
|
mit
|
C#
|
f73169702bb98b01a50ced0d8635ba4ac9544e2f
|
Fix fields serialization format
|
elastic/elasticsearch-net,elastic/elasticsearch-net
|
src/Nest/CommonAbstractions/Infer/Field/FieldFormatter.cs
|
src/Nest/CommonAbstractions/Infer/Field/FieldFormatter.cs
|
using Elasticsearch.Net;
namespace Nest
{
internal class FieldFormatter : IJsonFormatter<Field>, IObjectPropertyNameFormatter<Field>
{
private static readonly AutomataDictionary Fields = new AutomataDictionary
{
{ "field", 0 },
{ "boost", 1 },
{ "format", 2 },
};
public Field Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var token = reader.GetCurrentJsonToken();
switch (token)
{
case JsonToken.Null:
reader.ReadNext();
return null;
case JsonToken.String:
return new Field(reader.ReadString());
case JsonToken.BeginObject:
var count = 0;
string field = null;
double? boost = null;
string format = null;
// TODO: include Format in Field ctor
while (reader.ReadIsInObject(ref count))
{
var property = reader.ReadPropertyNameSegmentRaw();
if (Fields.TryGetValue(property, out var value))
{
switch (value)
{
case 0:
field = reader.ReadString();
break;
case 1:
boost = reader.ReadDouble();
break;
case 2:
format = reader.ReadString();
break;
}
}
else
reader.ReadNextBlock();
}
return new Field(field, boost, format);
default:
throw new JsonParsingException($"Cannot deserialize {typeof(Field).FullName} from {token}");
}
}
public void Serialize(ref JsonWriter writer, Field value, IJsonFormatterResolver formatterResolver) =>
Serialize(ref writer, value, formatterResolver, false);
private static void Serialize(ref JsonWriter writer, Field value, IJsonFormatterResolver formatterResolver, bool serializeAsString)
{
if (value == null)
{
writer.WriteNull();
return;
}
var settings = formatterResolver.GetConnectionSettings();
var fieldName = settings.Inferrer.Field(value);
if (serializeAsString || string.IsNullOrEmpty(value.Format))
writer.WriteString(fieldName);
else
{
writer.WriteBeginObject();
writer.WritePropertyName("field");
writer.WriteString(fieldName);
writer.WriteValueSeparator();
writer.WritePropertyName("format");
writer.WriteString(value.Format);
writer.WriteEndObject();
}
}
public void SerializeToPropertyName(ref JsonWriter writer, Field value, IJsonFormatterResolver formatterResolver) =>
Serialize(ref writer, value, formatterResolver, true);
public Field DeserializeFromPropertyName(ref JsonReader reader, IJsonFormatterResolver formatterResolver) =>
Deserialize(ref reader, formatterResolver);
}
}
|
using Elasticsearch.Net;
namespace Nest
{
internal class FieldFormatter : IJsonFormatter<Field>, IObjectPropertyNameFormatter<Field>
{
private static readonly AutomataDictionary Fields = new AutomataDictionary
{
{ "field", 0 },
{ "boost", 1 },
{ "format", 2 },
};
public Field Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var token = reader.GetCurrentJsonToken();
switch (token)
{
case JsonToken.Null:
reader.ReadNext();
return null;
case JsonToken.String:
return new Field(reader.ReadString());
case JsonToken.BeginObject:
var count = 0;
string field = null;
double? boost = null;
string format = null;
// TODO: include Format in Field ctor
while (reader.ReadIsInObject(ref count))
{
var property = reader.ReadPropertyNameSegmentRaw();
if (Fields.TryGetValue(property, out var value))
{
switch (value)
{
case 0:
field = reader.ReadString();
break;
case 1:
boost = reader.ReadDouble();
break;
case 2:
format = reader.ReadString();
break;
}
}
else
reader.ReadNextBlock();
}
return new Field(field, boost);
default:
throw new JsonParsingException($"Cannot deserialize {typeof(Field).FullName} from {token}");
}
}
public void Serialize(ref JsonWriter writer, Field value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
var settings = formatterResolver.GetConnectionSettings();
writer.WriteString(settings.Inferrer.Field(value));
}
public void SerializeToPropertyName(ref JsonWriter writer, Field value, IJsonFormatterResolver formatterResolver) =>
Serialize(ref writer, value, formatterResolver);
public Field DeserializeFromPropertyName(ref JsonReader reader, IJsonFormatterResolver formatterResolver) =>
Deserialize(ref reader, formatterResolver);
}
}
|
apache-2.0
|
C#
|
fc523bdbde7cfeaacce8f7128e775cf112745636
|
Remove extra `public`s from interface
|
TehPers/StardewValleyMods
|
src/TehPers.FishingOverhaul.Api/Effects/IFishingEffect.cs
|
src/TehPers.FishingOverhaul.Api/Effects/IFishingEffect.cs
|
using StardewValley;
namespace TehPers.FishingOverhaul.Api.Effects
{
/// <summary>
/// An effect that can be applied while fishing.
/// </summary>
public interface IFishingEffect
{
/// <summary>
/// Applies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
void Apply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
void Unapply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect from all players.
/// </summary>
void UnapplyAll();
}
}
|
using StardewValley;
namespace TehPers.FishingOverhaul.Api.Effects
{
/// <summary>
/// An effect that can be applied while fishing.
/// </summary>
public interface IFishingEffect
{
/// <summary>
/// Applies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
public void Apply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect.
/// </summary>
/// <param name="fishingInfo">Information about the <see cref="Farmer"/> that is fishing.</param>
public void Unapply(FishingInfo fishingInfo);
/// <summary>
/// Unapplies this effect from all players.
/// </summary>
public void UnapplyAll();
}
}
|
mit
|
C#
|
e749e2e3651ea40969c6a5d6c560f92f2784e8ed
|
Change suffix separator
|
ComputerWorkware/TeamCityApi
|
src/TeamCityApi/Consts.cs
|
src/TeamCityApi/Consts.cs
|
namespace TeamCityApi
{
public class Consts
{
public const string SuffixSeparator = " -- ";
}
}
|
namespace TeamCityApi
{
public class Consts
{
public const string SuffixSeparator = "` ";
}
}
|
mit
|
C#
|
f77b9d101de73f55d8597b649785ac6f782a72fc
|
move pack out to separate step
|
shiftkey/Reactive.EventAggregator
|
build.cake
|
build.cake
|
#tool nuget:?package=xunit.runner.console&version=2.1.0
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
// Define directories.
var buildDir = Directory("./src/Reactive.EventAggregator/Reactive.EventAggregator/bin") + Directory(configuration);
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory(buildDir);
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore("./src/Reactive.EventAggregator.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
MSBuild("./src/Reactive.EventAggregator.sln", settings =>
settings.SetConfiguration(configuration));
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
XUnit2("./src/**/bin/" + configuration + "/*.Tests.dll");
});
Task("Pack")
.IsDependentOn("Run-Unit-Tests")
.Does(() =>
{
// Use MSBuild
MSBuild("./src/Reactive.EventAggregator/Reactive.EventAggregator.csproj", settings =>
settings.SetConfiguration(configuration)
.WithTarget("Pack"));
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Pack");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
#tool nuget:?package=xunit.runner.console&version=2.1.0
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
// Define directories.
var buildDir = Directory("./src/Reactive.EventAggregator/Reactive.EventAggregator/bin") + Directory(configuration);
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory(buildDir);
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore("./src/Reactive.EventAggregator.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
if(IsRunningOnWindows())
{
// Use MSBuild
MSBuild("./src/Reactive.EventAggregator.sln", settings =>
settings.SetConfiguration(configuration));
}
else
{
// Use XBuild
XBuild("./src/Reactive.EventAggregator.sln", settings =>
settings.SetConfiguration(configuration));
}
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
XUnit2("./src/**/bin/" + configuration + "/*.Tests.dll");
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
|
mit
|
C#
|
2f62362261b20504c6b62bd9fc2636b67f97076f
|
use reprap settings as default
|
gradientspace/gsSlicerApps
|
MeshToGCodeDemo/Program.cs
|
MeshToGCodeDemo/Program.cs
|
using System;
using System.IO;
using g3;
using gs;
using gs.info;
namespace MeshToGCodeDemo
{
class Program
{
static void Main(string[] args)
{
CappedCylinderGenerator cylgen = new CappedCylinderGenerator() {
BaseRadius = 10, TopRadius = 5, Height = 20, Slices = 32
};
DMesh3 mesh = cylgen.Generate().MakeDMesh();
MeshTransforms.ConvertYUpToZUp(mesh); // g3 meshes are usually Y-up
// center mesh above origin
AxisAlignedBox3d bounds = mesh.CachedBounds;
Vector3d baseCenterPt = bounds.Center - bounds.Extents.z*Vector3d.AxisZ;
MeshTransforms.Translate(mesh, -baseCenterPt);
// create print mesh set
PrintMeshAssembly meshes = new PrintMeshAssembly();
meshes.AddMesh(mesh, PrintMeshOptions.Default);
// create settings
//MakerbotSettings settings = new MakerbotSettings(Makerbot.Models.Replicator2);
//PrintrbotSettings settings = new PrintrbotSettings(Printrbot.Models.Plus);
//MonopriceSettings settings = new MonopriceSettings(Monoprice.Models.MP_Select_Mini_V2);
RepRapSettings settings = new RepRapSettings(RepRap.Models.Unknown);
// do slicing
MeshPlanarSlicer slicer = new MeshPlanarSlicer() {
LayerHeightMM = settings.LayerHeightMM };
slicer.Add(meshes);
PlanarSliceStack slices = slicer.Compute();
// run print generator
SingleMaterialFFFPrintGenerator printGen =
new SingleMaterialFFFPrintGenerator(meshes, slices, settings);
if ( printGen.Generate() ) {
// export gcode
GCodeFile gcode = printGen.Result;
using (StreamWriter w = new StreamWriter("c:\\demo\\cone.gcode")) {
StandardGCodeWriter writer = new StandardGCodeWriter();
writer.WriteFile(gcode, w);
}
}
}
}
}
|
using System;
using System.IO;
using g3;
using gs;
using gs.info;
namespace MeshToGCodeDemo
{
class Program
{
static void Main(string[] args)
{
CappedCylinderGenerator cylgen = new CappedCylinderGenerator() {
BaseRadius = 10, TopRadius = 5, Height = 20, Slices = 32
};
DMesh3 mesh = cylgen.Generate().MakeDMesh();
MeshTransforms.ConvertYUpToZUp(mesh); // g3 meshes are usually Y-up
// center mesh above origin
AxisAlignedBox3d bounds = mesh.CachedBounds;
Vector3d baseCenterPt = bounds.Center - bounds.Extents.z*Vector3d.AxisZ;
MeshTransforms.Translate(mesh, -baseCenterPt);
// create print mesh set
PrintMeshAssembly meshes = new PrintMeshAssembly();
meshes.AddMesh(mesh, PrintMeshOptions.Default);
// create settings
MakerbotSettings settings = new MakerbotSettings(Makerbot.Models.Replicator2);
//PrintrbotSettings settings = new PrintrbotSettings(Printrbot.Models.Plus);
//MonopriceSettings settings = new MonopriceSettings(Monoprice.Models.MP_Select_Mini_V2);
//RepRapSettings settings = new RepRapSettings(RepRap.Models.Unknown);
// do slicing
MeshPlanarSlicer slicer = new MeshPlanarSlicer() {
LayerHeightMM = settings.LayerHeightMM };
slicer.Add(meshes);
PlanarSliceStack slices = slicer.Compute();
// run print generator
SingleMaterialFFFPrintGenerator printGen =
new SingleMaterialFFFPrintGenerator(meshes, slices, settings);
if ( printGen.Generate() ) {
// export gcode
GCodeFile gcode = printGen.Result;
using (StreamWriter w = new StreamWriter("c:\\demo\\cone.gcode")) {
StandardGCodeWriter writer = new StandardGCodeWriter();
writer.WriteFile(gcode, w);
}
}
}
}
}
|
mit
|
C#
|
541d652427ff84124199699012ee529280a580fc
|
bump pause before running data tests to give db time to come online
|
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
|
tests/FilterLists.Data.Tests/SeedFilterListsDbContextTests.cs
|
tests/FilterLists.Data.Tests/SeedFilterListsDbContextTests.cs
|
using System.Threading;
using FilterLists.Data.Seed.Extensions;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace FilterLists.Data.Tests
{
public class SeedFilterListsDbContextTests
{
[Fact]
public async void SeedOrUpdateAsync_DoesNotThrowException()
{
//TODO: replace with Polly or similar to optimize time waste
// allow time for db to init
Thread.Sleep(20000);
const string connString = "Server=mariadb;Database=filterlists;Uid=filterlists;Pwd=filterlists;";
var options = new DbContextOptionsBuilder<FilterListsDbContext>()
.UseMySql(connString, m => m.MigrationsAssembly("FilterLists.Api"))
.Options;
using (var context = new FilterListsDbContext(options))
{
await context.Database.EnsureCreatedAsync();
await SeedFilterListsDbContext.SeedOrUpdateAsync(context, "../../../data");
}
}
}
}
|
using System.Threading;
using FilterLists.Data.Seed.Extensions;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace FilterLists.Data.Tests
{
public class SeedFilterListsDbContextTests
{
[Fact]
public async void SeedOrUpdateAsync_DoesNotThrowException()
{
//TODO: replace with Polly or similar to optimize time waste
// allow time for db to init
Thread.Sleep(15000);
const string connString = "Server=mariadb;Database=filterlists;Uid=filterlists;Pwd=filterlists;";
var options = new DbContextOptionsBuilder<FilterListsDbContext>()
.UseMySql(connString, m => m.MigrationsAssembly("FilterLists.Api"))
.Options;
using (var context = new FilterListsDbContext(options))
{
await context.Database.EnsureCreatedAsync();
await SeedFilterListsDbContext.SeedOrUpdateAsync(context, "../../../data");
}
}
}
}
|
mit
|
C#
|
75a666b2120593b1690f18d991a523b2575052aa
|
Update DbConnection.cs
|
hMatoba/tetsujin,hMatoba/tetsujin,hMatoba/tetsujin,hMatoba/tetsujin,hMatoba/tetsujin
|
tetsujin/tetsujin/Scripts/DbConnection.cs
|
tetsujin/tetsujin/Scripts/DbConnection.cs
|
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Net.Sockets;
public class DbConnection
{
public static IMongoDatabase Db { get; set; }
public static void Connect(string connectionString, string dbName)
{
var url = new MongoUrl(connectionString);
var clientSettings = MongoClientSettings.FromUrl(url);
Action<Socket> socketConfigurator = s => s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
clientSettings.ClusterConfigurator = cb => cb.ConfigureTcp(tcp => tcp.With(socketConfigurator: socketConfigurator));
var client = new MongoClient(clientSettings);
Db = client.GetDatabase(dbName);
}
}
|
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Net.Sockets;
public class DbConnection
{
public static IMongoDatabase Db { get; set; }
public static void Connect(string connectionString, string dbName)
{
var url = new MongoUrl(connectionString);
var clientSettings = MongoClientSettings.FromUrl(url);
Action<Socket> socketConfigurator = s => s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
clientSettings.ClusterConfigurator = cb => cb.ConfigureTcp(tcp => tcp.With(socketConfigurator: socketConfigurator));
var client = new MongoClient(clientSettings);
Db = client.GetDatabase(dbName);
bool isMongoLive = Db.RunCommandAsync((Command<BsonDocument>)"{ping:1}").Wait(1000);
if (!isMongoLive)
{
throw new Exception("Failed to connect database.");
}
}
}
|
mit
|
C#
|
3cdaccf370c270258dfb61fba792605c569539bb
|
change space to tabs on AndroidKeyAction
|
bitcake/bitstrap
|
Assets/BitStrap/Plugins/Editor/UMake/BuildActions/Scripts/AndroidKeyAction.cs
|
Assets/BitStrap/Plugins/Editor/UMake/BuildActions/Scripts/AndroidKeyAction.cs
|
using UnityEditor;
using UnityEngine;
namespace BitStrap
{
public sealed class AndroidKeyAction : UMakeBuildAction
{
public string keyStoreName = "user.keystore";
public string keyStorePassword = "keyStorePassword";
public string keyAliasName = "aliasName";
public string keyAliasPassword = "keyAliasPassword";
private static string ProjectPath
{
get
{
return Application.dataPath.Remove(Application.dataPath.Length - 6, 6);
}
}
public override void Execute(UMake umake, UMakeTarget target)
{
PlayerSettings.keystorePass = keyStorePassword;
PlayerSettings.keyaliasPass = keyAliasPassword;
PlayerSettings.Android.keystoreName = ProjectPath + keyStoreName;
PlayerSettings.Android.keyaliasName = keyAliasName;
}
}
}
|
using UnityEditor;
using UnityEngine;
namespace BitStrap
{
public sealed class AndroidKeyAction : UMakeBuildAction
{
public string keyStoreName = "user.keystore";
public string keyStorePassword = "keyStorePassword";
public string keyAliasName = "aliasName";
public string keyAliasPassword = "keyAliasPassword";
private static string ProjectPath
{
get
{
return Application.dataPath.Remove(Application.dataPath.Length - 6, 6);
}
}
public override void Execute(UMake umake, UMakeTarget target)
{
PlayerSettings.keystorePass = keyStorePassword;
PlayerSettings.keyaliasPass = keyAliasPassword;
PlayerSettings.Android.keystoreName = ProjectPath + keyStoreName;
PlayerSettings.Android.keyaliasName = keyAliasName;
}
}
}
|
mit
|
C#
|
56204b9165fbcde35690c030c29f2a04b443c117
|
Update WebApiConfig.cs
|
aspnet/WebHooks,aspnet/WebHooks,garora/WebHooks
|
samples/MyGetReceiver/App_Start/WebApiConfig.cs
|
samples/MyGetReceiver/App_Start/WebApiConfig.cs
|
using System.Web.Http;
namespace MyGetReceiver
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Initialize MyGet WebHook receiver
config.InitializeReceiveMyGetWebHooks();
}
}
}
|
using System.Web.Http;
namespace MyGetReceiver
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Initialize Slack WebHook receiver
config.InitializeReceiveMyGetWebHooks();
}
}
}
|
apache-2.0
|
C#
|
60d42fbb44a590640eb54b338dd66b141771079b
|
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
|
autofac/Autofac.Extras.DynamicProxy,jango2015/Autofac.Extras.DynamicProxy
|
Properties/AssemblyInfo.cs
|
Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.DynamicProxy2")]
[assembly: ComVisible(false)]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.DynamicProxy2")]
[assembly: AssemblyDescription("Autofac Castle.DynamicProxy2 Integration")]
[assembly: ComVisible(false)]
|
mit
|
C#
|
ae66264a570c51a02650e187610ef667db091e2d
|
Update AssemblyInfo.cs
|
sarbian/DDSLoader
|
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("DDSLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DDSLoader")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f6bca58e-dd5c-4f90-89dd-7959143459b3")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: KSPAssembly("DDSLoader", 1, 3)]
|
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("DDSLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DDSLoader")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f6bca58e-dd5c-4f90-89dd-7959143459b3")]
// 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.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: KSPAssembly("DDSLoader", 1, 2)]
|
mit
|
C#
|
ca467bafd4b5ba2b2c49897ce93350e67337ec1f
|
Clean up task naming
|
sqeezy/FibonacciHeap,sqeezy/FibonacciHeap
|
build.cake
|
build.cake
|
var target = Argument("target", "Default");
var outputDir = "./bin";
Task("Default")
.IsDependentOn("Test");
Task("Test")
.IsDependentOn("Build")
.Does(()=>
{
DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj");
});
Task("Build")
.IsDependentOn("NugetRestore")
.Does(()=>
{
var settings = new DotNetCoreBuildSettings{Configuration = "Release"};
DotNetCoreBuild("FibonacciHeap.sln", settings);
});
Task("NugetRestore")
.IsDependentOn("Clean")
.Does(()=>
{
DotNetCoreRestore();
});
Task("Clean")
.Does(()=>
{
CleanDirectories("**/bin/**");
CleanDirectories("**/obj/**");
CleanDirectories("nupkgs");
});
RunTarget(target);
|
var target = Argument("target", "Default");
var outputDir = "./bin";
Task("Default")
.IsDependentOn("Xunit");
Task("Xunit")
.IsDependentOn("Build")
.Does(()=>
{
DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj");
});
Task("Build")
.IsDependentOn("NugetRestore")
.Does(()=>
{
var settings = new DotNetCoreBuildSettings{Configuration = "Release"};
DotNetCoreBuild("FibonacciHeap.sln", settings);
});
Task("NugetRestore")
.IsDependentOn("Clean")
.Does(()=>
{
DotNetCoreRestore();
});
Task("Clean")
.Does(()=>
{
CleanDirectories("**/bin/**");
CleanDirectories("**/obj/**");
CleanDirectories("nupkgs");
});
RunTarget(target);
|
mit
|
C#
|
4821be7246b34253d365678acdd3bb3c2f9adaef
|
remove unneeded versioning tasks
|
bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity
|
build.cake
|
build.cake
|
#addin nuget:?package=Cake.Git
#tool "nuget:?package=NUnit.ConsoleRunner"
var target = Argument("target", "Default");
var solution = File("./BugsnagUnity.sln");
var configuration = Argument("configuration", "Release");
var project = File("./src/BugsnagUnity/BugsnagUnity.csproj");
var version = "5.1.0";
Task("Restore-NuGet-Packages")
.Does(() => NuGetRestore(solution));
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() => {
MSBuild(solution, settings =>
settings
.SetVerbosity(Verbosity.Minimal)
.WithProperty("Version", version)
.SetConfiguration(configuration));
});
Task("Test")
.IsDependentOn("Build")
.Does(() => {
var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll");
NUnit3(assemblies);
});
Task("Default")
.IsDependentOn("Test");
RunTarget(target);
|
#addin nuget:?package=Cake.Git
#tool "nuget:?package=NUnit.ConsoleRunner"
var target = Argument("target", "Default");
var solution = File("./BugsnagUnity.sln");
var configuration = Argument("configuration", "Release");
var project = File("./src/BugsnagUnity/BugsnagUnity.csproj");
var version = "5.1.0";
Task("Restore-NuGet-Packages")
.Does(() => NuGetRestore(solution));
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("PopulateVersion")
.Does(() => {
MSBuild(solution, settings =>
settings
.SetVerbosity(Verbosity.Minimal)
.WithProperty("Version", version)
.SetConfiguration(configuration));
});
Task("LocalVersion")
.WithCriteria(BuildSystem.IsLocalBuild)
.Does(() => {
var tag = GitDescribe(".", GitDescribeStrategy.Tags).TrimStart('v');
if (tag.StartsWith("v"))
{
version = tag.TrimStart('v');
}
else
{
version = tag;
}
});
Task("TravisVersion")
.WithCriteria(!BuildSystem.IsLocalBuild)
.Does(() => {
if (string.IsNullOrEmpty(TravisCI.Environment.Build.Tag))
{
version = $"{version}-dev-{TravisCI.Environment.Repository.Commit.Substring(0, 7)}";
}
else
{
version = TravisCI.Environment.Build.Tag.TrimStart('v');
}
});
Task("PopulateVersion")
.IsDependentOn("LocalVersion")
.IsDependentOn("TravisVersion");
Task("Test")
.IsDependentOn("Build")
.Does(() => {
var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll");
NUnit3(assemblies);
});
Task("Default")
.IsDependentOn("Test");
RunTarget(target);
|
mit
|
C#
|
1e7cb3d9ed3ffeb00977cb17fb4846d2c35751ab
|
Fix build
|
Catel/Catel.Fody
|
build.cake
|
build.cake
|
//=======================================================
// DEFINE PARAMETERS
//=======================================================
// Define the required parameters
var Parameters = new Dictionary<string, object>();
Parameters["SolutionName"] = "Catel.Fody";
Parameters["Company"] = "CatenaLogic";
Parameters["RepositoryUrl"] = string.Format("https://github.com/{0}/{1}", GetBuildServerVariable("SolutionName"), GetBuildServerVariable("SolutionName"));
Parameters["StartYear"] = "2010";
// Note: the rest of the variables should be coming from the build server,
// see `/deployment/cake/*-variables.cake` for customization options
//
// If required, more variables can be overridden by specifying them via the
// Parameters dictionary, but the build server variables will always override
// them if defined by the build server. For example, to override the code
// sign wild card, add this to build.cake
//
// Parameters["CodeSignWildcard"] = "Orc.EntityFramework";
//=======================================================
// DEFINE COMPONENTS TO BUILD / PACKAGE
//=======================================================
Components.Add("Catel.Fody");
Components.Add("Catel.Fody.Attributes");
TestProjects.Add(string.Format("{0}.Tests", GetBuildServerVariable("SolutionName")));
//=======================================================
// REQUIRED INITIALIZATION, DO NOT CHANGE
//=======================================================
// Now all variables are defined, include the tasks, that
// script will take care of the rest of the magic
#l "./deployment/cake/tasks.cake"
|
//=======================================================
// DEFINE PARAMETERS
//=======================================================
// Define the required parameters
var Parameters = new Dictionary<string, object>();
Parameters["SolutionName"] = "Catel.Fody";
Parameters["Company"] = "CatenaLogic";
Parameters["RepositoryUrl"] = string.Format("https://github.com/{0}/{1}", GetBuildServerVariable("SolutionName"), GetBuildServerVariable("SolutionName"));
Parameters["StartYear"] = "2010";
// Note: the rest of the variables should be coming from the build server,
// see `/deployment/cake/*-variables.cake` for customization options
//
// If required, more variables can be overridden by specifying them via the
// Parameters dictionary, but the build server variables will always override
// them if defined by the build server. For example, to override the code
// sign wild card, add this to build.cake
//
// Parameters["CodeSignWildcard"] = "Orc.EntityFramework";
//=======================================================
// DEFINE COMPONENTS TO BUILD / PACKAGE
//=======================================================
var ComponentsToBuild = new string[]
{
"Catel.Fody",
"Catel.Fody.Attributes",
};
//=======================================================
// DEFINE WEB APPS TO BUILD / PACKAGE
//=======================================================
var WebAppsToBuild = new string[]
{
};
//=======================================================
// DEFINE WPF APPS TO BUILD / PACKAGE
//=======================================================
var WpfAppsToBuild = new string[]
{
};
//=======================================================
// DEFINE UWP APPS TO BUILD / PACKAGE
//=======================================================
var UwpAppsToBuild = new string[]
{
};
//=======================================================
// DEFINE TEST PROJECTS TO BUILD
//=======================================================
var TestProjectsToBuild = new string[]
{
string.Format("{0}.Tests", GetBuildServerVariable("SolutionName"))
};
//=======================================================
// REQUIRED INITIALIZATION, DO NOT CHANGE
//=======================================================
// Now all variables are defined, include the tasks, that
// script will take care of the rest of the magic
#l "./deployment/cake/tasks.cake"
|
mit
|
C#
|
d4cd35f5f0319880c5d70e8d164a4e0a993bac0e
|
Remove unnecessary tasks.
|
olsh/todoist-net
|
build.cake
|
build.cake
|
#addin "Cake.Incubator"
var target = Argument("target", "Default");
var extensionsVersion = Argument("version", "1.1.4");
var buildConfiguration = "Release";
var projectName = "Todoist.Net";
var testProjectName = "Todoist.Net.Tests";
var projectFolder = string.Format("./src/{0}/", projectName);
var testProjectFolder = string.Format("./src/{0}/", testProjectName);
Task("UpdateBuildVersion")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
var buildNumber = BuildSystem.AppVeyor.Environment.Build.Number;
BuildSystem.AppVeyor.UpdateBuildVersion(string.Format("{0}.{1}", extensionsVersion, buildNumber));
});
Task("NugetRestore")
.Does(() =>
{
DotNetCoreRestore();
});
Task("UpdateAssemblyVersion")
.Does(() =>
{
var assemblyFile = string.Format("{0}/Properties/AssemblyInfo.cs", projectFolder);
AssemblyInfoSettings assemblySettings = new AssemblyInfoSettings();
assemblySettings.Title = projectName;
assemblySettings.FileVersion = extensionsVersion;
assemblySettings.Version = extensionsVersion;
assemblySettings.InternalsVisibleTo = new [] { testProjectName };
CreateAssemblyInfo(assemblyFile, assemblySettings);
});
Task("Build")
.IsDependentOn("NugetRestore")
.IsDependentOn("UpdateAssemblyVersion")
.Does(() =>
{
MSBuild(string.Format("{0}.sln", projectName), new MSBuildSettings {
Verbosity = Verbosity.Minimal,
Configuration = buildConfiguration
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = buildConfiguration
};
DotNetCoreTest(testProjectFolder, settings);
});
Task("NugetPack")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = buildConfiguration,
OutputDirectory = "."
};
DotNetCorePack(projectFolder, settings);
});
Task("CreateArtifact")
.IsDependentOn("NugetPack")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.nupkg", projectName, extensionsVersion));
BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.symbols.nupkg", projectName, extensionsVersion));
});
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("NugetPack");
Task("CI")
.IsDependentOn("UpdateBuildVersion")
.IsDependentOn("Test")
.IsDependentOn("CreateArtifact");
RunTarget(target);
|
#addin "Cake.Incubator"
var target = Argument("target", "Default");
var extensionsVersion = Argument("version", "1.1.4");
var buildConfiguration = "Release";
var projectName = "Todoist.Net";
var testProjectName = "Todoist.Net.Tests";
var projectFolder = string.Format("./src/{0}/", projectName);
var testProjectFolder = string.Format("./src/{0}/", testProjectName);
Task("UpdateBuildVersion")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
var buildNumber = BuildSystem.AppVeyor.Environment.Build.Number;
BuildSystem.AppVeyor.UpdateBuildVersion(string.Format("{0}.{1}", extensionsVersion, buildNumber));
});
Task("NugetRestore")
.Does(() =>
{
DotNetCoreRestore();
});
Task("UpdateAssemblyVersion")
.Does(() =>
{
var assemblyFile = string.Format("{0}/Properties/AssemblyInfo.cs", projectFolder);
AssemblyInfoSettings assemblySettings = new AssemblyInfoSettings();
assemblySettings.Title = projectName;
assemblySettings.FileVersion = extensionsVersion;
assemblySettings.Version = extensionsVersion;
assemblySettings.InternalsVisibleTo = new [] { testProjectName };
CreateAssemblyInfo(assemblyFile, assemblySettings);
});
Task("Build")
.IsDependentOn("NugetRestore")
.IsDependentOn("UpdateAssemblyVersion")
.Does(() =>
{
MSBuild(string.Format("{0}.sln", projectName), new MSBuildSettings {
Verbosity = Verbosity.Minimal,
Configuration = buildConfiguration
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = buildConfiguration
};
var xunitSettings = new XUnit2Settings()
{
OutputDirectory = ".",
XmlReport = true
};
DotNetCoreTest(settings, testProjectFolder, xunitSettings);
});
Task("UploadTestResults")
.IsDependentOn("Test")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
BuildSystem.AppVeyor.UploadTestResults("src.xml", AppVeyorTestResultsType.XUnit);
});
Task("NugetPack")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = buildConfiguration,
OutputDirectory = "."
};
DotNetCorePack(projectFolder, settings);
});
Task("CreateArtifact")
.IsDependentOn("NugetPack")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.nupkg", projectName, extensionsVersion));
BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.symbols.nupkg", projectName, extensionsVersion));
});
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("NugetPack");
Task("CI")
.IsDependentOn("UpdateBuildVersion")
.IsDependentOn("UploadTestResults")
.IsDependentOn("CreateArtifact");
RunTarget(target);
|
mit
|
C#
|
0ba608f677b371a0d652fc67bc50e6fc652e7287
|
update cake
|
jguertl/SharePlugin,jguertl/SharePlugin
|
build.cake
|
build.cake
|
#addin nuget:https://nuget.org/api/v2/?package=Cake.FileHelpers&version=1.0.3.2
#addin nuget:https://nuget.org/api/v2/?package=Cake.Xamarin&version=1.2.3
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Default").Does (() =>
{
const string sln = "./Share.sln";
const string cfg = "Release";
// If the platform is Any build regardless
// If the platform is Win and we are running on windows build
// If the platform is Mac and we are running on Mac, build
if ((sln.Value == "Any")
|| (sln.Value == "Win" && IsRunningOnWindows ())
|| (sln.Value == "Mac" && IsRunningOnUnix ()))
{
// Bit of a hack to use nuget3 to restore packages for project.json
if (IsRunningOnWindows ())
{
Information ("RunningOn: {0}", "Windows");
NuGetRestore (sln.Key, new NuGetRestoreSettings
{
ToolPath = "./tools/nuget3.exe"
});
// Windows Phone / Universal projects require not using the amd64 msbuild
MSBuild (sln.Key, c =>
{
c.Configuration = "Release";
c.MSBuildPlatform = Cake.Common.Tools.MSBuild.MSBuildPlatform.x86;
});
}
else
{
// Mac is easy ;)
NuGetRestore (sln.Key);
DotNetBuild (sln.Key, c => c.Configuration = "Release");
}
}
});
Task ("NuGetPack")
.IsDependentOn ("Default")
.Does (() =>
{
NuGetPack ("./Share.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
ToolPath = "./tools/nuget3.exe"
});
});
RunTarget (TARGET);
|
#addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Default").Does (() =>
{
const string sln = "./Share.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Default")
.Does (() =>
{
NuGetPack ("./Share.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
ToolPath = "./tools/nuget3.exe"
});
});
RunTarget (TARGET);
|
mit
|
C#
|
e651fa9e9094c6ff42231889b6af823e8e9e1623
|
remove unused code in cake file
|
chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,siyo-wang/IdentityServer4,jbijlsma/IdentityServer4,siyo-wang/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,chrisowhite/IdentityServer4,IdentityServer/IdentityServer4,chrisowhite/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4
|
build.cake
|
build.cake
|
var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var packPath = Directory("./src/IdentityServer4");
var sourcePath = Directory("./src");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
var projects = GetFiles("./**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreTestSettings
{
Configuration = configuration
};
if (!IsRunningOnWindows())
{
Information("Not running on Windows - skipping tests for full .NET Framework");
settings.Framework = "netcoreapp1.0";
}
DotNetCoreTest(project.GetDirectory().FullPath, settings);
}
});
Task("Pack")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = buildArtifacts,
};
// add build suffix for CI builds
if(!isLocalBuild)
{
settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0');
}
DotNetCorePack(packPath, settings);
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore(sourcePath, settings);
DotNetCoreRestore(testsPath, settings);
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("RunTests")
.IsDependentOn("Pack");
RunTarget(target);
|
var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var packPath = Directory("./src/IdentityServer4");
var sourcePath = Directory("./src");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
var projects = GetFiles("./**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
//if (!IsRunningOnWindows())
//{
// Information("Not running on Windows - skipping build for full .NET Framework");
// settings.Framework = "netcoreapp1.0";
//}
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreTestSettings
{
Configuration = configuration
};
if (!IsRunningOnWindows())
{
Information("Not running on Windows - skipping tests for full .NET Framework");
settings.Framework = "netcoreapp1.0";
}
DotNetCoreTest(project.GetDirectory().FullPath, settings);
}
});
Task("Pack")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = buildArtifacts,
};
// add build suffix for CI builds
if(!isLocalBuild)
{
settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0');
}
DotNetCorePack(packPath, settings);
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore(sourcePath, settings);
DotNetCoreRestore(testsPath, settings);
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("RunTests")
.IsDependentOn("Pack");
RunTarget(target);
|
apache-2.0
|
C#
|
da42b47a35315c46426314c3ba479bd1b097c4ad
|
move iso copy nupkgs
|
MCGPPeters/Eru,MCGPPeters/Eru
|
build.cake
|
build.cake
|
#tool "nuget:?package=GitVersion.CommandLine"
#tool "nuget:?package=xunit.runner.console&version=2.2.0"
#addin "Cake.FileHelpers"
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var artifactsDir = Directory("./artifacts");
var solution = "./src/Eru.sln";
GitVersion versionInfo = null;
Task("Clean")
.Does(() =>
{
CleanDirectory(artifactsDir);
});
Task("SetVersionInfo")
.IsDependentOn("Clean")
.Does(() =>
{
versionInfo = GitVersion(new GitVersionSettings {
RepositoryPath = "."
});
Information(versionInfo.NuGetVersionV2);
});
Task("RestorePackages")
.IsDependentOn("SetVersionInfo")
.Does(() =>
{
NuGetRestore(solution);
});
Task("Build")
.IsDependentOn("RestorePackages")
.Does(() =>
{
MSBuild(solution, new MSBuildSettings
{
Verbosity = Verbosity.Minimal,
ToolVersion = MSBuildToolVersion.VS2017,
Configuration = configuration,
ArgumentCustomization = args => args.Append("/p:SemVer=" + versionInfo.NuGetVersionV2)
});
});
Task("RunTests")
.IsDependentOn("Build")
.Does(() =>
{
var testAssemblies = GetFiles("./src/**/bin/Release/*.Tests.dll");
XUnit2(testAssemblies,
new XUnit2Settings {
Parallelism = ParallelismOption.All,
HtmlReport = true,
NoAppDomain = true,
OutputDirectory = "./artifacts"
});
});
Task("MovePackages")
.IsDependentOn("Build")
.Does(() =>
{
var files = GetFiles("./src/Eru*/**/*.nupkg");
MoveFiles(files, "./artifacts");
});
Task("NuGetPublish")
.IsDependentOn("MovePackages")
.Does(() =>
{
var APIKey = EnvironmentVariable("NUGETAPIKEY");
var packages = GetFiles("./artifacts/*.nupkg");
NuGetPush(packages, new NuGetPushSettings {
Source = "https://www.nuget.org/api/v2/package",
ApiKey = APIKey
});
});
Task("Default")
.IsDependentOn("RunTests")
.IsDependentOn("NuGetPublish");
RunTarget(target);
|
#tool "nuget:?package=GitVersion.CommandLine"
#tool "nuget:?package=xunit.runner.console&version=2.2.0"
#addin "Cake.FileHelpers"
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var artifactsDir = Directory("./artifacts");
var solution = "./src/Eru.sln";
GitVersion versionInfo = null;
Task("Clean")
.Does(() =>
{
CleanDirectory(artifactsDir);
});
Task("SetVersionInfo")
.IsDependentOn("Clean")
.Does(() =>
{
versionInfo = GitVersion(new GitVersionSettings {
RepositoryPath = "."
});
Information(versionInfo.NuGetVersionV2);
});
Task("RestorePackages")
.IsDependentOn("SetVersionInfo")
.Does(() =>
{
NuGetRestore(solution);
});
Task("Build")
.IsDependentOn("RestorePackages")
.Does(() =>
{
MSBuild(solution, new MSBuildSettings
{
Verbosity = Verbosity.Minimal,
ToolVersion = MSBuildToolVersion.VS2017,
Configuration = configuration,
ArgumentCustomization = args => args.Append("/p:SemVer=" + versionInfo.NuGetVersionV2)
});
});
Task("RunTests")
.IsDependentOn("Build")
.Does(() =>
{
var testAssemblies = GetFiles("./src/**/bin/Release/*.Tests.dll");
XUnit2(testAssemblies,
new XUnit2Settings {
Parallelism = ParallelismOption.All,
HtmlReport = true,
NoAppDomain = true,
OutputDirectory = "./artifacts"
});
});
Task("CopyPackages")
.IsDependentOn("Build")
.Does(() =>
{
var files = GetFiles("./src/Eru*/**/*.nupkg");
CopyFiles(files, "./artifacts");
});
Task("NuGetPublish")
.IsDependentOn("CopyPackages")
.Does(() =>
{
var APIKey = EnvironmentVariable("NUGETAPIKEY");
var packages = GetFiles("./artifacts/*.nupkg");
NuGetPush(packages, new NuGetPushSettings {
Source = "https://www.nuget.org/api/v2/package",
ApiKey = APIKey
});
});
Task("Default")
.IsDependentOn("RunTests")
.IsDependentOn("NuGetPublish");
RunTarget(target);
|
mit
|
C#
|
e1162a87e17d4acf137ce6a13b0bb569a6352b33
|
add restore task before building
|
mderriey/version-release-brown-bag
|
build.cake
|
build.cake
|
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var sourceDirectory = Directory("./src").Path;
var testResultsDirectory = Directory("./test-results").Path;
var artifactsDirectory = Directory("./build-artifacts").Path;
var projectName = "MickaelDerriey.UsefulExtensions";
var testProjectName = "MickaelDerriey.UsefulExtensions.Tests";
var projectsNames = new[] { projectName, testProjectName };
Func<string, string> getProjectDirectoryPath = x =>
{
return sourceDirectory.Combine(x).FullPath;
};
Setup(() =>
{
CreateDirectory(testResultsDirectory);
CreateDirectory(artifactsDirectory);
});
Task("Restore")
.Does(() =>
{
DotNetCoreRestore(sourceDirectory.FullPath);
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
foreach (var projectName in projectsNames)
{
Information("Building {0}...", projectName);
DotNetCoreBuild(getProjectDirectoryPath(projectName), new DotNetCoreBuildSettings
{
Configuration = configuration
});
}
});
Task("UnitTests")
.IsDependentOn("Build")
.Does(() =>
{
Information("Running tests for {0}...", testProjectName);
DotNetCoreTest(getProjectDirectoryPath(testProjectName), new DotNetCoreTestSettings
{
Configuration = configuration,
NoBuild = true,
ArgumentCustomization = x => x
.Append("-xml")
.AppendQuoted(testResultsDirectory.CombineWithFilePath("test-results.xml").FullPath)
});
});
Task("CreatePackages")
.IsDependentOn("UnitTests")
.Does(() =>
{
Information("Creating NuGet package for {0}", projectName);
DotNetCorePack(getProjectDirectoryPath(projectName), new DotNetCorePackSettings
{
Configuration = configuration,
NoBuild = true,
OutputDirectory = artifactsDirectory
});
});
Task("Default")
.IsDependentOn("CreatePackages")
.Does(() =>
{
Information("Hello from the Default task with configuration {0}", configuration);
});
RunTarget(target);
|
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var sourceDirectory = Directory("./src").Path;
var testResultsDirectory = Directory("./test-results").Path;
var artifactsDirectory = Directory("./build-artifacts").Path;
var projectName = "MickaelDerriey.UsefulExtensions";
var testProjectName = "MickaelDerriey.UsefulExtensions.Tests";
var projectsNames = new[] { projectName, testProjectName };
Func<string, string> getProjectDirectoryPath = x =>
{
return sourceDirectory.Combine(x).FullPath;
};
Setup(() =>
{
CreateDirectory(testResultsDirectory);
CreateDirectory(artifactsDirectory);
});
Task("Build")
.Does(() =>
{
foreach (var projectName in projectsNames)
{
Information("Building {0}...", projectName);
DotNetCoreBuild(getProjectDirectoryPath(projectName), new DotNetCoreBuildSettings
{
Configuration = configuration
});
}
});
Task("UnitTests")
.IsDependentOn("Build")
.Does(() =>
{
Information("Running tests for {0}...", testProjectName);
DotNetCoreTest(getProjectDirectoryPath(testProjectName), new DotNetCoreTestSettings
{
Configuration = configuration,
NoBuild = true,
ArgumentCustomization = x => x
.Append("-xml")
.AppendQuoted(testResultsDirectory.CombineWithFilePath("test-results.xml").FullPath)
});
});
Task("CreatePackages")
.IsDependentOn("UnitTests")
.Does(() =>
{
Information("Creating NuGet package for {0}", projectName);
DotNetCorePack(getProjectDirectoryPath(projectName), new DotNetCorePackSettings
{
Configuration = configuration,
NoBuild = true,
OutputDirectory = artifactsDirectory
});
});
Task("Default")
.IsDependentOn("CreatePackages")
.Does(() =>
{
Information("Hello from the Default task with configuration {0}", configuration);
});
RunTarget(target);
|
mit
|
C#
|
e70e8c7235c261205b4d48446fc41b8e43f96e25
|
Remove unused namespaces
|
yonglehou/AttributeRouting,kenny-evitt/AttributeRouting,kenny-evitt/AttributeRouting,modulexcite/AttributeRouting,mccalltd/AttributeRouting,mccalltd/AttributeRouting,yonglehou/AttributeRouting,modulexcite/AttributeRouting
|
src/AttributeRouting.Http/HttpRouteAttribute.cs
|
src/AttributeRouting.Http/HttpRouteAttribute.cs
|
using System;
namespace AttributeRouting.Http
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class HttpRouteAttribute : Attribute, IRouteAttribute
{
public HttpRouteAttribute(string routeUrl, params string[] allowedMethods) {
if (routeUrl == null) throw new ArgumentNullException("routeUrl");
RouteUrl = routeUrl;
HttpMethods = allowedMethods;
Order = int.MaxValue;
Precedence = int.MaxValue;
}
/// <summary>
/// The HttpMethods this route is constrained against.
/// </summary>
public string[] HttpMethods { get; private set; }
/// <summary>
/// The url for this action.
/// </summary>
public string RouteUrl { get; private set; }
/// <summary>
/// The order of this route among all the routes defined against this action.
/// </summary>
public int Order { get; set; }
/// <summary>
/// The order of this route among all the routes defined against this controller.
/// </summary>
public int Precedence { get; set; }
/// <summary>
/// The name this route will be registered with in the RouteTable.
/// </summary>
public string RouteName { get; set; }
/// <summary>
/// If true, the generated route url will be applied from the root, skipping any relevant area name or route prefix.
/// </summary>
public bool IsAbsoluteUrl { get; set; }
/// <summary>
/// Key used by translation provider to lookup the translation for the <see cref="RouteUrl"/>.
/// </summary>
public string TranslationKey { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;
namespace AttributeRouting.Http
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class HttpRouteAttribute : Attribute, IRouteAttribute
{
public HttpRouteAttribute(string routeUrl, params string[] allowedMethods) {
if (routeUrl == null) throw new ArgumentNullException("routeUrl");
RouteUrl = routeUrl;
HttpMethods = allowedMethods;
Order = int.MaxValue;
Precedence = int.MaxValue;
}
/// <summary>
/// The HttpMethods this route is constrained against.
/// </summary>
public string[] HttpMethods { get; private set; }
/// <summary>
/// The url for this action.
/// </summary>
public string RouteUrl { get; private set; }
/// <summary>
/// The order of this route among all the routes defined against this action.
/// </summary>
public int Order { get; set; }
/// <summary>
/// The order of this route among all the routes defined against this controller.
/// </summary>
public int Precedence { get; set; }
/// <summary>
/// The name this route will be registered with in the RouteTable.
/// </summary>
public string RouteName { get; set; }
/// <summary>
/// If true, the generated route url will be applied from the root, skipping any relevant area name or route prefix.
/// </summary>
public bool IsAbsoluteUrl { get; set; }
/// <summary>
/// Key used by translation provider to lookup the translation for the <see cref="RouteUrl"/>.
/// </summary>
public string TranslationKey { get; set; }
}
}
|
mit
|
C#
|
3cc6b86d415093d52114caaf52ed0c3e3116142b
|
add message to monitoring response
|
LykkeCity/bitcoinservice,LykkeCity/bitcoinservice
|
src/BitcoinApi/Controllers/IsAliveController.cs
|
src/BitcoinApi/Controllers/IsAliveController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BitcoinApi.Filters;
using Core.Bitcoin;
using Core.Exceptions;
using Core.Providers;
using Core.Settings;
using LkeServices.Providers;
using Microsoft.AspNetCore.Mvc;
using QBitNinja.Client;
namespace BitcoinApi.Controllers
{
[Route("api/[controller]")]
public class IsAliveController : Controller
{
private readonly IRpcBitcoinClient _rpcClient;
private readonly Func<QBitNinjaClient> _qbitninja;
private readonly Func<SignatureApiProviderType, ISignatureApi> _signatureApiFactory;
public IsAliveController(IRpcBitcoinClient rpcClient, Func<QBitNinjaClient> qbitninja, Func<SignatureApiProviderType, ISignatureApi> signatureApiFactory)
{
_rpcClient = rpcClient;
_qbitninja = qbitninja;
_signatureApiFactory = signatureApiFactory;
}
[HttpGet]
public async Task<IActionResult> Get()
{
if (!await CheckSigninService(SignatureApiProviderType.Client))
return BadRequest(new { Message = "Client signin service is down" });
if (!await CheckSigninService(SignatureApiProviderType.Exchange))
return BadRequest(new { Message = "Server signin service is down" });
return Ok(new IsAliveResponse
{
Version = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion
});
}
private async Task<bool> CheckSigninService(SignatureApiProviderType type)
{
try
{
await _signatureApiFactory(type).IsAlive();
return true;
}
catch
{
// ignored
}
return false;
}
[HttpGet("rpc")]
public async Task RpcAlive()
{
await _rpcClient.GetBlockCount();
}
[HttpGet("ninja")]
public async Task NinjaAlive()
{
await _qbitninja().GetBlock(new QBitNinja.Client.Models.BlockFeature(1));
}
public class IsAliveResponse
{
public string Version { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Core.Bitcoin;
using Core.Providers;
using Core.Settings;
using LkeServices.Providers;
using Microsoft.AspNetCore.Mvc;
using QBitNinja.Client;
namespace BitcoinApi.Controllers
{
[Route("api/[controller]")]
public class IsAliveController : Controller
{
private readonly IRpcBitcoinClient _rpcClient;
private readonly Func<QBitNinjaClient> _qbitninja;
private readonly Func<SignatureApiProviderType, ISignatureApi> _signatureApiFactory;
private readonly BaseSettings _settings;
public IsAliveController(IRpcBitcoinClient rpcClient, Func<QBitNinjaClient> qbitninja, Func<SignatureApiProviderType, ISignatureApi> signatureApiFactory, BaseSettings settings)
{
_rpcClient = rpcClient;
_qbitninja = qbitninja;
_signatureApiFactory = signatureApiFactory;
_settings = settings;
}
[HttpGet]
public async Task<IsAliveResponse> Get()
{
await _signatureApiFactory(SignatureApiProviderType.Client).IsAlive();
await _signatureApiFactory(SignatureApiProviderType.Exchange).IsAlive();
return new IsAliveResponse
{
Version = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion
};
}
[HttpGet("rpc")]
public async Task RpcAlive()
{
await _rpcClient.GetBlockCount();
}
[HttpGet("ninja")]
public async Task NinjaAlive()
{
await _qbitninja().GetBlock(new QBitNinja.Client.Models.BlockFeature(1));
}
public class IsAliveResponse
{
public string Version { get; set; }
}
}
}
|
mit
|
C#
|
0de2ecc747ec078389727ae70be40a015cdcf31b
|
comment edit
|
DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod
|
Terraria_Server/Statics.cs
|
Terraria_Server/Statics.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Terraria_Server
{
public static class Statics
{
public static int build = 4;
public static bool cmdMessages = true;
public static bool debugMode = false;
public static int platform = 0;
public static bool isLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
public static string getWorldPath
{
get
{
return Statics.SavePath + systemSeperator + "Worlds";
}
}
public static string getPlayerPath
{
get
{
return Statics.SavePath + systemSeperator + "Players";
}
}
public static string getPluginPath
{
get
{
return Statics.SavePath + systemSeperator + "Plugins";
}
}
public static string getDataPath
{
get
{
return Statics.SavePath + systemSeperator + "Data";
}
}
public static string systemSeperator = "\\";
public static string SavePath = Environment.CurrentDirectory;
public static int currentRelease = 9;
public static string versionNumber = "v1.0.4";
public static bool IsActive = false;
public static bool IsFixedTimeStep = false;
public static bool serverStarted = false;
public static int fidefault = (int)((double)Main.maxTilesX * 0.0008); // need to find better place for this?
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Terraria_Server
{
public static class Statics
{
public static int build = 4;
public static bool cmdMessages = true;
public static bool debugMode = false;
public static int platform = 0;
public static bool isLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
public static string getWorldPath
{
get
{
return Statics.SavePath + systemSeperator + "Worlds";
}
}
public static string getPlayerPath
{
get
{
return Statics.SavePath + systemSeperator + "Players";
}
}
public static string getPluginPath
{
get
{
return Statics.SavePath + systemSeperator + "Plugins";
}
}
public static string getDataPath
{
get
{
return Statics.SavePath + systemSeperator + "Data";
}
}
public static string systemSeperator = "\\";
public static string SavePath = Environment.CurrentDirectory;
public static int currentRelease = 9;
public static string versionNumber = "v1.0.4";
public static bool IsActive = false;
public static bool IsFixedTimeStep = false;
public static bool serverStarted = false;
public static int fidefault = (int)((double)Main.maxTilesX * 0.0008);
}
}
|
mit
|
C#
|
65dddb5f57e740da3e292d3f53802808288dcb70
|
Add class LuryExceptionStrings
|
HaiTo/lury,nokok/lury,lury-lang/lury
|
src/Lury/Runtime/Exception/LuryExceptionType.cs
|
src/Lury/Runtime/Exception/LuryExceptionType.cs
|
//
// LuryExceptionType.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Lury.Runtime
{
public enum LuryExceptionType
{
Unknown = -1,
NilReference,
DivideByZero,
NotSupportedOperation,
NotEnoughFunctionArgumentNumber,
WrongBreak,
ConditionValueIsNotBoolean,
AttributeIsNotFound,
WrongLValue,
}
public static class LuryExceptionStrings
{
public static string GetMessage(this LuryExceptionType type, params object[] messageParams)
{
return String.Format(GetRawMessage(type), messageParams);
}
private static string GetRawMessage(LuryExceptionType type)
{
switch (type)
{
case LuryExceptionType.NilReference:
return "nil オブジェクトにはアクセスできません.";
case LuryExceptionType.DivideByZero:
return "整数値はゼロで除算できません.";
case LuryExceptionType.NotSupportedOperation:
return "'{0}' 操作を '{1}' と '{2}' 型の値に適用できません.";
case LuryExceptionType.NotEnoughFunctionArgumentNumber:
return "関数の引数の数が一致しません. '{0}' 関数は {1} 個の引数を受けますが、{2} 個の引数で呼び出されています.";
case LuryExceptionType.WrongBreak:
return "不正な break が存在します.";
case LuryExceptionType.ConditionValueIsNotBoolean:
return "条件の式は Boolean 型である必要があります. {0} 型が指定されています.";
case LuryExceptionType.AttributeIsNotFound:
return "存在しないオブジェクトを参照しました. '{0}' に属性 '{1}' は存在しません.";
case LuryExceptionType.WrongLValue:
return "'{0}' に代入できません.";
default:
return "不明なエラーです.";
}
}
}
}
|
//
// LuryExceptionType.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Lury.Runtime
{
public enum LuryExceptionType
{
Unknown = -1,
NilReference,
DivideByZero,
NotSupportedOperation,
NotEnoughFunctionArgumentNumber,
WrongBreak,
ConditionValueIsNotBoolean,
AttributeIsNotFound,
WrongLValue,
}
}
|
mit
|
C#
|
7c03a69e4d7977972b976af4a14b5dba0aae85b7
|
Change TaskFile to store rows as Strings.
|
jcheng31/todoPad
|
TodoPad/Models/TaskFile.cs
|
TodoPad/Models/TaskFile.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TodoPad.Models
{
class TaskFile
{
public String Path { get; set; }
public String[] Rows { get; set; }
public TaskFile(String path, String contents)
{
Path = path;
Rows = contents.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TodoPad.Models
{
class TaskFile
{
public String Path { get; set; }
public List<Row> Rows { get; set; }
public TaskFile(String path, String contents)
{
Path = path;
String[] lines = contents.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
Rows = new List<Row>(lines.Length);
foreach (string currentLine in lines)
{
Row currentRow = new Row(currentLine);
Rows.Add(currentRow);
}
}
}
}
|
mit
|
C#
|
aca0d881ecbf4ccc09d18135883808a76bed13af
|
Add webhooks to the client interface.
|
kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,ZA1/csharp-sparkpost,SparkPost/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost
|
src/SparkPost/IClient.cs
|
src/SparkPost/IClient.cs
|
namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets access to the webhooks resource of the SparkPost API.
/// </summary>
IWebhooks Webhooks { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
}
}
|
namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
}
}
|
apache-2.0
|
C#
|
b0ae2c345b8aebfe8d0671b522fc3ae2ac4e290a
|
Add more info when EqualTolerance() assert fails
|
anjdreas/UnitsNet,anjdreas/UnitsNet
|
UnitsNet.Tests/AssertEx.cs
|
UnitsNet.Tests/AssertEx.cs
|
using Xunit;
namespace UnitsNet.Tests
{
/// <summary>
/// Additional assert methods to XUnit's <see cref="Xunit.Assert" />.
/// </summary>
public static class AssertEx
{
public static void EqualTolerance(double expected, double actual, double tolerance)
{
Assert.True(actual >= expected - tolerance && actual <= expected + tolerance, $"Values are not equal within tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}");
}
}
}
|
using Xunit;
namespace UnitsNet.Tests
{
/// <summary>
/// Additional assert methods to XUnit's <see cref="Xunit.Assert" />.
/// </summary>
public static class AssertEx
{
public static void EqualTolerance(double expected, double actual, double tolerance)
{
Assert.True(actual >= expected - tolerance && actual <= expected + tolerance, "Within tolerance: " + tolerance);
}
}
}
|
mit
|
C#
|
7abf9d4363b63c18d1e428e801975fba96e62dff
|
create file locator from factory
|
vorou/play.NET,vorou/play.NET
|
Src/playNET.App/Bootstrapper.cs
|
Src/playNET.App/Bootstrapper.cs
|
using System.IO;
using Nancy;
using Nancy.TinyIoc;
namespace playNET.App
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register<Player>().AsSingleton();
container.Register<Singer>().AsSingleton();
container.Register((c, o) => new FileLocator(Path.GetTempPath())).AsSingleton();
}
}
}
|
using System.IO;
using Nancy;
using Nancy.TinyIoc;
namespace playNET.App
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register<Player>().AsSingleton();
container.Register<Singer>().AsSingleton();
container.Register(new FileLocator(Path.GetTempPath())).AsSingleton();
}
}
}
|
mit
|
C#
|
4046f07839495c751ceadf5db8446b01bb6b1b37
|
Sort battle roster by group, then by position desc
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
BatteryCommander.Web/Controllers/BattleRosterController.cs
|
BatteryCommander.Web/Controllers/BattleRosterController.cs
|
using BatteryCommander.Common;
using BatteryCommander.Common.Models;
using BatteryCommander.Web.Models;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BatteryCommander.Web.Controllers
{
public class BattleRosterController : BaseController
{
private readonly DataContext _db;
public BattleRosterController(UserManager<AppUser, int> userManager, DataContext db)
: base(userManager)
{
_db = db;
}
[Route("BattleRoster")]
public async Task<ActionResult> Show()
{
return View(new BattleRosterModel
{
Soldiers = await _db
.Soldiers
.Include(s => s.Qualifications)
.Where(s => s.Status == SoldierStatus.Active)
.OrderBy(s => s.Group)
.ThenByDescending(s => s.Position)
.ToListAsync(),
Qualifications = await _db
.Qualifications
.Where(q => q.ParentTaskId == null)
.ToListAsync()
});
}
}
}
|
using BatteryCommander.Common;
using BatteryCommander.Common.Models;
using BatteryCommander.Web.Models;
using Microsoft.AspNet.Identity;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BatteryCommander.Web.Controllers
{
public class BattleRosterController : BaseController
{
private readonly DataContext _db;
public BattleRosterController(UserManager<AppUser, int> userManager, DataContext db)
: base(userManager)
{
_db = db;
}
[Route("BattleRoster")]
public async Task<ActionResult> Show()
{
return View(new BattleRosterModel
{
Soldiers = await _db
.Soldiers
.Include(s => s.Qualifications)
.Where(s => s.Status == SoldierStatus.Active)
.OrderBy(s => s.Group)
.ThenBy(s => s.Rank)
.ToListAsync(),
Qualifications = await _db
.Qualifications
.Where(q => q.ParentTaskId == null)
.ToListAsync()
});
}
}
}
|
mit
|
C#
|
c7bc14ecce5ab744fec39f64b05709c27e8c3a97
|
Fix example 4 code
|
suvroc/selenium-mail-course,ronlouw/selenium-mail-course,Bartty9/selenium-mail-course,osieckiAdam/selenium-mail-course
|
EndToEndMailCourse/EndToEndMailCourse/04/Example04Tests.cs
|
EndToEndMailCourse/EndToEndMailCourse/04/Example04Tests.cs
|
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace EndToEndMailCourse._04
{
[TestFixture]
public class Example04Tests
{
private string testUrl = "https://suvroc.github.io/selenium-mail-course/04/example.html";
[Test]
public void ShouldTestExamplePage()
{
var driver = new ChromeDriver();
driver.Navigate().GoToUrl(testUrl);
var firstPage = new ExamplePage1(driver);
firstPage.Input1.SendKeys("Test text 1");
firstPage.Input2.SendKeys("Test text 2");
firstPage.Input3.SendKeys("Test text 3");
firstPage.NextButton.Click();
Assert.AreEqual(driver.Url, "https://suvroc.github.io/selenium-mail-course/04/example1.html");
var secondPage = new ExamplePage2(driver);
secondPage.BackButton.Click();
Assert.AreEqual(driver.Url, "https://suvroc.github.io/selenium-mail-course/04/example.html");
driver.Quit();
}
}
public class ExamplePage1
{
private readonly IWebDriver _driver;
public ExamplePage1(IWebDriver driver)
{
_driver = driver;
}
public IWebElement Input1
{
get { return _driver.FindElement(By.Id("input1")); }
}
public IWebElement Input2
{
get { return _driver.FindElement(By.Id("input2")); }
}
public IWebElement Input3
{
get { return _driver.FindElement(By.Id("input3")); }
}
public IWebElement NextButton
{
get { return _driver.FindElement(By.Id("nextButton")); }
}
}
public class ExamplePage2
{
private readonly IWebDriver _driver;
public ExamplePage2(IWebDriver driver)
{
_driver = driver;
}
public IWebElement BackButton
{
get { return _driver.FindElement(By.Id("backButton")); }
}
}
}
|
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace EndToEndMailCourse._04
{
[TestFixture]
public class Example04Tests
{
private string testUrl = "https://suvroc.github.io/selenium-mail-course/04/example.html";
[Test]
public void ShouldTestExamplePage()
{
var driver = new ChromeDriver();
driver.Navigate().GoToUrl(testUrl);
var firstPage = new ExamplePage1(driver);
firstPage.Input1.SendKeys("Test text 1");
firstPage.Input2.SendKeys("Test text 2");
firstPage.Input3.SendKeys("Test text 3");
firstPage.NextButton.Click();
Assert.AreEqual(driver.Url, "http://diwebsity.com/test/04/example1.html");
var secondPage = new ExamplePage2(driver);
secondPage.BackButton.Click();
Assert.AreEqual(driver.Url, "http://diwebsity.com/test/04/example.html");
driver.Quit();
}
}
public class ExamplePage1
{
private readonly IWebDriver _driver;
public ExamplePage1(IWebDriver driver)
{
_driver = driver;
}
public IWebElement Input1
{
get { return _driver.FindElement(By.Id("input1")); }
}
public IWebElement Input2
{
get { return _driver.FindElement(By.Id("input2")); }
}
public IWebElement Input3
{
get { return _driver.FindElement(By.Id("input3")); }
}
public IWebElement NextButton
{
get { return _driver.FindElement(By.Id("nextButton")); }
}
}
public class ExamplePage2
{
private readonly IWebDriver _driver;
public ExamplePage2(IWebDriver driver)
{
_driver = driver;
}
public IWebElement BackButton
{
get { return _driver.FindElement(By.Id("backButton")); }
}
}
}
|
mit
|
C#
|
d1774fbcdd789bcd5420c8b410c7f1391bbbd0b5
|
Add request body test
|
stoiveyp/Alexa.NET.Management
|
Tests/Alexa.NET.Management.Tests/UtteranceProfilerTests.cs
|
Tests/Alexa.NET.Management.Tests/UtteranceProfilerTests.cs
|
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Alexa.NET.Management.Api;
using Alexa.NET.Management.UtteranceProfiler;
using Newtonsoft.Json;
using Xunit;
namespace Alexa.NET.Management.Tests
{
public class UtteranceProfilerTests
{
[Fact]
public async Task AnalyzeGeneratesCorrectUrl()
{
var management = new ManagementApi("xxx", new ActionHandler(req =>
{
Assert.Equal(HttpMethod.Post, req.Method);
Assert.Equal("/v1/skills/skillId/stages/development/interactionModel/locales/en-GB/profileNlu", req.RequestUri.PathAndQuery);
},new UtteranceProfilerResponse()));
await management.UtteranceProfiler.Analyze("skillId",SkillStage.DEVELOPMENT,"en-GB","test");
}
[Fact]
public async Task AnalyzeGeneratesCorrectBody()
{
var management = new ManagementApi("xxx", new ActionHandler(async req =>
{
var body = JsonConvert.DeserializeObject<UtteranceProfilerRequest>(
await req.Content.ReadAsStringAsync());
Assert.Equal("test",body.Utterance);
Assert.Equal("test2",body.MultiTurnToken);
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject(new UtteranceProfilerResponse()))
};
}));
await management.UtteranceProfiler.Analyze("skillId", SkillStage.DEVELOPMENT, "en-GB", "test","test2");
}
}
}
|
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Alexa.NET.Management.Api;
using Alexa.NET.Management.UtteranceProfiler;
using Xunit;
namespace Alexa.NET.Management.Tests
{
public class UtteranceProfilerTests
{
[Fact]
public async Task AnalyzeCreatesCorrectUrl()
{
var management = new ManagementApi("xxx", new ActionHandler(req =>
{
Assert.Equal(HttpMethod.Post, req.Method);
Assert.Equal("/v1/skills/skillId/stages/development/interactionModel/locales/en-GB/profileNlu", req.RequestUri.PathAndQuery);
},new UtteranceProfilerResponse()));
var response = await management.UtteranceProfiler.Analyze("skillId",SkillStage.DEVELOPMENT,"en-GB","test");
}
}
}
|
mit
|
C#
|
12db7874cc36c4075512a6a29362df6928361546
|
Add getMe bot method
|
Dsouzavl/Talkative
|
src/Talkative/Bot.cs
|
src/Talkative/Bot.cs
|
using System;
using System.Text.RegularExpressions;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace Talkative
{
internal class Bot
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
private string _baseUrl { get; set; }
private string _token { get; set; }
private HttpClient _client { get; set;}
public Bot(string token, string baseUrl = null){
if(ValidateToken(token) == false){
throw new Exception("Invalid token");
};
_token = token;
if(baseUrl != null){
_baseUrl = baseUrl;
};
_baseUrl = "https://api.telegram.org/bot";
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Add("Talkative request",".NET Standard telegram bot client");
}
public async Task<Bot> GetMe(){
var url = _baseUrl + $"{_token}/getMe";
var requestResult = await _client.GetAsync(url);
var bot = JsonConvert.DeserializeObject<Bot>(await requestResult.Content.ReadAsStringAsync());
return bot;
}
private bool ValidateToken(string token){
var leftSide = token.Split(':');
var numCatch = new Regex(@"\d*");
if(token.Contains(" ") || !numCatch.Match(leftSide[0]).Success || leftSide[0].Length < 3){
return false;
}
return true;
}
}
}
|
using System;
using System.Text.RegularExpressions;
using System.Net.Http;
using Newtonsoft.Json;
namespace Talkative
{
internal class Bot
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
private string _baseUrl { get; set; }
private string _token { get; set; }
private HttpClient _client { get; set;}
public Bot(string token, string baseUrl = null){
if(ValidateToken(token) == false){
throw new Exception("Invalid token");
};
_token = token;
if(baseUrl != null){
_baseUrl = baseUrl;
};
_baseUrl = "https://api.telegram.org/bot";
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Add("Talkative request",".NET Standard telegram bot client");
}
public Bot GetMe(){
var url = _baseUrl + $"{_token}/getMe";
using(_client){
var request = _client.GetAsync(url);
var result= await request;
JsonConvert.DeserializeObject<Bot>(requestResult);
}
}
private bool ValidateToken(string token){
var leftSide = token.Split(':');
var numCatch = new Regex(@"\d*");
if(token.Contains(" ") || !numCatch.Match(leftSide[0]).Success || leftSide[0].Length < 3){
return false;
}
return true;
}
}
}
|
mit
|
C#
|
aa07b42acbe15436823024d22f11347f82c0aaaf
|
increment to 2.1.0
|
adamralph/xbehave.net,mvalipour/xbehave.net,mvalipour/xbehave.net,xbehave/xbehave.net
|
src/VersionInfo.2.cs
|
src/VersionInfo.2.cs
|
// <copyright file="VersionInfo.2.cs" company="xBehave.net contributors">
// Copyright (c) xBehave.net contributors. All rights reserved.
// </copyright>
using System.Reflection;
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]
|
// <copyright file="VersionInfo.2.cs" company="xBehave.net contributors">
// Copyright (c) xBehave.net contributors. All rights reserved.
// </copyright>
using System.Reflection;
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
|
mit
|
C#
|
67abdc8eba810a9b018626e7b004ec8c06b35bb1
|
Validate volatile scope in VolatileContext.Resolve.
|
pzavolinsky/Autocore
|
Autocore/Implementation/VolatileContext.cs
|
Autocore/Implementation/VolatileContext.cs
|
// The MIT License (MIT)
//
// Copyright (c) 2014 Patricio Zavolinsky
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
namespace Autocore.Implementation
{
public class VolatileContext : IVolatileContext
{
IImplicitContext _context;
public VolatileContext(IImplicitContext context)
{
_context = context;
}
public T Resolve<T>() where T : IVolatileDependency
{
if (_context.Container == null)
{
throw new InvalidOperationException("Attempted to access a volatile dependency outside a volatile scope. Consider wrapping this code in a call to IContainer.ExecuteInVolatileScope");
}
return _context.Container.Resolve<T>();
}
}
}
|
// The MIT License (MIT)
//
// Copyright (c) 2014 Patricio Zavolinsky
//
// 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.
//
namespace Autocore.Implementation
{
public class VolatileContext : IVolatileContext
{
IImplicitContext _context;
public VolatileContext(IImplicitContext context)
{
_context = context;
}
public T Resolve<T>() where T : IVolatileDependency
{
return _context.Container.Resolve<T>();
}
}
}
|
mit
|
C#
|
5025c2be0a1e9edda6a5ab07be7d862aeb0ef9be
|
Comment code
|
mstrother/BmpListener
|
BmpListener/Bgp/SubsequentAddressFamily.cs
|
BmpListener/Bgp/SubsequentAddressFamily.cs
|
namespace BmpListener.Bgp
{
// http://www.iana.org/assignments/safi-namespace/safi-namespace.xhtml
public enum SubsequentAddressFamily
{
Unicast = 1,
Multicast = 2
}
}
|
namespace BmpListener.Bgp
{
public enum SubsequentAddressFamily
{
Unicast = 1,
Multicast = 2
}
}
|
mit
|
C#
|
90c0338ed6406a44015fbe9a547dbe6b932f0e5c
|
Return ShaderContent for built-in shader stages.
|
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
|
ChamberLib.OpenTK/BuiltinShaderImporter.cs
|
ChamberLib.OpenTK/BuiltinShaderImporter.cs
|
using System;
using ChamberLib.Content;
namespace ChamberLib.OpenTK
{
public class BuiltinShaderImporter
{
public BuiltinShaderImporter(ShaderImporter next, ShaderStageImporter next2)
{
if (next == null) throw new ArgumentNullException("next");
if (next2 == null) throw new ArgumentNullException("next2");
this.next = next;
this.next2 = next2;
}
readonly ShaderImporter next;
readonly ShaderStageImporter next2;
public ShaderContent ImportShader(string filename, IContentImporter importer)
{
if (filename == "$basic")
{
return BuiltinShaders.BasicShaderContent;
}
if (filename == "$skinned")
{
return BuiltinShaders.SkinnedShaderContent;
}
return next(filename, importer);
}
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (filename == "$basic")
{
if (type != ShaderType.Vertex)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$basic\"");
return BuiltinShaders.BasicVertexShaderContent;
}
if (filename == "$skinned")
{
if (type != ShaderType.Vertex)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$skinned\"");
return BuiltinShaders.SkinnedVertexShaderContent;
}
if (filename == "$fragment")
{
if (type != ShaderType.Fragment)
throw new ArgumentOutOfRangeException(
"type",
"Wrong shader type for built-in shader \"$fragment\"");
return BuiltinShaders.BuiltinFragmentShaderContent;
}
return next2(filename, type, importer);
}
}
}
|
using System;
using ChamberLib.Content;
namespace ChamberLib.OpenTK
{
public class BuiltinShaderImporter
{
public BuiltinShaderImporter(ShaderImporter next, ShaderStageImporter next2)
{
if (next == null) throw new ArgumentNullException("next");
if (next2 == null) throw new ArgumentNullException("next2");
this.next = next;
this.next2 = next2;
}
readonly ShaderImporter next;
readonly ShaderStageImporter next2;
public ShaderContent ImportShader(string filename, IContentImporter importer)
{
if (filename == "$basic")
{
return BuiltinShaders.BasicShaderContent;
}
if (filename == "$skinned")
{
return BuiltinShaders.SkinnedShaderContent;
}
return next(filename, importer);
}
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (filename == "$basic")
{
throw new NotImplementedException("ImportShaderStage $basic");
}
if (filename == "$skinned")
{
throw new NotImplementedException("ImportShaderStage $skinned");
}
return next2(filename, type, importer);
}
}
}
|
lgpl-2.1
|
C#
|
782f87a82d0ff3fe9c3574116df429b93d3523d3
|
Throw ArgumentNullException.
|
alastairs/cgowebsite,alastairs/cgowebsite
|
src/CGO.Web.Tests/Controllers/UserControllerFacts.cs
|
src/CGO.Web.Tests/Controllers/UserControllerFacts.cs
|
using System;
using CGO.Web.Controllers;
using CGO.Web.Infrastructure;
using NSubstitute;
using NUnit.Framework;
using MvcContrib.TestHelper;
namespace CGO.Web.Tests.Controllers
{
class UserControllerFacts
{
[TestFixture]
public class ConstructorShould
{
[Test]
public void ThrowAnArgumentNullExceptionWhenTheFormsAuthenticationServiceIsNull()
{
Assert.That(() => new UserController(null), Throws.InstanceOf<ArgumentNullException>());
}
}
[TestFixture]
public class LoginShould
{
[Test]
public void DisplayTheLoginView()
{
var controller = new UserController(Substitute.For<IFormsAuthenticationService>());
var result = controller.Login();
result.AssertViewRendered().ForView("Login");
}
}
[TestFixture]
public class LogoutShould
{
[Test]
public void ClearTheAuthenticationCookie()
{
var formsAuthentication = Substitute.For<IFormsAuthenticationService>();
var controller = new UserController(formsAuthentication);
controller.Logout();
formsAuthentication.Received().SignOut();
}
[Test]
public void ReturnARedirectResult()
{
var controller = new UserController(Substitute.For<IFormsAuthenticationService>());
var result = controller.Logout();
result.AssertActionRedirect();
}
[Test]
public void RedirectToTheHomePage()
{
var controller = new UserController(Substitute.For<IFormsAuthenticationService>());
var result = controller.Logout();
result.AssertActionRedirect().ToAction((HomeController h) => h.Index());
}
}
}
}
|
using CGO.Web.Controllers;
using CGO.Web.Infrastructure;
using NSubstitute;
using NUnit.Framework;
using MvcContrib.TestHelper;
namespace CGO.Web.Tests.Controllers
{
class UserControllerFacts
{
[TestFixture]
public class LoginShould
{
[Test]
public void DisplayTheLoginView()
{
var controller = new UserController(Substitute.For<IFormsAuthenticationService>());
var result = controller.Login();
result.AssertViewRendered().ForView("Login");
}
}
[TestFixture]
public class LogoutShould
{
[Test]
public void ClearTheAuthenticationCookie()
{
var formsAuthentication = Substitute.For<IFormsAuthenticationService>();
var controller = new UserController(formsAuthentication);
controller.Logout();
formsAuthentication.Received().SignOut();
}
[Test]
public void ReturnARedirectResult()
{
var controller = new UserController(Substitute.For<IFormsAuthenticationService>());
var result = controller.Logout();
result.AssertActionRedirect();
}
[Test]
public void RedirectToTheHomePage()
{
var controller = new UserController(Substitute.For<IFormsAuthenticationService>());
var result = controller.Logout();
result.AssertActionRedirect().ToAction((HomeController h) => h.Index());
}
}
}
}
|
mit
|
C#
|
af2acbcd368ac4411eefa426e1cf92e3af4d0772
|
Make mutable struct members readonly.
|
mysql-net/MySqlConnector,mysql-net/MySqlConnector
|
src/MySqlConnector/MySql.Data.Types/MySqlDateTime.cs
|
src/MySqlConnector/MySql.Data.Types/MySqlDateTime.cs
|
using System;
namespace MySql.Data.Types
{
public struct MySqlDateTime : IComparable
{
public MySqlDateTime(int year, int month, int day, int hour, int minute, int second, int microsecond)
{
Year = year;
Month = month;
Day = day;
Hour = hour;
Minute = minute;
Second = second;
Microsecond = microsecond;
}
public MySqlDateTime(DateTime dt)
: this(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, (int) (dt.Ticks % 10_000_000) / 10)
{
}
public MySqlDateTime(MySqlDateTime other)
{
Year = other.Year;
Month = other.Month;
Day = other.Day;
Hour = other.Hour;
Minute = other.Minute;
Second = other.Second;
Microsecond = other.Microsecond;
}
public readonly bool IsValidDateTime => Year != 0 && Month != 0 && Day != 0;
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public int Hour { get; set; }
public int Minute { get; set; }
public int Second { get; set; }
public int Microsecond { get; set; }
public int Millisecond
{
get => Microsecond / 1000;
set => Microsecond = value * 1000;
}
public readonly DateTime GetDateTime() =>
!IsValidDateTime ? throw new MySqlConversionException("Cannot convert MySqlDateTime to DateTime when IsValidDateTime is false.") :
new DateTime(Year, Month, Day, Hour, Minute, Second, DateTimeKind.Unspecified).AddTicks(Microsecond * 10);
public readonly override string ToString() => IsValidDateTime ? GetDateTime().ToString() : "0000-00-00";
public static explicit operator DateTime(MySqlDateTime val) => !val.IsValidDateTime ? DateTime.MinValue : val.GetDateTime();
readonly int IComparable.CompareTo(object? obj)
{
if (!(obj is MySqlDateTime other))
throw new ArgumentException("CompareTo can only be called with another MySqlDateTime", nameof(obj));
if (Year < other.Year)
return -1;
if (Year > other.Year)
return 1;
if (Month < other.Month)
return -1;
if (Month > other.Month)
return 1;
if (Day < other.Day)
return -1;
if (Day > other.Day)
return 1;
if (Hour < other.Hour)
return -1;
if (Hour > other.Hour)
return 1;
if (Minute < other.Minute)
return -1;
if (Minute > other.Minute)
return 1;
if (Second < other.Second)
return -1;
if (Second > other.Second)
return 1;
return Microsecond.CompareTo(other.Microsecond);
}
}
}
|
using System;
namespace MySql.Data.Types
{
public struct MySqlDateTime : IComparable
{
public MySqlDateTime(int year, int month, int day, int hour, int minute, int second, int microsecond)
{
Year = year;
Month = month;
Day = day;
Hour = hour;
Minute = minute;
Second = second;
Microsecond = microsecond;
}
public MySqlDateTime(DateTime dt)
: this(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, (int) (dt.Ticks % 10_000_000) / 10)
{
}
public MySqlDateTime(MySqlDateTime other)
{
Year = other.Year;
Month = other.Month;
Day = other.Day;
Hour = other.Hour;
Minute = other.Minute;
Second = other.Second;
Microsecond = other.Microsecond;
}
public bool IsValidDateTime => Year != 0 && Month != 0 && Day != 0;
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public int Hour { get; set; }
public int Minute { get; set; }
public int Second { get; set; }
public int Microsecond { get; set; }
public int Millisecond
{
get => Microsecond / 1000;
set => Microsecond = value * 1000;
}
public DateTime GetDateTime() =>
!IsValidDateTime ? throw new MySqlConversionException("Cannot convert MySqlDateTime to DateTime when IsValidDateTime is false.") :
new DateTime(Year, Month, Day, Hour, Minute, Second, DateTimeKind.Unspecified).AddTicks(Microsecond * 10);
public override string ToString() => IsValidDateTime ? GetDateTime().ToString() : "0000-00-00";
public static explicit operator DateTime(MySqlDateTime val) => !val.IsValidDateTime ? DateTime.MinValue : val.GetDateTime();
int IComparable.CompareTo(object? obj)
{
if (!(obj is MySqlDateTime other))
throw new ArgumentException("CompareTo can only be called with another MySqlDateTime", nameof(obj));
if (Year < other.Year)
return -1;
if (Year > other.Year)
return 1;
if (Month < other.Month)
return -1;
if (Month > other.Month)
return 1;
if (Day < other.Day)
return -1;
if (Day > other.Day)
return 1;
if (Hour < other.Hour)
return -1;
if (Hour > other.Hour)
return 1;
if (Minute < other.Minute)
return -1;
if (Minute > other.Minute)
return 1;
if (Second < other.Second)
return -1;
if (Second > other.Second)
return 1;
return Microsecond.CompareTo(other.Microsecond);
}
}
}
|
mit
|
C#
|
0b1429cded35cf3b7b3337beeeb8c56bc2a1c080
|
Add Public to build target
|
jinyuliao/GenericGraph,jinyuliao/GenericGraph,jinyuliao/GenericGraph
|
Source/GenericGraphEditor/GenericGraphEditor.Build.cs
|
Source/GenericGraphEditor/GenericGraphEditor.Build.cs
|
using UnrealBuildTool;
public class GenericGraphEditor : ModuleRules
{
public GenericGraphEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
bLegacyPublicIncludePaths = false;
ShadowVariableWarningLevel = WarningLevel.Error;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
"GenericGraphEditor/Private",
"GenericGraphEditor/Public",
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UnrealEd",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"GenericGraphRuntime",
"AssetTools",
"Slate",
"SlateCore",
"GraphEditor",
"PropertyEditor",
"EditorStyle",
"Kismet",
"KismetWidgets",
"ApplicationCore",
"ToolMenus",
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}
|
using UnrealBuildTool;
public class GenericGraphEditor : ModuleRules
{
public GenericGraphEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
bLegacyPublicIncludePaths = false;
ShadowVariableWarningLevel = WarningLevel.Error;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
"GenericGraphEditor/Private",
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"UnrealEd",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"GenericGraphRuntime",
"AssetTools",
"Slate",
"SlateCore",
"GraphEditor",
"PropertyEditor",
"EditorStyle",
"Kismet",
"KismetWidgets",
"ApplicationCore",
"ToolMenus",
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}
|
mit
|
C#
|
39463c8dd07d5d6fa4d1d1040e049ae0a30d29ee
|
Use AllFlags constant in TypeInfo extension
|
pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,Microsoft/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet
|
Test/CoreSDK.Test/Net40/System/Reflection/TypeInfo.cs
|
Test/CoreSDK.Test/Net40/System/Reflection/TypeInfo.cs
|
using System.Collections.Generic;
namespace System.Reflection
{
internal class TypeInfo
{
private const BindingFlags AllFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
private Type type;
public TypeInfo(Type type)
{
this.type = type;
}
public bool IsPublic => type.IsPublic;
public bool IsSealed => type.IsSealed;
public bool IsGenericType => type.IsGenericType;
public bool IsAbstract => type.IsAbstract;
public bool IsValueType => type.IsValueType;
public bool IsAssignableFrom(TypeInfo typeInfo) => type.IsAssignableFrom(typeInfo.type);
public Type GetGenericTypeDefinition() => type.GetGenericTypeDefinition();
public Assembly Assembly => type.Assembly;
public string Name => type.Name;
public Type[] GenericTypeArguments => type.GetGenericArguments();
public IEnumerable<ConstructorInfo> DeclaredConstructors => type.GetConstructors(AllFlags);
public PropertyInfo GetDeclaredProperty(string name) => type.GetProperty(name, AllFlags);
public MethodInfo GetDeclaredMethod(string name) => type.GetMethod(name, AllFlags);
}
}
|
using System.Collections.Generic;
namespace System.Reflection
{
internal class TypeInfo
{
public const BindingFlags AllFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
private Type type;
public TypeInfo(Type type)
{
this.type = type;
}
public bool IsPublic => type.IsPublic;
public bool IsSealed => type.IsSealed;
public bool IsGenericType => type.IsGenericType;
public bool IsAbstract => type.IsAbstract;
public bool IsValueType => type.IsValueType;
public bool IsAssignableFrom(TypeInfo typeInfo) => type.IsAssignableFrom(typeInfo.type);
public Type GetGenericTypeDefinition() => type.GetGenericTypeDefinition();
public Assembly Assembly => type.Assembly;
public string Name => type.Name;
public Type[] GenericTypeArguments => type.GetGenericArguments();
public IEnumerable<ConstructorInfo> DeclaredConstructors => type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public PropertyInfo GetDeclaredProperty(string name) => type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
public MethodInfo GetDeclaredMethod(string name) => type.GetMethod(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
}
}
|
mit
|
C#
|
1f4a1872512a6d810d905ded980cf3594844bb40
|
Support listing charges by PaymentIntent id
|
richardlawley/stripe.net,stripe/stripe-dotnet
|
src/Stripe.net/Services/Charges/ChargeListOptions.cs
|
src/Stripe.net/Services/Charges/ChargeListOptions.cs
|
namespace Stripe
{
using System;
using Newtonsoft.Json;
public class ChargeListOptions : ListOptionsWithCreated
{
/// <summary>
/// Only return charges for the customer specified by this customer ID.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// Only return charges that were created by the PaymentIntent specified by this
/// PaymentIntent ID.
/// </summary>
[JsonProperty("payment_intent")]
public string PaymentIntentId { get; set; }
[Obsolete("This parameter is deprecated. Filter the returned list of charges instead.")]
[JsonProperty("source")]
public ChargeSourceListOptions Source { get; set; }
/// <summary>
/// Only return charges for this transfer group.
/// </summary>
[JsonProperty("transfer_group")]
public string TransferGroup { get; set; }
}
}
|
namespace Stripe
{
using Newtonsoft.Json;
public class ChargeListOptions : ListOptionsWithCreated
{
[JsonProperty("customer")]
public string CustomerId { get; set; }
[JsonProperty("source")]
public ChargeSourceListOptions Source { get; set; }
}
}
|
apache-2.0
|
C#
|
631d084a33694696cd75729642842afd47488e08
|
allow RecursiveFileEnumerator to enumerate a single file
|
GNOME/f-spot,Sanva/f-spot,mono/f-spot,Sanva/f-spot,nathansamson/F-Spot-Album-Exporter,mono/f-spot,nathansamson/F-Spot-Album-Exporter,mans0954/f-spot,mans0954/f-spot,mono/f-spot,mono/f-spot,mono/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,mans0954/f-spot,GNOME/f-spot,dkoeb/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,mono/f-spot,Yetangitu/f-spot,dkoeb/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,Yetangitu/f-spot,GNOME/f-spot,Yetangitu/f-spot,mans0954/f-spot,Sanva/f-spot,GNOME/f-spot,dkoeb/f-spot,Yetangitu/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,dkoeb/f-spot,mans0954/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,NguyenMatthieu/f-spot
|
src/Utils/RecursiveFileEnumerator.cs
|
src/Utils/RecursiveFileEnumerator.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using GLib;
namespace FSpot.Utils
{
public class RecursiveFileEnumerator : IEnumerable<File>
{
Uri root;
bool recurse;
public RecursiveFileEnumerator (Uri root) : this (root, true)
{
}
public RecursiveFileEnumerator (Uri root, bool recurse)
{
this.root = root;
this.recurse = recurse;
}
IEnumerable<File> ScanForFiles (File root)
{
var root_info = root.QueryInfo ("standard::name,standard::type", FileQueryInfoFlags.None, null);
if (root_info.FileType == FileType.Regular) {
yield return root;
} else if (root_info.FileType == FileType.Directory) {
foreach (var child in ScanDirectoryForFiles (root)) {
yield return child;
}
}
}
IEnumerable<File> ScanDirectoryForFiles (File root_dir)
{
var enumerator = root_dir.EnumerateChildren ("standard::name,standard::type", FileQueryInfoFlags.None, null);
foreach (FileInfo info in enumerator) {
File file = root_dir.GetChild (info.Name);
if (info.FileType == FileType.Regular) {
yield return file;
} else if (info.FileType == FileType.Directory && recurse) {
foreach (var child in ScanDirectoryForFiles (file)) {
yield return child;
}
}
info.Dispose ();
}
enumerator.Close (null);
}
public IEnumerator<File> GetEnumerator ()
{
var file = FileFactory.NewForUri (root);
return ScanForFiles (file).GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using GLib;
namespace FSpot.Utils
{
public class RecursiveFileEnumerator : IEnumerable<File>
{
Uri root;
bool recurse;
public RecursiveFileEnumerator (Uri root) : this (root, true)
{
}
public RecursiveFileEnumerator (Uri root, bool recurse)
{
this.root = root;
this.recurse = recurse;
}
IEnumerable<File> ScanForFiles (File root)
{
var enumerator = root.EnumerateChildren ("standard::name,standard::type", FileQueryInfoFlags.None, null);
foreach (FileInfo info in enumerator) {
File file = root.GetChild (info.Name);
if (info.FileType == FileType.Regular) {
yield return file;
} else if (info.FileType == FileType.Directory && recurse) {
foreach (var child in ScanForFiles (file)) {
yield return child;
}
}
info.Dispose ();
}
enumerator.Close (null);
}
public IEnumerator<File> GetEnumerator ()
{
var file = FileFactory.NewForUri (root);
return ScanForFiles (file).GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
}
|
mit
|
C#
|
ed6a0cbb06cec276a52423632b875f499f8866fb
|
update encoder
|
ceee/ReadSharp,alexeib/ReadSharp
|
ReadSharp/Encodings/Encoder.cs
|
ReadSharp/Encodings/Encoder.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReadSharp.Encodings
{
public class Encoder
{
/// <summary>
/// All available custom encodings
/// </summary>
private static Dictionary<string, string> customEncodings = new Dictionary<string, string>()
{
{ "windows-1250", "Windows1250" }
};
/// <summary>
/// Initializes a new instance of the <see cref="Encoder"/> class.
/// </summary>
public Encoder()
{
}
/// <summary>
/// Gets the encoding from string.
/// </summary>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
public Encoding GetEncodingFromString(string encoding)
{
Encoding correctEncoding = null;
if (!String.IsNullOrEmpty(encoding))
{
// try get encoding from string
try
{
correctEncoding = Encoding.GetEncoding(encoding);
}
catch (ArgumentException)
{
// encoding not found in environment
// handled in finally block as it could also generate null without throwing exceptions
}
finally
{
// use a custom encoder
if (correctEncoding == null)
{
try
{
KeyValuePair<string, string> customEncoder = customEncodings.FirstOrDefault(item => item.Key == encoding.ToLower());
if (!String.IsNullOrEmpty(customEncoder.Value))
{
Type encoderType = Type.GetType("ReadSharp.Encodings." + customEncoder.Value);
if (encoderType != null)
{
correctEncoding = (Encoding)System.Activator.CreateInstance(Type.GetType("ReadSharp.Encodings." + customEncoder.Value));
}
}
}
catch (Exception)
{
// couldn't create instance for whatever reason.
// nothing to do here, as the default encoder will be used in the program.
}
}
}
}
return correctEncoding;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReadSharp.Encodings
{
public class Encoder
{
/// <summary>
/// All available custom encodings
/// </summary>
private static Dictionary<string, string> customEncodings = new Dictionary<string, string>()
{
{ "windows-1250", "Windows1250" }
};
/// <summary>
/// Initializes a new instance of the <see cref="Encoder"/> class.
/// </summary>
public Encoder()
{
}
/// <summary>
/// Gets the encoding from string.
/// </summary>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
public Encoding GetEncodingFromString(string encoding)
{
Encoding correctEncoding = null;
if (!String.IsNullOrEmpty(encoding))
{
try
{
correctEncoding = Encoding.GetEncoding(encoding);
throw new Exception();
}
catch
{
KeyValuePair<string, string> customEncoder = customEncodings.FirstOrDefault(item => item.Key == encoding.ToLower());
if (!String.IsNullOrEmpty(customEncoder.Value))
{
correctEncoding = (Encoding)System.Activator.CreateInstance(Type.GetType("ReadSharp.Encodings." + customEncoder.Value));
}
else
{
correctEncoding = null;
}
}
}
return correctEncoding;
}
}
}
|
mit
|
C#
|
e6fea23a34395c4e449cd9e1cf61ec77540e4f9a
|
Update AppCenterExceptionTelemeter.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Framework.SharedMobile/Analytics/Telemetry/AppCenterExceptionTelemeter.cs
|
TIKSN.Framework.SharedMobile/Analytics/Telemetry/AppCenterExceptionTelemeter.cs
|
using System;
using System.Threading.Tasks;
using Microsoft.AppCenter;
namespace TIKSN.Analytics.Telemetry
{
public class AppCenterExceptionTelemeter : IExceptionTelemeter
{
public Task TrackExceptionAsync(Exception exception)
{
return TrackExceptionAsync(exception, TelemetrySeverityLevel.Information);
}
public Task TrackExceptionAsync(Exception exception, TelemetrySeverityLevel severityLevel)
{
switch (severityLevel)
{
case TelemetrySeverityLevel.Verbose:
AppCenterLog.Verbose(AppCenterLog.LogTag, exception.Message, exception);
break;
case TelemetrySeverityLevel.Information:
AppCenterLog.Info(AppCenterLog.LogTag, exception.Message, exception);
break;
case TelemetrySeverityLevel.Warning:
AppCenterLog.Warn(AppCenterLog.LogTag, exception.Message, exception);
break;
case TelemetrySeverityLevel.Error:
case TelemetrySeverityLevel.Critical:
AppCenterLog.Error(AppCenterLog.LogTag, exception.Message, exception);
break;
default:
throw new ArgumentOutOfRangeException(nameof(severityLevel));
}
return Task.CompletedTask;
}
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.AppCenter;
namespace TIKSN.Analytics.Telemetry
{
public class AppCenterExceptionTelemeter : IExceptionTelemeter
{
public Task TrackException(Exception exception)
{
return TrackException(exception, TelemetrySeverityLevel.Information);
}
public Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel)
{
switch (severityLevel)
{
case TelemetrySeverityLevel.Verbose:
AppCenterLog.Verbose(AppCenterLog.LogTag, exception.Message, exception);
break;
case TelemetrySeverityLevel.Information:
AppCenterLog.Info(AppCenterLog.LogTag, exception.Message, exception);
break;
case TelemetrySeverityLevel.Warning:
AppCenterLog.Warn(AppCenterLog.LogTag, exception.Message, exception);
break;
case TelemetrySeverityLevel.Error:
case TelemetrySeverityLevel.Critical:
AppCenterLog.Error(AppCenterLog.LogTag, exception.Message, exception);
break;
default:
throw new ArgumentOutOfRangeException(nameof(severityLevel));
}
return Task.CompletedTask;
}
}
}
|
mit
|
C#
|
aecc135d9c7afb9914b74c4c83eee7a8afa99625
|
Extend test for Jobs list
|
LordMike/TMDbLib
|
TMDbLibTests/ClientJobTests.cs
|
TMDbLibTests/ClientJobTests.cs
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TMDbLib.Objects.General;
namespace TMDbLibTests
{
[TestClass]
public class ClientJobTests
{
private TestConfig _config;
/// <summary>
/// Run once, on every test
/// </summary>
[TestInitialize]
public void Initiator()
{
_config = new TestConfig();
}
[TestMethod]
public void TestJobList()
{
List<Job> jobs = _config.Client.GetJobs();
Assert.IsNotNull(jobs);
Assert.IsTrue(jobs.Count > 0);
Assert.IsTrue(jobs.All(job => !string.IsNullOrEmpty(job.Department)));
Assert.IsTrue(jobs.All(job => job.JobList != null));
Assert.IsTrue(jobs.All(job => job.JobList.Count > 0));
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TMDbLib.Objects.General;
namespace TMDbLibTests
{
[TestClass]
public class ClientJobTests
{
private TestConfig _config;
/// <summary>
/// Run once, on every test
/// </summary>
[TestInitialize]
public void Initiator()
{
_config = new TestConfig();
}
[TestMethod]
public void TestJobList()
{
List<Job> jobs = _config.Client.GetJobs();
Assert.IsNotNull(jobs);
Assert.IsTrue(jobs.Count > 0);
Assert.IsTrue(jobs.All(job => job.JobList != null));
Assert.IsTrue(jobs.All(job => job.JobList.Count > 0));
}
}
}
|
mit
|
C#
|
59b24078ea10ba5d84f12fae6e4cc804b2ad8d90
|
fix MoneyUtils
|
linfx/LinFx,linfx/LinFx
|
src/LinFx/Utils/MoneyUtils.cs
|
src/LinFx/Utils/MoneyUtils.cs
|
using System;
namespace LinFx.Utils
{
public static class MoneyUtils
{
/// <summary>
/// 元转分
/// </summary>
/// <param name="yuan"></param>
/// <returns></returns>
public static string ToFen(decimal yuan)
{
int result = (int)(yuan * 100);
return result.ToString();
}
/// <summary>
/// 分转元
/// </summary>
/// <param name="fen"></param>
/// <returns></returns>
public static double ToYuan(int fen)
{
int result = fen / 100;
return result;
}
/// <summary>
/// 保留两位小数
/// </summary>
/// <param name="amt"></param>
/// <returns></returns>
public static string ToN2String(decimal amt)
{
return string.Format("{0:N2}", amt);
}
/// <summary>
/// 截取两位小数
/// </summary>
/// <param name="amt"></param>
/// <returns></returns>
public static decimal Truncate(decimal amt)
{
if (amt < 0)
throw new Exception("金额不能为负数!");
if (amt < 0.01m)
return 0;
amt = Math.Truncate(amt * 100) / 100;
return amt;
}
}
public static class MoneyEx
{
/// <summary>
/// 货币表示,带有逗号分隔符,默认小数点后保留两位,四舍五入
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static string ToMoneyString(this decimal d)
{
return string.Format("{0:C}", d);
}
public static decimal ToMoneyDecimal(this string amt)
{
decimal.TryParse(amt, out decimal tmpAmt);
return tmpAmt;
}
}
}
|
using System;
namespace LinFx.Utils
{
public static class MoneyUtils
{
public static string ToFen(decimal yuan)
{
int result = (int)(yuan * 100);
return result.ToString();
}
/// <summary>
/// 保留两位小数
/// </summary>
/// <param name="amt"></param>
/// <returns></returns>
public static string ToN2String(decimal amt)
{
return string.Format("{0:N2}", amt);
}
/// <summary>
/// 截取两位小数
/// </summary>
/// <param name="amt"></param>
/// <returns></returns>
public static decimal Truncate(decimal amt)
{
if (amt < 0)
throw new Exception("金额不能为负数!");
if (amt < 0.01m)
return 0;
amt = Math.Truncate(amt * 100) / 100;
return amt;
}
}
public static class MoneyEx
{
/// <summary>
/// 货币表示,带有逗号分隔符,默认小数点后保留两位,四舍五入
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static string ToMoneyString(this decimal d)
{
return string.Format("{0:C}", d);
}
public static decimal ToMoneyDecimal(this string amt)
{
decimal.TryParse(amt, out decimal tmpAmt);
return tmpAmt;
}
}
}
|
mit
|
C#
|
afd50052fc96cb8b1f1f241363d63e4f4b2302b3
|
Update ImageKey.cs
|
Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
src/Core2D/Renderer/ImageKey.cs
|
src/Core2D/Renderer/ImageKey.cs
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Core2D.Renderer
{
/// <summary>
/// Image key.
/// </summary>
public struct ImageKey
{
/// <summary>
/// Gets or sets image key.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Check whether the <see cref="Key"/> property has changed from its default value.
/// </summary>
/// <returns>Returns true if the property has changed; otherwise, returns false.</returns>
public bool ShouldSerializeKey() => !String.IsNullOrWhiteSpace(Key);
}
}
|
// 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.
namespace Core2D.Renderer
{
/// <summary>
/// Image key.
/// </summary>
public struct ImageKey
{
/// <summary>
/// Gets or sets image key.
/// </summary>
public string Key { get; set; }
}
}
|
mit
|
C#
|
d9792e28f8b4e572d079448b4133506864e740e6
|
implement MilkHttpClient.Post
|
masaru-b-cl/MilkSharp
|
src/MilkSharp/MilkHttpClient.cs
|
src/MilkSharp/MilkHttpClient.cs
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace MilkSharp
{
public class MilkHttpClient : IMilkHttpClient
{
public async Task<MilkHttpResponseMessage> Post(string url, IDictionary<string, string> parameters)
{
var httpClient = new HttpClient();
var httpContent = new FormUrlEncodedContent(parameters);
var httpResponseMessage = await httpClient.PostAsync(url, httpContent);
var responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
var result = new MilkHttpResponseMessage
{
Status = httpResponseMessage.StatusCode,
Content = responseContent
};
return await Task.FromResult(result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MilkSharp
{
public class MilkHttpClient : IMilkHttpClient
{
public async Task<MilkHttpResponseMessage> Post(string url, IDictionary<string, string> parameters)
{
return await Task.FromResult(new MilkHttpResponseMessage());
}
}
}
|
mit
|
C#
|
0f05588ab183d4627a0d7213d7bea40a519a7f23
|
Revert "Update comment to reflect possible config.json path"
|
Workshop2/noobot,noobot/noobot
|
src/Noobot.Runner/NoobotHost.cs
|
src/Noobot.Runner/NoobotHost.cs
|
using System;
using Common.Logging;
using Noobot.Core;
using Noobot.Core.Configuration;
using Noobot.Core.DependencyResolution;
namespace Noobot.Runner
{
/// <summary>
/// NoobotHost is required due to TopShelf.
/// </summary>
public class NoobotHost
{
private readonly IConfigReader _configReader;
private readonly ILog _logger;
private INoobotCore _noobotCore;
/// <summary>
/// Default constructor will use the default ConfigReader from Core.Configuration
/// and look for the configuration file at .\configuration\config.json
/// </summary>
public NoobotHost() : this(new ConfigReader()) { }
public NoobotHost(IConfigReader configReader)
{
_configReader = configReader;
_logger = LogManager.GetLogger(GetType());
}
public void Start()
{
IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger);
INoobotContainer container = containerFactory.CreateContainer();
_noobotCore = container.GetNoobotCore();
Console.WriteLine("Connecting...");
_noobotCore
.Connect()
.ContinueWith(task =>
{
if (!task.IsCompleted || task.IsFaulted)
{
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop()
{
Console.WriteLine("Disconnecting...");
_noobotCore.Disconnect();
}
}
}
|
using System;
using Common.Logging;
using Noobot.Core;
using Noobot.Core.Configuration;
using Noobot.Core.DependencyResolution;
namespace Noobot.Runner
{
/// <summary>
/// NoobotHost is required due to TopShelf.
/// </summary>
public class NoobotHost
{
private readonly IConfigReader _configReader;
private readonly ILog _logger;
private INoobotCore _noobotCore;
/// <summary>
/// Default constructor will use the default ConfigReader from Core.Configuration
/// and look for the config.json file inside a sub directory called 'configuration' with the current directory.
/// </summary>
public NoobotHost() : this(new ConfigReader()) { }
public NoobotHost(IConfigReader configReader)
{
_configReader = configReader;
_logger = LogManager.GetLogger(GetType());
}
public void Start()
{
IContainerFactory containerFactory = new ContainerFactory(new ConfigurationBase(), _configReader, _logger);
INoobotContainer container = containerFactory.CreateContainer();
_noobotCore = container.GetNoobotCore();
Console.WriteLine("Connecting...");
_noobotCore
.Connect()
.ContinueWith(task =>
{
if (!task.IsCompleted || task.IsFaulted)
{
Console.WriteLine($"Error connecting to Slack: {task.Exception}");
}
});
}
public void Stop()
{
Console.WriteLine("Disconnecting...");
_noobotCore.Disconnect();
}
}
}
|
mit
|
C#
|
60743d1693d17686f9171d148faacaf0384a60e3
|
Fix ConfigDumpParser format check.
|
nitrocaster/ListPlayers
|
src/Parsers/ConfigDumpParser.cs
|
src/Parsers/ConfigDumpParser.cs
|
/*
====================================================================================
This file is part of ListPlayers, the open-source S.T.A.L.K.E.R. multiplayer
statistics organizing tool for game server administrators.
Copyright (C) 2013 Pavel Kovalenko.
You should have received a copy of the MIT License along with ListPlayers sources.
If not, see <http://www.opensource.org/licenses/mit-license.php>.
For support and more information about ListPlayers,
visit <http://mpnetworks.ru> or <https://github.com/nitrocaster/ListPlayers>
====================================================================================
*/
using System.IO;
using System.Text;
using ListPlayers.PcdbModel;
namespace ListPlayers.Parsers
{
public sealed class ConfigDumpParser : ISpecificParser
{
private sealed class ConfigDumpParserImpl : PlayerDumpParser
{
public ConfigDumpParserImpl(HostParser host, PcdbFile database)
: base(host, database)
{}
public override void Parse(string path) { InternalParseDumpedFile(path, "config_dump_info"); }
}
public ParserBase GetParser(HostParser host, PcdbFile database)
{ return new ConfigDumpParserImpl(host, database); }
public string AcceptedFileExtension
{
get { return ".ltx"; }
}
public bool CheckFormat(string path)
{
if (Path.GetExtension(path).ToLowerInvariant() != AcceptedFileExtension)
return false;
using (var reader = new StreamReader(path, Encoding.Default))
{
return reader.ReadLine() != "[global]";
}
}
#region Singleton implementation
private ConfigDumpParser() {}
private static readonly ConfigDumpParser instance = new ConfigDumpParser();
public static ConfigDumpParser Instance
{
get { return instance; }
}
#endregion
}
}
|
/*
====================================================================================
This file is part of ListPlayers, the open-source S.T.A.L.K.E.R. multiplayer
statistics organizing tool for game server administrators.
Copyright (C) 2013 Pavel Kovalenko.
You should have received a copy of the MIT License along with ListPlayers sources.
If not, see <http://www.opensource.org/licenses/mit-license.php>.
For support and more information about ListPlayers,
visit <http://mpnetworks.ru> or <https://github.com/nitrocaster/ListPlayers>
====================================================================================
*/
using System.IO;
using ListPlayers.PcdbModel;
namespace ListPlayers.Parsers
{
public sealed class ConfigDumpParser : ISpecificParser
{
private sealed class ConfigDumpParserImpl : PlayerDumpParser
{
public ConfigDumpParserImpl(HostParser host, PcdbFile database)
: base(host, database)
{}
public override void Parse(string path) { InternalParseDumpedFile(path, "config_dump_info"); }
}
public ParserBase GetParser(HostParser host, PcdbFile database)
{ return new ConfigDumpParserImpl(host, database); }
public string AcceptedFileExtension
{
get { return ".ltx"; }
}
public bool CheckFormat(string path)
{ return (Path.GetExtension(path).ToLowerInvariant() == AcceptedFileExtension); }
#region Singleton implementation
private ConfigDumpParser() {}
private static readonly ConfigDumpParser instance = new ConfigDumpParser();
public static ConfigDumpParser Instance
{
get { return instance; }
}
#endregion
}
}
|
mit
|
C#
|
1f54e9bb01196f1ed1648c4416cdedbaaecdb638
|
Update program.cs
|
Jolka/indywidualneEla
|
program.cs
|
program.cs
|
int a=2;
int b=3;
|
int a=2;
|
mit
|
C#
|
f04f2cb4a4cd337b288eae268272081b8d1fb537
|
Fix test not waiting for async stop
|
EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
|
osu.Framework.Tests/Visual/Audio/TestSceneLoopingSample.cs
|
osu.Framework.Tests/Visual/Audio/TestSceneLoopingSample.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
namespace osu.Framework.Tests.Visual.Audio
{
public class TestSceneLoopingSample : FrameworkTestScene
{
private SampleChannel sampleChannel;
private ISampleStore samples;
[BackgroundDependencyLoader]
private void load(ISampleStore samples)
{
this.samples = samples;
}
[Test]
public void TestLoopingToggle()
{
AddStep("create sample", createSample);
AddAssert("not looping", () => !sampleChannel.Looping);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddUntilStep("is playing", () => sampleChannel.Playing);
AddWaitStep("wait", 10);
AddAssert("is still playing", () => sampleChannel.Playing);
AddStep("disable looping", () => sampleChannel.Looping = false);
AddUntilStep("ensure stops", () => !sampleChannel.Playing);
}
[Test]
public void TestStopWhileLooping()
{
AddStep("create sample", createSample);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("pl ay sample", () => sampleChannel.Play());
AddWaitStep("wait", 10);
AddAssert("is playing", () => sampleChannel.Playing);
AddStep("stop playing", () => sampleChannel.Stop());
AddUntilStep("not playing", () => !sampleChannel.Playing);
}
private void createSample()
{
sampleChannel?.Dispose();
sampleChannel = samples.Get("tone.wav");
// reduce volume of the tone due to how loud it normally is.
if (sampleChannel != null)
sampleChannel.Volume.Value = 0.05;
}
protected override void Dispose(bool isDisposing)
{
sampleChannel?.Dispose();
base.Dispose(isDisposing);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
namespace osu.Framework.Tests.Visual.Audio
{
public class TestSceneLoopingSample : FrameworkTestScene
{
private SampleChannel sampleChannel;
private ISampleStore samples;
[BackgroundDependencyLoader]
private void load(ISampleStore samples)
{
this.samples = samples;
}
[Test]
public void TestLoopingToggle()
{
AddStep("create sample", createSample);
AddAssert("not looping", () => !sampleChannel.Looping);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddAssert("is playing", () => sampleChannel.Playing);
AddWaitStep("wait", 1);
AddAssert("is still playing", () => sampleChannel.Playing);
AddStep("disable looping", () => sampleChannel.Looping = false);
AddUntilStep("ensure stops", () => !sampleChannel.Playing);
}
[Test]
public void TestStopWhileLooping()
{
AddStep("create sample", createSample);
AddStep("enable looping", () => sampleChannel.Looping = true);
AddStep("play sample", () => sampleChannel.Play());
AddWaitStep("wait", 1);
AddAssert("is playing", () => sampleChannel.Playing);
AddStep("stop playing", () => sampleChannel.Stop());
AddAssert("not playing", () => !sampleChannel.Playing);
}
private void createSample()
{
sampleChannel?.Dispose();
sampleChannel = samples.Get("tone.wav");
// reduce volume of the tone due to how loud it normally is.
if (sampleChannel != null)
sampleChannel.Volume.Value = 0.05;
}
protected override void Dispose(bool isDisposing)
{
sampleChannel?.Dispose();
base.Dispose(isDisposing);
}
}
}
|
mit
|
C#
|
e38055c03cd2e16f1ceb73ea828380f4f6c7cb91
|
Update Program.cs
|
cemdervis/SharpConfig
|
Sample/Program.cs
|
Sample/Program.cs
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Sample
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new MainForm() );
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Sample
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new MainForm() );
}
}
}
|
mit
|
C#
|
8262b77a3678d030e201f01cc48422ffe3e08e22
|
Fix indentation global.asax
|
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
|
Zk/Global.asax.cs
|
Zk/Global.asax.cs
|
using System;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Security;
using System.Web.Routing;
using WebMatrix.WebData;
using Zk.Models;
namespace Zk
{
public class MvcApplication : HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute ("{resource}.axd/{*pathInfo}");
routes.MapRoute (
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
/* Return to cleaner URL, cannot be used with external logins */
void Application_AuthenticateRequest(object sender, EventArgs e)
{
var cookieName = FormsAuthentication.FormsCookieName;
var authCookie = Context.Request.Cookies[cookieName];
if (authCookie == null)
{
/*
There is no authentication cookie. User is not authenticated.
Instead of using asp.net built in redirect with the returnUrl querystring,
this will redirect user to login.aspx.
The url of the current page will be checked to prevent the user from
being redirected to index.cshtml again when redirected to index.cshtml in
the first place.
*/
var url = Request.RawUrl.Split('?')[0];
if (url != "/Account/Login")
{
Response.Redirect("/Account/Login");
return;
}
}
}
protected void Application_Start()
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("ZkTestDatabaseConnection", "Users", "UserId", "Name", autoCreateTables: true);
}
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
|
using System;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Security;
using System.Web.Routing;
using WebMatrix.WebData;
using Zk.Models;
namespace Zk
{
public class MvcApplication : HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute ("{resource}.axd/{*pathInfo}");
routes.MapRoute (
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
protected void Application_Start()
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("ZkTestDatabaseConnection", "Users", "UserId", "Name", autoCreateTables: true);
}
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
|
mit
|
C#
|
44ef098b55b14c01bd0b13669a332522df7ed5ca
|
use correct casing in edit link
|
rtpHarry/OrchardDoc,dcinzona/OrchardDoc,dcinzona/OrchardDoc,MetSystem/OrchardDoc,SzymonSel/OrchardDoc,rtpHarry/OrchardDoc,wharri220/OrchardDoc,dcinzona/OrchardDoc,OrchardCMS/OrchardDoc,wharri220/OrchardDoc,OrchardCMS/OrchardDoc,SzymonSel/OrchardDoc,abhishekluv/OrchardDoc,armanforghani/OrchardDoc,armanforghani/OrchardDoc,phillipsj/OrchardDoc,phillipsj/OrchardDoc,phillipsj/OrchardDoc,wharri220/OrchardDoc,armanforghani/OrchardDoc,abhishekluv/OrchardDoc,rtpHarry/OrchardDoc,SzymonSel/OrchardDoc,abhishekluv/OrchardDoc,MetSystem/OrchardDoc,MetSystem/OrchardDoc
|
_PageStart.cshtml
|
_PageStart.cshtml
|
@{
var path = Request.PhysicalPath.Trim('\\');
if (path == Request.PhysicalApplicationPath.Trim('\\')) {
Page.DocumentTitle = "Orchard Documentation";
Page.Title = Page.DocumentTitle;
Page.EditUrl = "https://github.com/OrchardCMS/OrchardDoc/blob/master/Index.markdown";
}
else {
// https://github.com/NuGet/NuGetDocs/blob/master/Docs.Core/MarkdownEngine/MarkdownWebPage.cs
var caseSensitiveDocName = System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(Request.Path + ".markdown").Name;
var docNameWithoutExtension = Path.GetFileNameWithoutExtension(caseSensitiveDocName);
Page.DocumentTitle = docNameWithoutExtension.Replace('-', ' ');
Page.Title = Page.DocumentTitle + " - Orchard Documentation";
Page.EditUrl = "https://github.com/OrchardCMS/OrchardDoc/blob/master/Documentation/" + caseSensitiveDocName;
}
Page.IssuesUrl = "https://github.com/OrchardCMS/OrchardDoc/issues";
Layout = "_SiteLayout.cshtml";
}
|
@{
var path = Request.PhysicalPath.Trim('\\');
if (path == Request.PhysicalApplicationPath.Trim('\\')) {
Page.DocumentTitle = "Orchard Documentation";
Page.Title = Page.DocumentTitle;
Page.EditUrl = "https://github.com/OrchardCMS/OrchardDoc/blob/master/Index.markdown";
}
else {
var docName = Path.GetFileNameWithoutExtension(path);
Page.DocumentTitle = docName.Replace('-', ' ');
Page.Title = Page.DocumentTitle + " - Orchard Documentation";
Page.EditUrl = "https://github.com/OrchardCMS/OrchardDoc/blob/master/Documentation/" + docName + ".markdown";
}
Page.IssuesUrl = "https://github.com/OrchardCMS/OrchardDoc/issues";
Layout = "_SiteLayout.cshtml";
}
|
bsd-3-clause
|
C#
|
fcbb114467cdbdad0b90f1345a19b373d891dcb0
|
Fix `OverlayContainer` no longer blocking mouse move events
|
ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
|
osu.Framework/Graphics/Containers/OverlayContainer.cs
|
osu.Framework/Graphics/Containers/OverlayContainer.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.
#nullable disable
using System.Collections.Generic;
using osu.Framework.Input;
using osu.Framework.Input.Events;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An element which starts hidden and can be toggled to visible.
/// </summary>
public abstract class OverlayContainer : VisibilityContainer
{
/// <summary>
/// Whether we should block any positional input from interacting with things behind us.
/// </summary>
protected virtual bool BlockPositionalInput => true;
/// <summary>
/// Scroll events are sometimes required to be handled differently to general positional input.
/// This covers whether scroll events that occur within this overlay's bounds are blocked or not.
/// Defaults to the same value as <see cref="BlockPositionalInput"/>
/// </summary>
protected virtual bool BlockScrollInput => BlockPositionalInput;
/// <summary>
/// Whether we should block any non-positional input from interacting with things behind us.
/// </summary>
protected virtual bool BlockNonPositionalInput => false;
internal override bool BuildNonPositionalInputQueue(List<Drawable> queue, bool allowBlocking = true)
{
if (PropagateNonPositionalInputSubTree && HandleNonPositionalInput && BlockNonPositionalInput)
{
// when blocking non-positional input behind us, we still want to make sure the global handlers receive events
// but we don't want other drawables behind us handling them.
queue.RemoveAll(d => !(d is IHandleGlobalKeyboardInput));
}
return base.BuildNonPositionalInputQueue(queue, allowBlocking);
}
public override bool DragBlocksClick => false;
protected override bool OnHover(HoverEvent e) => BlockPositionalInput;
protected override bool OnMouseDown(MouseDownEvent e) => BlockPositionalInput;
protected override bool OnMouseMove(MouseMoveEvent e) => BlockPositionalInput;
protected override bool OnScroll(ScrollEvent e) => BlockScrollInput && base.ReceivePositionalInputAt(e.ScreenSpaceMousePosition);
}
}
|
// 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.
#nullable disable
using System.Collections.Generic;
using osu.Framework.Input;
using osu.Framework.Input.Events;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An element which starts hidden and can be toggled to visible.
/// </summary>
public abstract class OverlayContainer : VisibilityContainer
{
/// <summary>
/// Whether we should block any positional input from interacting with things behind us.
/// </summary>
protected virtual bool BlockPositionalInput => true;
/// <summary>
/// Scroll events are sometimes required to be handled differently to general positional input.
/// This covers whether scroll events that occur within this overlay's bounds are blocked or not.
/// Defaults to the same value as <see cref="BlockPositionalInput"/>
/// </summary>
protected virtual bool BlockScrollInput => BlockPositionalInput;
/// <summary>
/// Whether we should block any non-positional input from interacting with things behind us.
/// </summary>
protected virtual bool BlockNonPositionalInput => false;
internal override bool BuildNonPositionalInputQueue(List<Drawable> queue, bool allowBlocking = true)
{
if (PropagateNonPositionalInputSubTree && HandleNonPositionalInput && BlockNonPositionalInput)
{
// when blocking non-positional input behind us, we still want to make sure the global handlers receive events
// but we don't want other drawables behind us handling them.
queue.RemoveAll(d => !(d is IHandleGlobalKeyboardInput));
}
return base.BuildNonPositionalInputQueue(queue, allowBlocking);
}
public override bool DragBlocksClick => false;
protected override bool OnHover(HoverEvent e) => BlockPositionalInput;
protected override bool OnMouseDown(MouseDownEvent e) => BlockPositionalInput;
protected override bool OnScroll(ScrollEvent e) => BlockScrollInput && base.ReceivePositionalInputAt(e.ScreenSpaceMousePosition);
}
}
|
mit
|
C#
|
5ae9b4c79152e0e9489cf5e5c3a8e4267a6a92c4
|
Make CatchStacker testcase more useful
|
smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,Frontear/osuKyzer,johnneijzen/osu,peppy/osu,smoogipoo/osu,naoey/osu,naoey/osu,peppy/osu-new,smoogipoo/osu,2yangk23/osu,ppy/osu,ZLima12/osu,UselessToucan/osu,DrabWeb/osu,Nabile-Rahmani/osu,johnneijzen/osu,2yangk23/osu,DrabWeb/osu,EVAST9919/osu,naoey/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,NeoAdonis/osu,ZLima12/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu
|
osu.Game.Rulesets.Catch/Tests/TestCaseCatchStacker.cs
|
osu.Game.Rulesets.Catch/Tests/TestCaseCatchStacker.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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
[Ignore("getting CI working")]
public class TestCaseCatchStacker : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchStacker() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 512; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f + (i / 2048f * ((i % 10) - 5)), StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
[Ignore("getting CI working")]
public class TestCaseCatchStacker : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchStacker() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 256; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f, StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
|
mit
|
C#
|
361ef755dba6cb7bdb45996f1e5807af05002d07
|
Add equipped weapons info to Weapons console
|
iridinite/shiftdrive
|
Client/ConsoleWeapons.cs
|
Client/ConsoleWeapons.cs
|
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace ShiftDrive {
/// <summary>
/// The interface for the Weapons console.
/// </summary>
internal sealed class ConsoleWeapons : Console {
public override void Draw(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch) {
graphicsDevice.Clear(Color.FromNonPremultiplied(0, 0, 32, 255));
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointWrap);
DrawLocalArea(spriteBatch);
DrawFuelGauge(spriteBatch);
// draw a list of currently active weapons
int weaponBoxY = SDGame.Inst.GameHeight - Player.weaponMax * 90 - 20;
for (int i = 0; i < Player.weaponMax; i++) {
// draw box background
int weaponCurrentY = weaponBoxY + i * 90;
spriteBatch.Draw(Assets.txRect, new Rectangle(0, weaponCurrentY, 230, 80), Color.Gray);
// find the weapon in this index
Weapon wep = Player.weapons[i];
if (wep == null) {
spriteBatch.DrawString(Assets.fontDefault, Utils.LocaleGet("no_weapon"), new Vector2(18, weaponCurrentY + 10), Color.FromNonPremultiplied(48, 48, 48, 255));
continue;
}
// draw weapon details
spriteBatch.Draw(Assets.txItemIcons, new Rectangle(188, weaponCurrentY + 10, 32, 32), new Rectangle((int)wep.Type * 32, 32, 32, 32), Color.White);
spriteBatch.Draw(Assets.txChargeBar, new Rectangle(16, weaponCurrentY + 55, 128, 16), new Rectangle(0, 16, 128, 16), Color.White);
spriteBatch.DrawString(Assets.fontDefault, wep.Name, new Vector2(18, weaponCurrentY + 10), Color.Black);
spriteBatch.DrawString(Assets.fontDefault, wep.Name, new Vector2(16, weaponCurrentY + 8), Color.White);
}
spriteBatch.End();
}
public override void Update(GameTime gameTime) {
base.Update(gameTime);
}
}
}
|
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace ShiftDrive {
internal sealed class ConsoleWeapons : Console {
public override void Draw(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch) {
graphicsDevice.Clear(Color.FromNonPremultiplied(0, 0, 32, 255));
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointWrap);
DrawLocalArea(spriteBatch);
DrawFuelGauge(spriteBatch);
spriteBatch.End();
}
public override void Update(GameTime gameTime) {
}
}
}
|
bsd-3-clause
|
C#
|
c50380ae715ab516e1de0c1a7304fd7a75fde638
|
Remove the nuget environment variable.
|
shibayan/kudu,sitereactor/kudu,duncansmart/kudu,juvchan/kudu,WeAreMammoth/kudu-obsolete,chrisrpatterson/kudu,WeAreMammoth/kudu-obsolete,puneet-gupta/kudu,shrimpy/kudu,kali786516/kudu,shibayan/kudu,juoni/kudu,badescuga/kudu,duncansmart/kudu,chrisrpatterson/kudu,badescuga/kudu,sitereactor/kudu,barnyp/kudu,bbauya/kudu,EricSten-MSFT/kudu,kali786516/kudu,kali786516/kudu,barnyp/kudu,chrisrpatterson/kudu,uQr/kudu,shrimpy/kudu,kenegozi/kudu,puneet-gupta/kudu,projectkudu/kudu,kenegozi/kudu,sitereactor/kudu,sitereactor/kudu,juvchan/kudu,dev-enthusiast/kudu,YOTOV-LIMITED/kudu,badescuga/kudu,puneet-gupta/kudu,shanselman/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,badescuga/kudu,oliver-feng/kudu,juvchan/kudu,projectkudu/kudu,juoni/kudu,shibayan/kudu,barnyp/kudu,juvchan/kudu,projectkudu/kudu,EricSten-MSFT/kudu,oliver-feng/kudu,shibayan/kudu,MavenRain/kudu,duncansmart/kudu,uQr/kudu,barnyp/kudu,EricSten-MSFT/kudu,badescuga/kudu,oliver-feng/kudu,YOTOV-LIMITED/kudu,shrimpy/kudu,oliver-feng/kudu,uQr/kudu,dev-enthusiast/kudu,uQr/kudu,MavenRain/kudu,kenegozi/kudu,shrimpy/kudu,shibayan/kudu,duncansmart/kudu,chrisrpatterson/kudu,sitereactor/kudu,bbauya/kudu,juoni/kudu,WeAreMammoth/kudu-obsolete,mauricionr/kudu,projectkudu/kudu,kenegozi/kudu,dev-enthusiast/kudu,mauricionr/kudu,YOTOV-LIMITED/kudu,shanselman/kudu,mauricionr/kudu,juoni/kudu,bbauya/kudu,YOTOV-LIMITED/kudu,mauricionr/kudu,puneet-gupta/kudu,juvchan/kudu,dev-enthusiast/kudu,bbauya/kudu,kali786516/kudu,MavenRain/kudu,projectkudu/kudu,shanselman/kudu,MavenRain/kudu
|
Kudu.Core/Deployment/MsBuildSiteBuilder.cs
|
Kudu.Core/Deployment/MsBuildSiteBuilder.cs
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
// Disable this for now
// _msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
_msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
|
apache-2.0
|
C#
|
8a6d72bc07562fe9babf800de5de89efbec63dae
|
Fix null ref
|
manesiotise/Opserver,GABeech/Opserver,manesiotise/Opserver,opserver/Opserver,GABeech/Opserver,opserver/Opserver,manesiotise/Opserver,mqbk/Opserver,mqbk/Opserver,opserver/Opserver
|
Opserver/Views/Dashboard/Node.Stats.cshtml
|
Opserver/Views/Dashboard/Node.Stats.cshtml
|
@model StackExchange.Opserver.Data.Dashboard.Node
<div class="row small">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
CPU Utilization
</div>
<div class="panel-body">
<div class="history-graph" id="cpu-container"></div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">Memory Utilization <span cass="text-muted">(@(Model.TotalMemory.GetValueOrDefault(0).ToSize()))</span></div>
<div class="panel-body">
<div class="history-graph" id="memory-container" data-max="@((Model.TotalMemory/1024/1024)?.ToString(CultureInfo.InvariantCulture))"></div>
</div>
</div>
</div>
</div>
<script>
$(function () {
$('#cpu-container').cpuGraph({ id: '@Model.Id', realtime: true });
$('#memory-container').memoryGraph({ id: '@Model.Id' });
});
</script>
@if (Model.Interfaces.Any())
{
@Html.Partial("Node.Interfaces", Model)
}
@if (Model.Services?.Any() == true)
{
@Html.Partial("Node.Services", Model)
}
@if (Current.Settings.Dashboard.ShowVolumePerformance && Model.Volumes.Any())
{
@Html.Partial("Node.Volumes", Model)
}
|
@model StackExchange.Opserver.Data.Dashboard.Node
<div class="row small">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
CPU Utilization
</div>
<div class="panel-body">
<div class="history-graph" id="cpu-container"></div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">Memory Utilization <span cass="text-muted">(@(Model.TotalMemory.GetValueOrDefault(0).ToSize()))</span></div>
<div class="panel-body">
<div class="history-graph" id="memory-container" data-max="@((Model.TotalMemory/1024/1024)?.ToString(CultureInfo.InvariantCulture))"></div>
</div>
</div>
</div>
</div>
<script>
$(function () {
$('#cpu-container').cpuGraph({ id: '@Model.Id', realtime: true });
$('#memory-container').memoryGraph({ id: '@Model.Id' });
});
</script>
@if (Model.Interfaces.Any())
{
@Html.Partial("Node.Interfaces", Model)
}
@if (Model.Services.Any())
{
@Html.Partial("Node.Services", Model)
}
@if (Current.Settings.Dashboard.ShowVolumePerformance && Model.Volumes.Any())
{
@Html.Partial("Node.Volumes", Model)
}
|
mit
|
C#
|
2d3cba6c7c6ad799086c24d37a71ec3262706769
|
Set WebResourceName comparison to case sensitive
|
aluxnimm/outlookcaldavsynchronizer
|
CalDavSynchronizer/DataAccess/WebResourceName.cs
|
CalDavSynchronizer/DataAccess/WebResourceName.cs
|
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
namespace CalDavSynchronizer.DataAccess
{
public class WebResourceName
{
public string OriginalAbsolutePath {get; set; }
public string Id {get; set; }
public WebResourceName (Uri uri)
: this (uri.AbsolutePath)
{
}
public WebResourceName (string absolutePath)
{
OriginalAbsolutePath = absolutePath;
Id = DecodedString (absolutePath);
}
private static string DecodedString (string value)
{
string newValue;
while ((newValue = Uri.UnescapeDataString (value)) != value)
value = newValue;
return newValue;
}
public string GetServerFileName()
{
return Path.GetFileName(OriginalAbsolutePath);
}
public WebResourceName ()
{
}
public override string ToString ()
{
return OriginalAbsolutePath;
}
public override int GetHashCode ()
{
return Comparer.GetHashCode (this);
}
public override bool Equals (object obj)
{
return Comparer.Equals (this, obj as WebResourceName);
}
public static readonly IEqualityComparer<WebResourceName> Comparer = new WebResourceNameEqualityComparer();
private class WebResourceNameEqualityComparer : IEqualityComparer<WebResourceName>
{
private static readonly IEqualityComparer<string> s_stringComparer = StringComparer.Ordinal;
public bool Equals (WebResourceName x, WebResourceName y)
{
if (x == null)
return y == null;
if (y == null)
return false;
return s_stringComparer.Equals (x.Id, y.Id);
}
public int GetHashCode (WebResourceName obj)
{
return s_stringComparer.GetHashCode (obj.Id);
}
}
}
}
|
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
namespace CalDavSynchronizer.DataAccess
{
public class WebResourceName
{
public string OriginalAbsolutePath {get; set; }
public string Id {get; set; }
public WebResourceName (Uri uri)
: this (uri.AbsolutePath)
{
}
public WebResourceName (string absolutePath)
{
OriginalAbsolutePath = absolutePath;
Id = DecodedString (absolutePath);
}
private static string DecodedString (string value)
{
string newValue;
while ((newValue = Uri.UnescapeDataString (value)) != value)
value = newValue;
return newValue;
}
public string GetServerFileName()
{
return Path.GetFileName(OriginalAbsolutePath);
}
public WebResourceName ()
{
}
public override string ToString ()
{
return OriginalAbsolutePath;
}
public override int GetHashCode ()
{
return Comparer.GetHashCode (this);
}
public override bool Equals (object obj)
{
return Comparer.Equals (this, obj as WebResourceName);
}
public static readonly IEqualityComparer<WebResourceName> Comparer = new WebResourceNameEqualityComparer();
private class WebResourceNameEqualityComparer : IEqualityComparer<WebResourceName>
{
private static readonly IEqualityComparer<string> s_stringComparer = StringComparer.OrdinalIgnoreCase;
public bool Equals (WebResourceName x, WebResourceName y)
{
if (x == null)
return y == null;
if (y == null)
return false;
return s_stringComparer.Equals (x.Id, y.Id);
}
public int GetHashCode (WebResourceName obj)
{
return s_stringComparer.GetHashCode (obj.Id);
}
}
}
}
|
agpl-3.0
|
C#
|
5f7dc9b3f81f98a1c43e07132111e42263399acb
|
Make SingleJointInverseKinematicsSolver use the new Swing class
|
virtuallynaked/virtually-naked,virtuallynaked/virtually-naked
|
Viewer/src/actor/animation/inversekinematics/SingleJointInverseKinematicsSolver.cs
|
Viewer/src/actor/animation/inversekinematics/SingleJointInverseKinematicsSolver.cs
|
using SharpDX;
public class SingleJointInverseKinematicsSolver : IInverseKinematicsSolver {
private const int TwistAxis = Swing.XAxis;
private readonly string boneName;
public SingleJointInverseKinematicsSolver(string boneName) {
this.boneName = boneName;
}
public void Solve(RigidBoneSystem boneSystem, InverseKinematicsProblem problem, RigidBoneSystemInputs inputs) {
var bone = boneSystem.BonesByName[boneName];
//get bone transforms with the current bone rotation zeroed out
inputs.Rotations[bone.Index] = Vector3.Zero;
var boneTransforms = boneSystem.GetBoneTransforms(inputs);
var boneTransform = boneTransforms[bone.Index];
var worldSourcePosition = boneTransforms[problem.SourceBone.Index].Transform(problem.UnposedSourcePosition);
var worldTargetPosition = problem.TargetPosition;
var worldCenterPosition = boneTransform.Transform(bone.CenterPoint);
var worldSourceDirection = Vector3.Normalize(worldSourcePosition - worldCenterPosition);
var worldTargetDirection = Vector3.Normalize(worldTargetPosition - worldCenterPosition);
//transform source and target to bone's oriented space
var parentTotalRotation = bone.Parent != null ? boneTransforms[bone.Parent.Index].Rotation : Quaternion.Identity;
var orientedSpaceToWorldTransform = bone.OrientationSpace.Orientation.Chain(parentTotalRotation);
var worldToOrientatedSpaceTransform = Quaternion.Invert(orientedSpaceToWorldTransform);
var orientedSourceDirection = Vector3.Transform(worldSourceDirection, worldToOrientatedSpaceTransform);
var orientedTargetDirection = Vector3.Transform(worldTargetDirection, worldToOrientatedSpaceTransform);
var newOrientedRotation = Swing.FromTo(TwistAxis, orientedSourceDirection, orientedTargetDirection).AsQuaternion(TwistAxis);
bone.SetOrientedSpaceRotation(inputs, newOrientedRotation, true);
}
}
|
using SharpDX;
public class SingleJointInverseKinematicsSolver : IInverseKinematicsSolver {
private readonly string boneName;
public SingleJointInverseKinematicsSolver(string boneName) {
this.boneName = boneName;
}
public void Solve(RigidBoneSystem boneSystem, InverseKinematicsProblem problem, RigidBoneSystemInputs inputs) {
var bone = boneSystem.BonesByName[boneName];
//get bone transforms with the current bone rotation zeroed out
inputs.Rotations[bone.Index] = Vector3.Zero;
var boneTransforms = boneSystem.GetBoneTransforms(inputs);
var boneTransform = boneTransforms[bone.Index];
var worldSourcePosition = boneTransforms[problem.SourceBone.Index].Transform(problem.UnposedSourcePosition);
var worldTargetPosition = problem.TargetPosition;
var worldCenterPosition = boneTransform.Transform(bone.CenterPoint);
var worldSourceDirection = Vector3.Normalize(worldSourcePosition - worldCenterPosition);
var worldTargetDirection = Vector3.Normalize(worldTargetPosition - worldCenterPosition);
//transform source and target to bone's oriented space
var parentTotalRotation = bone.Parent != null ? boneTransforms[bone.Parent.Index].Rotation : Quaternion.Identity;
var orientedSpaceToWorldTransform = bone.OrientationSpace.Orientation.Chain(parentTotalRotation);
var worldToOrientatedSpaceTransform = Quaternion.Invert(orientedSpaceToWorldTransform);
var orientedSourceDirection = Vector3.Transform(worldSourceDirection, worldToOrientatedSpaceTransform);
var orientedTargetDirection = Vector3.Transform(worldTargetDirection, worldToOrientatedSpaceTransform);
var newOrientedRotation = QuaternionExtensions.RotateBetween(orientedSourceDirection, orientedTargetDirection);
bone.SetOrientedSpaceRotation(inputs, newOrientedRotation, true);
}
}
|
mit
|
C#
|
9b922ff78f55184991b215dbe79a1807ecd2e9c8
|
Make constructor as public
|
JKennedy24/Xamarin.Forms.GoogleMaps,amay077/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps
|
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Helpers/CameraUpdateConverter.cs
|
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Helpers/CameraUpdateConverter.cs
|
using System;
using System.Collections.Generic;
namespace Xamarin.Forms.GoogleMaps.Helpers
{
public sealed class CameraUpdateConverter : TypeConverter
{
public override bool CanConvertFrom(Type sourceType)
{
return sourceType == typeof(CameraUpdate);
}
public override object ConvertFromInvariantString(string value)
{
var err = $@"{value} is invalid format. Expects are ""lat, lon"", ""lat, lon, zoom"", ""lat, lon, zoom, rotation"" and ""lat, lon, zoom, rotation, tilt"" ";
var values = value.Split(',');
if (values.Length < 2)
{
throw new ArgumentException(err);
}
var nums = new List<double>();
foreach (var v in values)
{
double ret;
if (!double.TryParse(v, out ret))
{
throw new ArgumentException(err);
}
nums.Add(ret);
}
if (nums.Count == 2)
{
return CameraUpdateFactory.NewPosition(new Position(nums[0], nums[1]));
}
if (nums.Count == 3)
{
return CameraUpdateFactory.NewPositionZoom(new Position(nums[0], nums[1]), nums[2]);
}
if (nums.Count == 4)
{
return CameraUpdateFactory.NewCameraPosition(new CameraPosition(
new Position(nums[0], nums[1]),
nums[2],
nums[3]));
}
return CameraUpdateFactory.NewCameraPosition(new CameraPosition(
new Position(nums[0], nums[1]),
nums[2],
nums[3],
nums[4]));
}
}
}
|
using System;
using System.Collections.Generic;
namespace Xamarin.Forms.GoogleMaps.Helpers
{
public sealed class CameraUpdateConverter : TypeConverter
{
internal CameraUpdateConverter()
{
}
public override bool CanConvertFrom(Type sourceType)
{
return sourceType == typeof(CameraUpdate);
}
public override object ConvertFromInvariantString(string value)
{
var err = $@"{value} is invalid format. Expects are ""lat, lon"", ""lat, lon, zoom"", ""lat, lon, zoom, rotation"" and ""lat, lon, zoom, rotation, tilt"" ";
var values = value.Split(',');
if (values.Length < 2)
{
throw new ArgumentException(err);
}
var nums = new List<double>();
foreach (var v in values)
{
double ret;
if (!double.TryParse(v, out ret))
{
throw new ArgumentException(err);
}
nums.Add(ret);
}
if (nums.Count == 2)
{
return CameraUpdateFactory.NewPosition(new Position(nums[0], nums[1]));
}
if (nums.Count == 3)
{
return CameraUpdateFactory.NewPositionZoom(new Position(nums[0], nums[1]), nums[2]);
}
if (nums.Count == 4)
{
return CameraUpdateFactory.NewCameraPosition(new CameraPosition(
new Position(nums[0], nums[1]),
nums[2],
nums[3]));
}
return CameraUpdateFactory.NewCameraPosition(new CameraPosition(
new Position(nums[0], nums[1]),
nums[2],
nums[3],
nums[4]));
}
}
}
|
mit
|
C#
|
e7bd98d8a4ed84ad142ceb8a53c9100f34e0b122
|
Fix AssemblyInfo
|
imasm/PrismSamples
|
DemoEventAgregator/TestApp/Properties/AssemblyInfo.cs
|
DemoEventAgregator/TestApp/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("TestApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ivan Masmtijà")]
[assembly: AssemblyProduct("TestApp")]
[assembly: AssemblyCopyright("Copyright © Ivan Masmtijà 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM.
[assembly: Guid("54fd2d53-d038-46bd-b35c-4f87344c1462")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
//[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;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("TestApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Esteban Espuña")]
[assembly: AssemblyProduct("TestApp")]
[assembly: AssemblyCopyright("Copyright © Esteban Espuña 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM.
[assembly: Guid("54fd2d53-d038-46bd-b35c-4f87344c1462")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
//[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
apache-2.0
|
C#
|
7f5328663200954897ac3c50815ccf3ce960b894
|
disable new command scheduler tests
|
askheaves/Its.Cqrs,commonsensesoftware/Its.Cqrs,askheaves/Its.Cqrs,commonsensesoftware/Its.Cqrs,commonsensesoftware/Its.Cqrs,askheaves/Its.Cqrs
|
Domain.Sql.Tests/SqlCommandSchedulerTests_New.cs
|
Domain.Sql.Tests/SqlCommandSchedulerTests_New.cs
|
using System;
using System.Threading.Tasks;
using Microsoft.Its.Domain.Sql.CommandScheduler;
using NUnit.Framework;
using Sample.Domain.Ordering;
namespace Microsoft.Its.Domain.Sql.Tests
{
[Ignore("Not ready")]
[TestFixture]
public class SqlCommandSchedulerTests_New : SqlCommandSchedulerTests
{
protected override void ConfigureScheduler(Configuration configuration)
{
configuration.Container.Register<SqlCommandScheduler>(c =>
{
throw new NotSupportedException("SqlCommandScheduler (legacy) is disabled");
return null;
});
configuration.UseCommandSchedulerPipeline<Order>(
c => c.UseSqlStorage());
}
protected override async Task SchedulerWorkComplete()
{
}
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.Its.Domain.Sql.CommandScheduler;
using NUnit.Framework;
using Sample.Domain.Ordering;
namespace Microsoft.Its.Domain.Sql.Tests
{
[TestFixture]
public class SqlCommandSchedulerTests_New : SqlCommandSchedulerTests
{
protected override void ConfigureScheduler(Configuration configuration)
{
configuration.Container.Register<SqlCommandScheduler>(c =>
{
throw new NotSupportedException("SqlCommandScheduler (legacy) is disabled");
return null;
});
configuration.UseCommandSchedulerPipeline<Order>(
c => c.UseSqlStorage());
}
protected override async Task SchedulerWorkComplete()
{
}
}
}
|
mit
|
C#
|
10a66c812f0dcbf890fbd76730771298fa9ed45c
|
reformat all after .editorconfig
|
mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker
|
Ductus.FluentDocker/Executors/ProcessExecutor.cs
|
Ductus.FluentDocker/Executors/ProcessExecutor.cs
|
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Ductus.FluentDocker.Common;
using Ductus.FluentDocker.Extensions;
using Ductus.FluentDocker.Model.Containers;
namespace Ductus.FluentDocker.Executors
{
public sealed class ProcessExecutor<T, TE> where T : IProcessResponseParser<TE>, IProcessResponse<TE>, new()
{
private readonly string _arguments;
private readonly string _command;
private readonly string _workingdir;
public ProcessExecutor(string command, string arguments, string workingdir = null)
{
_workingdir = workingdir;
if (command.StartsWith("echo") || command.StartsWith("sudo"))
{
_command = CommandExtensions.DefaultShell;
_arguments = $"-c \"{command} {arguments}\"";
return;
}
_command = command;
_arguments = arguments;
}
public IDictionary<string, string> Env { get; } = new Dictionary<string, string>();
public CommandResponse<TE> Execute()
{
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
Arguments = _arguments,
FileName = _command,
WorkingDirectory = _workingdir
};
if (0 != Env.Count)
foreach (var key in Env.Keys)
{
#if COREFX
startInfo.Environment[key] = Env[key];
#else
startInfo.EnvironmentVariables[key] = Env[key];
#endif
}
Logger.Log($"cmd: {_command} - arg: {_arguments}");
using (var process = new Process { StartInfo = startInfo })
{
var output = new StringBuilder();
var err = new StringBuilder();
process.OutputDataReceived += (sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
output.AppendLine(args.Data);
};
process.ErrorDataReceived += (sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
err.AppendLine(args.Data);
};
if (!process.Start())
throw new FluentDockerException($"Could not start process {_command}");
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return
new T().Process(new ProcessExecutionResult(_command, output.ToString(), err.ToString(), process.ExitCode))
.Response;
}
}
}
}
|
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Ductus.FluentDocker.Common;
using Ductus.FluentDocker.Extensions;
using Ductus.FluentDocker.Model.Containers;
namespace Ductus.FluentDocker.Executors
{
public sealed class ProcessExecutor<T, TE> where T : IProcessResponseParser<TE>, IProcessResponse<TE>, new()
{
private readonly string _arguments;
private readonly string _command;
private readonly string _workingdir;
public ProcessExecutor(string command, string arguments, string workingdir = null)
{
_workingdir = workingdir;
if (command.StartsWith("echo") || command.StartsWith("sudo"))
{
_command = CommandExtensions.DefaultShell;
_arguments = $"-c \"{command} {arguments}\"";
return;
}
_command = command;
_arguments = arguments;
}
public IDictionary<string, string> Env { get; } = new Dictionary<string, string>();
public CommandResponse<TE> Execute()
{
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
Arguments = _arguments,
FileName = _command,
WorkingDirectory = _workingdir
};
if (0 != Env.Count)
foreach (var key in Env.Keys)
{
#if COREFX
startInfo.Environment[key] = Env[key];
#else
startInfo.EnvironmentVariables[key] = Env[key];
#endif
}
Logger.Log($"cmd: {_command} - arg: {_arguments}");
using (var process = new Process {StartInfo = startInfo})
{
var output = new StringBuilder();
var err = new StringBuilder();
process.OutputDataReceived += (sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data)) output.AppendLine(args.Data);
};
process.ErrorDataReceived += (sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data)) err.AppendLine(args.Data);
};
if (!process.Start()) throw new FluentDockerException($"Could not start process {_command}");
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return
new T().Process(new ProcessExecutionResult(_command, output.ToString(), err.ToString(), process.ExitCode))
.Response;
}
}
}
}
|
apache-2.0
|
C#
|
4f9f82d660650c502d4806718c0b94df791a27cb
|
Fix for issue#1 - random direction selector was throwing an exception
|
vnads/Fight-Fleet,vnads/Fight-Fleet,vnads/Fight-Fleet
|
FightFleetApi/FightFleet/RandomBoardGenerator.cs
|
FightFleetApi/FightFleet/RandomBoardGenerator.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FightFleet
{
/// <summary>
/// Randomly places 5 ships to a game board.
/// </summary>
public class RandomlyGenerateBoard : GenerateBoard
{
public override void Generate() {
// Place 5 ships on the board
RandomlyPlaceShip(new AircraftCarrier());
RandomlyPlaceShip(new BattleShip());
RandomlyPlaceShip(new Submarine());
RandomlyPlaceShip(new Cruiser());
RandomlyPlaceShip(new Destroyer());
}
/// <summary>
/// Randomly places a ship in the board. Random location as well as direction (horizontal, vertical) of the ship
/// </summary>
/// <param name="ship"></param>
public void RandomlyPlaceShip(Ship ship) {
var random = new Random();
while (true)
{
var randomPosition = new KeyValuePair<int, int>(random.Next(0, GameBoard.XSIZE),
random.Next(0, GameBoard.YSIZE));
if (Board.BoardCells[randomPosition.Key, randomPosition.Value] != (int) BoardCellStatus.Blank)
continue;
// try to pick a random direction 6 (can be changed) times. If not successful precede to pick another random position
for (int i = 0; i <= 5; i++)
{
var randomDirection = random.Next(1, Enum.GetNames(typeof (ShipDirections)).Count() + 1);
var shipPositions = ShipCellPositions((ShipDirections) randomDirection, randomPosition, ship.Size);
if (shipPositions != null)
{
MarkBoardWithShipPositions(shipPositions);
return;
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FightFleet
{
/// <summary>
/// Randomly places 5 ships to a game board.
/// </summary>
public class RandomlyGenerateBoard : GenerateBoard
{
public override void Generate() {
// Place 5 ships on the board
RandomlyPlaceShip(new AircraftCarrier());
RandomlyPlaceShip(new BattleShip());
RandomlyPlaceShip(new Submarine());
RandomlyPlaceShip(new Cruiser());
RandomlyPlaceShip(new Destroyer());
}
/// <summary>
/// Randomly places a ship in the board. Random location as well as direction (horizontal, vertical) of the ship
/// </summary>
/// <param name="ship"></param>
public void RandomlyPlaceShip(Ship ship) {
var random = new Random();
while (true) {
var randomPosition = new KeyValuePair<int, int>(random.Next(0, GameBoard.XSIZE),
random.Next(0, GameBoard.YSIZE));
if (Board.BoardCells[randomPosition.Key, randomPosition.Value] != (int)BoardCellStatus.Blank)
continue;
var directions = (int[])Enum.GetValues(typeof(ShipDirections));
// Randomly sort the direction array to pick a random direction of the ship
directions.OrderBy(x => random.Next());
// tries all possible directions until it find an appropriate one.
foreach (int direction in directions) {
var shipPositions = ShipCellPositions((ShipDirections)direction, randomPosition, ship.Size);
if (shipPositions != null) {
MarkBoardWithShipPositions(shipPositions);
return;
}
}
// it it getts to this point, it means the ship has not been placed on the board.
// So we try with a different random location
RandomlyPlaceShip(ship);
}
}
}
}
|
mit
|
C#
|
a742bf87c455084bc17fa4a2dbe90db11d4a6ef7
|
add comment
|
martinlindhe/Punku
|
punku/Extensions/ByteArrayExtensions.cs
|
punku/Extensions/ByteArrayExtensions.cs
|
using System;
using System.Text;
public static class ByteArrayExtensions
{
/**
* Returns a hex string representation of the content
*/
public static string ToHexString (this byte[] bytes)
{
byte b;
var res = new StringBuilder ();
for (int bx = 0; bx < bytes.Length; bx++) {
b = (byte)(bytes [bx] >> 4);
res.Append ((char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30));
b = (byte)(bytes [bx] & 0x0F);
res.Append ((char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30));
}
return res.ToString ();
}
/**
* Decodes byte array to a C-string (each letter is 1 byte, 0 = end of text)
*/
public static string ToCString (this byte[] bytes)
{
var res = new StringBuilder ();
foreach (byte x in bytes) {
if (x == 0)
break;
res.Append ((char)x);
}
return res.ToString ();
}
/**
* Decodes byte array to a DOS $-terminated string (each letter is 1 byte, $ = end of text)
*/
public static string ToDosString (this byte[] bytes)
{
var res = new StringBuilder ();
foreach (byte x in bytes) {
if (x == (byte)'$')
break;
res.Append ((char)x);
}
return res.ToString ();
}
/**
* Returns a char[] from the byte[]
*/
public static char[] ToCharArray (this byte[] bytes)
{
var res = new char[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
res [i] = (char)bytes [i];
return res;
}
/**
* Returns an array shifted to the right by shift
*/
public static byte[] RotateRight (this byte[] bytes, int shift)
{
byte[] Table = new byte[byte.MaxValue + 1];
// NOTE: we exploit byte rounding to fill the shift table
for (int i = 0; i <= byte.MaxValue; i++)
Table [i] = (byte)(i + shift);
byte[] arr = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
arr [i] = Table [bytes [i]];
return arr;
}
/**
* Returns an array shifted to the left by shift
*/
public static byte[] RotateLeft (this byte[] bytes, int shift)
{
byte[] Table = new byte[byte.MaxValue + 1];
// NOTE: we exploit byte rounding to fill the shift table
for (int i = 0; i <= byte.MaxValue; i++)
Table [i] = (byte)(i - shift);
byte[] arr = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
arr [i] = Table [bytes [i]];
return arr;
}
}
|
using System;
using System.Text;
public static class ByteArrayExtensions
{
/**
* Returns a hex string representation of the content
*/
public static string ToHexString (this byte[] bytes)
{
byte b;
var res = new StringBuilder ();
for (int bx = 0; bx < bytes.Length; bx++) {
b = (byte)(bytes [bx] >> 4);
res.Append ((char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30));
b = (byte)(bytes [bx] & 0x0F);
res.Append ((char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30));
}
return res.ToString ();
}
/**
* Decodes byte array to a C-string (each letter is 1 byte, 0 = end of text)
*/
public static string ToCString (this byte[] bytes)
{
var res = new StringBuilder ();
foreach (byte x in bytes) {
if (x == 0)
break;
res.Append ((char)x);
}
return res.ToString ();
}
/**
* Decodes byte array to a DOS $-terminated string (each letter is 1 byte, $ = end of text)
*/
public static string ToDosString (this byte[] bytes)
{
var res = new StringBuilder ();
foreach (byte x in bytes) {
if (x == (byte)'$')
break;
res.Append ((char)x);
}
return res.ToString ();
}
public static char[] ToCharArray (this byte[] bytes)
{
// TODO add test this method!
char[] res = new char[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
res [i] = (char)bytes [i];
return res;
}
/**
* Returns an array shifted to the right by shift
*/
public static byte[] RotateRight (this byte[] bytes, int shift)
{
byte[] Table = new byte[byte.MaxValue + 1];
// NOTE: we exploit byte rounding to fill the shift table
for (int i = 0; i <= byte.MaxValue; i++)
Table [i] = (byte)(i + shift);
byte[] arr = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
arr [i] = Table [bytes [i]];
return arr;
}
/**
* Returns an array shifted to the left by shift
*/
public static byte[] RotateLeft (this byte[] bytes, int shift)
{
byte[] Table = new byte[byte.MaxValue + 1];
// NOTE: we exploit byte rounding to fill the shift table
for (int i = 0; i <= byte.MaxValue; i++)
Table [i] = (byte)(i - shift);
byte[] arr = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
arr [i] = Table [bytes [i]];
return arr;
}
}
|
mit
|
C#
|
4c8cc28d58516e8613a02d1c0ee39c056dd2b55e
|
Fix for redirect port
|
ppittle/pMixins,ppittle/pMixins,ppittle/pMixins
|
pMixins.Mvc/Controllers/HomeController.cs
|
pMixins.Mvc/Controllers/HomeController.cs
|
//-----------------------------------------------------------------------
// <copyright file="HomeController.cs" company="Copacetic Software">
// Copyright (c) Copacetic Software.
// <author>Philip Pittle</author>
// <date>Friday, May 2, 2014 2:50:42 PM</date>
// Licensed under the Apache License, Version 2.0,
// you may not use this file except in compliance with this 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.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Web.Mvc;
namespace CopaceticSoftware.pMixins.Mvc.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
if (Request.Url.AbsoluteUri.ToLower().Contains("pmixins.apphb.com"))
{
var newUrlBuilder =
new UriBuilder(
Request.Url.AbsoluteUri.ToLower().Replace(
"pmixins.apphb.com", "pmixins.com"))
{
Port = 80
};
return RedirectPermanent(newUrlBuilder.Uri.AbsoluteUri);
}
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="HomeController.cs" company="Copacetic Software">
// Copyright (c) Copacetic Software.
// <author>Philip Pittle</author>
// <date>Friday, May 2, 2014 2:50:42 PM</date>
// Licensed under the Apache License, Version 2.0,
// you may not use this file except in compliance with this 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.
// </copyright>
//-----------------------------------------------------------------------
using System.Web.Mvc;
namespace CopaceticSoftware.pMixins.Mvc.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
if (Request.Url.AbsoluteUri.ToLower().Contains("pmixins.apphb.com"))
return RedirectPermanent(
Request.Url.AbsoluteUri.ToLower().Replace(
"pmixins.apphb.com", "pmixins.com"));
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
apache-2.0
|
C#
|
ff9dd7f8add303e2f8aff32acd7caaef026b3447
|
build fx
|
andreyleskov/GridDomain,linkelf/GridDomain
|
GridDomain.Logging/DefaultLoggerConfiguration.cs
|
GridDomain.Logging/DefaultLoggerConfiguration.cs
|
using System.Configuration;
using Serilog;
namespace GridDomain.Logging
{
public class DefaultLoggerConfiguration : LoggerConfiguration
{
public DefaultLoggerConfiguration()
{
var filePath = ConfigurationManager.AppSettings["logFilePath"] ?? @"C:\Logs";
var elasticEndpoint = ConfigurationManager.AppSettings["logElasticEndpoint"] ?? "http://soloinfra.cloudapp.net:9222";
WriteTo.RollingFile(filePath + "\\logs-{Date}.txt")
//.WriteTo.Slack("https://hooks.slack.com/services/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")
.WriteTo.Elasticsearch(elasticEndpoint)
.WriteTo.Console()
.Enrich
.WithMachineName();
foreach (var type in TypesForScalarDescruptionHolder.Types)
{
Destructure.AsScalar(type);
}
}
}
}
|
using System.Configuration;
using Serilog;
namespace GridDomain.Logging
{
public class DefaultLoggerConfiguration : LoggerConfiguration
{
public DefaultLoggerConfiguration()
{
var filePath = ConfigurationManager.AppSettings["logFilePath"] ?? @"C:\Logs";
var elasticEndpoint = ConfigurationManager.AppSettings["logElasticEndpoint"] ?? "http://soloinfra.cloudapp.net:9222";
WriteTo.RollingFile(filePath + "\\logs-{Date}.txt").
//.WriteTo.Slack("https://hooks.slack.com/services/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")
WriteTo.Elasticsearch(elasticEndpoint)
WriteTo.Console()
.Enrich
.WithMachineName();
foreach (var type in TypesForScalarDescruptionHolder.Types)
{
Destructure.AsScalar(type);
}
}
}
}
|
apache-2.0
|
C#
|
32deee84f4372a1e5a64ba8a96d5a98c3d79c1fa
|
implement (FindLast/FindAll)In_Tests
|
miraimann/Knuth-Morris-Pratt
|
KnuthMorrisPratt/KnuthMorrisPratt.Tests/Tests.cs
|
KnuthMorrisPratt/KnuthMorrisPratt.Tests/Tests.cs
|
using NUnit.Framework;
using StringSearch;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KnuthMorrisPratt.Tests
{
[TestFixture]
public class Tests
{
private readonly IFinderFactory<char> _finderFactory =
new FinderFactory<char>();
[TestCaseSource(typeof(TestCasesProvider.Exists), "All__TestCases")]
public bool ExistsIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.ExistsIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindFirst), "All__TestCases")]
public int FindIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindLast), "All__TestCases")]
public int FindLastIn_Test()
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindLastIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindAll), "All__TestCases")]
public IEnumerable<int> FindAllIn_Test()
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindAllIn(@case.Sequence);
}
}
}
|
using NUnit.Framework;
using StringSearch;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KnuthMorrisPratt.Tests
{
[TestFixture]
public class Tests
{
private readonly IFinderFactory<char> _finderFactory =
new FinderFactory<char>();
[TestCaseSource(typeof(TestCasesProvider.Exists), "All__TestCases")]
public bool ExistsIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.ExistsIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindFirst), "All__TestCases")]
public int FindIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindIn(@case.Sequence);
}
public int FindLastIn_Test()
{
throw new NotImplementedException();
}
public IEnumerable<int> FindAllIn_Test()
{
throw new NotImplementedException();
}
private static class A
{
}
}
}
|
mit
|
C#
|
151612eb1763a624c87f8c7b1b2834dc37988d42
|
add argument:case (fix compilation errors)
|
miraimann/Knuth-Morris-Pratt
|
KnuthMorrisPratt/KnuthMorrisPratt.Tests/Tests.cs
|
KnuthMorrisPratt/KnuthMorrisPratt.Tests/Tests.cs
|
using NUnit.Framework;
using StringSearch;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KnuthMorrisPratt.Tests
{
[TestFixture]
public class Tests
{
private readonly IFinderFactory<char> _finderFactory =
new FinderFactory<char>();
[TestCaseSource(typeof(TestCasesProvider.Exists), "All__TestCases")]
public bool ExistsIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.ExistsIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindFirst), "All__TestCases")]
public int FindIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindLast), "All__TestCases")]
public int FindLastIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindLastIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindAll), "All__TestCases")]
public IEnumerable<int> FindAllIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindAllIn(@case.Sequence);
}
}
}
|
using NUnit.Framework;
using StringSearch;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KnuthMorrisPratt.Tests
{
[TestFixture]
public class Tests
{
private readonly IFinderFactory<char> _finderFactory =
new FinderFactory<char>();
[TestCaseSource(typeof(TestCasesProvider.Exists), "All__TestCases")]
public bool ExistsIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.ExistsIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindFirst), "All__TestCases")]
public int FindIn_Test(Case<char> @case)
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindLast), "All__TestCases")]
public int FindLastIn_Test()
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindLastIn(@case.Sequence);
}
[TestCaseSource(typeof(TestCasesProvider.FindAll), "All__TestCases")]
public IEnumerable<int> FindAllIn_Test()
{
return _finderFactory.CreateFrom(@case.Pattern)
.FindAllIn(@case.Sequence);
}
}
}
|
mit
|
C#
|
be31644585516cf560c63057a48652c44d5a5b1d
|
Fix AtomicDateTime constructor
|
Fluzzarn/LiveSplit,Glurmo/LiveSplit,Dalet/LiveSplit,kugelrund/LiveSplit,Glurmo/LiveSplit,chloe747/LiveSplit,Fluzzarn/LiveSplit,kugelrund/LiveSplit,kugelrund/LiveSplit,Dalet/LiveSplit,ROMaster2/LiveSplit,ROMaster2/LiveSplit,chloe747/LiveSplit,LiveSplit/LiveSplit,chloe747/LiveSplit,ROMaster2/LiveSplit,Dalet/LiveSplit,Glurmo/LiveSplit,Fluzzarn/LiveSplit
|
LiveSplit/LiveSplit.Core/Model/AtomicDateTime.cs
|
LiveSplit/LiveSplit.Core/Model/AtomicDateTime.cs
|
using System;
namespace LiveSplit.Model
{
public struct AtomicDateTime
{
public DateTime Time { get; private set; }
public bool SyncedWithAtomicClock { get; private set; }
public AtomicDateTime(DateTime time, bool synced) : this()
{
Time = time;
SyncedWithAtomicClock = synced;
}
public static TimeSpan operator -(AtomicDateTime a, AtomicDateTime b)
{
return a.Time - b.Time;
}
public static TimeSpan operator -(AtomicDateTime a, DateTime b)
{
return a.Time - b;
}
}
}
|
using System;
namespace LiveSplit.Model
{
public struct AtomicDateTime
{
public DateTime Time { get; private set; }
public bool SyncedWithAtomicClock { get; private set; }
public AtomicDateTime(DateTime time, bool synced)
{
Time = time;
SyncedWithAtomicClock = synced;
}
public static TimeSpan operator -(AtomicDateTime a, AtomicDateTime b)
{
return a.Time - b.Time;
}
public static TimeSpan operator -(AtomicDateTime a, DateTime b)
{
return a.Time - b;
}
}
}
|
mit
|
C#
|
a961f5379eb8f43de1fdbc1055a9af6c0ae976d6
|
Remove shared link
|
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
|
PlatformSamples/AspNetCoreMvc/Views/Home/Index.cshtml
|
PlatformSamples/AspNetCoreMvc/Views/Home/Index.cshtml
|
@{
ViewData["Title"] = "Ooui";
var formsSamples = SamplesController.Samples.Where(x => x.Title.StartsWith("Xamarin.Forms "));
var otherSamples = SamplesController.Samples.Where(x => !x.Title.StartsWith("Xamarin.Forms "));
}
<div class="row" style="margin-top:4em;">
<div class="col-md-2">
<img src="images/Icon.png" />
</div>
<div class="col-md-2">
<h1>Ooui</h1>
<p>Write interactive web apps in C# and F#</p>
<p><a href="https://github.com/praeclarum/Ooui">Source Code on GitHub</a></p>
</div>
</div>
<div class="row" style="margin-top:4em;">
<div class="col-md-4">
<h3>Xamarin.Forms Samples</h3>
<ul>
@foreach (var s in formsSamples) {
<li>
<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title">@s.Title.Substring(14)</a>
</li>
}
</ul>
</div>
<div class="col-md-4">
<h3>Plain Web Samples</h3>
<ul>
@foreach (var s in otherSamples) {
<li>
<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title">@s.Title</a>
</li>
}
</ul>
</div>
</div>
|
@{
ViewData["Title"] = "Ooui";
var formsSamples = SamplesController.Samples.Where(x => x.Title.StartsWith("Xamarin.Forms "));
var otherSamples = SamplesController.Samples.Where(x => !x.Title.StartsWith("Xamarin.Forms "));
}
<div class="row" style="margin-top:4em;">
<div class="col-md-2">
<img src="images/Icon.png" />
</div>
<div class="col-md-2">
<h1>Ooui</h1>
<p>Write interactive web apps in C# and F#</p>
<p><a href="https://github.com/praeclarum/Ooui">Source Code on GitHub</a></p>
</div>
</div>
<div class="row" style="margin-top:4em;">
<div class="col-md-4">
<h3>Xamarin.Forms Samples</h3>
<ul>
@foreach (var s in formsSamples) {
<li>
<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title">@s.Title.Substring(14)</a>
(<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title" asp-route-shared="@true">Shared</a>)
</li>
}
</ul>
</div>
<div class="col-md-4">
<h3>Plain Web Samples</h3>
<ul>
@foreach (var s in otherSamples) {
<li>
<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title">@s.Title</a>
(<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title" asp-route-shared="@true">Shared</a>)
</li>
}
</ul>
</div>
</div>
|
mit
|
C#
|
d88e856f1e36514f5c0cb59b62c559a75c94007e
|
improve assembly scanning
|
loresoft/AutoData,loresoft/DataGenerator
|
Source/DataGenerator/Extensions/AssemblyExtensions.cs
|
Source/DataGenerator/Extensions/AssemblyExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DataGenerator.Extensions
{
/// <summary>
/// <see cref="Assembly"/> extension methods
/// </summary>
public static class AssemblyExtensions
{
/// <summary>
/// Gets the types assignable from <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type to determine whether if it can be assigned.</typeparam>
/// <param name="assembly">The assembly to search types.</param>
/// <returns>An enumerable list of types the are assignable from <typeparamref name="T"/>.</returns>
/// <exception cref="System.ArgumentNullException">When assembly is null.</exception>
public static IEnumerable<Type> GetTypesAssignableFrom<T>(this Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
var type = typeof(T);
return assembly
.GetLoadableTypes()
.Where(t => t.IsPublic && !t.IsAbstract && type.IsAssignableFrom(t));
}
/// <summary>
/// Gets the public types defined in this assembly that are visible and can be loaded outside the assembly.
/// </summary>
/// <param name="assembly">The assembly to search types.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">assembly</exception>
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
// skip dynamic assemblies
if (assembly.IsDynamic)
return Enumerable.Empty<Type>();
Type[] types;
try
{
types = assembly.GetExportedTypes();
}
catch (ReflectionTypeLoadException e)
{
//not interested in the types which cause the problem, load what we can
types = e.Types.Where(t => t != null).ToArray();
}
catch(NotSupportedException)
{
// some assemblies don't support getting types, ignore
return Enumerable.Empty<Type>();
}
return types;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DataGenerator.Extensions
{
/// <summary>
/// <see cref="Assembly"/> extension methods
/// </summary>
public static class AssemblyExtensions
{
/// <summary>
/// Gets the types assignable from <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type to determine whether if it can be assigned.</typeparam>
/// <param name="assembly">The assembly to search types.</param>
/// <returns>An enumerable list of types the are assignable from <typeparamref name="T"/>.</returns>
/// <exception cref="System.ArgumentNullException">When assembly is null.</exception>
public static IEnumerable<Type> GetTypesAssignableFrom<T>(this Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
var type = typeof(T);
return assembly
.GetLoadableTypes()
.Where(t => t.IsPublic && !t.IsAbstract && type.IsAssignableFrom(t));
}
/// <summary>
/// Gets the public types defined in this assembly that are visible and can be loaded outside the assembly.
/// </summary>
/// <param name="assembly">The assembly to search types.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">assembly</exception>
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
Type[] types;
try
{
types = assembly.GetExportedTypes();
}
catch (ReflectionTypeLoadException e)
{
//not interested in the types which cause the problem, load what we can
types = e.Types.Where(t => t != null).ToArray();
}
return types;
}
}
}
|
apache-2.0
|
C#
|
16726f32a2d14b6c991e60e2983aa941bdc8a627
|
Build and publish Rock.Core.XSerializer nuget package
|
RockFramework/Rock.Core
|
Rock.Core.XSerializer/Properties/AssemblyInfo.cs
|
Rock.Core.XSerializer/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("Rock.Core.XSerializer")]
[assembly: AssemblyDescription("Core classes that use the XSerializer serialization library.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Core.XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2014-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("1b862782-3819-4348-93a1-dfcff22d2955")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.2")]
[assembly: AssemblyInformationalVersion("0.9.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("Rock.Core.XSerializer")]
[assembly: AssemblyDescription("Core classes that use the XSerializer serialization library.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Core.XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2014-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("1b862782-3819-4348-93a1-dfcff22d2955")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.1")]
[assembly: AssemblyInformationalVersion("0.9.1")]
|
mit
|
C#
|
10cda40e9b6647b59387669bcfba4cc2c5d43657
|
make tests pass
|
Pondidum/NScientist,Pondidum/NScientist
|
NScientist/Experiment.cs
|
NScientist/Experiment.cs
|
using System;
namespace NScientist
{
public class Experiment
{
public static ExperimentConfig<object> On(Action action)
{
return new ExperimentConfig<object>(() =>
{
action();
return null;
});
}
public static ExperimentConfig<T> On<T>(Func<T> action)
{
return new ExperimentConfig<T>(action);
}
}
public class ExperimentConfig<TResult>
{
private readonly Func<TResult> _control;
private Action _test;
public ExperimentConfig(Func<TResult> action)
{
_control = action;
}
public ExperimentConfig<TResult> Try(Action action)
{
_test = action;
return this;
}
public TResult Run()
{
_test();
return _control();
}
}
}
|
using System;
namespace NScientist
{
public class Experiment
{
public static ExperimentConfig<object> On(Action action)
{
return new ExperimentConfig<object>();
}
public static ExperimentConfig<T> On<T>(Func<T> action)
{
return new ExperimentConfig<T>();
}
}
public class ExperimentConfig<TResult>
{
public ExperimentConfig<TResult> Try(Action action)
{
throw new NotImplementedException();
}
public TResult Run()
{
throw new NotImplementedException();
}
}
}
|
lgpl-2.1
|
C#
|
2535ec35f22e5f7305cc261bbbe52f62b9e663ab
|
Update sortedBitSearch.cs
|
michaeljwebb/Algorithm-Practice
|
Other/sortedBitSearch.cs
|
Other/sortedBitSearch.cs
|
//Given an array of sorted 0s and 1s, count how many 1st exist
//Space complexity: O(1)
//Time complexity: O(log(N)) where N is the number of digits
//Example: [0,0,0,0,0,1,1,1] -> 3
using System;
public class Program
{
public static void Main()
{
int[] arr = { 0, 0, 0, 1, 1, 1, 1 };
int n = arr.Length;
Console.WriteLine("Count of 1's in given array is: " + CountOnes(arr, 0, n - 1));
}
public static int CountOnes(int[] arr, int left, int right)
{
//if last element of array is 0, no ones are present since its sorted
if(arr[right] == 0)
{
return 0;
}
//if first element of array is 1, all elements are 1 since its sorted
if(arr[left] == 1)
{
return (right - left + 1);
}
//divide array into left and right sub array
int mid = (left + right) / 2;
return CountOnes(arr, left, mid) + CountOnes(arr, mid + 1, right);
}
}
|
//Given an array of sorted 0s and 1s, count how many 1st exist
//Space complexity: O(1)
//Time complexity: O(log(N)) where N is the number of digits
//Example: [0,0,0,0,0,1,1,1] -> 3
using System;
public class Program
{
public static void Main()
{
int[] arr = { 0, 0, 0, 1, 1, 1, 1 };
int n = arr.Length;
Console.WriteLine("Count of 1's in given array is: " + CountOnes(arr, 0, n - 1));
}
public static int CountOnes(int[] arr, int left, int right)
{
//if last element of array is 0, no ones are present since its sorted
if(arr[right] == 0)
{
return 0;
}
//if first element of array is 1, all elements are 1 since its sorted
if(arr[left] == 1)
{
return (right - left + 1);
}
//divide array into left and right sub array
int mid = (left + right) / 2;
return CountOnes(arr, left, mid) + CountOnes(arr, mid + 1, right);
}
}
|
mit
|
C#
|
860df035bc7f39b4f043cddf8aa4eaf1cd607641
|
Fix header behavior for the fixed length types
|
forcewake/FlatFile
|
src/FlatFile.FixedLength.Attributes/Infrastructure/FixedLayoutDescriptorProvider.cs
|
src/FlatFile.FixedLength.Attributes/Infrastructure/FixedLayoutDescriptorProvider.cs
|
namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container)
{
HasHeader = false
};
return descriptor;
}
}
}
|
namespace FlatFile.FixedLength.Attributes.Infrastructure
{
using System;
using System.Linq;
using FlatFile.Core;
using FlatFile.Core.Attributes.Extensions;
using FlatFile.Core.Attributes.Infrastructure;
using FlatFile.Core.Base;
public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>>
{
public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>()
{
var container = new FieldsContainer<FixedFieldSettings>();
var fileMappingType = typeof(T);
var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>();
if (fileAttribute == null)
{
throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute",
fileMappingType.Name,
typeof(FixedLengthFileAttribute).Name));
}
var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>();
foreach (var p in properties)
{
var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute;
if (attribute != null)
{
var fieldSettings = attribute.GetFieldSettings(p.Property);
container.AddOrUpdate(fieldSettings, false);
}
}
var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container);
return descriptor;
}
}
}
|
mit
|
C#
|
e3d5f8d39b1d0da877d24bd1c41f675ede719e70
|
Clean up type checking code
|
stratisproject/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode
|
Stratis.Bitcoin/Builder/Feature/FeaturesExtensions.cs
|
Stratis.Bitcoin/Builder/Feature/FeaturesExtensions.cs
|
using System.Collections.Generic;
using System.Linq;
namespace Stratis.Bitcoin.Builder.Feature
{
/// <summary>
/// Extensions to features collection.
/// </summary>
public static class FeaturesExtensions
{
/// <summary>
/// Ensures a dependency feature type is present in the feature list.
/// </summary>
/// <typeparam name="T">The dependency feature type.</typeparam>
/// <param name="features">List of features.</param>
/// <returns>List of features.</returns>
/// <exception cref="MissingDependencyException">Thrown if feature type is missing.</exception>
public static IEnumerable<IFullNodeFeature> EnsureFeature<T>(this IEnumerable<IFullNodeFeature> features)
{
if (!features.OfType<T>().Any())
{
throw new MissingDependencyException($"Dependency feature {typeof(T)} cannot be found.");
}
return features;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Stratis.Bitcoin.Builder.Feature
{
/// <summary>
/// Extensions to features collection.
/// </summary>
public static class FeaturesExtensions
{
/// <summary>
/// Ensures a dependency feature type is present in the feature registration.
/// </summary>
/// <typeparam name="T">The dependency feature type.</typeparam>
/// <param name="features">List of feature registrations.</param>
/// <returns>List of feature registrations.</returns>
/// <exception cref="MissingDependencyException">Thrown if feature type is missing.</exception>
public static IEnumerable<IFullNodeFeature> EnsureFeature<T>(this IEnumerable<IFullNodeFeature> features)
{
if (!features.Any(i => i.GetType() == typeof(T)))
{
throw new MissingDependencyException($"Dependency feature {typeof(T)} cannot be found.");
}
return features;
}
}
}
|
mit
|
C#
|
4280ede14393bc708932c78681eb4a469fe9d74a
|
Improve Beam-weapon toString to include rating value
|
skeolan/FireAndManeuver
|
GameModel/entities/unitSystems/Weapons/BeamBatterySystem.cs
|
GameModel/entities/unitSystems/Weapons/BeamBatterySystem.cs
|
// <copyright file="BeamBatterySystem.cs" company="Patrick Maughan">
// Copyright (c) Patrick Maughan. All rights reserved.
// </copyright>
namespace FireAndManeuver.GameModel
{
using System.Xml.Serialization;
public class BeamBatterySystem : ArcWeaponSystem
{
[XmlIgnore]
private const string BaseSystemName = "Beam Battery System";
[XmlIgnore]
private string arcs;
public BeamBatterySystem()
: base()
{
this.SystemName = "Beam Battery System";
this.Rating = 1;
this.Arcs = "(All arcs)";
}
public BeamBatterySystem(int rating)
{
this.SystemName = $"Beam Battery System";
this.Rating = rating;
// Default is "all arcs" for a B1
this.Arcs = rating == 1 ? "(All arcs)" : "(F)";
}
public BeamBatterySystem(int rating, string arcs)
{
this.SystemName = $"Beam Battery System";
this.Rating = rating;
this.Arcs = arcs;
}
[XmlAttribute("rating")]
public int Rating { get; set; } = 1;
[XmlAttribute("arcs")]
public override string Arcs
{
get
{
var arcString = this.Rating == 1 ? "(All arcs)" : string.IsNullOrWhiteSpace(this.arcs) ? "(F)" : this.arcs;
return arcString;
}
set
{
this.arcs = value;
}
}
public override string ToString()
{
this.SystemName = $"Class-{this.Rating} {BaseSystemName}";
return base.ToString();
}
}
}
|
// <copyright file="BeamBatterySystem.cs" company="Patrick Maughan">
// Copyright (c) Patrick Maughan. All rights reserved.
// </copyright>
namespace FireAndManeuver.GameModel
{
using System.Xml.Serialization;
public class BeamBatterySystem : ArcWeaponSystem
{
[XmlIgnore]
private string arcs;
public BeamBatterySystem()
: base()
{
this.SystemName = "Class-1 Beam Battery System";
this.Rating = 1;
this.Arcs = "(All arcs)";
}
public BeamBatterySystem(int rating)
{
this.SystemName = $"Class-{rating} Beam Battery System";
this.Rating = rating;
// Default is "all arcs" for a B1,
this.Arcs = rating == 1 ? "(All arcs)" : "(F)";
}
public BeamBatterySystem(int rating, string arcs)
{
this.SystemName = $"Class-{rating} Beam Battery System";
this.Rating = rating;
this.Arcs = arcs;
}
[XmlAttribute("rating")]
public int Rating { get; set; } = 1;
[XmlAttribute("arcs")]
public override string Arcs
{
get
{
var arcString = this.Rating == 1 ? "(All arcs)" : string.IsNullOrWhiteSpace(this.arcs) ? "(F)" : this.arcs;
return arcString;
}
set
{
this.arcs = value;
}
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.