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 |
|---|---|---|---|---|---|---|---|---|
db1ad6b75439dea596052234ca78cc74e61d4485 | fix the icon position | PatrickDinh/frankenwiki,frankenwiki/frankenwiki,bendetat/frankenwiki | src/Frankenwiki.Example.NancyWeb/Views/page.cshtml | src/Frankenwiki.Example.NancyWeb/Views/page.cshtml | @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Frankenwiki.Frankenpage>
@using System
@using System.Linq
@{
Layout = "_Layout.cshtml";
ViewBag.Title = Model.Title;
}
@section tools {
<li><span class="glyphicon glyphicon-link"></span> <a href="/what-links-to/@Model.Slug" title="A list of articles that link to this article">What links here</a></li>
}
<h1>@Model.Title</h1>
<hr />
@Html.Raw(Model.Html)
@if (Model.Categories.Any())
{
<hr />
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-education"></span> Categories</h3>
<div class="panel-body">
<ul>
@foreach (var category in Model.Categories)
{
<li><a href="/category/@category.Slug">@category.Name</a></li>
}
</ul>
</div>
</div>
</div>
}
| @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Frankenwiki.Frankenpage>
@using System
@using System.Linq
@{
Layout = "_Layout.cshtml";
ViewBag.Title = Model.Title;
}
@section tools {
<li><a href="/what-links-to/@Model.Slug" title="A list of articles that link to this article"><span class="glyphicon glyphicon-link"></span> What links here</a></li>
}
<h1>@Model.Title</h1>
<hr />
@Html.Raw(Model.Html)
@if (Model.Categories.Any())
{
<hr />
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-education"></span> Categories</h3>
<div class="panel-body">
<ul>
@foreach (var category in Model.Categories)
{
<li><a href="/category/@category.Slug">@category.Name</a></li>
}
</ul>
</div>
</div>
</div>
}
| apache-2.0 | C# |
b90fc4cbf579f2ea0bb4923ae9c9591004a92bbe | clean up assembly properties for nuget. | mikeckennedy/mongodb-query-helper-for-dotnet,ChrisMcKee/mongodb-query-helper-for-dotnet | src/MongoDB.QueryHelper/Properties/AssemblyInfo.cs | src/MongoDB.QueryHelper/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("MongoDB.Kennedy")]
[assembly: AssemblyDescription("MongoDB query helper library.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("PDX Web Properties, LLC.")]
[assembly: AssemblyProduct("MongoDB.QueryHelper")]
[assembly: AssemblyCopyright("Copyright © Michael Kennedy 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MongoDB.QueryHelper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MongoDB.QueryHelper")]
[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("ac177cc9-a6fd-4caf-8fa9-c7a120f18608")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
3b80815c4ec60a35ae318d1ac81f3fcc350f5b84 | Rewrite ExceptionPanel component to use Alert component. | maraf/Money,maraf/Money,maraf/Money | src/Money.UI.Blazor/Components/ExceptionPanel.cshtml | src/Money.UI.Blazor/Components/ExceptionPanel.cshtml | @inject Neptuo.Exceptions.Handlers.ExceptionHandlerBuilder ExceptionHandlerBuilder
@inject Money.Services.MessageBuilder MessageBuilder
@if (LastException != null)
{
<Alert Title="@Title" Message="@Message" Mode="AlertMode.Error" IsDismissible="true" />
}
@functions {
public Exception LastException { get; private set; }
public string Title { get; private set; }
public string Message { get; private set; }
protected override async Task OnInitAsync()
{
ExceptionHandlerBuilder.Handler(e =>
{
LastException = e;
if (e is Neptuo.Models.AggregateRootException)
{
string message = null;
if (e is CurrencyAlreadyAsDefaultException)
message = MessageBuilder.CurrencyAlreadyAsDefault();
else if (e is CurrencyAlreadyExistsException)
message = MessageBuilder.CurrencyAlreadyExists();
else if (e is CurrencyDoesNotExistException)
message = MessageBuilder.CurrencyDoesNotExist();
else if (e is CurrencyExchangeRateDoesNotExistException)
message = MessageBuilder.CurrencyExchangeRateDoesNotExist();
else if (e is OutcomeAlreadyDeletedException)
message = MessageBuilder.OutcomeAlreadyDeleted();
else if (e is OutcomeAlreadyHasCategoryException)
message = MessageBuilder.OutcomeAlreadyHasCategory();
else if (e is CantDeleteDefaultCurrencyException)
message = MessageBuilder.CantDeleteDefaultCurrency();
else if (e is CantDeleteLastCurrencyException)
message = MessageBuilder.CantDeleteLastCurrency();
Message = message;
}
if (Message == null)
{
Title = LastException.GetType().FullName;
Message = LastException.Message;
}
else
{
Title = null;
}
StateHasChanged();
});
}
}
| @inject Neptuo.Exceptions.Handlers.ExceptionHandlerBuilder ExceptionHandlerBuilder
@inject Money.Services.MessageBuilder MessageBuilder
@if (LastException != null)
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
@if (LastExceptionUserMessage != null)
{
<strong>
@LastExceptionUserMessage
</strong>
}
else
{
<strong>
@LastException.GetType().FullName:
</strong>
<span>
@LastException.Message
</span>
}
</div>
}
@functions {
public Exception LastException { get; private set; }
public string LastExceptionUserMessage { get; private set; }
protected override async Task OnInitAsync()
{
ExceptionHandlerBuilder.Handler(e =>
{
LastException = e;
if (e is Neptuo.Models.AggregateRootException)
{
string message = null;
if (e is CurrencyAlreadyAsDefaultException)
message = MessageBuilder.CurrencyAlreadyAsDefault();
else if (e is CurrencyAlreadyExistsException)
message = MessageBuilder.CurrencyAlreadyExists();
else if (e is CurrencyDoesNotExistException)
message = MessageBuilder.CurrencyDoesNotExist();
else if (e is CurrencyExchangeRateDoesNotExistException)
message = MessageBuilder.CurrencyExchangeRateDoesNotExist();
else if (e is OutcomeAlreadyDeletedException)
message = MessageBuilder.OutcomeAlreadyDeleted();
else if (e is OutcomeAlreadyHasCategoryException)
message = MessageBuilder.OutcomeAlreadyHasCategory();
else if (e is CantDeleteDefaultCurrencyException)
message = MessageBuilder.CantDeleteDefaultCurrency();
else if (e is CantDeleteLastCurrencyException)
message = MessageBuilder.CantDeleteLastCurrency();
LastExceptionUserMessage = message;
}
StateHasChanged();
});
}
}
| apache-2.0 | C# |
f87c98458de0b3695c7eadd62886b94d56121a62 | Improve the documentation on IArgument<>. | mikebarker/Plethora.NET | src/Plethora.Cache/IArgument.cs | src/Plethora.Cache/IArgument.cs | using System.Collections.Generic;
namespace Plethora.Cache
{
/// <summary>
/// Interface defining the methods required by the <see cref="CacheBase{TData,TArgument}"/> class.
/// </summary>
/// <typeparam name="TData">The data type returned by </typeparam>
/// <typeparam name="TArgument">The implementation type of this interface.</typeparam>
/// <example>
/// To use this interface with the <see cref="CacheBase{TData,TArgument}"/> class, the
/// generic parameter <typeparamref name="TArgument"/> should be set to the implementing
/// class, e.g.:
/// <code>
/// <![CDATA[
/// public class FooBarArgument : IArgument<FooBar, FooBarArgument>
/// {
/// //...
/// }
/// ]]>
/// </code>
/// </example>
/// <remarks>
/// <see cref="IArgument{TData,TArgument}"/> should be thought of as representing a set within the
/// key-space of the data class. That is if the data is uniquely identified by a single ID field,
/// then the <see cref="IArgument{TData,TArgument}"/> implementation should describe the ID (or IDs)
/// of data required. It may represent a single ID (e.g. 10564) or a range (e.g. 10200-10800).
/// </remarks>
public interface IArgument<TData, TArgument>
{
/// <summary>
/// Gets a value indicating whether two arguments overlap in the key-space which they represent.
/// </summary>
/// <param name="B">
/// An instance of <see cref="IArgument{TData,TArgument}"/> which is to be tested against this instance.
/// </param>
/// <param name="notInB">
/// <para>
/// The enumeration of <see cref="IArgument{TData,TArgument}"/> which represents the portion of
/// this which is not overlapped by <paramref name="B"/>.
/// </para>
/// <para>
/// In the case where this is entirely covered by <paramref name="B"/> the <paramref name="notInB"/>
/// argument can be returned as null or as an empty enumeration.
/// </para>
/// <para>
/// The return value is ignored in the case where false is returned, as there is no overlap.
/// </para>
/// </param>
/// <returns></returns>
/// <remarks>
/// If one considers the aruments which represent the following sets over the key space:
/// <code>
/// <![CDATA[
/// (B)
/// +----------------------+
/// | | this
/// | +-------|-------------+
/// | | |#############|
/// | | |#############|
/// | | |#############|
/// | | |#############|
/// +----------------------+#############|
/// |#####################|
/// |#####################|
/// +---------------------+
/// ]]>
/// </code>
/// In the above case <see cref="IsOverlapped"/> should return true (since this and B share
/// some of the key-space, and <paramref name="notInB"/> should represent the hashed area.
/// </remarks>
bool IsOverlapped(
TArgument B,
out IEnumerable<TArgument> notInB);
/// <summary>
/// A filtering function which returns a flag indicating whether data is represented by this
/// argument instance.
/// </summary>
/// <param name="data">The data to be tested.</param>
/// <returns>true if the <paramref name="data"/> parameter is represented by this instance.</returns>
bool IsDataIncluded(TData data);
}
}
| using System.Collections.Generic;
namespace Plethora.Cache
{
public interface IArgument<TData, TArgument>
{
//TODO: Type documentation
bool IsOverlapped(
TArgument B,
out IEnumerable<TArgument> notInB);
bool IsDataIncluded(TData data);
}
}
| mit | C# |
74a6faf9b9b87a3dd28805686a5bb0e9c40780e1 | Bring tasks in | jefking/King.Service.ServiceBus | Demo/King.Service.ServiceBus.WorkerRole/Factory.cs | Demo/King.Service.ServiceBus.WorkerRole/Factory.cs | namespace King.Service.ServiceBus
{
using King.Service.ServiceBus.Queue;
using King.Service.WorkerRole;
using King.Service.WorkerRole.Queue;
using System.Collections.Generic;
/// <summary>
/// Facotry
/// </summary>
public class Factory : ITaskFactory<Configuration>
{
/// <summary>
/// Load Tasks
/// </summary>
/// <param name="passthrough"></param>
/// <returns></returns>
public IEnumerable<IRunnable> Tasks(Configuration config)
{
//Connections
var pollReceiver = new BusQueueReciever(config.PollingName, config.Connection);
var pollSender = new BusQueueSender(config.PollingName, config.Connection);
var eventReciever = new BusQueueReciever(config.EventsName, config.Connection);
var eventSender = new BusQueueSender(config.EventsName, config.Connection);
var bufferReciever = new BusQueueReciever(config.BufferedEventsName, config.Connection);
var bufferSender = new BusQueueSender(config.BufferedEventsName, config.Connection);
//Initialize Polling
yield return new InitializeBusQueue(pollReceiver);
yield return new InitializeBusQueue(eventSender);
yield return new InitializeBusQueue(bufferReciever);
//Load polling dequeue object to run
var dequeue = new BusDequeue<ExampleModel>(pollReceiver, new ExampleProcessor());
//Polling Dequeue Runner
yield return new AdaptiveRunner(dequeue);
//Task for watching for queue events
yield return new BusEvents<ExampleModel>(eventReciever, new EventHandler());
//Task for recieving queue events to specific times
yield return new BufferedReciever<ExampleModel>(bufferReciever, new EventHandler());
//Tasks for queuing work
yield return new QueueForAction(pollSender, "Poll");
yield return new QueueForAction(eventSender, "Event");
yield return new QueueForBuffer(bufferSender);
}
}
} | namespace King.Service.ServiceBus
{
using King.Service.ServiceBus.Queue;
using King.Service.WorkerRole;
using King.Service.WorkerRole.Queue;
using System.Collections.Generic;
/// <summary>
/// Facotry
/// </summary>
public class Factory : ITaskFactory<Configuration>
{
/// <summary>
/// Load Tasks
/// </summary>
/// <param name="passthrough"></param>
/// <returns></returns>
public IEnumerable<IRunnable> Tasks(Configuration config)
{
//Connections
var pollReceiver = new BusQueueReciever(config.PollingName, config.Connection);
var pollSender = new BusQueueSender(config.PollingName, config.Connection);
var eventReciever = new BusQueueReciever(config.EventsName, config.Connection);
var eventSender = new BusQueueSender(config.EventsName, config.Connection);
var bufferReciever = new BusQueueReciever(config.BufferedEventsName, config.Connection);
var bufferSender = new BusQueueSender(config.BufferedEventsName, config.Connection);
//Initialize Polling
yield return new InitializeBusQueue(pollReceiver);
yield return new InitializeBusQueue(eventSender);
yield return new InitializeBusQueue(bufferReciever);
//Load polling dequeue object to run
var dequeue = new BusDequeue<ExampleModel>(pollReceiver, new ExampleProcessor());
//Polling Dequeue Runner
//yield return new AdaptiveRunner(dequeue);
//Task for watching for queue events
//yield return new BusEvents<ExampleModel>(eventReciever, new EventHandler());
//Task for recieving queue events to specific times
yield return new BufferedReciever<ExampleModel>(bufferReciever, new EventHandler());
//Tasks for queuing work
yield return new QueueForAction(pollSender, "Poll");
yield return new QueueForAction(eventSender, "Event");
yield return new QueueForAction(bufferSender, "Buffer");
}
}
} | mit | C# |
f9d87f03431c9067f903ede535b5b6067f50e2c4 | Bump to version 0.3.1 | neitsa/PrepareLanding,neitsa/PrepareLanding | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PrepareLanding")]
[assembly: AssemblyDescription("A RimWorld Alpha 17 mod")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("neitsa")]
[assembly: AssemblyProduct("PrepareLanding")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("417e7144-1b89-42b4-ae98-7b3bbd6303da")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.1.0")]
[assembly: AssemblyFileVersion("0.3.1.0")]
| 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("PrepareLanding")]
[assembly: AssemblyDescription("A RimWorld Alpha 17 mod")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("neitsa")]
[assembly: AssemblyProduct("PrepareLanding")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("417e7144-1b89-42b4-ae98-7b3bbd6303da")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
| mit | C# |
e7931ef4c79302434d5468cdbf3acadb0b771ff8 | Add a default icon when a ruleset isn't present | NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,Drezi126/osu,NeoAdonis/osu,peppy/osu,peppy/osu,UselessToucan/osu,DrabWeb/osu,smoogipoo/osu,2yangk23/osu,naoey/osu,Frontear/osuKyzer,ZLima12/osu,ppy/osu,DrabWeb/osu,UselessToucan/osu,ZLima12/osu,naoey/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,DrabWeb/osu,ppy/osu,johnneijzen/osu,naoey/osu,johnneijzen/osu,Nabile-Rahmani/osu,smoogipooo/osu | osu.Game/Beatmaps/Drawables/DifficultyIcon.cs | osu.Game/Beatmaps/Drawables/DifficultyIcon.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using OpenTK;
namespace osu.Game.Beatmaps.Drawables
{
public class DifficultyIcon : DifficultyColouredContainer
{
private readonly BeatmapInfo beatmap;
public DifficultyIcon(BeatmapInfo beatmap) : base(beatmap)
{
this.beatmap = beatmap;
Size = new Vector2(20);
}
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = AccentColour,
Icon = FontAwesome.fa_circle
},
new ConstrainedIconContainer
{
RelativeSizeAxes = Axes.Both,
// the null coalesce here is only present to make unit tests work (ruleset dlls aren't copied correctly for testing at the moment)
Icon = beatmap.Ruleset?.CreateInstance().CreateIcon() ?? new SpriteIcon { Icon = FontAwesome.fa_question_circle_o }
}
};
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using OpenTK;
namespace osu.Game.Beatmaps.Drawables
{
public class DifficultyIcon : DifficultyColouredContainer
{
private readonly BeatmapInfo beatmap;
public DifficultyIcon(BeatmapInfo beatmap) : base(beatmap)
{
this.beatmap = beatmap;
Size = new Vector2(20);
}
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = AccentColour,
Icon = FontAwesome.fa_circle
},
new ConstrainedIconContainer
{
RelativeSizeAxes = Axes.Both,
Icon = beatmap.Ruleset.CreateInstance().CreateIcon()
}
};
}
}
}
| mit | C# |
fb3ffe229fb968d394068179d15fe4fd2447e338 | Make some properties get-only | dirkrombauts/pickles,magicmonty/pickles,picklesdoc/pickles,blorgbeard/pickles,magicmonty/pickles,blorgbeard/pickles,picklesdoc/pickles,blorgbeard/pickles,picklesdoc/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,magicmonty/pickles,ludwigjossieaux/pickles,magicmonty/pickles,blorgbeard/pickles,dirkrombauts/pickles | src/Pickles/Pickles/DirectoryCrawler/FeatureNode.cs | src/Pickles/Pickles/DirectoryCrawler/FeatureNode.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="FeatureNode.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO.Abstractions;
using PicklesDoc.Pickles.Extensions;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.DirectoryCrawler
{
public class FeatureNode : INode
{
public FeatureNode(FileSystemInfoBase location, string relativePathFromRoot, Feature feature)
{
this.OriginalLocation = location;
this.OriginalLocationUrl = location.ToUri();
this.RelativePathFromRoot = relativePathFromRoot;
this.Feature = feature;
}
public Feature Feature { get; }
public NodeType NodeType
{
get { return NodeType.Content; }
}
public string Name
{
get { return this.Feature.Name; }
}
public FileSystemInfoBase OriginalLocation { get; }
public Uri OriginalLocationUrl { get; }
public string RelativePathFromRoot { get; }
public string GetRelativeUriTo(Uri other, string newExtension)
{
return other.GetUriForTargetRelativeToMe(this.OriginalLocation, newExtension);
}
public string GetRelativeUriTo(Uri other)
{
return this.GetRelativeUriTo(other, ".html");
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="FeatureNode.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO.Abstractions;
using PicklesDoc.Pickles.Extensions;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.DirectoryCrawler
{
public class FeatureNode : INode
{
public FeatureNode(FileSystemInfoBase location, string relativePathFromRoot, Feature feature)
{
this.OriginalLocation = location;
this.OriginalLocationUrl = location.ToUri();
this.RelativePathFromRoot = relativePathFromRoot;
this.Feature = feature;
}
public Feature Feature { get; set; }
public NodeType NodeType
{
get { return NodeType.Content; }
}
public string Name
{
get { return this.Feature.Name; }
}
public FileSystemInfoBase OriginalLocation { get; private set; }
public Uri OriginalLocationUrl { get; private set; }
public string RelativePathFromRoot { get; private set; }
public string GetRelativeUriTo(Uri other, string newExtension)
{
return other.GetUriForTargetRelativeToMe(this.OriginalLocation, newExtension);
}
public string GetRelativeUriTo(Uri other)
{
return this.GetRelativeUriTo(other, ".html");
}
}
}
| apache-2.0 | C# |
5c13cbcf88e9e2c9ab85fef356fe55af8d66cc05 | add version to seal status | rajanadar/VaultSharp | src/VaultSharp/Backends/System/Models/SealStatus.cs | src/VaultSharp/Backends/System/Models/SealStatus.cs | using Newtonsoft.Json;
namespace VaultSharp.Backends.System.Models
{
/// <summary>
/// Represents the Seal status of the Vault.
/// </summary>
public class SealStatus
{
/// <summary>
/// Gets or sets a value indicating about the <see cref="SealStatus"/>.
/// </summary>
/// <value>
/// <c>true</c> if sealed; otherwise, <c>false</c>.
/// </value>
[JsonProperty("sealed")]
public bool Sealed { get; set; }
/// <summary>
/// Gets or sets the number of shares required to reconstruct the master key.
/// </summary>
/// <value>
/// The secret threshold.
/// </value>
[JsonProperty("t")]
public int SecretThreshold { get; set; }
/// <summary>
/// Gets or sets the number of shares to split the master key into.
/// </summary>
/// <value>
/// The secret shares.
/// </value>
[JsonProperty("n")]
public int SecretShares { get; set; }
/// <summary>
/// Gets or sets the number of shares that have been successfully applied to reconstruct the master key.
/// When the value is about to reach <see cref="SecretThreshold"/>, the Vault will be unsealed and the value will become <value>0</value>.
/// </summary>
/// <value>
/// The progress count.
/// </value>
[JsonProperty("progress")]
public int Progress { get; set; }
/// <summary>
/// Gets or sets the vault version.
/// </summary>
/// <value>
/// The version.
/// </value>
[JsonProperty("version")]
public string Version { get; set; }
}
} | using Newtonsoft.Json;
namespace VaultSharp.Backends.System.Models
{
/// <summary>
/// Represents the Seal status of the Vault.
/// </summary>
public class SealStatus
{
/// <summary>
/// Gets or sets a value indicating about the <see cref="SealStatus"/>.
/// </summary>
/// <value>
/// <c>true</c> if sealed; otherwise, <c>false</c>.
/// </value>
[JsonProperty("sealed")]
public bool Sealed { get; set; }
/// <summary>
/// Gets or sets the number of shares required to reconstruct the master key.
/// </summary>
/// <value>
/// The secret threshold.
/// </value>
[JsonProperty("t")]
public int SecretThreshold { get; set; }
/// <summary>
/// Gets or sets the number of shares to split the master key into.
/// </summary>
/// <value>
/// The secret shares.
/// </value>
[JsonProperty("n")]
public int SecretShares { get; set; }
/// <summary>
/// Gets or sets the number of shares that have been successfully applied to reconstruct the master key.
/// When the value is about to reach <see cref="SecretThreshold"/>, the Vault will be unsealed and the value will become <value>0</value>.
/// </summary>
/// <value>
/// The progress count.
/// </value>
[JsonProperty("progress")]
public int Progress { get; set; }
}
} | apache-2.0 | C# |
52c5a096b9b7225e3c9a7902f7d539ed7187e51b | Add comment. | EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,peppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,naoey/osu-framework,RedNesto/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,RedNesto/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,default0/osu-framework,peppy/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,default0/osu-framework | osu.Framework/Graphics/Containers/AsyncLoadContainer.cs | osu.Framework/Graphics/Containers/AsyncLoadContainer.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Threading.Tasks;
using osu.Framework.Allocation;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A container which asynchronously loads its children.
/// </summary>
public class AsyncLoadContainer : Container
{
/// <param name="content">The content which should be asynchronously loaded. Note that the <see cref="RelativeSizeAxes"/> and <see cref="AutoSizeAxes"/> of this container
/// will be transferred as the default for this <see cref="AsyncLoadContainer"/>'s content.</param>
public AsyncLoadContainer(Container content)
{
if (content == null)
throw new ArgumentNullException(nameof(content), $@"{nameof(AsyncLoadContainer)} required non-null {nameof(content)}.");
this.content = content;
RelativeSizeAxes = content.RelativeSizeAxes;
AutoSizeAxes = content.AutoSizeAxes;
}
private readonly Container content;
protected virtual bool ShouldLoadContent => true;
[BackgroundDependencyLoader]
private void load()
{
if (ShouldLoadContent)
loadContentAsync();
}
protected override void Update()
{
base.Update();
if (!LoadTriggered && ShouldLoadContent)
loadContentAsync();
}
private Task loadTask;
private void loadContentAsync()
{
loadTask = LoadComponentAsync(content, AddInternal);
}
/// <summary>
/// True if the load task for our content has been started.
/// Will remain true even after load is completed.
/// </summary>
protected bool LoadTriggered => loadTask != null;
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Threading.Tasks;
using osu.Framework.Allocation;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A container which asynchronously loads its children.
/// </summary>
public class AsyncLoadContainer : Container
{
public AsyncLoadContainer(Container content)
{
if (content == null)
throw new ArgumentNullException(nameof(content), $@"{nameof(AsyncLoadContainer)} required non-null {nameof(content)}.");
this.content = content;
RelativeSizeAxes = content.RelativeSizeAxes;
AutoSizeAxes = content.AutoSizeAxes;
}
private readonly Container content;
protected virtual bool ShouldLoadContent => true;
[BackgroundDependencyLoader]
private void load()
{
if (ShouldLoadContent)
loadContentAsync();
}
protected override void Update()
{
base.Update();
if (!LoadTriggered && ShouldLoadContent)
loadContentAsync();
}
private Task loadTask;
private void loadContentAsync()
{
loadTask = LoadComponentAsync(content, AddInternal);
}
/// <summary>
/// True if the load task for our content has been started.
/// Will remain true even after load is completed.
/// </summary>
protected bool LoadTriggered => loadTask != null;
}
}
| mit | C# |
8a988b95daa51254abb93aa59b535b6650e564e7 | Add ExpectedPaymentDate and PlannedPaymentDate to Invoice model | jcvandan/XeroAPI.Net,XeroAPI/XeroAPI.Net,TDaphneB/XeroAPI.Net,MatthewSteeples/XeroAPI.Net | source/XeroApi/Model/Invoice.cs | source/XeroApi/Model/Invoice.cs | using System;
namespace XeroApi.Model
{
public class Invoice : EndpointModelBase, IAttachmentParent
{
[ItemId]
public virtual Guid InvoiceID { get; set; }
[ItemNumber]
public string InvoiceNumber { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public string Type { get; set; }
public string Reference { get; set; }
[ReadOnly]
public Payments Payments { get; set; }
[ReadOnly]
public CreditNotes CreditNotes { get; set; }
[ReadOnly]
public decimal? AmountDue { get; set; }
[ReadOnly]
public decimal? AmountPaid { get; set; }
[ReadOnly]
public decimal? AmountCredited { get; set; }
public string Url { get; set; }
[ReadOnly]
public string ExternalLinkProviderName { get; set; }
[ReadOnly]
public bool? SentToContact { get; set; }
[ReadOnly]
public bool? HasAttachments { get; set; }
public decimal? CurrencyRate { get; set; }
public Contact Contact { get; set; }
public DateTime? Date { get; set; }
public DateTime? DueDate { get; set; }
public virtual Guid? BrandingThemeID { get; set; }
public virtual string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public virtual LineItems LineItems { get; set; }
public virtual decimal? SubTotal { get; set; }
public virtual decimal? TotalDiscount { get; set; }
public virtual decimal? TotalTax { get; set; }
public virtual decimal? Total { get; set; }
public virtual string CurrencyCode { get; set; }
[ReadOnly]
public DateTime? FullyPaidOnDate { get; set; }
public DateTime? ExpectedPaymentDate { get; set; }
public DateTime? PlannedPaymentDate { get; set; }
public override string ToString()
{
return string.Format("Invoice:{0} Id:{1}", InvoiceNumber, InvoiceID);
}
}
public class Invoices : ModelList<Invoice>
{
}
} | using System;
namespace XeroApi.Model
{
public class Invoice : EndpointModelBase, IAttachmentParent
{
[ItemId]
public virtual Guid InvoiceID { get; set; }
[ItemNumber]
public string InvoiceNumber { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public string Type { get; set; }
public string Reference { get; set; }
[ReadOnly]
public Payments Payments { get; set; }
[ReadOnly]
public CreditNotes CreditNotes { get; set; }
[ReadOnly]
public decimal? AmountDue { get; set; }
[ReadOnly]
public decimal? AmountPaid { get; set; }
[ReadOnly]
public decimal? AmountCredited { get; set; }
public string Url { get; set; }
[ReadOnly]
public string ExternalLinkProviderName { get; set; }
[ReadOnly]
public bool? SentToContact { get; set; }
[ReadOnly]
public bool? HasAttachments { get; set; }
public decimal? CurrencyRate { get; set; }
public Contact Contact { get; set; }
public DateTime? Date { get; set; }
public DateTime? DueDate { get; set; }
public virtual Guid? BrandingThemeID { get; set; }
public virtual string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public virtual LineItems LineItems { get; set; }
public virtual decimal? SubTotal { get; set; }
public virtual decimal? TotalDiscount { get; set; }
public virtual decimal? TotalTax { get; set; }
public virtual decimal? Total { get; set; }
public virtual string CurrencyCode { get; set; }
[ReadOnly]
public DateTime? FullyPaidOnDate { get; set; }
public override string ToString()
{
return string.Format("Invoice:{0} Id:{1}", InvoiceNumber, InvoiceID);
}
}
public class Invoices : ModelList<Invoice>
{
}
} | mit | C# |
904a4daa985b8f5e37573520a9147ad9adb80167 | Add todo comment reminding of updating friends list along | ppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,peppy/osu | osu.Game/Overlays/Profile/Header/Components/AddFriendButton.cs | osu.Game/Overlays/Profile/Header/Components/AddFriendButton.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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Overlays.Profile.Header.Components
{
public class AddFriendButton : ProfileHeaderButton
{
public readonly Bindable<User> User = new Bindable<User>();
public override string TooltipText => "friends";
private OsuSpriteText followerText;
[BackgroundDependencyLoader]
private void load()
{
Child = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Direction = FillDirection.Horizontal,
Padding = new MarginPadding { Right = 10 },
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Icon = FontAwesome.Solid.User,
FillMode = FillMode.Fit,
Size = new Vector2(50, 14)
},
followerText = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Font = OsuFont.GetFont(weight: FontWeight.Bold)
}
}
};
// todo: when friending/unfriending is implemented, the APIAccess.Friends list should be updated accordingly.
User.BindValueChanged(user => updateFollowers(user.NewValue), true);
}
private void updateFollowers(User user) => followerText.Text = user?.FollowerCount.ToString("#,##0");
}
}
| // 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Overlays.Profile.Header.Components
{
public class AddFriendButton : ProfileHeaderButton
{
public readonly Bindable<User> User = new Bindable<User>();
public override string TooltipText => "friends";
private OsuSpriteText followerText;
[BackgroundDependencyLoader]
private void load()
{
Child = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Direction = FillDirection.Horizontal,
Padding = new MarginPadding { Right = 10 },
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Icon = FontAwesome.Solid.User,
FillMode = FillMode.Fit,
Size = new Vector2(50, 14)
},
followerText = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Font = OsuFont.GetFont(weight: FontWeight.Bold)
}
}
};
User.BindValueChanged(user => updateFollowers(user.NewValue), true);
}
private void updateFollowers(User user) => followerText.Text = user?.FollowerCount.ToString("#,##0");
}
}
| mit | C# |
b31a671a983372810c5f9ff7c947d544bf33272d | reset template to use protected OnConstruct-Method | dotmos/uGameFramework,dotmos/uGameFramework | Unity/Assets/GameFramework/Modules/ECS/_GenTemplates/_GenComponent.cs | Unity/Assets/GameFramework/Modules/ECS/_GenTemplates/_GenComponent.cs |
using System;
using System.Collections;
using System.Collections.Generic;
using ECS;
/*name:using*/ /*endname*/
/// <summary>
/*name:componentComment*/ /*endname*/
/// </summary>
[System.Serializable]
public partial class /*name:ComponentName*/GenTemplateComponent/*endname*/ : ECS.Component {
/*block:enum*/
/// <summary>
/*name:comment*//*endname*/
/// </summary>
public enum /*name:enumName*/State/*endname*/ : int
{
/*block:entry*//*block:comment*/
/// <summary>
/*name:comment*//*endname*/
/// </summary>/*endblock:comment*/
/*name:entryName*/
state1/*endname*/ /*name:entryNumber*//*endname*/,
/*endblock:entry*/
/*block:rip*/ state2 = 1,
state3 = 2,
/*endblock:rip*/
}
/*endblock:enum*/
/*block:field*/
/// <summary>
/*name:comment*//*endname*/
/// </summary>
/*name:attributes*//*endname*/
public /*name:type*/State/*endname*/ /*name:name*/state/*endname*/ /*name:value*/= State.state1/*endname*/;
/*endblock:field*/
protected override void OnConstruct() {
base.OnConstruct();
/*block:newInstance*/ this./*name:name*/state/*endname*/ = new /*name:type*/State()/*endname*/;
/*endblock:newInstance*/
}
/// <summary>
/// Copy values from other component. Shallow copy.
/// </summary>
/// <param name="target"></param>
public override void CopyValues(IComponent target) {
/*name:ComponentName*/GenTemplateComponent/*endname*/ component = (/*name:ComponentName*/GenTemplateComponent/*endname*/)target;
/*block:copyField*/ this./*name:name*/state/*endname*/ = component./*name:name*/state/*endname*/;
/*endblock:copyField*/
/*block:shallowCopy*/ this./*name:name*/state/*endname*/ = new /*name:type*/State()/*endname*/;
/*endblock:shallowCopy*/
}
public override IComponent Clone() {
var clone = new /*name:ComponentName*/GenTemplateComponent/*endname*/();
clone.CopyValues(this);
return clone;
}
}
/*block:rip*/
[System.Serializable]
public class GenTemplateComponent2 : ECS.Component
{
public float time;
public override IComponent Clone() {
throw new NotImplementedException();
}
public override void CopyValues(IComponent target) {
throw new NotImplementedException();
}
}
/*endblock:rip*/ |
using System;
using System.Collections;
using System.Collections.Generic;
using ECS;
/*name:using*/ /*endname*/
/// <summary>
/*name:componentComment*/ /*endname*/
/// </summary>
[System.Serializable]
public partial class /*name:ComponentName*/GenTemplateComponent/*endname*/ : ECS.Component {
/*block:enum*/
/// <summary>
/*name:comment*//*endname*/
/// </summary>
public enum /*name:enumName*/State/*endname*/ : int
{
/*block:entry*//*block:comment*/
/// <summary>
/*name:comment*//*endname*/
/// </summary>/*endblock:comment*/
/*name:entryName*/
state1/*endname*/ /*name:entryNumber*//*endname*/,
/*endblock:entry*/
/*block:rip*/ state2 = 1,
state3 = 2,
/*endblock:rip*/
}
/*endblock:enum*/
/*block:field*/
/// <summary>
/*name:comment*//*endname*/
/// </summary>
/*name:attributes*//*endname*/
public /*name:type*/State/*endname*/ /*name:name*/state/*endname*/ /*name:value*/= State.state1/*endname*/;
/*endblock:field*/
public override void OnConstruct() {
base.OnConstruct();
/*block:newInstance*/ this./*name:name*/state/*endname*/ = new /*name:type*/State()/*endname*/;
/*endblock:newInstance*/
}
/// <summary>
/// Copy values from other component. Shallow copy.
/// </summary>
/// <param name="target"></param>
public override void CopyValues(IComponent target) {
/*name:ComponentName*/GenTemplateComponent/*endname*/ component = (/*name:ComponentName*/GenTemplateComponent/*endname*/)target;
/*block:copyField*/ this./*name:name*/state/*endname*/ = component./*name:name*/state/*endname*/;
/*endblock:copyField*/
/*block:shallowCopy*/ this./*name:name*/state/*endname*/ = new /*name:type*/State()/*endname*/;
/*endblock:shallowCopy*/
}
public override IComponent Clone() {
var clone = new /*name:ComponentName*/GenTemplateComponent/*endname*/();
clone.CopyValues(this);
return clone;
}
}
/*block:rip*/
[System.Serializable]
public class GenTemplateComponent2 : ECS.Component
{
public float time;
public override IComponent Clone() {
throw new NotImplementedException();
}
public override void CopyValues(IComponent target) {
throw new NotImplementedException();
}
}
/*endblock:rip*/ | mit | C# |
20ec50d5d26f2052afcfcf640c69c6049208e799 | use WebHost.CreateDefaultBuilder in IdentitySample.Mvc | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | samples/IdentitySample.Mvc/Program.cs | samples/IdentitySample.Mvc/Program.cs | using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace IdentitySample
{
public static class Program
{
public static void Main(string[] args) => BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace IdentitySample
{
public static class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
} | apache-2.0 | C# |
5bb758469123e2c76d25b948ceda52dfa109370a | support for the new _count format | NickCraver/NEST,azubanov/elasticsearch-net,gayancc/elasticsearch-net,starckgates/elasticsearch-net,wawrzyn/elasticsearch-net,amyzheng424/elasticsearch-net,junlapong/elasticsearch-net,tkirill/elasticsearch-net,alanprot/elasticsearch-net,LeoYao/elasticsearch-net,LeoYao/elasticsearch-net,tkirill/elasticsearch-net,UdiBen/elasticsearch-net,adam-mccoy/elasticsearch-net,Grastveit/NEST,abibell/elasticsearch-net,SeanKilleen/elasticsearch-net,starckgates/elasticsearch-net,faisal00813/elasticsearch-net,gayancc/elasticsearch-net,DavidSSL/elasticsearch-net,amyzheng424/elasticsearch-net,tkirill/elasticsearch-net,faisal00813/elasticsearch-net,ststeiger/elasticsearch-net,junlapong/elasticsearch-net,TheFireCookie/elasticsearch-net,robrich/elasticsearch-net,DavidSSL/elasticsearch-net,starckgates/elasticsearch-net,junlapong/elasticsearch-net,Grastveit/NEST,faisal00813/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,cstlaurent/elasticsearch-net,UdiBen/elasticsearch-net,geofeedia/elasticsearch-net,geofeedia/elasticsearch-net,wawrzyn/elasticsearch-net,adam-mccoy/elasticsearch-net,jonyadamit/elasticsearch-net,Grastveit/NEST,robrich/elasticsearch-net,mac2000/elasticsearch-net,elastic/elasticsearch-net,ststeiger/elasticsearch-net,wawrzyn/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,jonyadamit/elasticsearch-net,SeanKilleen/elasticsearch-net,ststeiger/elasticsearch-net,RossLieberman/NEST,alanprot/elasticsearch-net,abibell/elasticsearch-net,geofeedia/elasticsearch-net,mac2000/elasticsearch-net,RossLieberman/NEST,robertlyson/elasticsearch-net,cstlaurent/elasticsearch-net,joehmchan/elasticsearch-net,KodrAus/elasticsearch-net,NickCraver/NEST,DavidSSL/elasticsearch-net,adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net,alanprot/elasticsearch-net,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,gayancc/elasticsearch-net,jonyadamit/elasticsearch-net,cstlaurent/elasticsearch-net,elastic/elasticsearch-net,alanprot/elasticsearch-net,NickCraver/NEST,joehmchan/elasticsearch-net,joehmchan/elasticsearch-net,KodrAus/elasticsearch-net,LeoYao/elasticsearch-net,robrich/elasticsearch-net,TheFireCookie/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,SeanKilleen/elasticsearch-net,robertlyson/elasticsearch-net,amyzheng424/elasticsearch-net,KodrAus/elasticsearch-net,robertlyson/elasticsearch-net | src/Nest/DSL/CountDescriptor.cs | src/Nest/DSL/CountDescriptor.cs | using System;
using Newtonsoft.Json;
using Nest.Resolvers.Converters;
namespace Nest
{
[DescriptorFor("Count")]
public partial class CountDescriptor<T>
: QueryPathDescriptorBase<CountDescriptor<T>, T, CountQueryString>
, IPathInfo<CountQueryString>
where T : class
{
[JsonProperty("query")]
internal BaseQuery _Query { get; set; }
public CountDescriptor<T> Query(Func<QueryDescriptor<T>, BaseQuery> querySelector)
{
this._Query = querySelector(new QueryDescriptor<T>());
return this;
}
ElasticsearchPathInfo<CountQueryString> IPathInfo<CountQueryString>.ToPathInfo(IConnectionSettings settings)
{
var pathInfo = base.ToPathInfo<CountQueryString>(settings, this._QueryString);
var qs = this._QueryString;
pathInfo.HttpMethod = !qs._source.IsNullOrEmpty()
? PathInfoHttpMethod.GET
: PathInfoHttpMethod.POST;
return pathInfo;
}
}
}
| using System;
using Newtonsoft.Json;
using Nest.Resolvers.Converters;
namespace Nest
{
[DescriptorFor("Count")]
[JsonConverter(typeof(CustomJsonConverter))]
public partial class CountDescriptor<T>
: QueryPathDescriptorBase<CountDescriptor<T>, T, CountQueryString>
, IActAsQuery
, IPathInfo<CountQueryString>
, ICustomJson
where T : class
{
BaseQuery IActAsQuery._Query { get; set; }
public CountDescriptor<T> Query(Func<QueryDescriptor<T>, BaseQuery> querySelector)
{
((IActAsQuery)this)._Query = querySelector(new QueryDescriptor<T>());
return this;
}
ElasticsearchPathInfo<CountQueryString> IPathInfo<CountQueryString>.ToPathInfo(IConnectionSettings settings)
{
var pathInfo = base.ToPathInfo<CountQueryString>(settings, this._QueryString);
var qs = this._QueryString;
pathInfo.HttpMethod = !qs._source.IsNullOrEmpty()
? PathInfoHttpMethod.GET
: PathInfoHttpMethod.POST;
return pathInfo;
}
object ICustomJson.GetCustomJson()
{
return ((IActAsQuery) this)._Query;
}
}
}
| apache-2.0 | C# |
c9e8c340251ec3afcd4032d10cb6d363a1bd4245 | Use Json.Net type stamping instead of assembly qualified name. | Hihaj/SlashTodo,Hihaj/SlashTodo | src/SlashTodo.Infrastructure/AzureTables/ComplexTableEntity.cs | src/SlashTodo.Infrastructure/AzureTables/ComplexTableEntity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
namespace SlashTodo.Infrastructure.AzureTables
{
public abstract class ComplexTableEntity<T> : TableEntity
{
private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
};
public string SerializedData { get; set; }
protected ComplexTableEntity() { }
protected ComplexTableEntity(T data, Func<T, string> partitionKey, Func<T, string> rowKey)
{
PartitionKey = partitionKey(data);
RowKey = rowKey(data);
SerializedData = JsonConvert.SerializeObject(data, SerializerSettings);
}
public T GetData()
{
return (T)JsonConvert.DeserializeObject(SerializedData, SerializerSettings);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
namespace SlashTodo.Infrastructure.AzureTables
{
public abstract class ComplexTableEntity<T> : TableEntity
{
public string DataTypeAssemblyQualifiedName { get; set; }
public string SerializedData { get; set; }
protected ComplexTableEntity() { }
protected ComplexTableEntity(T data, Func<T, string> partitionKey, Func<T, string> rowKey)
{
PartitionKey = partitionKey(data);
RowKey = rowKey(data);
SerializedData = JsonConvert.SerializeObject(data);
DataTypeAssemblyQualifiedName = data.GetType().AssemblyQualifiedName;
}
public T GetData()
{
return (T)JsonConvert.DeserializeObject(SerializedData, Type.GetType(DataTypeAssemblyQualifiedName));
}
}
}
| mit | C# |
13fc2f65b29ca11fa15ad35bd6bd27a2c8f240c9 | Store an item when it is added to the basket | lukedrury/super-market-kata | engine/engine/tests/SupermarketAcceptanceTests.cs | engine/engine/tests/SupermarketAcceptanceTests.cs | using NUnit.Framework;
namespace engine.tests
{
[TestFixture]
public class SupermarketAcceptanceTests
{
[Test]
public void EmptyBasket()
{
var till = new Till();
var basket = new Basket();
var total = till.CalculatePrice(basket);
var expected = 0;
Assert.That(total, Is.EqualTo(expected));
}
[Test]
public void SingleItemInBasket()
{
var till = new Till();
var basket = new Basket();
basket.Add("pennySweet", 1);
var total = till.CalculatePrice(basket);
var expected = 1;
Assert.That(total, Is.EqualTo(expected));
}
}
public class Basket
{
private readonly IList<BasketItem> items = new List<BasketItem>();
public void Add(string item, int unitPrice)
{
items.Add(new BasketItem(item, unitPrice));
}
}
public class BasketItem
{
public string Item { get; private set; }
public int UnitPrice { get; private set; }
public BasketItem(string item, int unitPrice)
{
Item = item;
UnitPrice = unitPrice;
}
}
public class Till
{
public int CalculatePrice(Basket basket)
{
return 0;
}
}
} | using NUnit.Framework;
namespace engine.tests
{
[TestFixture]
public class SupermarketAcceptanceTests
{
[Test]
public void EmptyBasket()
{
var till = new Till();
var basket = new Basket();
var total = till.CalculatePrice(basket);
var expected = 0;
Assert.That(total, Is.EqualTo(expected));
}
[Test]
public void SingleItemInBasket()
{
var till = new Till();
var basket = new Basket();
basket.Add("pennySweet", 1);
var total = till.CalculatePrice(basket);
var expected = 1;
Assert.That(total, Is.EqualTo(expected));
}
}
public class Basket
{
public void Add(string item, int unitPrice)
{
}
}
public class Till
{
public int CalculatePrice(Basket basket)
{
return 0;
}
}
} | mit | C# |
a91b8d555c84d1d8b4fc14b39504f743d1e42544 | Modify tag count to actual value | genlu/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,tmat/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,diryboy/roslyn,KevinRansom/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,physhi/roslyn,AmadeusW/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,dotnet/roslyn,genlu/roslyn,heejaechang/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,mgoertz-msft/roslyn,physhi/roslyn,physhi/roslyn,tmat/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,dotnet/roslyn,stephentoub/roslyn,wvdd007/roslyn,diryboy/roslyn,sharwell/roslyn,mavasani/roslyn,wvdd007/roslyn,mavasani/roslyn,aelij/roslyn,gafter/roslyn,AmadeusW/roslyn,weltkante/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,gafter/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,sharwell/roslyn,KevinRansom/roslyn,stephentoub/roslyn,aelij/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,aelij/roslyn,gafter/roslyn,brettfo/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,sharwell/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,tmat/roslyn,mavasani/roslyn,diryboy/roslyn,jasonmalinowski/roslyn | src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicKeywordHighlighting.cs | src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicKeywordHighlighting.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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicKeywordHighlighting : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicKeywordHighlighting(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicKeywordHighlighting))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void NavigationBetweenKeywords()
{
VisualStudio.Editor.SetText(@"
Class C
Sub Main()
For a = 0 To 1 Step 1
For b = 0 To 2
Next b, a
End Sub
End Class");
Verify("To", 4);
VisualStudio.ExecuteCommand("Edit.NextHighlightedReference");
VisualStudio.Editor.Verify.CurrentLineText("For a = 0 To 1 Step$$ 1", assertCaretPosition: true, trimWhitespace: true);
}
private void Verify(string marker, int expectedCount)
{
VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.Classification,
FeatureAttribute.KeywordHighlighting);
Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags().Length);
}
}
}
| // 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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicKeywordHighlighting : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicKeywordHighlighting(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicKeywordHighlighting))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void NavigationBetweenKeywords()
{
VisualStudio.Editor.SetText(@"
Class C
Sub Main()
For a = 0 To 1 Step 1
For b = 0 To 2
Next b, a
End Sub
End Class");
Verify("To", 3);
VisualStudio.ExecuteCommand("Edit.NextHighlightedReference");
VisualStudio.Editor.Verify.CurrentLineText("For a = 0 To 1 Step$$ 1", assertCaretPosition: true, trimWhitespace: true);
}
private void Verify(string marker, int expectedCount)
{
VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.Classification,
FeatureAttribute.KeywordHighlighting);
Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags().Length);
}
}
}
| mit | C# |
fac55bc78b70a1f8a3a53b222d9df515e32e82ae | Change ISnmpModule to use scene references | RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim | OpenSim/Region/Framework/Interfaces/ISnmpModule.cs | OpenSim/Region/Framework/Interfaces/ISnmpModule.cs | ///////////////////////////////////////////////////////////////////
//
// (c) Careminster LImited, Melanie Thielker and the Meta7 Team
//
// This file is not open source. All rights reserved
// Mod 2
using OpenSim.Region.Framework.Scenes;
public interface ISnmpModule
{
void Trap(int code, string Message, Scene scene);
void Critcal(string Message, Scene scene);
void Warning(string Message, Scene scene);
void Major(string Message, Scene scene);
void ColdStart(int step , Scene scene);
void Shutdown(int step , Scene scene);
}
| ///////////////////////////////////////////////////////////////////
//
// (c) Careminster LImited, Melanie Thielker and the Meta7 Team
//
// This file is not open source. All rights reserved
// Mod 2
public interface ISnmpModule
{
void Trap(int code,string simname,string Message);
void ColdStart(int step , string simname);
}
| bsd-3-clause | C# |
edf4869a7ee54be9d2331931c28c60b9149a5b0a | Increment minor version | TeamnetGroup/cap-net,darbio/cap-net | src/CAPNet/Properties/AssemblyInfo.cs | src/CAPNet/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("cap-net")]
[assembly: AssemblyDescription("A Common Alerting Protocol serialization library for the .NET framework.")]
[assembly: AssemblyProduct("cap-net")]
[assembly: AssemblyCopyright("Copyright © 2013 Matt Chandler and contributors")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0-alpha")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("cap-net")]
[assembly: AssemblyDescription("A Common Alerting Protocol serialization library for the .NET framework.")]
[assembly: AssemblyProduct("cap-net")]
[assembly: AssemblyCopyright("Copyright © 2013 Matt Chandler and contributors")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0-alpha")]
| mit | C# |
9ca68d35e3f0d56262d3401b754dafe5256f2a1c | Add loop | cdonges/cricket | CricketScores/Program.cs | CricketScores/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Net;
using System.IO.Ports;
namespace CricketScores
{
class Program
{
static void Main(string[] args)
{
Regex country = new Regex("<title>.*Australia.*</title>");
Regex wickets = new Regex("/(?<wickets>[0-9]{1,2})");
using (SerialPort serial = new SerialPort("COM5", 38400))
{
serial.Open();
string prevWickets = string.Empty;
using (WebClient wc = new WebClient())
{
while (true)
{
string html = wc.DownloadString("http://static.cricinfo.com/rss/livescores.xml");
var countryMatch = country.Match(html);
if (countryMatch.Success)
{
var wicketsMatch = wickets.Matches(countryMatch.Value);
string wicketsStr = string.Join(",", wicketsMatch.Cast<Match>().Select(m => m.Groups[1].Value));
Console.WriteLine(wicketsStr);
if (serial.IsOpen && wicketsStr != prevWickets)
{
prevWickets = wicketsStr;
serial.Write(new byte[] { 0x77 }, 0, 1);
}
}
System.Threading.Thread.Sleep(60 * 1000);
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Net;
using System.IO.Ports;
namespace CricketScores
{
class Program
{
static void Main(string[] args)
{
Regex country = new Regex("<title>.*Australia.*</title>");
Regex wickets = new Regex("/(?<wickets>[0-9]{1,2})");
using (SerialPort serial = new SerialPort("COM5", 38400))
{
serial.Open();
string prevWickets = string.Empty;
using (WebClient wc = new WebClient())
{
string html = wc.DownloadString("http://static.cricinfo.com/rss/livescores.xml");
var countryMatch = country.Match(html);
if (countryMatch.Success)
{
var wicketsMatch = wickets.Matches(countryMatch.Value);
string wicketsStr = string.Join(",", wicketsMatch.Cast<Match>().Select(m => m.Groups[1].Value));
Console.WriteLine(wicketsStr);
if (serial.IsOpen && wicketsStr != prevWickets)
{
prevWickets = wicketsStr;
serial.Write(new byte[] { 0x77 }, 0, 1);
}
}
}
}
}
}
}
| mit | C# |
2037acda211b8a55889b5f0adaab5c4c4d462a72 | Add WikiPageExtensions.CreateCategoriesGenerator. | CXuesong/WikiClientLibrary | WikiClientLibrary/Generators/WikiPageExtensions.cs | WikiClientLibrary/Generators/WikiPageExtensions.cs | using System;
using System.Collections.Generic;
using System.Text;
using WikiClientLibrary.Pages;
namespace WikiClientLibrary.Generators
{
/// <summary>
/// Extension method for constructing generators from <see cref="WikiPage"/>.
/// </summary>
public static class WikiPageExtensions
{
/// <summary>
/// Creates a <see cref="LinksGenerator"/> instance from the specified page,
/// which generates pages from all links on the page.
/// </summary>
/// <param name="page">The page.</param>
public static LinksGenerator CreateLinksGenerator(this WikiPage page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
return new LinksGenerator(page.Site, page.PageStub);
}
/// <summary>
/// Creates a <see cref="TransclusionsGenerator"/> instance from the specified page,
/// which generates pages from all pages (typically templates) transcluded in the page.
/// </summary>
/// <param name="page">The page.</param>
public static TransclusionsGenerator CreateTransclusionsGenerator(this WikiPage page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
return new TransclusionsGenerator(page.Site, page.PageStub);
}
/// <summary>
/// Creates a <see cref="RevisionsGenerator"/> instance from the specified page,
/// which enumerates the sequence of revisions on the page.
/// </summary>
/// <param name="page">The page.</param>
public static RevisionsGenerator CreateRevisionsGenerator(this WikiPage page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
return new RevisionsGenerator(page.Site, page.PageStub);
}
/// <summary>
/// Creates a <see cref="CategoriesGenerator"/> instance from the specified page,
/// which enumerates the categories used on the page.
/// </summary>
/// <param name="page">The page.</param>
public static CategoriesGenerator CreateCategoriesGenerator(this WikiPage page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
return new CategoriesGenerator(page.Site, page.PageStub);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using WikiClientLibrary.Pages;
namespace WikiClientLibrary.Generators
{
/// <summary>
/// Extension method for constructing generators from <see cref="WikiPage"/>.
/// </summary>
public static class WikiPageExtensions
{
/// <summary>
/// Creates a <see cref="LinksGenerator"/> instance from the specified page,
/// which generates pages from all links on the page.
/// </summary>
/// <param name="page">The page.</param>
public static LinksGenerator CreateLinksGenerator(this WikiPage page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
return new LinksGenerator(page.Site, page.PageStub);
}
/// <summary>
/// Creates a <see cref="TransclusionsGenerator"/> instance from the specified page,
/// which generates pages from all pages (typically templates) transcluded in the page.
/// </summary>
/// <param name="page">The page.</param>
public static TransclusionsGenerator CreateTransclusionsGenerator(this WikiPage page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
return new TransclusionsGenerator(page.Site, page.PageStub);
}
/// <summary>
/// Creates a <see cref="RevisionsGenerator"/> instance from the specified page,
/// which enumerates the sequence of revisions on the page.
/// </summary>
/// <param name="page">The page.</param>
public static RevisionsGenerator CreateRevisionsGenerator(this WikiPage page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
return new RevisionsGenerator(page.Site, page.PageStub);
}
}
}
| apache-2.0 | C# |
d73457628ae1cd950617d30acc5ff088f01f8f00 | fix assembly version | xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents | iOS/FacebookPop/source/Properties/AssemblyInfo.cs | iOS/FacebookPop/source/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using Foundation;
// This attribute allows you to mark your assemblies as “safe to link”.
// When the attribute is present, the linker—if enabled—will process the assembly
// even if you’re using the “Link SDK assemblies only” option, which is the default for device builds.
[assembly: LinkerSafe]
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("FacebookPop")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using Foundation;
// This attribute allows you to mark your assemblies as “safe to link”.
// When the attribute is present, the linker—if enabled—will process the assembly
// even if you’re using the “Link SDK assemblies only” option, which is the default for device builds.
[assembly: LinkerSafe]
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("FacebookPop")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("redth")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
496311462fee6e7719e96949bccf4f688ea6306e | Fix implements for LLVMConstHelper#True and False | nokok/lury,lury-lang/lury,HaiTo/lury | src/Lury/Compiling/LLVMConstHelper.cs | src/Lury/Compiling/LLVMConstHelper.cs | //
// LLVMConstHelper.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;
using LLVMSharp;
using System.Runtime.InteropServices;
namespace Lury.Compiling
{
public class LLVMConstHelper
{
#region -- Private Fields --
private LLVMHelper llvmHelper;
#region Value Constants
private static readonly LLVMBool @false = new LLVMBool(0);
private static readonly LLVMBool @true = new LLVMBool(1);
#endregion
#region Type
private LLVMTypeRef booleanType;
#endregion
#endregion
#region -- Public Properties --
public LLVMHelper LLVMHelper { get { return this.llvmHelper; } }
#region Value Constants
private LLVMBool False { get { return @false; } }
private LLVMBool True { get { return @true; } }
#endregion
#region Type
private LLVMTypeRef BooleanType { get { return this.booleanType ?? (this.booleanType = LLVM.Int1TypeInContext(this.llvmHelper.Context)); } }
#endregion
#endregion
#region -- Constructors --
public LLVMConstHelper(LLVMHelper llvmHelper)
{
this.llvmHelper = llvmHelper;
}
#endregion
#region -- Public Methods --
#endregion
}
}
| //
// LLVMConstHelper.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;
using LLVMSharp;
using System.Runtime.InteropServices;
namespace Lury.Compiling
{
public class LLVMConstHelper
{
#region -- Private Fields --
private LLVMHelper llvmHelper;
#region Value Constants
private LLVMBool @false, @true;
#endregion
#region Type
private LLVMTypeRef booleanType;
#endregion
#endregion
#region -- Public Properties --
public LLVMHelper LLVMHelper { get { return this.llvmHelper; } }
#region Value Constants
private LLVMBool False { get { return this.@false ?? (this.@false = new LLVMBool(0)); } }
private LLVMBool True { get { return this.@true ?? (this.@true = new LLVMBool(1)); } }
#endregion
#region Type
private LLVMTypeRef BooleanType { get { return this.booleanType ?? (this.booleanType = LLVM.Int1TypeInContext(this.llvmHelper.Context)); } }
#endregion
#endregion
#region -- Constructors --
public LLVMConstHelper(LLVMHelper llvmHelper)
{
this.llvmHelper = llvmHelper;
}
#endregion
#region -- Public Methods --
#endregion
}
}
| mit | C# |
af8a40f7495ed50384e5581b03e4ef25af49bf52 | Correct indentation | openmedicus/dbus-sharp,arfbtwn/dbus-sharp,openmedicus/dbus-sharp,Tragetaschen/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,mono/dbus-sharp,arfbtwn/dbus-sharp | examples/TestExceptions.cs | examples/TestExceptions.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTestExceptions
{
public static void Main ()
{
Bus bus = Bus.Session;
string myNameReq = "org.ndesk.testexceptions";
ObjectPath myOpath = new ObjectPath ("/org/ndesk/testexceptions");
DemoObject demo;
if (bus.NameHasOwner (myNameReq)) {
demo = bus.GetObject<DemoObject> (myNameReq, myOpath);
} else {
demo = new DemoObject ();
bus.Register (myNameReq, myOpath, demo);
RequestNameReply nameReply = bus.RequestName (myNameReq, NameFlag.None);
Console.WriteLine ("RequestNameReply: " + nameReply);
while (true)
bus.Iterate ();
}
Console.WriteLine ();
//org.freedesktop.DBus.Error.InvalidArgs: Requested bus name "" is not valid
try {
bus.RequestName ("");
} catch (Exception e) {
Console.WriteLine (e);
}
//TODO: make this work as expected (what is expected?)
Console.WriteLine ();
try {
demo.ThrowSomeException ();
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.ThrowSomeExceptionNoRet ();
} catch (Exception e) {
Console.WriteLine (e);
}
//handle the thrown exception
//conn.Iterate ();
Console.WriteLine ();
try {
demo.HandleVariant (null);
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.HandleString (null);
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.HandleArray (null);
} catch (Exception e) {
Console.WriteLine (e);
}
}
}
[Interface ("org.ndesk.testexceptions")]
public class DemoObject : MarshalByRefObject
{
public int ThrowSomeException ()
{
Console.WriteLine ("Asked to throw some Exception");
throw new Exception ("Some Exception");
}
public void ThrowSomeExceptionNoRet ()
{
Console.WriteLine ("Asked to throw some Exception NoRet");
throw new Exception ("Some Exception NoRet");
}
public void HandleVariant (object o)
{
Console.WriteLine (o);
}
public void HandleString (string str)
{
Console.WriteLine (str);
}
public void HandleArray (byte[] arr)
{
Console.WriteLine (arr);
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTestExceptions
{
public static void Main ()
{
Bus bus = Bus.Session;
string myNameReq = "org.ndesk.testexceptions";
ObjectPath myOpath = new ObjectPath ("/org/ndesk/testexceptions");
DemoObject demo;
if (bus.NameHasOwner (myNameReq)) {
demo = bus.GetObject<DemoObject> (myNameReq, myOpath);
} else {
demo = new DemoObject ();
bus.Register (myNameReq, myOpath, demo);
RequestNameReply nameReply = bus.RequestName (myNameReq, NameFlag.None);
Console.WriteLine ("RequestNameReply: " + nameReply);
while (true)
bus.Iterate ();
}
Console.WriteLine ();
//org.freedesktop.DBus.Error.InvalidArgs: Requested bus name "" is not valid
try {
bus.RequestName ("");
} catch (Exception e) {
Console.WriteLine (e);
}
//TODO: make this work as expected (what is expected?)
Console.WriteLine ();
try {
demo.ThrowSomeException ();
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.ThrowSomeExceptionNoRet ();
} catch (Exception e) {
Console.WriteLine (e);
}
//handle the thrown exception
//conn.Iterate ();
Console.WriteLine ();
try {
demo.HandleVariant (null);
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.HandleString (null);
} catch (Exception e) {
Console.WriteLine (e);
}
Console.WriteLine ();
try {
demo.HandleArray (null);
} catch (Exception e) {
Console.WriteLine (e);
}
}
}
[Interface ("org.ndesk.testexceptions")]
public class DemoObject : MarshalByRefObject
{
public int ThrowSomeException ()
{
Console.WriteLine ("Asked to throw some Exception");
throw new Exception ("Some Exception");
}
public void ThrowSomeExceptionNoRet ()
{
Console.WriteLine ("Asked to throw some Exception NoRet");
throw new Exception ("Some Exception NoRet");
}
public void HandleVariant (object o)
{
Console.WriteLine (o);
}
public void HandleString (string str)
{
Console.WriteLine (str);
}
public void HandleArray (byte[] arr)
{
Console.WriteLine (arr);
}
}
| mit | C# |
4c13190f5ea3a59ec19390abdcdc5e99b6c12471 | Update Viktor.cs | FireBuddy/adevade | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
. var End = new vector3 => sender.GetWaypoints().Last();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
. var End = new vector3() => sender.GetWaypoints().Last();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| mit | C# |
28ad5398cc928deb58ec68fbb3d0d24313bec175 | Remove the changes in convert spinner | UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,DrabWeb/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,naoey/osu,2yangk23/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,DrabWeb/osu,ZLima12/osu,DrabWeb/osu,ppy/osu,ZLima12/osu,peppy/osu-new,naoey/osu,EVAST9919/osu,johnneijzen/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,peppy/osu,naoey/osu,NeoAdonis/osu | osu.Game/Rulesets/Objects/Legacy/Catch/ConvertSpinner.cs | osu.Game/Rulesets/Objects/Legacy/Catch/ConvertSpinner.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Objects.Legacy.Catch
{
/// <summary>
/// Legacy osu!catch Spinner-type, used for parsing Beatmaps.
/// </summary>
internal sealed class ConvertSpinner : HitObject, IHasEndTime
{
public double EndTime { get; set; }
public double Duration => EndTime - StartTime;
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Objects.Legacy.Catch
{
/// <summary>
/// Legacy osu!catch Spinner-type, used for parsing Beatmaps.
/// </summary>
internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasXPosition
{
public float X { get; set; }
public double EndTime { get; set; }
public double Duration => EndTime - StartTime;
}
}
| mit | C# |
4039734e8a97a4703cd72103cccd8b3ff926e45e | Add data annotation | CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site | Coop_Listing_Site/Coop_Listing_Site/Models/Major.cs | Coop_Listing_Site/Coop_Listing_Site/Models/Major.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Coop_Listing_Site.Models
{
public class Major
{
public int MajorID { get; set; }
[Required]
public string Name { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Coop_Listing_Site.Models
{
public class Major
{
public int MajorID { get; set; }
public string Name { get; set; }
}
} | mit | C# |
7bd4e4d9571df6f4d46267d8a1ed3059a7a6813a | Remove spurious new line | jagrem/slang,jagrem/slang,jagrem/slang | slang/Lexing/Rules/Rule.cs | slang/Lexing/Rules/Rule.cs | namespace slang.Lexing.Rules
{
public abstract class Rule
{
public static Rule operator | (Rule left, Rule right)
{
return new OrRule (left, right);
}
public static Rule operator + (Rule left, Rule right)
{
return new AndRule (left, right);
}
public static implicit operator Rule (char value)
{
return new ConstantRule (value);
}
}
}
| namespace slang.Lexing.Rules
{
public abstract class Rule
{
public static Rule operator | (Rule left, Rule right)
{
return new OrRule (left, right);
}
public static Rule operator + (Rule left, Rule right)
{
return new AndRule (left, right);
}
public static implicit operator Rule (char value)
{
return new ConstantRule (value);
}
}
}
| mit | C# |
00a041d46ee1cd9c4afd32bf25727f39495cb027 | Update AsyncServiceTest.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Core/NakedObjects.Core.Test/Async/AsyncServiceTest.cs | Core/NakedObjects.Core.Test/Async/AsyncServiceTest.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System.Threading.Tasks;
using Moq;
using NakedObjects.Architecture.Component;
using NUnit.Framework;
namespace NakedObjects.Core.Async {
[TestFixture]
public class AsyncServiceTest {
[Test]
public void TestAction() {
AsyncTest().Wait(1000);
}
private async Task AsyncTest() {
var mockFramework = new Mock<INakedObjectsFramework>();
var mockResolver = new Mock<IFrameworkResolver>();
var mockTransactionManager = new Mock<ITransactionManager>();
mockFramework.Setup(f => f.FrameworkResolver).Returns(mockResolver.Object);
mockResolver.Setup(r => r.GetFramework()).Returns(mockFramework.Object);
mockFramework.Setup(f => f.TransactionManager).Returns(mockTransactionManager.Object);
var testService = new AsyncService {Framework = mockFramework.Object};
var run = 0;
var task = testService.RunAsync(c => run++);
await task;
Assert.IsNull(task.Exception);
Assert.AreEqual(1, run);
}
}
} | //// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
//// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
//// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
//// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
//// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//// See the License for the specific language governing permissions and limitations under the License.
//using System.Threading.Tasks;
//using Microsoft.VisualStudio.TestTools.UnitTesting;
//using Moq;
//using NakedObjects.Architecture.Component;
//namespace NakedObjects.Core.Async {
// [TestClass]
// public class AsyncServiceTest {
// [TestMethod]
// public void TestAction() {
// AsyncTest().Wait(1000);
// }
// private async Task AsyncTest() {
// var mockFramework = new Mock<INakedObjectsFramework>();
// var mockResolver = new Mock<IFrameworkResolver>();
// var mockTransactionManager = new Mock<ITransactionManager>();
// mockFramework.Setup(f => f.FrameworkResolver).Returns(mockResolver.Object);
// mockResolver.Setup(r => r.GetFramework()).Returns(mockFramework.Object);
// mockFramework.Setup(f => f.TransactionManager).Returns(mockTransactionManager.Object);
// var testService = new AsyncService {Framework = mockFramework.Object};
// var run = 0;
// var task = testService.RunAsync(c => run++);
// await task;
// Assert.IsNull(task.Exception);
// Assert.AreEqual(1, run);
// }
// }
//} | apache-2.0 | C# |
8b38dd8664c1acdf338db128a0a044f35a369b25 | Clean up | fvilers/Darjeel,fvilers/Darjeel,fvilers/Darjeel | Darjeel/Darjeel/Messaging/Handling/CommandExecuter.cs | Darjeel/Darjeel/Messaging/Handling/CommandExecuter.cs | using System;
using System.Threading.Tasks;
namespace Darjeel.Messaging.Handling
{
public class CommandExecuter : ICommandExecuter
{
private readonly ICommandHandlerRegistry _registry;
public CommandExecuter(ICommandHandlerRegistry registry)
{
if (registry == null) throw new ArgumentNullException(nameof(registry));
_registry = registry;
}
public async Task ExecuteAsync(ICommand command, string correlationId = null)
{
if (command == null) throw new ArgumentNullException(nameof(command));
var commandType = command.GetType();
ICommandHandler handler;
if (_registry.TryGetHandler(commandType, out handler))
{
Logging.Darjeel.TraceInformation($"Command '{commandType.FullName}' handled by '{handler.GetType().FullName}.");
await ((dynamic)handler).HandleAsync((dynamic)command);
}
}
}
}
| using System;
using System.Threading.Tasks;
namespace Darjeel.Messaging.Handling
{
public class CommandExecuter : ICommandExecuter
{
private readonly ICommandHandlerRegistry _registry;
public CommandExecuter(ICommandHandlerRegistry registry)
{
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
_registry = registry;
}
public async Task ExecuteAsync(ICommand command, string correlationId = null)
{
if (command == null) throw new ArgumentNullException(nameof(command));
var commandType = command.GetType();
ICommandHandler handler;
if (_registry.TryGetHandler(commandType, out handler))
{
Logging.Darjeel.TraceInformation($"Command '{commandType.FullName}' handled by '{handler.GetType().FullName}.");
await ((dynamic)handler).HandleAsync((dynamic)command);
}
}
}
}
| mit | C# |
dba4145d846733ad1cbcbc834f05ca3397069090 | Use member value in MemberEqualByComparer | JohanLarsson/Gu.State,JohanLarsson/Gu.State,JohanLarsson/Gu.ChangeTracking | Gu.State/EqualBy/Comparers/MemberEqualByComparer.cs | Gu.State/EqualBy/Comparers/MemberEqualByComparer.cs | namespace Gu.State
{
using System;
using System.Reflection;
internal class MemberEqualByComparer : EqualByComparer
{
private readonly IGetterAndSetter getterAndSetter;
private readonly Lazy<EqualByComparer> comparer;
private MemberEqualByComparer(IGetterAndSetter getterAndSetter, Lazy<EqualByComparer> comparer)
{
this.getterAndSetter = getterAndSetter;
this.comparer = comparer;
}
public override bool Equals(object x, object y, MemberSettings settings, ReferencePairCollection referencePairs)
{
var xv = this.getterAndSetter.GetValue(x);
var yv = this.getterAndSetter.GetValue(y);
if (TryGetEitherNullEquals(xv, yv, out var result))
{
return result;
}
return this.comparer.Value.Equals(xv, yv, settings, referencePairs);
}
internal static MemberEqualByComparer Create(MemberInfo member, MemberSettings settings)
{
var getterAndSetter = settings.GetOrCreateGetterAndSetter(member);
return new MemberEqualByComparer(getterAndSetter, new Lazy<EqualByComparer>(() => settings.GetEqualByComparer(getterAndSetter.ValueType, checkReferenceHandling: true)));
}
}
} | namespace Gu.State
{
using System;
using System.Reflection;
internal class MemberEqualByComparer : EqualByComparer
{
private readonly IGetterAndSetter getterAndSetter;
private readonly Lazy<EqualByComparer> comparer;
private MemberEqualByComparer(IGetterAndSetter getterAndSetter, Lazy<EqualByComparer> comparer)
{
this.getterAndSetter = getterAndSetter;
this.comparer = comparer;
}
public override bool Equals(object x, object y, MemberSettings settings, ReferencePairCollection referencePairs)
{
return TryGetEitherNullEquals(x, y, out var result)
? result
: this.comparer.Value.Equals(this.getterAndSetter.GetValue(x), this.getterAndSetter.GetValue(y), settings, referencePairs);
}
internal static MemberEqualByComparer Create(MemberInfo member, MemberSettings settings)
{
var getterAndSetter = settings.GetOrCreateGetterAndSetter(member);
return new MemberEqualByComparer(getterAndSetter, new Lazy<EqualByComparer>(() => settings.GetEqualByComparer(getterAndSetter.ValueType, checkReferenceHandling: true)));
}
}
} | mit | C# |
c44f1e0662bba3e186a61376fd912c2569204abf | Update test. | rgani/roslyn,antonssonj/roslyn,brettfo/roslyn,davkean/roslyn,davkean/roslyn,swaroop-sridhar/roslyn,mattscheffer/roslyn,diryboy/roslyn,jhendrixMSFT/roslyn,Maxwe11/roslyn,agocke/roslyn,bartdesmet/roslyn,aanshibudhiraja/Roslyn,akrisiun/roslyn,MichalStrehovsky/roslyn,amcasey/roslyn,leppie/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,HellBrick/roslyn,khellang/roslyn,a-ctor/roslyn,dpoeschl/roslyn,KevinRansom/roslyn,Inverness/roslyn,heejaechang/roslyn,KevinRansom/roslyn,ljw1004/roslyn,khyperia/roslyn,natgla/roslyn,mmitche/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,Pvlerick/roslyn,VPashkov/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,mavasani/roslyn,AnthonyDGreen/roslyn,MichalStrehovsky/roslyn,lorcanmooney/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,xasx/roslyn,aelij/roslyn,tmeschter/roslyn,vslsnap/roslyn,stephentoub/roslyn,tmat/roslyn,tannergooding/roslyn,vslsnap/roslyn,tmat/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,tvand7093/roslyn,mattwar/roslyn,MatthieuMEZIL/roslyn,jasonmalinowski/roslyn,xasx/roslyn,AnthonyDGreen/roslyn,Giftednewt/roslyn,khyperia/roslyn,jhendrixMSFT/roslyn,jamesqo/roslyn,a-ctor/roslyn,eriawan/roslyn,Pvlerick/roslyn,tannergooding/roslyn,AArnott/roslyn,cston/roslyn,michalhosala/roslyn,amcasey/roslyn,natidea/roslyn,mseamari/Stuff,diryboy/roslyn,leppie/roslyn,tvand7093/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,balajikris/roslyn,agocke/roslyn,cston/roslyn,sharadagrawal/Roslyn,balajikris/roslyn,SeriaWei/roslyn,Hosch250/roslyn,jamesqo/roslyn,VSadov/roslyn,orthoxerox/roslyn,Inverness/roslyn,mmitche/roslyn,Inverness/roslyn,mattscheffer/roslyn,xasx/roslyn,basoundr/roslyn,jeffanders/roslyn,budcribar/roslyn,moozzyk/roslyn,nguerrera/roslyn,wvdd007/roslyn,aelij/roslyn,leppie/roslyn,vslsnap/roslyn,KirillOsenkov/roslyn,jaredpar/roslyn,MattWindsor91/roslyn,drognanar/roslyn,paulvanbrenk/roslyn,ljw1004/roslyn,Maxwe11/roslyn,Maxwe11/roslyn,Hosch250/roslyn,diryboy/roslyn,physhi/roslyn,zooba/roslyn,bbarry/roslyn,jaredpar/roslyn,eriawan/roslyn,orthoxerox/roslyn,MatthieuMEZIL/roslyn,rgani/roslyn,CaptainHayashi/roslyn,amcasey/roslyn,xoofx/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jkotas/roslyn,jcouv/roslyn,paulvanbrenk/roslyn,basoundr/roslyn,Hosch250/roslyn,CaptainHayashi/roslyn,budcribar/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,mmitche/roslyn,AArnott/roslyn,SeriaWei/roslyn,zooba/roslyn,reaction1989/roslyn,srivatsn/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,thomaslevesque/roslyn,xoofx/roslyn,KevinH-MS/roslyn,mattwar/roslyn,ericfe-ms/roslyn,abock/roslyn,tmat/roslyn,jcouv/roslyn,mgoertz-msft/roslyn,jhendrixMSFT/roslyn,vcsjones/roslyn,cston/roslyn,vcsjones/roslyn,danielcweber/roslyn,yeaicc/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,lorcanmooney/roslyn,KiloBravoLima/roslyn,tvand7093/roslyn,VPashkov/roslyn,michalhosala/roslyn,genlu/roslyn,michalhosala/roslyn,dotnet/roslyn,genlu/roslyn,Shiney/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,managed-commons/roslyn,jbhensley/roslyn,Shiney/roslyn,jeffanders/roslyn,jcouv/roslyn,SeriaWei/roslyn,robinsedlaczek/roslyn,moozzyk/roslyn,brettfo/roslyn,panopticoncentral/roslyn,weltkante/roslyn,robinsedlaczek/roslyn,swaroop-sridhar/roslyn,VSadov/roslyn,sharadagrawal/Roslyn,MattWindsor91/roslyn,HellBrick/roslyn,akrisiun/roslyn,TyOverby/roslyn,Pvlerick/roslyn,bartdesmet/roslyn,DustinCampbell/roslyn,CaptainHayashi/roslyn,OmarTawfik/roslyn,thomaslevesque/roslyn,OmarTawfik/roslyn,jbhensley/roslyn,basoundr/roslyn,gafter/roslyn,oocx/roslyn,kelltrick/roslyn,danielcweber/roslyn,danielcweber/roslyn,mattscheffer/roslyn,genlu/roslyn,mseamari/Stuff,wvdd007/roslyn,ErikSchierboom/roslyn,kelltrick/roslyn,dotnet/roslyn,mseamari/Stuff,CyrusNajmabadi/roslyn,KevinH-MS/roslyn,antonssonj/roslyn,ValentinRueda/roslyn,TyOverby/roslyn,bkoelman/roslyn,sharwell/roslyn,bbarry/roslyn,akrisiun/roslyn,OmarTawfik/roslyn,oocx/roslyn,jmarolf/roslyn,jkotas/roslyn,natidea/roslyn,gafter/roslyn,pdelvo/roslyn,budcribar/roslyn,robinsedlaczek/roslyn,oocx/roslyn,orthoxerox/roslyn,mavasani/roslyn,brettfo/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,VPashkov/roslyn,drognanar/roslyn,KevinRansom/roslyn,VSadov/roslyn,KiloBravoLima/roslyn,DustinCampbell/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,sharadagrawal/Roslyn,mattwar/roslyn,pdelvo/roslyn,xoofx/roslyn,physhi/roslyn,MattWindsor91/roslyn,rgani/roslyn,bkoelman/roslyn,a-ctor/roslyn,ValentinRueda/roslyn,wvdd007/roslyn,thomaslevesque/roslyn,natgla/roslyn,jkotas/roslyn,reaction1989/roslyn,srivatsn/roslyn,ValentinRueda/roslyn,ErikSchierboom/roslyn,AnthonyDGreen/roslyn,moozzyk/roslyn,AlekseyTs/roslyn,KevinH-MS/roslyn,balajikris/roslyn,nguerrera/roslyn,khellang/roslyn,jamesqo/roslyn,tmeschter/roslyn,bbarry/roslyn,stephentoub/roslyn,nguerrera/roslyn,ericfe-ms/roslyn,drognanar/roslyn,mavasani/roslyn,tmeschter/roslyn,Shiney/roslyn,dotnet/roslyn,natidea/roslyn,ljw1004/roslyn,managed-commons/roslyn,khyperia/roslyn,weltkante/roslyn,DustinCampbell/roslyn,jbhensley/roslyn,antonssonj/roslyn,managed-commons/roslyn,bkoelman/roslyn,Giftednewt/roslyn,abock/roslyn,HellBrick/roslyn,pdelvo/roslyn,dpoeschl/roslyn,davkean/roslyn,Giftednewt/roslyn,AlekseyTs/roslyn,paulvanbrenk/roslyn,mgoertz-msft/roslyn,MatthieuMEZIL/roslyn,ericfe-ms/roslyn,yeaicc/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,reaction1989/roslyn,dpoeschl/roslyn,vcsjones/roslyn,MichalStrehovsky/roslyn,jeffanders/roslyn,srivatsn/roslyn,TyOverby/roslyn,khellang/roslyn,KiloBravoLima/roslyn,natgla/roslyn,AArnott/roslyn,MattWindsor91/roslyn,aelij/roslyn,AmadeusW/roslyn,abock/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,kelltrick/roslyn,jaredpar/roslyn,aanshibudhiraja/Roslyn,sharwell/roslyn,gafter/roslyn,agocke/roslyn,aanshibudhiraja/Roslyn,physhi/roslyn,weltkante/roslyn,yeaicc/roslyn,shyamnamboodiripad/roslyn,zooba/roslyn | src/EditorFeatures/Test/Outlining/OutliningSpanTests.cs | src/EditorFeatures/Test/Outlining/OutliningSpanTests.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Editor.Implementation.Outlining;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Outlining
{
public class OutliningSpanTests
{
[Fact]
public void TestProperties()
{
var span = TextSpan.FromBounds(0, 1);
var hintSpan = TextSpan.FromBounds(2, 3);
var bannerText = "Foo";
var autoCollapse = true;
var outliningRegion = new OutliningSpan(span, hintSpan, bannerText, autoCollapse);
Assert.Equal(span, outliningRegion.TextSpan);
Assert.Equal(hintSpan, outliningRegion.HintSpan);
Assert.Equal(bannerText, outliningRegion.BannerText);
Assert.Equal(autoCollapse, outliningRegion.AutoCollapse);
}
[Fact]
public void TestToStringWithHintSpan()
{
var span = TextSpan.FromBounds(0, 1);
var hintSpan = TextSpan.FromBounds(2, 3);
var bannerText = "Foo";
var autoCollapse = true;
var outliningRegion = new OutliningSpan(span, hintSpan, bannerText, autoCollapse);
Assert.Equal("{Span=[0..1), HintSpan=[2..3), BannerText=\"Foo\", AutoCollapse=True, IsDefaultCollapsed=False}", outliningRegion.ToString());
}
[Fact]
public void TestToStringWithoutHintSpan()
{
var span = TextSpan.FromBounds(0, 1);
var bannerText = "Foo";
var autoCollapse = true;
var outliningRegion = new OutliningSpan(span, bannerText, autoCollapse);
Assert.Equal("{Span=[0..1), BannerText=\"Foo\", AutoCollapse=True, IsDefaultCollapsed=False}", outliningRegion.ToString());
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Editor.Implementation.Outlining;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Outlining
{
public class OutliningSpanTests
{
[Fact]
public void TestProperties()
{
var span = TextSpan.FromBounds(0, 1);
var hintSpan = TextSpan.FromBounds(2, 3);
var bannerText = "Foo";
var autoCollapse = true;
var outliningRegion = new OutliningSpan(span, hintSpan, bannerText, autoCollapse);
Assert.Equal(span, outliningRegion.TextSpan);
Assert.Equal(hintSpan, outliningRegion.HintSpan);
Assert.Equal(bannerText, outliningRegion.BannerText);
Assert.Equal(autoCollapse, outliningRegion.AutoCollapse);
}
[Fact]
public void TestToStringWithHintSpan()
{
var span = TextSpan.FromBounds(0, 1);
var hintSpan = TextSpan.FromBounds(2, 3);
var bannerText = "Foo";
var autoCollapse = true;
var outliningRegion = new OutliningSpan(span, hintSpan, bannerText, autoCollapse);
Assert.Equal("{Span=[0..1), HintSpan=[2..3), BannerText=\"Foo\", AutoCollapse=True}", outliningRegion.ToString());
}
[Fact]
public void TestToStringWithoutHintSpan()
{
var span = TextSpan.FromBounds(0, 1);
var bannerText = "Foo";
var autoCollapse = true;
var outliningRegion = new OutliningSpan(span, bannerText, autoCollapse);
Assert.Equal("{Span=[0..1), BannerText=\"Foo\", AutoCollapse=True}", outliningRegion.ToString());
}
}
}
| mit | C# |
6ea7347d30b9f79e126d170fe1b99b1845b3c667 | correct version of ClrExtensionsIntegrationTestFixture | KingJiangNet/boo,bamboo/boo,Unity-Technologies/boo,rmboggs/boo,drslump/boo,wbardzinski/boo,KidFashion/boo,drslump/boo,wbardzinski/boo,BillHally/boo,bamboo/boo,drslump/boo,BitPuffin/boo,hmah/boo,BitPuffin/boo,hmah/boo,scottstephens/boo,hmah/boo,hmah/boo,KidFashion/boo,BillHally/boo,Unity-Technologies/boo,hmah/boo,Unity-Technologies/boo,rmartinho/boo,rmboggs/boo,scottstephens/boo,bamboo/boo,KingJiangNet/boo,wbardzinski/boo,BITechnologies/boo,boo-lang/boo,KidFashion/boo,BillHally/boo,Unity-Technologies/boo,wbardzinski/boo,rmartinho/boo,rmartinho/boo,bamboo/boo,scottstephens/boo,BitPuffin/boo,BITechnologies/boo,hmah/boo,KingJiangNet/boo,BitPuffin/boo,KidFashion/boo,rmartinho/boo,BillHally/boo,BITechnologies/boo,rmartinho/boo,Unity-Technologies/boo,BitPuffin/boo,wbardzinski/boo,boo-lang/boo,boo-lang/boo,hmah/boo,wbardzinski/boo,bamboo/boo,KingJiangNet/boo,BITechnologies/boo,rmartinho/boo,boo-lang/boo,BitPuffin/boo,BitPuffin/boo,BillHally/boo,wbardzinski/boo,hmah/boo,wbardzinski/boo,KidFashion/boo,drslump/boo,Unity-Technologies/boo,KingJiangNet/boo,BillHally/boo,KingJiangNet/boo,rmartinho/boo,BITechnologies/boo,bamboo/boo,scottstephens/boo,rmartinho/boo,scottstephens/boo,boo-lang/boo,BitPuffin/boo,drslump/boo,boo-lang/boo,BITechnologies/boo,BITechnologies/boo,KidFashion/boo,Unity-Technologies/boo,rmboggs/boo,KidFashion/boo,BillHally/boo,hmah/boo,rmboggs/boo,scottstephens/boo,rmboggs/boo,scottstephens/boo,rmboggs/boo,boo-lang/boo,Unity-Technologies/boo,scottstephens/boo,KingJiangNet/boo,drslump/boo,KingJiangNet/boo,rmboggs/boo,bamboo/boo,drslump/boo,BITechnologies/boo,boo-lang/boo,rmboggs/boo | tests/BooCompiler.Tests/ClrExtensionsIntegrationTestFixture.cs | tests/BooCompiler.Tests/ClrExtensionsIntegrationTestFixture.cs | namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class ClrExtensionsIntegrationTestFixture : AbstractCompilerTestCase
{
[Test]
public void clrextensions_1()
{
RunCompilerTestCase(@"clrextensions-1.boo");
}
[Test]
public void clrextensions_2()
{
RunCompilerTestCase(@"clrextensions-2.boo");
}
[Test]
public void infer_closure_singature()
{
RunCompilerTestCase(@"infer-closure-singature.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "integration/clr-extensions";
}
}
}
| namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class ClrextensionsIntegrationTestFixture : AbstractCompilerTestCase
{
[Test]
public void clrextensions_1()
{
RunCompilerTestCase(@"clrextensions-1.boo");
}
[Test]
public void clrextensions_2()
{
RunCompilerTestCase(@"clrextensions-2.boo");
}
[Test]
public void infer_closure_singature()
{
RunCompilerTestCase(@"infer-closure-singature.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "integration/clrextensions";
}
}
}
| bsd-3-clause | C# |
a24fdf67944b4954ba7f25e2d5cd7df521293741 | Disable failing unit test | JohnStov/ReSharperFixieRunner | ResharperFixieTestRunner.Tests/FixieTaskRunnerTest.cs | ResharperFixieTestRunner.Tests/FixieTaskRunnerTest.cs | using JetBrains.ReSharper.TaskRunnerFramework;
using NSubstitute;
using ReSharperFixieTestRunner;
namespace ResharperFixieTestRunner.Tests
{
public class FixieTaskRunnerTests
{
private void CanExecuteRecursive()
{
var remoteTaskServer = Substitute.For<IRemoteTaskServer>();
var taskRunner = new TaskRunner(remoteTaskServer);
var remoteTask = Substitute.For<RemoteTask>("RemoteTask");
var node = new TaskExecutionNode(null, remoteTask);
taskRunner.ExecuteRecursive(node);
remoteTaskServer.Received().TaskStarting(Arg.Any<RemoteTask>());
remoteTaskServer.Received().TaskFinished(Arg.Any<RemoteTask>(), Arg.Any<string>(), TaskResult.Success);
}
}
}
| using JetBrains.ReSharper.TaskRunnerFramework;
using NSubstitute;
using ReSharperFixieTestRunner;
namespace ResharperFixieTestRunner.Tests
{
public class FixieTaskRunnerTests
{
public void CanExecuteRecursive()
{
var remoteTaskServer = Substitute.For<IRemoteTaskServer>();
var taskRunner = new TaskRunner(remoteTaskServer);
var remoteTask = Substitute.For<RemoteTask>("RemoteTask");
var node = new TaskExecutionNode(null, remoteTask);
taskRunner.ExecuteRecursive(node);
remoteTaskServer.Received().TaskStarting(Arg.Any<RemoteTask>());
remoteTaskServer.Received().TaskFinished(Arg.Any<RemoteTask>(), Arg.Any<string>(), TaskResult.Success);
}
}
}
| mit | C# |
b9d01a86cde039443515f74d8ad8f9c4e6332ec8 | Update CompositeCrossCurrencyConverter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Finance/CompositeCrossCurrencyConverter.cs | TIKSN.Core/Finance/CompositeCrossCurrencyConverter.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Finance
{
public class CompositeCrossCurrencyConverter : CompositeCurrencyConverter
{
public CompositeCrossCurrencyConverter(ICurrencyConversionCompositionStrategy compositionStrategy)
: base(compositionStrategy)
{
}
public override async Task<Money> ConvertCurrencyAsync(Money baseMoney, CurrencyInfo counterCurrency,
DateTimeOffset asOn, CancellationToken cancellationToken) =>
await this.compositionStrategy.ConvertCurrencyAsync(baseMoney, this.converters, counterCurrency, asOn,
cancellationToken);
public override async Task<IEnumerable<CurrencyPair>> GetCurrencyPairsAsync(DateTimeOffset asOn,
CancellationToken cancellationToken)
{
var pairs = new HashSet<CurrencyPair>();
foreach (var converter in this.converters)
{
var currentPairs = await converter.GetCurrencyPairsAsync(asOn, cancellationToken);
foreach (var currentPair in currentPairs)
{
pairs.Add(currentPair);
}
}
return pairs;
}
public override async Task<decimal> GetExchangeRateAsync(CurrencyPair pair, DateTimeOffset asOn,
CancellationToken cancellationToken) =>
await this.compositionStrategy.GetExchangeRateAsync(this.converters, pair, asOn, cancellationToken);
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Finance
{
public class CompositeCrossCurrencyConverter : CompositeCurrencyConverter
{
public CompositeCrossCurrencyConverter(ICurrencyConversionCompositionStrategy compositionStrategy)
: base(compositionStrategy)
{
}
public override async Task<Money> ConvertCurrencyAsync(Money baseMoney, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken)
{
return await compositionStrategy.ConvertCurrencyAsync(baseMoney, this.converters, counterCurrency, asOn, cancellationToken);
}
public override async Task<IEnumerable<CurrencyPair>> GetCurrencyPairsAsync(DateTimeOffset asOn, CancellationToken cancellationToken)
{
var pairs = new HashSet<CurrencyPair>();
foreach (var converter in this.converters)
{
var currentPairs = await converter.GetCurrencyPairsAsync(asOn, cancellationToken);
foreach (var currentPair in currentPairs)
{
pairs.Add(currentPair);
}
}
return pairs;
}
public override async Task<decimal> GetExchangeRateAsync(CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken)
{
return await compositionStrategy.GetExchangeRateAsync(this.converters, pair, asOn, cancellationToken);
}
}
} | mit | C# |
d8fd692ab9233652207cc299f2f2a6055dcc4791 | Hide methods from editor. | telerik/JustMockLite | Telerik.JustMock/Core/Context/AsyncContextResolver.cs | Telerik.JustMock/Core/Context/AsyncContextResolver.cs | /*
JustMock Lite
Copyright © 2019 Progress Software Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
public static MethodBase GetContext()
{
return resolver.GetContext();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
| /*
JustMock Lite
Copyright © 2019 Progress Software Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return resolver.GetContext();
}
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
| apache-2.0 | C# |
79cbae0080d5f45a95581e68746ae01526ce5027 | Allow continuous camera zoom control | mysticfall/Alensia | Assets/Alensia/Core/Camera/OrbitingCameraControl.cs | Assets/Alensia/Core/Camera/OrbitingCameraControl.cs | using System.Collections.Generic;
using Alensia.Core.Input;
using Alensia.Core.Input.Generic;
using UniRx;
namespace Alensia.Core.Camera
{
public class OrbitingCameraControl : RotatableCameraControl
{
public IBindingKey<IAxisInput> Zoom => Keys.Zoom;
protected IAxisInput Scroll { get; private set; }
public override bool Valid => base.Valid && Scroll != null;
public OrbitingCameraControl(
ICameraManager cameraManager,
IInputManager inputManager) : base(cameraManager, inputManager)
{
}
protected override ICollection<IBindingKey> PrepareBindings()
{
return new List<IBindingKey>(base.PrepareBindings()) {Zoom};
}
protected override void OnBindingChange(IBindingKey key)
{
base.OnBindingChange(key);
if (Equals(key, Keys.Zoom))
{
Scroll = InputManager.Get(Keys.Zoom);
}
}
protected override void OnActivate()
{
base.OnActivate();
var zoom = Scroll.Value
.Where(_ => CameraManager.Mode is IZoomableCamera)
.Select(v => v * -15);
Subsribe(zoom, OnZoom);
}
protected void OnZoom(float input)
{
OnZoom(input, (IZoomableCamera) CameraManager.Mode);
}
protected virtual void OnZoom(float input, IZoomableCamera camera)
{
camera.Distance += input;
}
public new class Keys : RotatableCameraControl.Keys
{
public static IBindingKey<IAxisInput> Zoom = new BindingKey<IAxisInput>(Id + ".Zoom");
}
}
} | using System;
using System.Collections.Generic;
using Alensia.Core.Input;
using Alensia.Core.Input.Generic;
using UniRx;
namespace Alensia.Core.Camera
{
public class OrbitingCameraControl : RotatableCameraControl
{
public IBindingKey<IAxisInput> Zoom => Keys.Zoom;
protected IAxisInput Scroll { get; private set; }
public override bool Valid => base.Valid && Scroll != null;
public OrbitingCameraControl(
ICameraManager cameraManager,
IInputManager inputManager) : base(cameraManager, inputManager)
{
}
protected override ICollection<IBindingKey> PrepareBindings()
{
return new List<IBindingKey>(base.PrepareBindings()) {Zoom};
}
protected override void OnBindingChange(IBindingKey key)
{
base.OnBindingChange(key);
if (Equals(key, Keys.Zoom))
{
Scroll = InputManager.Get(Keys.Zoom);
}
}
protected override void OnActivate()
{
base.OnActivate();
var zoom = Scroll.Value
.Where(_ => CameraManager.Mode is IZoomableCamera)
.Select(v => (float) -Math.Sign(v));
Subsribe(zoom, OnZoom);
}
protected void OnZoom(float input)
{
OnZoom(input, (IZoomableCamera) CameraManager.Mode);
}
protected virtual void OnZoom(float input, IZoomableCamera camera)
{
camera.Distance += input;
}
public new class Keys : RotatableCameraControl.Keys
{
public static IBindingKey<IAxisInput> Zoom = new BindingKey<IAxisInput>(Id + ".Zoom");
}
}
} | apache-2.0 | C# |
5b44a5c0c38aa8fe3af8e8ea100df6beacee8ac7 | Update AssemblyVersion | dmitry-shechtman/AsyncInit | AsyncInit.Unity/Portable/Properties/AssemblyInfo.cs | AsyncInit.Unity/Portable/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Ditto.AsyncInit.Unity")]
[assembly: AssemblyDescription("Unity Container Async Extensions")]
[assembly: AssemblyVersion("1.6.0.*")]
[assembly: ComVisible(false)]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Ditto.AsyncInit.Unity")]
[assembly: AssemblyDescription("Unity Container Async Extensions")]
[assembly: AssemblyVersion("1.5.0.*")]
[assembly: ComVisible(false)]
| apache-2.0 | C# |
465da45b02dfdb105be9a824b88b16a34813d6dc | Make namespace upperclase like it should be. | WisconsinRobotics/BadgerJAUS.NET | BadgerJaus/messages/discovery/QueryConfiguration.cs | BadgerJaus/messages/discovery/QueryConfiguration.cs | /*
* Copyright (c) 2015, Wisconsin Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Wisconsin Robotics nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL WISCONSIN ROBOTICS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BadgerJaus.Messages;
using BadgerJaus.Util;
namespace BadgerJaus.Messages.Discovery
{
public class QueryConfiguration : Message
{
public const int SUBSYSTEM_CONFIGURATION = 2;
public const int NODE_CONFIGURATION = 3;
JausByte queryType;
protected override int CommandCode
{
get { return JausCommandCode.QUERY_IDENTIFICATION; }
}
protected override void InitFieldData()
{
queryType = new JausByte(SUBSYSTEM_CONFIGURATION);
}
protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset)
{
return queryType.Serialize(buffer, index, out indexOffset);
}
// Takes Super's payload, and unpacks it into Message Fields
protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset)
{
indexOffset = index;
queryType.Value = buffer[indexOffset];
indexOffset += JausBaseType.BYTE_BYTE_SIZE;
return true;
}
}
}
| /*
* Copyright (c) 2015, Wisconsin Robotics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Wisconsin Robotics nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL WISCONSIN ROBOTICS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BadgerJaus.Messages;
using BadgerJaus.Util;
namespace BadgerJaus.Messages.discovery
{
public class QueryConfiguration : Message
{
public const int SUBSYSTEM_CONFIGURATION = 2;
public const int NODE_CONFIGURATION = 3;
JausByte queryType;
protected override int CommandCode
{
get { return JausCommandCode.QUERY_IDENTIFICATION; }
}
protected override void InitFieldData()
{
queryType = new JausByte(SUBSYSTEM_CONFIGURATION);
}
protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset)
{
return queryType.Serialize(buffer, index, out indexOffset);
}
// Takes Super's payload, and unpacks it into Message Fields
protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset)
{
indexOffset = index;
queryType.Value = buffer[indexOffset];
indexOffset += JausBaseType.BYTE_BYTE_SIZE;
return true;
}
}
}
| bsd-3-clause | C# |
8e2eac31780540b263e22aa4df2f44d51e95ac44 | fix parsing | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Parsing/Messages/S_REQUEST_CITY_WAR_MAP_INFO_DETAIL.cs | TCC.Core/Parsing/Messages/S_REQUEST_CITY_WAR_MAP_INFO_DETAIL.cs | using System;
using System.Collections.Generic;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class S_REQUEST_CITY_WAR_MAP_INFO_DETAIL : ParsedMessage
{
public List<Tuple<uint, string>> GuildDetails;
public S_REQUEST_CITY_WAR_MAP_INFO_DETAIL(TeraMessageReader reader) : base(reader)
{
GuildDetails = new List<Tuple<uint, string>>();
try
{
var count = reader.ReadUInt16();
if (count == 0) return;
var offset = reader.ReadUInt16();
reader.BaseStream.Position = offset - 4;
for (int i = 0; i < count; i++)
{
var current = reader.ReadUInt16();
var next = reader.ReadUInt16();
reader.Skip(6);
var id = reader.ReadUInt32();
var name = reader.ReadTeraString();
var gm = reader.ReadTeraString();
var logo = reader.ReadTeraString();
//TODO: use gm and logo?
GuildDetails.Add(new Tuple<uint, string>(id, name));
if (next != 0) reader.BaseStream.Position = next - 4;
}
}
catch (Exception e)
{
}
}
}
} | using System;
using System.Collections.Generic;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class S_REQUEST_CITY_WAR_MAP_INFO_DETAIL : ParsedMessage
{
public List<Tuple<uint, string>> GuildDetails;
public S_REQUEST_CITY_WAR_MAP_INFO_DETAIL(TeraMessageReader reader) : base(reader)
{
GuildDetails = new List<Tuple<uint, string>>();
try
{
var count = reader.ReadUInt16();
if (count == 0) return;
var offset = reader.ReadUInt16();
reader.BaseStream.Position = offset - 4;
for (int i = 0; i < count; i++)
{
var current = reader.ReadUInt16();
var next = reader.ReadUInt16();
var id = reader.ReadUInt32();
var name = reader.ReadTeraString();
var gm = reader.ReadTeraString();
var logo = reader.ReadTeraString();
//TODO: use gm and logo?
GuildDetails.Add(new Tuple<uint, string>(id, name));
if (next != 0) reader.BaseStream.Position = next - 4;
}
}
catch (Exception e)
{
}
}
}
} | mit | C# |
75ad5b3c696a9fa474cabc129bfadb3b982246d9 | increment patch version | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1")]
/*
* Version 0.1.1
*
* - renamed Experimental(adjective) to Experiment(noun).
* Although this results in breaking change, it can be treated as patch
* version because according to semver(v2), major version zero is allowed
* to make breaking changes.
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
/*
* Version 0.1.0
*
* - TheoremAttribute is test attribute specified on method to indicate
* test-case which is the same with FactAttribute of xunit.
*
* - TheoremAttribute supports parameterized test, which is the same with
* TheoryAttribute of xunit.
*/ | mit | C# |
4f580f3e96ce9a8a65df8a68d024b230f070a142 | Change the page header | benlam62/app-service-mobile-dotnet-fieldengineer | server/FieldEngineer/Views/Admin/Index.cshtml | server/FieldEngineer/Views/Admin/Index.cshtml | @model IEnumerable<FieldEngineerLiteService.DataObjects.Job>
@{
ViewBag.Title = "Index";
}
<h2>Tasks for my Hong Kong agents</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
Agent
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Status)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerName)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerAddress)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerPhoneNumber)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.AgentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerName)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerPhoneNumber)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
| @model IEnumerable<FieldEngineerLiteService.DataObjects.Job>
@{
ViewBag.Title = "Index";
}
<h2>Tasks for my agents</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
Agent
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Status)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerName)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerAddress)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerPhoneNumber)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.AgentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerName)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerPhoneNumber)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
| mit | C# |
a0394a69b1e7d7593af7b94ade50070ad44fc219 | Improve TracRevisionLog textual !ChangeLog format (1/3): Refactoring log_changelog.cs to use the ClearSilver ''with'' command. | rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac | templates/log_changelog.cs | templates/log_changelog.cs | #
# ChangeLog for <?cs var:log.path ?>
#
# Generated by Trac <?cs var:trac.version ?>
# <?cs var:trac.time ?>
#
<?cs each:item = $log.items ?>
<?cs with:changeset = log.changes[item.rev] ?>
<?cs var:changeset.date ?> <?cs
var:changeset.author ?> [<?cs var:item.rev ?>]
<?cs each:file = $changeset.files ?>
* <?cs var:file ?>:<?cs
/each ?>
<?cs var:changeset.message ?>
<?cs /with ?>
<?cs /each ?>
| #
# ChangeLog for <?cs var:log.path ?>
#
# Generated by Trac <?cs var:trac.version ?>
# <?cs var:trac.time ?>
#
<?cs each:item = $log.items ?>
<?cs var:log.changes[item.rev].date ?> <?cs
var:log.changes[item.rev].author ?> [<?cs var:item.rev ?>]
<?cs each:file = $log.changes[item.rev].files ?>
* <?cs var:file ?>:<?cs
/each ?>
<?cs var:log.changes[item.rev].message ?>
<?cs /each ?>
| bsd-3-clause | C# |
d8f387f7cbdc3a1554a1508af3fa03162481088f | Make CryptoConfiguration depend on inteface, not implmentation | RockFramework/Rock.Encryption | Rock.Encryption/Symmetric/CryptoConfiguration.cs | Rock.Encryption/Symmetric/CryptoConfiguration.cs | using System.Collections.Generic;
namespace RockLib.Encryption.Symmetric
{
/// <summary>
/// Defines an xml-serializable object that contains the information needed to configure an
/// instance of <see cref="SymmetricCrypto"/>.
/// </summary>
public class CryptoConfiguration
{
/// <summary>
/// Gets the collection of credentials that will be available for encryption or
/// decryption operations.
/// </summary>
public List<ICredential> Credentials { get; set; } = new List<ICredential>();
}
} | using System.Collections.Generic;
namespace RockLib.Encryption.Symmetric
{
/// <summary>
/// Defines an xml-serializable object that contains the information needed to configure an
/// instance of <see cref="SymmetricCrypto"/>.
/// </summary>
public class CryptoConfiguration
{
/// <summary>
/// Gets the collection of credentials that will be available for encryption or
/// decryption operations.
/// </summary>
public List<Credential> Credentials { get; set; } = new List<Credential>();
}
} | mit | C# |
bf08411873416dabba1f082b8a3f64e18e889196 | Add fullname class in test AllClassesShouldBeSealedTests | SiliconStudio/SharpDiff,xoofx/SharpDiff | SharpDiff.Tests/AllClassesShouldBeSealedTests.cs | SharpDiff.Tests/AllClassesShouldBeSealedTests.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
namespace SharpDiff.Tests
{
[TestFixture]
public class AllClassesShouldBeSealedTests
{
public IEnumerable<Type> AllTypesInDiffLib()
{
return
from type in typeof(Diff2).Assembly.GetTypes()
where type.IsPublic
&& type.IsClass
select type;
}
[TestCaseSource("AllTypesInDiffLib")]
public void TypeShouldBeSealed(Type type)
{
Assert.That(type.IsSealed, Is.True, $"Type {type.FullName} is not sealed");
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
namespace SharpDiff.Tests
{
[TestFixture]
public class AllClassesShouldBeSealedTests
{
public IEnumerable<Type> AllTypesInDiffLib()
{
return
from type in typeof(Diff2).Assembly.GetTypes()
where type.IsPublic
&& type.IsClass
select type;
}
[TestCaseSource("AllTypesInDiffLib")]
public void TypeShouldBeSealed(Type type)
{
Assert.That(type.IsSealed, Is.True);
}
}
} | bsd-3-clause | C# |
efd3e47c0d3d936edb7377e24a3dc6151d8d3c67 | fix closing tag | pedroreys/docs.particular.net,pashute/docs.particular.net,eclaus/docs.particular.net,SzymonPobiega/docs.particular.net,yuxuac/docs.particular.net,WojcikMike/docs.particular.net | Snippets/Snippets_5/DefineCriticalErrorAction.cs | Snippets/Snippets_5/DefineCriticalErrorAction.cs | using NServiceBus;
// ReSharper disable once ConvertToLambdaExpression
public class DefineCriticalErrorAction
{
public void Simple()
{
// start code DefineCriticalErrorActionV5
var configure = Configure.With(builder =>
{
builder.DefineCriticalErrorAction((s, exception) =>
{
// custom exception handling
});
});
// end code DefineCriticalErrorActionV5
}
} | using NServiceBus;
// ReSharper disable once ConvertToLambdaExpression
public class DefineCriticalErrorAction
{
public void Simple()
{
// start code DefineCriticalErrorActionV5
var configure = Configure.With(builder =>
{
builder.DefineCriticalErrorAction((s, exception) =>
{
// custom exception handling
});
});
// end code DefineCriticalErrorActionV
}
} | apache-2.0 | C# |
0287a7aeafc61bcc9a39350fe35ed564c79d9525 | Fix FirstOrNothing returning wrong maybe value. | muhbaasu/fx-sharp | src/FxSharp/Extensions/EnumerableExtensions.cs | src/FxSharp/Extensions/EnumerableExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace FxSharp.Extensions
{
public static class EnumerableExtensions
{
/// <summary>
/// Convert a single value into an one item-sized enumerable.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val"></param>
/// <returns></returns>
public static IEnumerable<T> ToEnumerable<T>(this T val)
{
yield return val;
}
/// <summary>
/// Similiar to FirstOrDefault but return a Maybe.
/// </summary>
/// <typeparam name="TSource">The type of the enumerable.</typeparam>
/// <param name="source">The enumerable.</param>
/// <param name="predicate">The predicate to filter with.</param>
/// <returns>Maybe.Nothing(T) if no value matches the predicate.</returns>
public static Maybe<TSource> FirstOrNothing<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
if (source == null || predicate == null)
{
return Maybe.Nothing<TSource>();
}
var enumerable = source as TSource[] ?? source.ToArray();
return !enumerable.Any(predicate)
? Maybe.Nothing<TSource>()
: Maybe.Just(enumerable.FirstOrDefault(predicate));
}
/// <summary>
/// Similiar to FirstOrDefault but return a Maybe.
/// </summary>
/// <typeparam name="TSource">The type of the enumerable.</typeparam>
/// <param name="source">The enumerable.</param>
/// <returns>Maybe.Nothing(T) if no value matches the predicate.</returns>
public static Maybe<TSource> FirstOrNothing<TSource>(
this IEnumerable<TSource> source)
{
if (source == null)
{
return Maybe.Nothing<TSource>();
}
var enumerable = source as TSource[] ?? source.ToArray();
return enumerable.Any()
? Maybe.Just(enumerable.FirstOrDefault())
: Maybe.Nothing<TSource>();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace FxSharp.Extensions
{
public static class EnumerableExtensions
{
/// <summary>
/// Convert a single value into an one item-sized enumerable.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val"></param>
/// <returns></returns>
public static IEnumerable<T> ToEnumerable<T>(this T val)
{
yield return val;
}
/// <summary>
/// Similiar to FirstOrDefault but return a Maybe.
/// </summary>
/// <typeparam name="TSource">The type of the enumerable.</typeparam>
/// <param name="source">The enumerable.</param>
/// <param name="predicate">The predicate to filter with.</param>
/// <returns>Maybe.Nothing(T) if no value matches the predicate.</returns>
public static Maybe<TSource> FirstOrNothing<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
if (source == null || predicate == null)
{
return Maybe.Nothing<TSource>();
}
var enumerable = source as TSource[] ?? source.ToArray();
return !enumerable.Any(predicate)
? Maybe.Nothing<TSource>()
: Maybe.Just(enumerable.FirstOrDefault(predicate));
}
/// <summary>
/// Similiar to FirstOrDefault but return a Maybe.
/// </summary>
/// <typeparam name="TSource">The type of the enumerable.</typeparam>
/// <param name="source">The enumerable.</param>
/// <returns>Maybe.Nothing(T) if no value matches the predicate.</returns>
public static Maybe<TSource> FirstOrNothing<TSource>(
this IEnumerable<TSource> source)
{
if (source == null)
{
return Maybe.Nothing<TSource>();
}
var enumerable = source as TSource[] ?? source.ToArray();
return enumerable.Any()
? Maybe.Nothing<TSource>()
: Maybe.Just(enumerable.FirstOrDefault());
}
}
} | apache-2.0 | C# |
ffdbc86904ecbf2dd05e32c914ed436b0d5fce7c | correct link generation | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.Dashboard/Views/Shared/LoginStatus.cshtml | WebAPI.Dashboard/Views/Shared/LoginStatus.cshtml | @using WebAPI.Common.Extensions
@model WebAPI.Common.Models.Raven.Users.Account
| <i class="glyphicon glyphicon-user"></i> @Html.ActionLink(Model.Name.DefaultIfNullOrEmpty("Update profile"), "Index", "Profile", new { Area = "secure" }, null) | <i class="glyphicon glyphicon-road"></i>
@Html.ActionLink("Log Out", "Logout") | @using WebAPI.Common.Extensions
@model WebAPI.Common.Models.Raven.Users.Account
| <i class="glyphicon glyphicon-user"></i> @Html.ActionLink(Model.Name.DefaultIfNullOrEmpty("Update profile"), "Index", "Profile") | <i class="glyphicon glyphicon-road"></i>
@Html.ActionLink("Log Out", "Logout") | mit | C# |
3905f6c7e9ca8284a9d753dad8ee9abc42cb0a8c | Make CommandStrings file path independent of working directory. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | src/MitternachtBot/Resources/CommandStrings.cs | src/MitternachtBot/Resources/CommandStrings.cs | using System;
using System.IO;
using System.Linq;
using Mitternacht.Common.Collections;
using NLog;
using YamlDotNet.Serialization;
namespace Mitternacht.Resources {
public class CommandStrings {
private static readonly Logger _logger;
private static readonly string CmdStringPath = Path.Combine(Path.GetDirectoryName(typeof(CommandStrings).Assembly.Location), "_strings/commandstrings.yml");
private static ConcurrentHashSet<CommandStringsModel> _commandStrings;
static CommandStrings() {
_logger = LogManager.GetCurrentClassLogger();
LoadCommandStrings();
}
public static void LoadCommandStrings() {
try {
var yml = File.ReadAllText(CmdStringPath);
var deserializer = new Deserializer();
_commandStrings = deserializer.Deserialize<ConcurrentHashSet<CommandStringsModel>>(yml);
} catch(Exception e) {
_logger.Error(e);
}
}
public static CommandStringsModel GetCommandStringModel(string name)
=> _commandStrings.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) ?? throw new Exception($"CommandStringsModel for command '{name}' not found.");
}
} | using System;
using System.IO;
using System.Linq;
using Mitternacht.Common.Collections;
using NLog;
using YamlDotNet.Serialization;
namespace Mitternacht.Resources {
public class CommandStrings {
private static readonly Logger _logger;
private const string CmdStringPath = @"./_strings/commandstrings.yml";
private static ConcurrentHashSet<CommandStringsModel> _commandStrings;
static CommandStrings() {
_logger = LogManager.GetCurrentClassLogger();
LoadCommandStrings();
}
public static void LoadCommandStrings() {
try {
var yml = File.ReadAllText(CmdStringPath);
var deserializer = new Deserializer();
_commandStrings = deserializer.Deserialize<ConcurrentHashSet<CommandStringsModel>>(yml);
} catch(Exception e) {
_logger.Error(e);
}
}
public static CommandStringsModel GetCommandStringModel(string name)
=> _commandStrings.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) ?? throw new Exception($"CommandStringsModel for command '{name}' not found.");
}
} | mit | C# |
6d64f232dab6b9a8064008741f9e5db78826a384 | Add test to commands remove repl | MichaelSimons/cli,MichaelSimons/cli,harshjain2/cli,nguerrera/cli,nguerrera/cli,weshaggard/cli,dasMulli/cli,ravimeda/cli,weshaggard/cli,naamunds/cli,nguerrera/cli,Faizan2304/cli,JohnChen0/cli,livarcocc/cli-1,borgdylan/dotnet-cli,schellap/cli,weshaggard/cli,johnbeisner/cli,EdwardBlair/cli,livarcocc/cli-1,FubarDevelopment/cli,ravimeda/cli,schellap/cli,svick/cli,borgdylan/dotnet-cli,mlorbetske/cli,blackdwarf/cli,ravimeda/cli,FubarDevelopment/cli,naamunds/cli,MichaelSimons/cli,MichaelSimons/cli,dasMulli/cli,weshaggard/cli,jonsequitur/cli,weshaggard/cli,AbhitejJohn/cli,JohnChen0/cli,borgdylan/dotnet-cli,mylibero/cli,blackdwarf/cli,schellap/cli,mylibero/cli,borgdylan/dotnet-cli,johnbeisner/cli,AbhitejJohn/cli,svick/cli,blackdwarf/cli,MichaelSimons/cli,livarcocc/cli-1,AbhitejJohn/cli,schellap/cli,svick/cli,dasMulli/cli,mlorbetske/cli,mylibero/cli,naamunds/cli,EdwardBlair/cli,mlorbetske/cli,jonsequitur/cli,schellap/cli,harshjain2/cli,nguerrera/cli,AbhitejJohn/cli,mlorbetske/cli,Faizan2304/cli,johnbeisner/cli,Faizan2304/cli,JohnChen0/cli,borgdylan/dotnet-cli,naamunds/cli,mylibero/cli,EdwardBlair/cli,jonsequitur/cli,blackdwarf/cli,naamunds/cli,harshjain2/cli,JohnChen0/cli,FubarDevelopment/cli,mylibero/cli,jonsequitur/cli,schellap/cli,FubarDevelopment/cli | src/dotnet/commands/dotnet-help/HelpCommand.cs | src/dotnet/commands/dotnet-help/HelpCommand.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Tools.Help
{
public class HelpCommand
{
private const string ProductLongName = ".NET Command Line Tools";
private const string UsageText = @"Usage: dotnet [common-options] [command] [arguments]
Arguments:
[command] The command to execute
[arguments] Arguments to pass to the command
Common Options (passed before the command):
-v|--verbose Enable verbose output
--version Display .NET CLI Version Number
--info Display .NET CLI Info
Common Commands:
new Initialize a basic .NET project
restore Restore dependencies specified in the .NET project
build Builds a .NET project
publish Publishes a .NET project for deployment (including the runtime)
run Compiles and immediately executes a .NET project
test Runs unit tests using the test runner specified in the project
pack Creates a NuGet package";
public static readonly string ProductVersion = GetProductVersion();
private static string GetProductVersion()
{
var attr = typeof(HelpCommand).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
return attr?.InformationalVersion;
}
public static int Run(string[] args)
{
if (args.Length == 0)
{
PrintHelp();
return 0;
}
else
{
return Cli.Program.Main(new[] { args[0], "--help" });
}
}
public static void PrintHelp()
{
PrintVersionHeader();
Reporter.Output.WriteLine(UsageText);
}
public static void PrintVersionHeader()
{
var versionString = string.IsNullOrEmpty(ProductVersion) ?
string.Empty :
$" ({ProductVersion})";
Reporter.Output.WriteLine(ProductLongName + versionString);
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Tools.Help
{
public class HelpCommand
{
private const string ProductLongName = ".NET Command Line Tools";
private const string UsageText = @"Usage: dotnet [common-options] [command] [arguments]
Arguments:
[command] The command to execute
[arguments] Arguments to pass to the command
Common Options (passed before the command):
-v|--verbose Enable verbose output
--version Display .NET CLI Version Number
--info Display .NET CLI Info
Common Commands:
new Initialize a basic .NET project
restore Restore dependencies specified in the .NET project
build Builds a .NET project
publish Publishes a .NET project for deployment (including the runtime)
run Compiles and immediately executes a .NET project
test Executes tests in a test project
repl Launch an interactive session (read, eval, print, loop)
pack Creates a NuGet package";
public static readonly string ProductVersion = GetProductVersion();
private static string GetProductVersion()
{
var attr = typeof(HelpCommand).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
return attr?.InformationalVersion;
}
public static int Run(string[] args)
{
if (args.Length == 0)
{
PrintHelp();
return 0;
}
else
{
return Cli.Program.Main(new[] { args[0], "--help" });
}
}
public static void PrintHelp()
{
PrintVersionHeader();
Reporter.Output.WriteLine(UsageText);
}
public static void PrintVersionHeader()
{
var versionString = string.IsNullOrEmpty(ProductVersion) ?
string.Empty :
$" ({ProductVersion})";
Reporter.Output.WriteLine(ProductLongName + versionString);
}
}
}
| mit | C# |
9ad5d34e47e2ecfafd58f6d5100e58fd5848e247 | Test fix | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Tests/UnitTests/ValidateMethodTests.cs | WalletWasabi.Tests/UnitTests/ValidateMethodTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using WalletWasabi.Gui.Converters;
using WalletWasabi.Gui.ViewModels.Validation;
using WalletWasabi.Models;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class ValidateMethodTests
{
public class ValidateTestClass
{
public ErrorDescriptors ValidateProperty()
{
return new ErrorDescriptors(new ErrorDescriptor(ErrorSeverity.Warning, "My warning error descriptor"), new ErrorDescriptor(ErrorSeverity.Error, "My error error descriptor"));
}
[ValidateMethod(nameof(ValidateProperty))]
private bool BooleanProperty { get; set; }
[ValidateMethod(nameof(ValidateProperty))]
private string StringProperty { get; set; }
}
[Fact]
public void PropertiesWithValidationTest()
{
var testClass = new ValidateTestClass();
var validator = Validator.PropertiesWithValidation(testClass);
Assert.Equal(2, validator.Count());
}
[Fact]
public void ErrorDescriptorsTest()
{
ErrorDescriptors eds = new ErrorDescriptors()
{
new ErrorDescriptor(ErrorSeverity.Default,"My default error descriptor"),
new ErrorDescriptor(ErrorSeverity.Info,"My info error descriptor"),
new ErrorDescriptor(ErrorSeverity.Warning,"My warning error descriptor"),
new ErrorDescriptor(ErrorSeverity.Error,"My error error descriptor")
};
// Constructor tests
Assert.Equal("My info error descriptor", eds[1].Message);
Assert.Equal(ErrorSeverity.Info, eds[1].Severity);
// Serialize and de-serialize test
var serialized = JsonConvert.SerializeObject(eds);
var converter = new ErrorDescriptorsJsonConverter();
var deserialized = (ErrorDescriptors)converter.Convert(new[] { new Exception(serialized) }, eds.GetType(), null, CultureInfo.InvariantCulture);
Assert.Equal(4, deserialized.Count());
for (int i = 0; i < eds.Count; i++)
{
Assert.Equal(eds[i], deserialized[i]);
}
}
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using WalletWasabi.Gui.Converters;
using WalletWasabi.Gui.ViewModels.Validation;
using WalletWasabi.Models;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class ValidateMethodTests
{
public class ValidateTestClass
{
public ErrorDescriptors ValidateProperty()
{
return new ErrorDescriptors(new ErrorDescriptor(ErrorSeverity.Warning, "My warning error descriptor"), new ErrorDescriptor(ErrorSeverity.Error, "My error error descriptor"));
}
[ValidateMethod(nameof(ValidateProperty))]
private bool BooleanProperty { get; set; }
[ValidateMethod(nameof(ValidateProperty))]
private string StringProperty { get; set; }
}
[Fact]
public void PropertiesWithValidationTest()
{
var testClass = new ValidateTestClass();
var validator = Validator.PropertiesWithValidation(testClass);
Assert.Equal(2, validator.Count());
foreach (var method in validator)
{
method.Item2.Invoke(null, null);
}
}
[Fact]
public void ErrorDescriptorsTest()
{
ErrorDescriptors eds = new ErrorDescriptors()
{
new ErrorDescriptor(ErrorSeverity.Default,"My default error descriptor"),
new ErrorDescriptor(ErrorSeverity.Info,"My info error descriptor"),
new ErrorDescriptor(ErrorSeverity.Warning,"My warning error descriptor"),
new ErrorDescriptor(ErrorSeverity.Error,"My error error descriptor")
};
// Constructor tests
Assert.Equal("My info error descriptor", eds[1].Message);
Assert.Equal(ErrorSeverity.Info, eds[1].Severity);
// Serialize and de-serialize test
var serialized = JsonConvert.SerializeObject(eds);
var converter = new ErrorDescriptorsJsonConverter();
var deserialized = (ErrorDescriptors)converter.Convert(new[] { new Exception(serialized) }, eds.GetType(), null, CultureInfo.InvariantCulture);
Assert.Equal(4, deserialized.Count());
for (int i = 0; i < eds.Count; i++)
{
Assert.Equal(eds[i], deserialized[i]);
}
}
}
}
| mit | C# |
4e24590220accc7114662b6cf263d55f272fbb99 | add Xml comments for RandomPageGenerator | CXuesong/WikiClientLibrary | WikiClientLibrary/Generators/RandomPageGenerator.cs | WikiClientLibrary/Generators/RandomPageGenerator.cs | using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using WikiClientLibrary.Client;
using WikiClientLibrary.Generators;
using WikiClientLibrary.Generators.Primitive;
using WikiClientLibrary.Pages;
using WikiClientLibrary.Sites;
namespace WikiClientLibrary.Generators
{
/// <summary>
/// Gets random pages in a specific namespace.
/// </summary>
class RandomPageGenerator : WikiPageGenerator
{
/// <inheritdoc />
public RandomPageGenerator(WikiSite site) : base(site)
{
}
/// <inheritdoc />
protected override WikiPageStub ItemFromJson(JToken json)
{
return new WikiPageStub((int)json["id"], (string)json["title"], (int)json["ns"]);
}
/// <inheritdoc />
public int NamespaceId { get; set; } = 0;
/// <summary>
/// How to filter redirects.
/// </summary>
public PropertyFilterOption RedirectsFilter { get; set; }
/// <inheritdoc/>
public override string ListName => "random";
/// <inheritdoc/>
public override IEnumerable<KeyValuePair<string, object>> EnumListParameters()
{
return new Dictionary<string, object>
{
{ "rnnamespace", NamespaceId},
{"rnfilterredir", RedirectsFilter},
{"rnlimit", PaginationSize},
};
}
}
}
| using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using WikiClientLibrary.Client;
using WikiClientLibrary.Generators;
using WikiClientLibrary.Generators.Primitive;
using WikiClientLibrary.Pages;
using WikiClientLibrary.Sites;
namespace WikiClientLibrary.Generators
{
/// <summary>
/// Gets random pages in a specific namespace.
/// </summary>
class RandomPageGenerator : WikiPageGenerator
{
/// <inheritdoc />
public RandomPageGenerator(WikiSite site) : base(site)
{
}
protected override WikiPageStub ItemFromJson(JToken json)
{
return new WikiPageStub((int)json["id"], (string)json["title"], (int)json["ns"]);
}
public int NamespaceId { get; set; } = 0;
/// <summary>
/// How to filter redirects.
/// </summary>
public PropertyFilterOption RedirectsFilter { get; set; }
/// <inheritdoc/>
public override string ListName => "random";
/// <inheritdoc/>
public override IEnumerable<KeyValuePair<string, object>> EnumListParameters()
{
return new Dictionary<string, object>
{
{ "rnnamespace", NamespaceId},
{"rnfilterredir", RedirectsFilter},
{"rnlimit", PaginationSize},
};
}
}
}
}
| apache-2.0 | C# |
ea89ef669692a1fce1d63540ce85a58702c00c46 | Replace GetUnixTime() with more elegant .NET 4.6 alternative | JustArchi/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,KlappPc/ArchiSteamFarm,KlappPc/ArchiSteamFarm,i3at/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,i3at/ArchiSteamFarm,JustArchi/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,KlappPc/ArchiSteamFarm | ArchiSteamFarm/Utilities.cs | ArchiSteamFarm/Utilities.cs | /*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
Copyright 2015-2016 Łukasz "JustArchi" Domeradzki
Contact: JustArchi@JustArchi.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
namespace ArchiSteamFarm {
internal static class Utilities {
private static readonly Random Random = new Random();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[SuppressMessage("ReSharper", "UnusedParameter.Global")]
internal static void Forget(this object obj) { }
internal static string GetCookieValue(this CookieContainer cookieContainer, string url, string name) {
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(name)) {
ASF.ArchiLogger.LogNullError(nameof(url) + " || " + nameof(name));
return null;
}
Uri uri;
try {
uri = new Uri(url);
} catch (UriFormatException e) {
ASF.ArchiLogger.LogGenericException(e);
return null;
}
CookieCollection cookies = cookieContainer.GetCookies(uri);
return cookies.Count != 0 ? (from Cookie cookie in cookies where cookie.Name.Equals(name) select cookie.Value).FirstOrDefault() : null;
}
internal static uint GetUnixTime() => (uint) DateTimeOffset.Now.ToUnixTimeSeconds();
internal static int RandomNext(int maxWithout) {
if (maxWithout <= 0) {
ASF.ArchiLogger.LogNullError(nameof(maxWithout));
return -1;
}
if (maxWithout == 1) {
return 0;
}
lock (Random) {
return Random.Next(maxWithout);
}
}
}
} | /*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
Copyright 2015-2016 Łukasz "JustArchi" Domeradzki
Contact: JustArchi@JustArchi.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
namespace ArchiSteamFarm {
internal static class Utilities {
private static readonly Random Random = new Random();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[SuppressMessage("ReSharper", "UnusedParameter.Global")]
internal static void Forget(this object obj) { }
internal static string GetCookieValue(this CookieContainer cookieContainer, string url, string name) {
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(name)) {
ASF.ArchiLogger.LogNullError(nameof(url) + " || " + nameof(name));
return null;
}
Uri uri;
try {
uri = new Uri(url);
} catch (UriFormatException e) {
ASF.ArchiLogger.LogGenericException(e);
return null;
}
CookieCollection cookies = cookieContainer.GetCookies(uri);
return cookies.Count != 0 ? (from Cookie cookie in cookies where cookie.Name.Equals(name) select cookie.Value).FirstOrDefault() : null;
}
internal static uint GetUnixTime() => (uint) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
internal static int RandomNext(int maxWithout) {
if (maxWithout <= 0) {
ASF.ArchiLogger.LogNullError(nameof(maxWithout));
return -1;
}
if (maxWithout == 1) {
return 0;
}
lock (Random) {
return Random.Next(maxWithout);
}
}
}
} | apache-2.0 | C# |
55694a96e82a9722e7029798361fe16eb0a18bc9 | Remove website url from product description | protyposis/Aurio,protyposis/Aurio | Aurio/GlobalAssemblyInfo.cs | Aurio/GlobalAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// http://stackoverflow.com/questions/62353/what-are-the-best-practices-for-using-assembly-attributes
[assembly: AssemblyCompany("Mario Guggenberger / protyposis.net")]
[assembly: AssemblyProduct("Aurio Audio Processing, Analysis and Retrieval Library")]
//[assembly: AssemblyTrademark("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// 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: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0 Alpha")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// http://stackoverflow.com/questions/62353/what-are-the-best-practices-for-using-assembly-attributes
[assembly: AssemblyCompany("Mario Guggenberger / protyposis.net")]
[assembly: AssemblyProduct("Aurio Audio Processing, Analysis and Retrieval Library http://protyposis.net")]
//[assembly: AssemblyTrademark("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// 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: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0 Alpha")]
| agpl-3.0 | C# |
d464ddffbcd190c297c8c8be9fc8f2d5de51be6d | add client signature | LykkeCity/bitcoinservice,LykkeCity/bitcoinservice | src/BitcoinJob/Functions/ClientSignaturesFunction.cs | src/BitcoinJob/Functions/ClientSignaturesFunction.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Common.Log;
using Core;
using Core.Helpers;
using Core.Providers;
using Core.Repositories.Transactions;
using LkeServices.Providers;
using Lykke.JobTriggers.Triggers.Attributes;
using Lykke.JobTriggers.Triggers.Bindings;
namespace BackgroundWorker.Functions
{
public class ClientSignedTransactionMessage
{
public Guid TransactionId { get; set; }
public string Transaction { get; set; }
public string Error { get; set; }
}
public class ClientSignaturesFunction
{
private readonly ITransactionBlobStorage _transactionBlobStorage;
private readonly ISignatureApiProvider _signatureApiProvider;
public ClientSignaturesFunction(ITransactionBlobStorage transactionBlobStorage, Func<SignatureApiProviderType, ISignatureApiProvider> signatureApiProviderFactory)
{
_transactionBlobStorage = transactionBlobStorage;
_signatureApiProvider = signatureApiProviderFactory(SignatureApiProviderType.Client);
}
[QueueTrigger(Constants.ClientSignedTransactionQueue, 100, true, "client")]
public async Task ProcessMessage(ClientSignedTransactionMessage message, QueueTriggeringContext context)
{
var initialTr = await _transactionBlobStorage.GetTransaction(message.TransactionId, TransactionBlobType.Initial);
if (string.IsNullOrEmpty(initialTr))
{
message.Error = "Inital transaction was not found";
context.MoveMessageToPoison(message.ToJson());
return;
}
if (!TransactionComparer.CompareTransactions(initialTr, message.Transaction))
{
message.Error = "Client transaction is not equal to initial transaction";
context.MoveMessageToPoison(message.ToJson());
return;
}
var signed = await _signatureApiProvider.SignTransaction(message.Transaction);
await _transactionBlobStorage.AddOrReplaceTransaction(message.TransactionId, TransactionBlobType.Client, signed);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Core;
using Core.Helpers;
using Core.Repositories.Transactions;
using Lykke.JobTriggers.Triggers.Attributes;
using Lykke.JobTriggers.Triggers.Bindings;
namespace BackgroundWorker.Functions
{
public class ClientSignedTransactionMessage
{
public Guid TransactionId { get; set; }
public string Transaction { get; set; }
public string Error { get; set; }
}
public class ClientSignaturesFunction
{
private readonly ITransactionBlobStorage _transactionBlobStorage;
public ClientSignaturesFunction(ITransactionBlobStorage transactionBlobStorage)
{
_transactionBlobStorage = transactionBlobStorage;
}
[QueueTrigger(Constants.ClientSignedTransactionQueue, 100, true, "client")]
public async Task ProcessMessage(ClientSignedTransactionMessage message, QueueTriggeringContext context)
{
var initialTr = await _transactionBlobStorage.GetTransaction(message.TransactionId, TransactionBlobType.Initial);
if (string.IsNullOrEmpty(initialTr))
{
message.Error = "Inital transaction was not found";
context.MoveMessageToPoison(message.ToJson());
return;
}
if (!TransactionComparer.CompareTransactions(initialTr, message.Transaction))
{
message.Error = "Client transaction is not equal to initial transaction";
context.MoveMessageToPoison(message.ToJson());
return;
}
await _transactionBlobStorage.AddOrReplaceTransaction(message.TransactionId, TransactionBlobType.Client, message.Transaction);
}
}
}
| mit | C# |
34f875187c8eb00b0829fb75d22b8a9483fc3dc3 | Copy time between `ControlPoint`s | ppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,ppy/osu | osu.Game/Beatmaps/ControlPoints/ControlPoint.cs | osu.Game/Beatmaps/ControlPoints/ControlPoint.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
using osu.Game.Graphics;
using osu.Game.Utils;
using osuTK.Graphics;
namespace osu.Game.Beatmaps.ControlPoints
{
public abstract class ControlPoint : IComparable<ControlPoint>, IDeepCloneable<ControlPoint>
{
/// <summary>
/// The time at which the control point takes effect.
/// </summary>
[JsonIgnore]
public double Time { get; set; }
public void AttachGroup(ControlPointGroup pointGroup) => Time = pointGroup.Time;
public int CompareTo(ControlPoint other) => Time.CompareTo(other.Time);
public virtual Color4 GetRepresentingColour(OsuColour colours) => colours.Yellow;
/// <summary>
/// Determines whether this <see cref="ControlPoint"/> results in a meaningful change when placed alongside another.
/// </summary>
/// <param name="existing">An existing control point to compare with.</param>
/// <returns>Whether this <see cref="ControlPoint"/> is redundant when placed alongside <paramref name="existing"/>.</returns>
public abstract bool IsRedundant(ControlPoint existing);
/// <summary>
/// Create an unbound copy of this control point.
/// </summary>
public ControlPoint DeepClone()
{
var copy = (ControlPoint)Activator.CreateInstance(GetType());
copy.CopyFrom(this);
return copy;
}
public virtual void CopyFrom(ControlPoint other)
{
Time = other.Time;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
using osu.Game.Graphics;
using osu.Game.Utils;
using osuTK.Graphics;
namespace osu.Game.Beatmaps.ControlPoints
{
public abstract class ControlPoint : IComparable<ControlPoint>, IDeepCloneable<ControlPoint>
{
/// <summary>
/// The time at which the control point takes effect.
/// </summary>
[JsonIgnore]
public double Time => controlPointGroup?.Time ?? 0;
private ControlPointGroup controlPointGroup;
public void AttachGroup(ControlPointGroup pointGroup) => controlPointGroup = pointGroup;
public int CompareTo(ControlPoint other) => Time.CompareTo(other.Time);
public virtual Color4 GetRepresentingColour(OsuColour colours) => colours.Yellow;
/// <summary>
/// Determines whether this <see cref="ControlPoint"/> results in a meaningful change when placed alongside another.
/// </summary>
/// <param name="existing">An existing control point to compare with.</param>
/// <returns>Whether this <see cref="ControlPoint"/> is redundant when placed alongside <paramref name="existing"/>.</returns>
public abstract bool IsRedundant(ControlPoint existing);
/// <summary>
/// Create an unbound copy of this control point.
/// </summary>
public ControlPoint DeepClone()
{
var copy = (ControlPoint)Activator.CreateInstance(GetType());
copy.CopyFrom(this);
return copy;
}
public virtual void CopyFrom(ControlPoint other)
{
}
}
}
| mit | C# |
e2bf2252964a37e2f5fb85404b4f46229684c176 | Enable test for NH-2404 for dialects which does not support futures. | nkreipke/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core | src/NHibernate.Test/NHSpecificTest/NH2404/Fixture.cs | src/NHibernate.Test/NHSpecificTest/NH2404/Fixture.cs | using System.Linq;
using NHibernate.Linq;
using NHibernate.Transform;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH2404
{
[TestFixture]
public class Fixture : BugTestCase
{
protected override void OnSetUp()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
session.Save(new TestEntity
{
Id = 1,
Name = "Test Entity"
});
session.Save(new TestEntity
{
Id = 2,
Name = "Test Entity"
});
transaction.Commit();
}
}
protected override void OnTearDown()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
session.Delete("from System.Object");
transaction.Commit();
}
}
[Test]
public void ProjectionsShouldWorkWithLinqProviderAndFutures()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var query1 = (from entity in session.Query<TestEntity>()
select new TestEntityDto {EntityId = entity.Id, EntityName = entity.Name}).ToList();
Assert.AreEqual(2, query1.Count());
var query2 = (from entity in session.Query<TestEntity>()
select new TestEntityDto {EntityId = entity.Id, EntityName = entity.Name}).ToFuture();
Assert.AreEqual(2, query2.Count());
}
}
[Test]
public void ProjectionsShouldWorkWithHqlAndFutures()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var query1 =
session.CreateQuery("select e.Id as EntityId, e.Name as EntityName from TestEntity e").SetResultTransformer(
Transformers.AliasToBean(typeof (TestEntityDto)))
.List<TestEntityDto>();
Assert.AreEqual(2, query1.Count());
var query2 =
session.CreateQuery("select e.Id as EntityId, e.Name as EntityName from TestEntity e").SetResultTransformer(
Transformers.AliasToBean(typeof (TestEntityDto)))
.Future<TestEntityDto>();
Assert.AreEqual(2, query2.Count());
}
}
}
}
| using System.Linq;
using NHibernate.Impl;
using NHibernate.Linq;
using NHibernate.Transform;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH2404
{
[TestFixture]
public class Fixture : BugTestCase
{
protected override void OnSetUp()
{
base.OnSetUp();
using (var session = this.OpenSession())
using (var tx = session.BeginTransaction())
{
var entity = new TestEntity();
entity.Id = 1;
entity.Name = "Test Entity";
session.Save(entity);
var entity1 = new TestEntity();
entity1.Id = 2;
entity1.Name = "Test Entity";
session.Save(entity1);
tx.Commit();
}
}
protected override void OnTearDown()
{
base.OnTearDown();
using (ISession session = this.OpenSession())
{
string hql = "from System.Object";
session.Delete(hql);
session.Flush();
}
}
[Test]
public void ProjectionsShouldWorkWithLinqProviderAndFutures()
{
using (ISession session = this.OpenSession())
{
if (((SessionFactoryImpl)sessions).ConnectionProvider.Driver.SupportsMultipleQueries == false)
{
Assert.Ignore("Not applicable for dialects that do not support multiple queries");
}
var query1 = (
from entity in session.Query<TestEntity>()
select new TestEntityDto {EntityId = entity.Id, EntityName = entity.Name}
).ToList();
Assert.AreEqual(2, query1.Count());
var query2 = (
from entity in session.Query<TestEntity>()
select new TestEntityDto { EntityId = entity.Id, EntityName = entity.Name }
).ToFuture();
Assert.AreEqual(2, query2.Count());
}
}
[Test]
public void ProjectionsShouldWorkWithHqlAndFutures()
{
using (ISession session = this.OpenSession())
{
if (((SessionFactoryImpl)sessions).ConnectionProvider.Driver.SupportsMultipleQueries == false)
{
Assert.Ignore("Not applicable for dialects that do not support multiple queries");
}
var query1 =
session.CreateQuery("select e.Id as EntityId, e.Name as EntityName from TestEntity e").SetResultTransformer(
Transformers.AliasToBean(typeof (TestEntityDto)))
.List<TestEntityDto>();
Assert.AreEqual(2, query1.Count());
var query2 =
session.CreateQuery("select e.Id as EntityId, e.Name as EntityName from TestEntity e").SetResultTransformer(
Transformers.AliasToBean(typeof (TestEntityDto)))
.Future<TestEntityDto>();
Assert.AreEqual(2, query2.Count());
}
}
}
}
| lgpl-2.1 | C# |
134b2a12fb3552495e38ccbab5ab7709517eeb6d | Add Last4 in AU BECS Source and Deprecating Last3 | stripe/stripe-dotnet | src/Stripe.net/Entities/Sources/SourceAuBecsDebit.cs | src/Stripe.net/Entities/Sources/SourceAuBecsDebit.cs | namespace Stripe
{
using System;
using Newtonsoft.Json;
public class SourceAuBecsDebit : StripeEntity
{
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
[JsonProperty("bsb_number")]
public string BsbNumber { get; set; }
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
[Obsolete("This property is deprecated, please use Last4 going forward.")]
[JsonProperty("last3")]
public string Last3 { get; set; }
[JsonProperty("last4")]
public string Last4 { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
public class SourceAuBecsDebit : StripeEntity
{
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
[JsonProperty("bsb_number")]
public string BsbNumber { get; set; }
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
[JsonProperty("last3")]
public string Last3 { get; set; }
}
}
| apache-2.0 | C# |
cd52d8380355c4459315055ba7dca9da4ed98e33 | Add Tags | dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch | src/TeacherPouch/ViewModels/PhotoDetailsViewModel.cs | src/TeacherPouch/ViewModels/PhotoDetailsViewModel.cs | using System.Collections.Generic;
using System.Linq;
using TeacherPouch.Models;
namespace TeacherPouch.ViewModels
{
public class PhotoDetailsViewModel
{
public PhotoDetailsViewModel(
Photo photo,
string photoUrl,
string smallFileSize,
string largeFileSize,
Tag searchResultTag,
Tag searchResultTag2,
Photo previousPhoto,
Photo nextPhoto,
bool userIsAdmin)
{
Photo = photo;
PhotoUrl = photoUrl;
Tags = photo.PhotoTags.Select(pt => pt.Tag);
Questions = photo.Questions;
SmallFileSize = smallFileSize;
LargeFileSize = largeFileSize;
SearchResultTag = searchResultTag;
SearchResultTag2 = searchResultTag2;
PreviousPhoto = previousPhoto;
NextPhoto = nextPhoto;
ShowAdminLinks = userIsAdmin;
}
public Photo Photo { get; }
public string PhotoUrl { get; }
public IEnumerable<Tag> Tags { get; }
public IEnumerable<Question> Questions { get; }
public string SmallFileSize { get; }
public string LargeFileSize { get; }
public Tag SearchResultTag { get; }
public Tag SearchResultTag2 { get; }
public Photo PreviousPhoto { get; }
public Photo NextPhoto { get; }
public bool ShowAdminLinks { get; }
}
}
| using System.Collections.Generic;
using TeacherPouch.Models;
namespace TeacherPouch.ViewModels
{
public class PhotoDetailsViewModel
{
public PhotoDetailsViewModel(
Photo photo,
string photoUrl,
string smallFileSize,
string largeFileSize,
Tag searchResultTag,
Tag searchResultTag2,
Photo previousPhoto,
Photo nextPhoto,
bool userIsAdmin)
{
Photo = photo;
PhotoUrl = photoUrl;
SmallFileSize = smallFileSize;
LargeFileSize = largeFileSize;
SearchResultTag = searchResultTag;
SearchResultTag2 = searchResultTag2;
PreviousPhoto = previousPhoto;
NextPhoto = nextPhoto;
ShowAdminLinks = userIsAdmin;
}
public Photo Photo { get; }
public string PhotoUrl { get; }
public string SmallFileSize { get; }
public string LargeFileSize { get; }
public Tag SearchResultTag { get; }
public Tag SearchResultTag2 { get; }
public Photo PreviousPhoto { get; }
public Photo NextPhoto { get; }
public IEnumerable<Question> Questions { get; }
public bool ShowAdminLinks { get; }
}
}
| mit | C# |
a84414d8627946028f9e25236379a4f590eda621 | Add unit test for the stripping out of import statements | kendallb/PreMailer.Net,CodeAnimal/PreMailer.Net,tobio/PreMailer.Net,rohk/PreMailer.Net,CarterTsai/PreMailer.Net,milkshakesoftware/PreMailer.Net | PreMailer.Net/PreMailer.Net.Tests/CssParserTests.cs | PreMailer.Net/PreMailer.Net.Tests/CssParserTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PreMailer.Net.Tests
{
[TestClass]
public class CssParserTests
{
[TestMethod]
public void AddStylesheet_ContainsAtCharsetRule_ShouldStripRuleAndParseStylesheet()
{
var stylesheet = "@charset utf-8; div { width: 100% }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
}
[TestMethod]
public void AddStylesheet_ContainsAtPageSection_ShouldStripRuleAndParseStylesheet()
{
var stylesheet = "@page :first { margin: 2in 3in; } div { width: 100% }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(1, parser.Styles.Count);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
}
[TestMethod]
public void AddStylesheet_ContainsUnsupportedMediaQuery_ShouldStrip()
{
var stylesheet = "@media print { div { width: 90%; } }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(0, parser.Styles.Count);
}
[TestMethod]
public void AddStylesheet_ContainsUnsupportedMediaQueryAndNormalRules_ShouldStripMediaQueryAndParseRules()
{
var stylesheet = "div { width: 600px; } @media only screen and (max-width:620px) { div { width: 100% } } p { font-family: serif; }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(2, parser.Styles.Count);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
Assert.AreEqual("600px", parser.Styles["div"].Attributes["width"].Value);
Assert.IsTrue(parser.Styles.ContainsKey("p"));
Assert.AreEqual("serif", parser.Styles["p"].Attributes["font-family"].Value);
}
[TestMethod]
public void AddStylesheet_ContainsSupportedMediaQuery_ShouldParseQueryRules()
{
var stylesheet = "@media only screen { div { width: 600px; } }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(1, parser.Styles.Count);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
Assert.AreEqual("600px", parser.Styles["div"].Attributes["width"].Value);
}
[TestMethod]
public void AddStylesheet_ContainsUnsupportedImportStatement_ShouldStripOutImportStatement()
{
var stylesheet = "@import url(http://google.com/stylesheet); div { width : 600px; }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(1, parser.Styles.Count);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
Assert.AreEqual("600px", parser.Styles["div"].Attributes["width"].Value);
}
}
} | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PreMailer.Net.Tests
{
[TestClass]
public class CssParserTests
{
[TestMethod]
public void AddStylesheet_ContainsAtCharsetRule_ShouldStripRuleAndParseStylesheet()
{
var stylesheet = "@charset utf-8; div { width: 100% }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
}
[TestMethod]
public void AddStylesheet_ContainsAtPageSection_ShouldStripRuleAndParseStylesheet()
{
var stylesheet = "@page :first { margin: 2in 3in; } div { width: 100% }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(1, parser.Styles.Count);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
}
[TestMethod]
public void AddStylesheet_ContainsUnsupportedMediaQuery_ShouldStrip()
{
var stylesheet = "@media print { div { width: 90%; } }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(0, parser.Styles.Count);
}
[TestMethod]
public void AddStylesheet_ContainsUnsupportedMediaQueryAndNormalRules_ShouldStripMediaQueryAndParseRules()
{
var stylesheet = "div { width: 600px; } @media only screen and (max-width:620px) { div { width: 100% } } p { font-family: serif; }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(2, parser.Styles.Count);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
Assert.AreEqual("600px", parser.Styles["div"].Attributes["width"].Value);
Assert.IsTrue(parser.Styles.ContainsKey("p"));
Assert.AreEqual("serif", parser.Styles["p"].Attributes["font-family"].Value);
}
[TestMethod]
public void AddStylesheet_ContainsSupportedMediaQuery_ShouldParseQueryRules()
{
var stylesheet = "@media only screen { div { width: 600px; } }";
var parser = new CssParser();
parser.AddStyleSheet(stylesheet);
Assert.AreEqual(1, parser.Styles.Count);
Assert.IsTrue(parser.Styles.ContainsKey("div"));
Assert.AreEqual("600px", parser.Styles["div"].Attributes["width"].Value);
}
}
} | mit | C# |
74b0c054e1d8e5eded00208b4176f60f0f561923 | remove Start Coding reference | IBM-Bluemix/asp.net5-cloudant,IBM-Bluemix/asp.net5-cloudant | src/dotnetCloudantWebstarter/Views/Home/Index.cshtml | src/dotnetCloudantWebstarter/Views/Home/Index.cshtml | <!DOCTYPE html>
<html>
<head>
<title>ASP.NET Core Cloudant Starter Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="~/css/style.css" />
</head>
<body>
<div class="leftHalf">
<img class="newappIcon" src="~/images/newapp-icon.png" />
<h1>
Welcome to the <span class="blue">ASP.NET Cloudant Web Starter</span> on Bluemix!
</h1>
</div>
<div class="rightHalf">
<div class="center">
<header>
<div class='title'>
ASP.NET Cloudant Web Starter
</div>
</header>
<table id='notes' class='records'><tbody></tbody></table>
<div id="loading"> Please wait while the database is being initialized ...</div>
<footer>
<div class='tips'>
Click the Add button to add a record.
<button class='addBtn' onclick="addItem()" title='add record'>
<img src='~/images/add.png' alt='add' />
</button>
</div>
</footer>
<script type="text/javascript" src="~/scripts/util.js"></script>
<script type="text/javascript" src="~/scripts/index.js"></script>
</div>
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<title>ASP.NET Core Cloudant Starter Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="~/css/style.css" />
</head>
<body>
<div class="leftHalf">
<img class="newappIcon" src="~/images/newapp-icon.png" />
<h1>
Welcome to the <span class="blue">ASP.NET Cloudant Web Starter</span> on Bluemix!
</h1>
<p class="description">To get started see the Start Coding guide under your app in your dashboard.</p>
</div>
<div class="rightHalf">
<div class="center">
<header>
<div class='title'>
ASP.NET Cloudant Web Starter
</div>
</header>
<table id='notes' class='records'><tbody></tbody></table>
<div id="loading"> Please wait while the database is being initialized ...</div>
<footer>
<div class='tips'>
Click the Add button to add a record.
<button class='addBtn' onclick="addItem()" title='add record'>
<img src='~/images/add.png' alt='add' />
</button>
</div>
</footer>
<script type="text/javascript" src="~/scripts/util.js"></script>
<script type="text/javascript" src="~/scripts/index.js"></script>
</div>
</div>
</body>
</html>
| apache-2.0 | C# |
c6f32ff017e8a319f27841247d8493e0f684870b | test that fatal validation problem will break | strotz/pustota,strotz/pustota,strotz/pustota | src/Pustota.Maven.Base.Tests/RepositortValidatorTests.cs | src/Pustota.Maven.Base.Tests/RepositortValidatorTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Pustota.Maven.Externals;
using Pustota.Maven.Models;
using Pustota.Maven.Validation;
namespace Pustota.Maven.Base.Tests
{
[TestFixture]
public class RepositortValidatorTests
{
private RepositoryValidator _validator;
private Mock<IProjectValidationFactory> _factory;
private Mock<IProjectsRepository> _repo;
private Mock<IExternalModulesRepository> _externals;
private ValidationContext _context;
[SetUp]
public void Initialize()
{
_factory = new Mock<IProjectValidationFactory>();
_repo = new Mock<IProjectsRepository>();
_externals = new Mock<IExternalModulesRepository>();
_validator = new RepositoryValidator(_factory.Object);
_context = new ValidationContext
{
Repository = _repo.Object,
ExternalModules = _externals.Object
};
}
[TearDown]
public void Shutdown()
{
}
[Test]
public void EmptyTest()
{
var result = _validator.Validate(_context);
Assert.IsNotNull(result);
Assert.That(result, Is.Empty);
}
[Test]
public void SingleTest()
{
var project = new Mock<IProject>();
_repo.Setup(r => r.AllProjects).Returns(new[] {project.Object});
var problem = new ValidationProblem
{
Severity = ProblemSeverity.ProjectWarning
};
var validator = new Mock<IProjectValidator>();
validator.Setup(v => v.Validate(It.IsAny<ValidationContext>(), project.Object)).Returns(new[] { problem });
_factory.Setup(f => f.BuildProjectValidationSequence()).Returns(new[] { validator.Object });
var result = _validator.Validate(_context);
Assert.IsNotNull(result);
Assert.That(result.Single(), Is.EqualTo(problem));
}
[Test]
public void BreakOnFatalTest()
{
var project1 = new Mock<IProject>();
var project2 = new Mock<IProject>();
_repo.Setup(r => r.AllProjects).Returns(new[] { project1.Object, project2.Object });
var fatal = new ValidationProblem { Severity = ProblemSeverity.ProjectFatal };
var warning = new ValidationProblem { Severity = ProblemSeverity.ProjectWarning };
var v1 = new Mock<IProjectValidator>();
v1.Setup(v => v.Validate(It.IsAny<ValidationContext>(), project1.Object)).Returns(new[] { fatal });
var v2 = new Mock<IProjectValidator>();
v2.Setup(v => v.Validate(It.IsAny<ValidationContext>(), project1.Object)).Returns(new[] { warning });
_factory.Setup(f => f.BuildProjectValidationSequence()).Returns(new[] { v1.Object, v2.Object });
var result = _validator.Validate(_context);
Assert.IsNotNull(result);
Assert.That(result.Single(), Is.EqualTo(fatal));
v1.Verify(v => v.Validate(It.IsAny<ValidationContext>(), project1.Object), Times.Once());
v1.Verify(v => v.Validate(It.IsAny<ValidationContext>(), project2.Object), Times.Once());
v2.Verify(v => v.Validate(It.IsAny<ValidationContext>(), project1.Object), Times.Never());
v2.Verify(v => v.Validate(It.IsAny<ValidationContext>(), project2.Object), Times.Once());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Pustota.Maven.Externals;
using Pustota.Maven.Models;
using Pustota.Maven.Validation;
namespace Pustota.Maven.Base.Tests
{
[TestFixture]
public class RepositortValidatorTests
{
private RepositoryValidator _validator;
private Mock<IProjectValidationFactory> _factory;
private Mock<IProjectsRepository> _repo;
private Mock<IExternalModulesRepository> _externals;
private ValidationContext _context;
[SetUp]
public void Initialize()
{
_factory = new Mock<IProjectValidationFactory>();
_repo = new Mock<IProjectsRepository>();
_externals = new Mock<IExternalModulesRepository>();
_validator = new RepositoryValidator(_factory.Object);
_context = new ValidationContext
{
Repository = _repo.Object,
ExternalModules = _externals.Object
};
}
[TearDown]
public void Shutdown()
{
}
[Test]
public void EmptyTest()
{
var result = _validator.Validate(_context);
Assert.IsNotNull(result);
Assert.That(result, Is.Empty);
}
[Test]
public void SingleTest()
{
var project = new Mock<IProject>();
_repo.Setup(r => r.AllProjects).Returns(new[] {project.Object});
var problem = new ValidationProblem
{
Severity = ProblemSeverity.ProjectWarning
};
var validator = new Mock<IProjectValidator>();
validator.Setup(v => v.Validate(It.IsAny<ValidationContext>(), project.Object)).Returns(new[] { problem });
_factory.Setup(f => f.BuildProjectValidationSequence()).Returns(new[] { validator.Object });
var result = _validator.Validate(_context);
Assert.IsNotNull(result);
Assert.That(result.Single(), Is.EqualTo(problem));
}
}
}
| mit | C# |
116518b1426b06b3c8905c54ff4ad51f6e9d8479 | Fix typo in summary comment | wvdd007/roslyn,tvand7093/roslyn,balajikris/roslyn,tvand7093/roslyn,HellBrick/roslyn,shyamnamboodiripad/roslyn,jeffanders/roslyn,stephentoub/roslyn,dotnet/roslyn,sharadagrawal/Roslyn,natgla/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,Maxwe11/roslyn,bbarry/roslyn,danielcweber/roslyn,srivatsn/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jmarolf/roslyn,AArnott/roslyn,swaroop-sridhar/roslyn,srivatsn/roslyn,mavasani/roslyn,jamesqo/roslyn,MattWindsor91/roslyn,VSadov/roslyn,KevinRansom/roslyn,bbarry/roslyn,bartdesmet/roslyn,aanshibudhiraja/Roslyn,mmitche/roslyn,nguerrera/roslyn,jmarolf/roslyn,thomaslevesque/roslyn,leppie/roslyn,jhendrixMSFT/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,TyOverby/roslyn,ErikSchierboom/roslyn,oocx/roslyn,drognanar/roslyn,ValentinRueda/roslyn,diryboy/roslyn,AnthonyDGreen/roslyn,tvand7093/roslyn,oocx/roslyn,jkotas/roslyn,budcribar/roslyn,physhi/roslyn,AmadeusW/roslyn,mmitche/roslyn,DustinCampbell/roslyn,brettfo/roslyn,tmat/roslyn,michalhosala/roslyn,vslsnap/roslyn,jbhensley/roslyn,KiloBravoLima/roslyn,drognanar/roslyn,VSadov/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,TyOverby/roslyn,panopticoncentral/roslyn,AArnott/roslyn,genlu/roslyn,mattscheffer/roslyn,MattWindsor91/roslyn,xasx/roslyn,michalhosala/roslyn,vcsjones/roslyn,managed-commons/roslyn,VPashkov/roslyn,MatthieuMEZIL/roslyn,moozzyk/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,natgla/roslyn,mseamari/Stuff,mseamari/Stuff,paulvanbrenk/roslyn,oocx/roslyn,xasx/roslyn,bartdesmet/roslyn,Inverness/roslyn,jamesqo/roslyn,SeriaWei/roslyn,MatthieuMEZIL/roslyn,vslsnap/roslyn,davkean/roslyn,antonssonj/roslyn,danielcweber/roslyn,a-ctor/roslyn,paulvanbrenk/roslyn,VSadov/roslyn,Shiney/roslyn,weltkante/roslyn,Shiney/roslyn,tmeschter/roslyn,mmitche/roslyn,wvdd007/roslyn,jkotas/roslyn,panopticoncentral/roslyn,khellang/roslyn,tannergooding/roslyn,lorcanmooney/roslyn,moozzyk/roslyn,aelij/roslyn,heejaechang/roslyn,zooba/roslyn,eriawan/roslyn,pdelvo/roslyn,diryboy/roslyn,Giftednewt/roslyn,basoundr/roslyn,nguerrera/roslyn,yeaicc/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,SeriaWei/roslyn,khyperia/roslyn,Inverness/roslyn,CaptainHayashi/roslyn,natidea/roslyn,Hosch250/roslyn,sharadagrawal/Roslyn,budcribar/roslyn,ljw1004/roslyn,thomaslevesque/roslyn,amcasey/roslyn,jamesqo/roslyn,jhendrixMSFT/roslyn,xasx/roslyn,KiloBravoLima/roslyn,sharwell/roslyn,khyperia/roslyn,KevinH-MS/roslyn,jasonmalinowski/roslyn,davkean/roslyn,Pvlerick/roslyn,akrisiun/roslyn,bkoelman/roslyn,mattwar/roslyn,dpoeschl/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,mattwar/roslyn,amcasey/roslyn,danielcweber/roslyn,weltkante/roslyn,a-ctor/roslyn,OmarTawfik/roslyn,jaredpar/roslyn,antonssonj/roslyn,agocke/roslyn,KiloBravoLima/roslyn,a-ctor/roslyn,AnthonyDGreen/roslyn,robinsedlaczek/roslyn,stephentoub/roslyn,brettfo/roslyn,srivatsn/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,akrisiun/roslyn,vcsjones/roslyn,HellBrick/roslyn,jaredpar/roslyn,jcouv/roslyn,michalhosala/roslyn,natidea/roslyn,eriawan/roslyn,jbhensley/roslyn,jeffanders/roslyn,DustinCampbell/roslyn,swaroop-sridhar/roslyn,mattscheffer/roslyn,mseamari/Stuff,ericfe-ms/roslyn,genlu/roslyn,abock/roslyn,AmadeusW/roslyn,diryboy/roslyn,budcribar/roslyn,gafter/roslyn,DustinCampbell/roslyn,tmeschter/roslyn,ericfe-ms/roslyn,OmarTawfik/roslyn,rgani/roslyn,agocke/roslyn,aelij/roslyn,ValentinRueda/roslyn,cston/roslyn,AlekseyTs/roslyn,orthoxerox/roslyn,physhi/roslyn,mattwar/roslyn,tmeschter/roslyn,dpoeschl/roslyn,Hosch250/roslyn,mattscheffer/roslyn,jbhensley/roslyn,bbarry/roslyn,zooba/roslyn,jcouv/roslyn,natidea/roslyn,rgani/roslyn,wvdd007/roslyn,yeaicc/roslyn,vcsjones/roslyn,khellang/roslyn,davkean/roslyn,balajikris/roslyn,KevinRansom/roslyn,Pvlerick/roslyn,kelltrick/roslyn,bkoelman/roslyn,aanshibudhiraja/Roslyn,jcouv/roslyn,orthoxerox/roslyn,pdelvo/roslyn,nguerrera/roslyn,weltkante/roslyn,robinsedlaczek/roslyn,MichalStrehovsky/roslyn,Giftednewt/roslyn,jeffanders/roslyn,ErikSchierboom/roslyn,robinsedlaczek/roslyn,Maxwe11/roslyn,lorcanmooney/roslyn,rgani/roslyn,yeaicc/roslyn,lorcanmooney/roslyn,ljw1004/roslyn,HellBrick/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,VPashkov/roslyn,aanshibudhiraja/Roslyn,thomaslevesque/roslyn,aelij/roslyn,managed-commons/roslyn,agocke/roslyn,ljw1004/roslyn,antonssonj/roslyn,cston/roslyn,AArnott/roslyn,jhendrixMSFT/roslyn,CaptainHayashi/roslyn,Pvlerick/roslyn,xoofx/roslyn,mavasani/roslyn,Hosch250/roslyn,orthoxerox/roslyn,akrisiun/roslyn,OmarTawfik/roslyn,reaction1989/roslyn,genlu/roslyn,jaredpar/roslyn,sharwell/roslyn,Shiney/roslyn,natgla/roslyn,abock/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,CaptainHayashi/roslyn,mavasani/roslyn,Inverness/roslyn,paulvanbrenk/roslyn,mgoertz-msft/roslyn,zooba/roslyn,Giftednewt/roslyn,dpoeschl/roslyn,leppie/roslyn,ValentinRueda/roslyn,MatthieuMEZIL/roslyn,jmarolf/roslyn,bartdesmet/roslyn,physhi/roslyn,khellang/roslyn,basoundr/roslyn,xoofx/roslyn,KevinRansom/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,kelltrick/roslyn,xoofx/roslyn,abock/roslyn,balajikris/roslyn,CyrusNajmabadi/roslyn,KevinH-MS/roslyn,gafter/roslyn,AmadeusW/roslyn,khyperia/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,kelltrick/roslyn,AlekseyTs/roslyn,managed-commons/roslyn,tmat/roslyn,jkotas/roslyn,moozzyk/roslyn,ericfe-ms/roslyn,SeriaWei/roslyn,tannergooding/roslyn,basoundr/roslyn,reaction1989/roslyn,TyOverby/roslyn,stephentoub/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,MichalStrehovsky/roslyn,MattWindsor91/roslyn,amcasey/roslyn,cston/roslyn,drognanar/roslyn,Maxwe11/roslyn,vslsnap/roslyn,sharadagrawal/Roslyn,tmat/roslyn,AnthonyDGreen/roslyn,gafter/roslyn,mgoertz-msft/roslyn,VPashkov/roslyn,bkoelman/roslyn,CyrusNajmabadi/roslyn,leppie/roslyn,panopticoncentral/roslyn,swaroop-sridhar/roslyn,KevinH-MS/roslyn | src/Compilers/Core/Portable/SourceCodeKind.cs | src/Compilers/Core/Portable/SourceCodeKind.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies the C# or VB source code kind.
/// </summary>
public enum SourceCodeKind
{
/// <summary>
/// No scripting. Used for .cs/.vb file parsing.
/// </summary>
Regular = 0,
/// <summary>
/// Allows top-level statements, declarations, and optional trailing expression.
/// Used for parsing .csx/.vbx and interactive submissions.
/// </summary>
Script = 1,
/// <summary>
/// The same as <see cref="Script"/>.
/// </summary>
[Obsolete("Use Script instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
Interactive = 2,
}
internal static partial class SourceCodeKindExtensions
{
internal static bool IsValid(this SourceCodeKind value)
{
return value >= SourceCodeKind.Regular && value <= SourceCodeKind.Script;
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies the C# or VB source code kind.
/// </summary>
public enum SourceCodeKind
{
/// <summary>
/// No scripting. Used for .cs/.vb file parsing.
/// </summary>
Regular = 0,
/// <summary>
/// Allows top-level statementsm, declarations, and optional trailing expression.
/// Used for parsing .csx/.vbx and interactive submissions.
/// </summary>
Script = 1,
/// <summary>
/// The same as <see cref="Script"/>.
/// </summary>
[Obsolete("Use Script instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
Interactive = 2,
}
internal static partial class SourceCodeKindExtensions
{
internal static bool IsValid(this SourceCodeKind value)
{
return value >= SourceCodeKind.Regular && value <= SourceCodeKind.Script;
}
}
}
| mit | C# |
dd2a631692fcaab96bba6361255a2d23aceba19b | Fix nullref when no consumer is waiting | titanium007/EventHook,titanium007/Windows-User-Action-Hook,justcoding121/Windows-User-Action-Hook | src/EventHook/Helpers/AsyncConcurrentQueue.cs | src/EventHook/Helpers/AsyncConcurrentQueue.cs | using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace EventHook.Helpers
{
/// <summary>
/// A concurrent queue facilitating async dequeue with minimal locking
/// Assumes single/multi-threaded producer and a single-threaded consumer
/// </summary>
/// <typeparam name="T"></typeparam>
internal class AsyncConcurrentQueue<T>
{
/// <summary>
/// Backing queue
/// </summary>
private readonly ConcurrentQueue<T> queue = new ConcurrentQueue<T>();
/// <summary>
/// Wake up any pending dequeue task
/// </summary>
private TaskCompletionSource<bool> dequeueTask;
private SemaphoreSlim @dequeueTaskLock = new SemaphoreSlim(1);
private CancellationToken taskCancellationToken;
internal AsyncConcurrentQueue(CancellationToken taskCancellationToken)
{
this.taskCancellationToken = taskCancellationToken;
}
/// <summary>
/// Supports multi-threaded producers
/// </summary>
/// <param name="value"></param>
internal void Enqueue(T value)
{
queue.Enqueue(value);
//signal
dequeueTaskLock.Wait();
dequeueTask?.TrySetResult(true);
dequeueTaskLock.Release();
}
/// <summary>
/// Assumes a single-threaded consumer!
/// </summary>
/// <returns></returns>
internal async Task<T> DequeueAsync()
{
T result;
queue.TryDequeue(out result);
if (result != null)
{
return result;
}
await dequeueTaskLock.WaitAsync();
dequeueTask = new TaskCompletionSource<bool>();
dequeueTaskLock.Release();
taskCancellationToken.Register(() => dequeueTask.TrySetCanceled());
await dequeueTask.Task;
queue.TryDequeue(out result);
return result;
}
}
}
| using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace EventHook.Helpers
{
/// <summary>
/// A concurrent queue facilitating async dequeue with minimal locking
/// Assumes single/multi-threaded producer and a single-threaded consumer
/// </summary>
/// <typeparam name="T"></typeparam>
internal class AsyncConcurrentQueue<T>
{
/// <summary>
/// Backing queue
/// </summary>
private readonly ConcurrentQueue<T> queue = new ConcurrentQueue<T>();
/// <summary>
/// Wake up any pending dequeue task
/// </summary>
private TaskCompletionSource<bool> dequeueTask;
private SemaphoreSlim @dequeueTaskLock = new SemaphoreSlim(1);
private CancellationToken taskCancellationToken;
internal AsyncConcurrentQueue(CancellationToken taskCancellationToken)
{
this.taskCancellationToken = taskCancellationToken;
}
/// <summary>
/// Supports multi-threaded producers
/// </summary>
/// <param name="value"></param>
internal void Enqueue(T value)
{
queue.Enqueue(value);
//signal
dequeueTaskLock.Wait();
dequeueTask.TrySetResult(true);
dequeueTaskLock.Release();
}
/// <summary>
/// Assumes a single-threaded consumer!
/// </summary>
/// <returns></returns>
internal async Task<T> DequeueAsync()
{
T result;
queue.TryDequeue(out result);
if (result != null)
{
return result;
}
await dequeueTaskLock.WaitAsync();
dequeueTask = new TaskCompletionSource<bool>();
dequeueTaskLock.Release();
taskCancellationToken.Register(() => dequeueTask.TrySetCanceled());
await dequeueTask.Task;
queue.TryDequeue(out result);
return result;
}
}
}
| mit | C# |
b91c1bf09ef719361ce497f760950af11b4e33f4 | Increment the stats counters in bulk | adamzolotarev/Exceptionless,adamzolotarev/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless,adamzolotarev/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless | Source/Core/Pipeline/090_IncrementCountersAction.cs | Source/Core/Pipeline/090_IncrementCountersAction.cs | #region Copyright 2014 Exceptionless
// 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.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Exceptionless.Core.AppStats;
using Exceptionless.Core.Billing;
using Exceptionless.Core.Plugins.EventProcessor;
using Foundatio.Metrics;
namespace Exceptionless.Core.Pipeline {
[Priority(90)]
public class IncrementCountersAction : EventPipelineActionBase {
private readonly IMetricsClient _stats;
public IncrementCountersAction(IMetricsClient stats) {
_stats = stats;
}
protected override bool ContinueOnError { get { return true; } }
public override void ProcessBatch(ICollection<EventContext> contexts) {
_stats.Counter(MetricNames.EventsProcessed, contexts.Count);
if (contexts.First().Organization.PlanId != BillingManager.FreePlan.Id)
_stats.Counter(MetricNames.EventsPaidProcessed, contexts.Count);
}
public override void Process(EventContext ctx) {}
}
} | #region Copyright 2014 Exceptionless
// 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.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using Exceptionless.Core.AppStats;
using Exceptionless.Core.Billing;
using Exceptionless.Core.Plugins.EventProcessor;
using Foundatio.Metrics;
namespace Exceptionless.Core.Pipeline {
[Priority(90)]
public class IncrementCountersAction : EventPipelineActionBase {
private readonly IMetricsClient _stats;
public IncrementCountersAction(IMetricsClient stats) {
_stats = stats;
}
protected override bool ContinueOnError { get { return true; } }
public override void Process(EventContext ctx) {
_stats.Counter(MetricNames.EventsProcessed);
if (ctx.Organization.PlanId != BillingManager.FreePlan.Id)
_stats.Counter(MetricNames.EventsPaidProcessed);
}
}
} | apache-2.0 | C# |
b93c79d9edbd5a3e8259b5f235c7877eac569ac6 | Simplify LowCeremony convention. | fixie/fixie | src/Fixie.Samples/LowCeremony/CustomConvention.cs | src/Fixie.Samples/LowCeremony/CustomConvention.cs | namespace Fixie.Samples.LowCeremony
{
using System;
using System.Linq;
public class CustomConvention : Convention
{
static readonly string[] LifecycleMethods = { "FixtureSetUp", "FixtureTearDown", "SetUp", "TearDown" };
public CustomConvention()
{
Classes
.Where(x => x.IsInNamespace(GetType().Namespace))
.Where(x => x.Name.EndsWith("Tests"));
Methods
.Where(x => !LifecycleMethods.Contains(x.Name))
.OrderBy(x => x.Name, StringComparer.Ordinal);
Lifecycle<CallSetUpTearDownMethodsByName>();
}
class CallSetUpTearDownMethodsByName : Lifecycle
{
public void Execute(TestClass testClass, Action<CaseAction> runCases)
{
var instance = testClass.Construct();
void Execute(string method)
=> testClass.Execute(instance, method);
Execute("FixtureSetUp");
runCases(@case =>
{
Execute("SetUp");
@case.Execute(instance);
Execute("TearDown");
});
Execute("FixtureTearDown");
instance.Dispose();
}
}
}
} | namespace Fixie.Samples.LowCeremony
{
using System;
using System.Linq;
public class CustomConvention : Convention
{
static readonly string[] LifecycleMethods = { "FixtureSetUp", "FixtureTearDown", "SetUp", "TearDown" };
public CustomConvention()
{
Classes
.Where(x => x.IsInNamespace(GetType().Namespace))
.Where(x => x.Name.EndsWith("Tests"));
Methods
.Where(x => LifecycleMethods.All(lifecycleMethod => lifecycleMethod != x.Name))
.OrderBy(x => x.Name, StringComparer.Ordinal);
Lifecycle<CallSetUpTearDownMethodsByName>();
}
class CallSetUpTearDownMethodsByName : Lifecycle
{
public void Execute(TestClass testClass, Action<CaseAction> runCases)
{
var instance = testClass.Construct();
void Execute(string method)
=> testClass.Execute(instance, method);
Execute("FixtureSetUp");
runCases(@case =>
{
Execute("SetUp");
@case.Execute(instance);
Execute("TearDown");
});
Execute("FixtureTearDown");
instance.Dispose();
}
}
}
} | mit | C# |
ed2313dac17a6e0605b5e72dc7c0535427982f9f | Fix up versions in AssemblyInfoStatic | mono/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,openmedicus/dbus-sharp,openmedicus/dbus-sharp,arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp | src/AssemblyInfoStatic.cs | src/AssemblyInfoStatic.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
// This AssemblyInfo file is used in builds that aren't driven by autoconf, eg. Visual Studio
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyFileVersion("0.7.0")]
[assembly: AssemblyInformationalVersion("0.7.0")]
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyTitle ("dbus-sharp")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker and others")]
#if STRONG_NAME
[assembly: InternalsVisibleTo ("dbus-sharp-tests, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-daemon, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
#else
[assembly: InternalsVisibleTo ("dbus-sharp-tests")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies")]
#endif
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
// This AssemblyInfo file is used in builds that aren't driven by autoconf, eg. Visual Studio
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyFileVersion("@VERSION@")]
[assembly: AssemblyInformationalVersion("@VERSION@")]
[assembly: AssemblyVersion("@API_VERSION@")]
[assembly: AssemblyTitle ("dbus-sharp")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker and others")]
#if STRONG_NAME
[assembly: InternalsVisibleTo ("dbus-sharp-tests, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-daemon, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
#else
[assembly: InternalsVisibleTo ("dbus-sharp-tests")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies")]
#endif
| mit | C# |
5919e34461c96b5d023d6a2cc9d7f853b774da1b | Bump version | rileywhite/Cilador | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | /***************************************************************************/
// Copyright 2013-2014 Riley White
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/***************************************************************************/
using System.Reflection;
[assembly: AssemblyCompany("Riley White")]
[assembly: AssemblyProduct("Bix.Mixers.Fody")]
[assembly: AssemblyCopyright("Copyright © Riley White 2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion(CommonAssemblyInfo.Version)]
[assembly: AssemblyFileVersion(CommonAssemblyInfo.Version)]
internal static class CommonAssemblyInfo
{
public const string Version = "0.1.5.0";
} | /***************************************************************************/
// Copyright 2013-2014 Riley White
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/***************************************************************************/
using System.Reflection;
[assembly: AssemblyCompany("Riley White")]
[assembly: AssemblyProduct("Bix.Mixers.Fody")]
[assembly: AssemblyCopyright("Copyright © Riley White 2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion(CommonAssemblyInfo.Version)]
[assembly: AssemblyFileVersion(CommonAssemblyInfo.Version)]
internal static class CommonAssemblyInfo
{
public const string Version = "0.1.4.0";
} | apache-2.0 | C# |
f7c7a4c12afb473e079ca6afec44e8103ac94637 | Change version to alpha2 | fhchina/elmah-mvc,jmptrader/elmah-mvc,alexbeletsky/elmah-mvc,mmsaffari/elmah-mvc | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Elmah.Mvc")]
[assembly: AssemblyCopyright("Copyright © Atif Aziz, James Driscoll, Alexander Beletsky 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyVersion("2.1.2.*")]
[assembly: AssemblyFileVersion("2.1.2")]
[assembly: AssemblyInformationalVersion("2.1.2-alpha2")] | using System.Reflection;
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Elmah.Mvc")]
[assembly: AssemblyCopyright("Copyright © Atif Aziz, James Driscoll, Alexander Beletsky 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyVersion("2.1.2.*")]
[assembly: AssemblyFileVersion("2.1.2")]
[assembly: AssemblyInformationalVersion("2.1.2-alpha1")] | apache-2.0 | C# |
89c38dc19c3eaabf7a4738e8c4a2f00b3a05fa18 | Improve deprecation error message on SortQuery | Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore,Research-Institute/json-api-dotnet-core | src/JsonApiDotNetCore/Internal/Query/SortQuery.cs | src/JsonApiDotNetCore/Internal/Query/SortQuery.cs | using JsonApiDotNetCore.Models;
using System;
namespace JsonApiDotNetCore.Internal.Query
{
/// <summary>
/// An internal representation of the raw sort query.
/// </summary>
public class SortQuery : BaseQuery
{
[Obsolete("Use constructor overload (SortDirection, string) instead. The string should be the publicly exposed attribute name.", error: true)]
public SortQuery(SortDirection direction, AttrAttribute sortedAttribute)
: base(sortedAttribute.PublicAttributeName) { }
public SortQuery(SortDirection direction, string attribute)
: base(attribute)
{
Direction = direction;
}
/// <summary>
/// Direction the sort should be applied
/// </summary>
public SortDirection Direction { get; set; }
[Obsolete("Use string based Attribute instead.", error: true)]
public AttrAttribute SortedAttribute { get; set; }
}
}
| using JsonApiDotNetCore.Models;
using System;
namespace JsonApiDotNetCore.Internal.Query
{
/// <summary>
/// An internal representation of the raw sort query.
/// </summary>
public class SortQuery : BaseQuery
{
[Obsolete("Use constructor overload (SortDirection, string) instead.", error: true)]
public SortQuery(SortDirection direction, AttrAttribute sortedAttribute)
: base(sortedAttribute.PublicAttributeName) { }
public SortQuery(SortDirection direction, string attribute)
: base(attribute)
{
Direction = direction;
}
/// <summary>
/// Direction the sort should be applied
/// </summary>
public SortDirection Direction { get; set; }
[Obsolete("Use string based Attribute instead.", error: true)]
public AttrAttribute SortedAttribute { get; set; }
}
}
| mit | C# |
256951182a4d78f5575bd31c66754e40566750d7 | Write exceptions to console error stream | astorch/motoi | src/libs/Tessa/EntryPoint.cs | src/libs/Tessa/EntryPoint.cs | using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Tessa {
/// <summary> Provides the entry point for the application. </summary>
class EntryPoint {
/// <summary> Implements the entry point of the application. </summary>
/// <param name="args">Execution arguments</param>
static void Main(string[] args) {
// TODO Print options to console
if (args.Length == 0) return;
if (args.Any(arg => arg == "debug"))
Debugger.Launch();
/* (1) Path to csproj
* (2) Path to compiled assembly
* (3) [Optional] Path to ouput directory
*/
// Default output directory
string currentDir = Directory.GetCurrentDirectory();
// Check for custom output directory
if (args.Length > 2) {
string customOutputPath = args[2];
DirectoryInfo directoryInfo = new DirectoryInfo(customOutputPath);
if (!directoryInfo.Exists)
throw new InvalidOperationException($"Custom output path '{directoryInfo.FullName}' does not exist");
currentDir = directoryInfo.FullName;
}
// Build output directory path
string pluginOutputPath = $@"{currentDir}\\plug-ins\\";
// Perform packaging
try {
Packager.Instance.PackMarc(args[0], args[1], pluginOutputPath);
} catch (Exception ex) {
Console.Error.WriteLine(ex);
throw;
}
// Print result to console
FileInfo csprojFileInfo = new FileInfo(args[0]);
string fileName = Path.GetFileNameWithoutExtension(csprojFileInfo.FullName);
string marcFilePath = pluginOutputPath.Replace(@"\\", @"\") + fileName + ".marc";
Console.WriteLine("[Tessa] {0} -> {1}", fileName, marcFilePath);
}
}
} | using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Tessa {
/// <summary> Provides the entry point for the application. </summary>
class EntryPoint {
/// <summary> Implements the entry point of the application. </summary>
/// <param name="args">Execution arguments</param>
static void Main(string[] args) {
// TODO Print options to console
if (args.Length == 0) return;
if (args.Any(arg => arg == "debug"))
Debugger.Launch();
/* (1) Path to csproj
* (2) Path to compiled assembly
* (3) [Optional] Path to ouput directory
*/
// Default output directory
string currentDir = Directory.GetCurrentDirectory();
// Check for custom output directory
if (args.Length > 2) {
string customOutputPath = args[2];
DirectoryInfo directoryInfo = new DirectoryInfo(customOutputPath);
if (!directoryInfo.Exists)
throw new InvalidOperationException($"Custom output path '{directoryInfo.FullName}' does not exist");
currentDir = directoryInfo.FullName;
}
// Build output directory path
string pluginOutputPath = $@"{currentDir}\\plug-ins\\";
// Perform packaging
Packager.Instance.PackMarc(args[0], args[1], pluginOutputPath);
// Print result to console
FileInfo csprojFileInfo = new FileInfo(args[0]);
string fileName = Path.GetFileNameWithoutExtension(csprojFileInfo.FullName);
string marcFilePath = pluginOutputPath.Replace(@"\\", @"\") + fileName + ".marc";
Console.WriteLine("[Tessa] {0} -> {1}", fileName, marcFilePath);
}
}
} | mit | C# |
2e0f99f70be9404d9c5685e0e1e793536d3dec68 | Test where on enumerables mapping | chartjunk/SubMapper | test/EnumerableWhereTests.cs | test/EnumerableWhereTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using SubMapper.EnumerableMapping.Adders;
using System.Collections.Generic;
using System.Linq;
namespace SubMapper.UnitTest
{
[TestClass]
public class EnumerableWhereTests
{
[TestMethod]
public void MapPartialUsingMultipleWhere()
{
var mapping = Mapping.FromTo<SourceType, TargetType>()
.FromEnum(s => s.Enumerable1, t => t, fromEnumMapping => fromEnumMapping
.UsingArrayConcatAdder()
.First(s => s.EnumerableInt1 == 1 && (s.EnumerableString1 == "Enumerable1 String1"))
.Sub(s => s.EnumerableSub1, t => t, subMapping => subMapping
.Map(s => s.EnumerableSubString1, t => t.String1)));
var si = SourceType.GetTestInstance();
var ti = new TargetType();
var si2 = new SourceType();
mapping.TranslateAToB(si, ti);
mapping.TranslateBToA(si2, ti);
Assert.AreEqual(si.Enumerable1.First(i => i.EnumerableInt1 == 1 && i.EnumerableString1 == "Enumerable1 String1").EnumerableSub1.EnumerableSubString1, ti.String1);
Assert.AreEqual(si2.Enumerable1.First(i => i.EnumerableInt1 == 1 && i.EnumerableString1 == "Enumerable1 String1").EnumerableSub1.EnumerableSubString1, ti.String1);
}
[TestMethod]
public void MapEnumerablesUsingWhere()
{
var mapping = Mapping.FromTo<SourceType, TargetType>()
.Enums(s => s.EnumerableList1, t => t.EnumerableList1, eM => eM
.UsingArrayConcatAdder()
.Where(s => s.EnumerableInt1 == 1, t => t.EnumerableInt1 == 999)
.Map(s => s.EnumerableString1, t => t.EnumerableString1));
var si = SourceType.GetTestInstance();
var ti = new TargetType();
var si2 = new SourceType();
mapping.TranslateAToB(si, ti);
mapping.TranslateBToA(si2, ti);
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using SubMapper.EnumerableMapping.Adders;
using System.Linq;
namespace SubMapper.UnitTest
{
[TestClass]
public class EnumerableWhereTests
{
[TestMethod]
public void MapUsingMultipleWhere()
{
var mapping = Mapping.FromTo<SourceType, TargetType>()
.FromEnum(s => s.Enumerable1, t => t, fromEnumMapping => fromEnumMapping
.UsingArrayConcatAdder()
.First(s => s.EnumerableInt1 == 1 && (s.EnumerableString1 == "Enumerable1 String1"))
.Sub(s => s.EnumerableSub1, t => t, subMapping => subMapping
.Map(s => s.EnumerableSubString1, t => t.String1)));
var si = SourceType.GetTestInstance();
var ti = new TargetType();
var si2 = new SourceType();
mapping.TranslateAToB(si, ti);
mapping.TranslateBToA(si2, ti);
Assert.AreEqual(si.Enumerable1.First(i => i.EnumerableInt1 == 1 && i.EnumerableString1 == "Enumerable1 String1").EnumerableSub1.EnumerableSubString1, ti.String1);
Assert.AreEqual(si2.Enumerable1.First(i => i.EnumerableInt1 == 1 && i.EnumerableString1 == "Enumerable1 String1").EnumerableSub1.EnumerableSubString1, ti.String1);
}
}
}
| apache-2.0 | C# |
ed3045854d2deaa2e71daf841e8c3bd9803bbb41 | Remove unnecessary "using" statements. | adebisi-fa/telegram.bot | src/Telegram.Bot/Types/Interfaces/IReplyMarkup.cs | src/Telegram.Bot/Types/Interfaces/IReplyMarkup.cs | namespace Telegram.Bot.Types.Interfaces
{
public interface IReplyMarkup { }
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Telegram.Bot.Types.Interfaces
{
public interface IReplyMarkup { }
}
| mit | C# |
9f8f420368e53f21fe950507777f8ca87fd6d5f6 | improve test program | nerai/CMenu | src/ConsoleMenu/Program.cs | src/ConsoleMenu/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleMenu
{
/// <summary>
/// Test program for CMenu.
/// </summary>
class Program
{
static CMenu menu;
static void Main (string[] args)
{
Basics ();
InputModification ();
CaseSensitivity ();
}
static void Basics ()
{
Console.WriteLine ("Simple CMenu demonstration");
Console.WriteLine ("Enter \"help\" for help.");
// Create menu
menu = new CMenu ();
// Add simple Hello World command
menu.Add ("hello", s => Console.WriteLine ("Hello world!"));
/*
* If the command happens to be more complex, you can just put it in a separate method.
*/
menu.Add ("len", s => PrintLen (s));
/*
* It is also possible to return an exit code to signal that processing should be stopped.
* By default, the command "quit" exists for this purpose. Let's add an alternative way to stop processing input.
*/
menu.Add ("exit", s => MenuResult.Quit);
/*
* To create a command with help text, simply add it during definition.
*/
menu.Add ("time",
s => Console.WriteLine (DateTime.UtcNow),
"Help for \"time\": Writes the current time");
/*
* You can also access individual commands to edit them later, though this is rarely required.
*/
((CMenuItem) menu["time"]).HelpText += " (UTC).";
// Run menu. The menu will run until quit by the user.
menu.Run ();
Console.WriteLine ("Finished!");
}
static void PrintLen (string s)
{
Console.WriteLine ("String \"" + s + "\" has length " + s.Length);
}
static void Repeat (string s)
{
menu.Input (s, true);
menu.Input (s, true);
menu.Input (s, true);
}
static void InputModification ()
{
/*
* It is also possible to modify the input queue.
* Check out how the "repeat" command adds its argument to the input queue three times.
*/
menu.Add ("repeat",
s => Repeat (s),
"Repeats a command 3 times.");
// Run menu. The menu will run until quit by the user.
Console.WriteLine ("New command available: repeat");
menu.Run ();
}
static void CaseSensitivity ()
{
/*
* Commands are case *in*sensitive by default. This can be changed using the `StringComparison` property.
*/
menu.StringComparison = StringComparison.InvariantCulture;
menu.Add ("Hello", s => Console.WriteLine ("Hi!"));
Console.WriteLine ("The menu is now case sensitive.");
menu.Run ();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleMenu
{
/// <summary>
/// Test program for CMenu.
/// </summary>
class Program
{
static CMenu menu;
static void Main (string[] args)
{
Basics ();
InputModification ();
CaseSensitivity ();
}
static void Basics ()
{
Console.WriteLine ("Simple CMenu demonstration");
Console.WriteLine ("Enter \"help\" for help.");
// Create menu
menu = new CMenu ();
// Add simple Hello World command
menu.Add ("hello", s => Console.WriteLine ("Hello world!"));
/*
* If the command happens to be more complex, you can just put it in a separate method.
*/
menu.Add ("len", s => PrintLen (s));
/*
* It is also possible to return an exit code to signal that processing should be stopped.
* By default, the command "quit" exists for this purpose. Let's add an alternative way to stop processing input.
*/
menu.Add ("exit", s => MenuResult.Quit);
/*
* To create a command with help text, simply add it during definition or later.
*/
menu.Add ("time",
s => Console.WriteLine (DateTime.UtcNow),
"Writes the current time");
menu["time"].HelpText += " (UTC).";
// Run menu. The menu will run until quit by the user.
menu.Run ();
Console.WriteLine ("Finished!");
}
static void PrintLen (string s)
{
Console.WriteLine ("String \"" + s + "\" has length " + s.Length);
}
static void Repeat (string s)
{
menu.Input (s, true);
menu.Input (s, true);
menu.Input (s, true);
}
static void InputModification ()
{
/*
* It is also possible to modify the input queue.
* Check out how the "repeat" command adds its argument to the input queue three times.
*/
menu.Add ("repeat",
s => Repeat (s),
"Repeats a command 3 times.");
// Run menu. The menu will run until quit by the user.
Console.WriteLine ("New command available: repeat");
menu.Run ();
}
static void CaseSensitivity ()
{
/*
* Commands are case *in*sensitive by default. This can be changed using the `StringComparison` property.
*/
menu.StringComparison = StringComparison.InvariantCulture;
menu.Add ("Hello", s => Console.WriteLine ("Hi!"));
Console.WriteLine ("The menu is now case sensitive.");
menu.Run ();
}
}
}
| mit | C# |
1549f011a9cfabbe00ea82343fae057943b6a3b4 | Add IsVersionOrLater method | ektrah/nsec | src/Cryptography/Sodium.cs | src/Cryptography/Sodium.cs | using System;
using static Interop.Libsodium;
namespace NSec.Cryptography
{
internal static class Sodium
{
private static readonly Lazy<int> s_initialized = new Lazy<int>(new Func<int>(sodium_init));
private static readonly Lazy<int> s_versionMajor = new Lazy<int>(new Func<int>(sodium_library_version_major));
private static readonly Lazy<int> s_versionMinor = new Lazy<int>(new Func<int>(sodium_library_version_minor));
public static bool IsVersionOrLater(int major, int minor)
{
return (s_versionMajor.Value > major)
|| (s_versionMajor.Value == major && s_versionMinor.Value >= minor);
}
public static bool TryInitialize()
{
// Require libsodium 1.0.9 or later
if (!IsVersionOrLater(9, 2))
{
return false;
}
// sodium_init() returns 0 on success, -1 on failure, and 1 if the
// library had already been initialized. We call sodium_init() only
// once, but if another library p/invokes into libsodium it might
// already have been initialized.
return (s_initialized.Value == 0) || (s_initialized.Value == 1);
}
}
}
| using System;
using static Interop.Libsodium;
namespace NSec.Cryptography
{
internal static class Sodium
{
private static readonly Lazy<int> s_initialized = new Lazy<int>(new Func<int>(sodium_init));
private static readonly Lazy<int> s_versionMajor = new Lazy<int>(new Func<int>(sodium_library_version_major));
private static readonly Lazy<int> s_versionMinor = new Lazy<int>(new Func<int>(sodium_library_version_minor));
public static bool TryInitialize()
{
// Require libsodium 1.0.9 or later
if ((s_versionMajor.Value < 9) || (s_versionMajor.Value == 9 && s_versionMinor.Value < 2))
{
return false;
}
// sodium_init() returns 0 on success, -1 on failure, and 1 if the
// library had already been initialized. We call sodium_init() only
// once, but if another library p/invokes into libsodium it might
// already have been initialized.
return (s_initialized.Value == 0) || (s_initialized.Value == 1);
}
}
}
| mit | C# |
c8b2052fb45521e230e8586607423baa5a7b6f01 | add one more summary | HattMarris1/HoloToolkit-Unity,ForrestTrepte/HoloToolkit-Unity,willcong/HoloToolkit-Unity,paseb/HoloToolkit-Unity,paseb/MixedRealityToolkit-Unity,dbastienMS/HoloToolkit-Unity,chadbramwell/HoloToolkit-Unity,NeerajW/HoloToolkit-Unity,out-of-pixel/HoloToolkit-Unity,HoloFan/HoloToolkit-Unity | Assets/HoloToolkit/Utilities/Scripts/FileSystemHelper.cs | Assets/HoloToolkit/Utilities/Scripts/FileSystemHelper.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if UNITY_EDITOR
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Helper functions for file I/O
/// </summary>
public static class FileSystemHelper
{
public static void WriteBytesToLocalFile(string filename, byte[] content)
{
try
{
var fs = new System.IO.FileStream(filename, System.IO.FileMode.Create);
var bw = new System.IO.BinaryWriter(fs);
bw.Write(content);
bw.Close();
fs.Close();
}
catch (System.Exception ex)
{
Debug.LogError("Error writing to file: " + ex.ToString());
}
}
public static byte[] ReadBytesFromLocalFile(string fullPath)
{
var path = fullPath;
byte[] result = null;
try
{
var fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
var br = new System.IO.BinaryReader(fs);
if (fs.Length > int.MaxValue)
{
throw new System.ArgumentOutOfRangeException();
}
result = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
}
catch (System.Exception ex)
{
Debug.LogError("Read file exception: " + ex.ToString());
}
return result;
}
}
}
#endif | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if UNITY_EDITOR
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class FileSystemHelper
{
public static void WriteBytesToLocalFile(string filename, byte[] content)
{
try
{
var fs = new System.IO.FileStream(filename, System.IO.FileMode.Create);
var bw = new System.IO.BinaryWriter(fs);
bw.Write(content);
bw.Close();
fs.Close();
}
catch (System.Exception ex)
{
Debug.LogError("Error writing to file: " + ex.ToString());
}
}
public static byte[] ReadBytesFromLocalFile(string fullPath)
{
var path = fullPath;
byte[] result = null;
try
{
var fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
var br = new System.IO.BinaryReader(fs);
if (fs.Length > int.MaxValue)
{
throw new System.ArgumentOutOfRangeException();
}
result = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
}
catch (System.Exception ex)
{
Debug.LogError("Read file exception: " + ex.ToString());
}
return result;
}
}
}
#endif | mit | C# |
2bf3053f1d96c5b4df2b54964a6e668be86e4ac1 | expand customer fields | tbstudee/IntacctClient | Entities/IntacctCustomer.cs | Entities/IntacctCustomer.cs | using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Intacct.Infrastructure;
namespace Intacct.Entities
{
[IntacctName("customer")]
public class IntacctCustomer : IntacctObject
{
[IntacctName("customerid")]
public string Id { get; set; }
public string Name { get; set; }
public string ParentId { get; set; }
public string TermName { get; set; }
public string CustRepId { get; set; }
public string AccountLabel { get; set; }
public string GLAccountNo { get; set; }
public string Status { get; set; }
public string ExternalId { get; set; }
public IntacctContact PrimaryContact { get; set; }
/// <summary>
/// Create a new customer record.
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
public IntacctCustomer(string id, string name)
{
Id = id;
Name = name;
}
public IntacctCustomer(XElement data)
{
this.SetPropertyValue(x => Id, data);
this.SetPropertyValue(x => Name, data);
this.SetPropertyValue(x => ExternalId, data, isOptional: true);
var primaryContactElement = data.Element("primary");
if (primaryContactElement != null && primaryContactElement.HasElements)
{
PrimaryContact = new IntacctContact(primaryContactElement);
}
}
internal override XObject[] ToXmlElements()
{
var elements = new List<XObject>
{
new XElement("customerid", Id),
new XElement("name", Name),
new XElement("parentid", ParentId),
new XElement("termname", TermName),
new XElement("custrepid", CustRepId),
new XElement("accountlabel", AccountLabel),
new XElement("externalid", ExternalId),
new XElement("primary", PrimaryContact?.ToXmlElements().Cast<object>()),
};
return elements.ToArray();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Intacct.Infrastructure;
namespace Intacct.Entities
{
[IntacctName("customer")]
public class IntacctCustomer : IntacctObject
{
[IntacctName("customerid")]
public string Id { get; set; }
public string Name { get; set; }
public string ExternalId { get; set; }
public IntacctContact PrimaryContact { get; set; }
/// <summary>
/// Create a new customer record.
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
public IntacctCustomer(string id, string name)
{
Id = id;
Name = name;
}
public IntacctCustomer(XElement data)
{
this.SetPropertyValue(x => Id, data);
this.SetPropertyValue(x => Name, data);
this.SetPropertyValue(x => ExternalId, data, isOptional: true);
var primaryContactElement = data.Element("primary");
if (primaryContactElement != null && primaryContactElement.HasElements)
{
PrimaryContact = new IntacctContact(primaryContactElement);
}
}
internal override XObject[] ToXmlElements()
{
var elements = new List<XObject>
{
new XElement("customerid", Id),
new XElement("name", Name),
new XElement("externalid", ExternalId),
};
if (PrimaryContact != null)
{
elements.Add(new XElement("primary", new XElement("contact", PrimaryContact.ToXmlElements().Cast<object>())));
}
return elements.ToArray();
}
}
}
| mit | C# |
e0b459062c8b24e23c5703589f7cc6aef52708c8 | Revert "Fixes #400 Added command line help information." | anobleperson/GitVersion,anobleperson/GitVersion,anobleperson/GitVersion | GitVersionExe/HelpWriter.cs | GitVersionExe/HelpWriter.cs | namespace GitVersion
{
using System;
class HelpWriter
{
public static void Write()
{
WriteTo(Console.WriteLine);
}
public static void WriteTo(Action<string> writeAction)
{
const string message = @"Use convention to derive a SemVer product version from a GitFlow or GitHub based repository.
GitVersion [path]
path The directory containing .git. If not defined current directory is used. (Must be first argument)
init Creates a sample GitVersion.yaml config file in the repository. Must be used with no other args
/h or /? Shows Help
/targetpath Same as 'path', but not positional
/output Determines the output to the console. Can be either 'json' or 'buildserver', will default to 'json'.
/showvariable Used in conjuntion with /output json, will output just a particular variable.
eg /output json /showvariable SemVer - will output `1.2.3+beta.4`
/l Path to logfile.
/showconfig Outputs the effective GitVersion config (defaults + custom from GitVersion.yaml) in yaml format
# AssemblyInfo updating
/updateassemblyinfo
Will recursively search for all 'AssemblyInfo.cs' files in the git repo and update them
/updateassemblyinfofilename
Specify name of AssemblyInfo file. Can also /updateAssemblyInfo GlobalAssemblyInfo.cs as a shorthand
# Remote repository args
/url Url to remote git repository.
/b Name of the branch to use on the remote repository, must be used in combination with /url.
/u Username in case authentication is required.
/p Password in case authentication is required.
/c The commit id to check. If not specified, the latest available commit on the specified branch will be used.
# Execute build args
/exec Executes target executable making GitVersion variables available as environmental variables
/execargs Arguments for the executable specified by /exec
/proj Build a msbuild file, GitVersion variables will be passed as msbuild properties
/projargs Additional arguments to pass to msbuild
";
writeAction(message);
}
}
} | namespace GitVersion
{
using System;
class HelpWriter
{
public static void Write()
{
WriteTo(Console.WriteLine);
}
public static void WriteTo(Action<string> writeAction)
{
const string message = @"Use convention to derive a SemVer product version from a GitFlow or GitHub based repository.
GitVersion [path]
path The directory containing .git. If not defined current directory is used. (Must be first argument)
init Creates a sample GitVersion.yaml config file in the repository. Must be used with no other args
/h or /? Shows Help
/targetpath Same as 'path', but not positional
/output Determines the output to the console. Can be either 'json' or 'buildserver', will default to 'json'.
/showvariable Used in conjuntion with /output json, will output just a particular variable.
eg /output json /showvariable SemVer - will output `1.2.3+beta.4`
/l Path to logfile.
/showconfig Outputs the effective GitVersion config (defaults + custom from GitVersion.yaml) in yaml format
/includeuntrackedbranches
Allows untracked branches to be used in the calculation of version.
# AssemblyInfo updating
/updateassemblyinfo
Will recursively search for all 'AssemblyInfo.cs' files in the git repo and update them
/updateassemblyinfofilename
Specify name of AssemblyInfo file. Can also /updateAssemblyInfo GlobalAssemblyInfo.cs as a shorthand
# Remote repository args
/url Url to remote git repository.
/b Name of the branch to use on the remote repository, must be used in combination with /url.
/u Username in case authentication is required.
/p Password in case authentication is required.
/c The commit id to check. If not specified, the latest available commit on the specified branch will be used.
# Execute build args
/exec Executes target executable making GitVersion variables available as environmental variables
/execargs Arguments for the executable specified by /exec
/proj Build a msbuild file, GitVersion variables will be passed as msbuild properties
/projargs Additional arguments to pass to msbuild
";
writeAction(message);
}
}
} | mit | C# |
3df04b284ee5a88cc4ee8f6c57e8433c1a751fe6 | test upgrade | fandrei/AppMetrics,fandrei/AppMetrics | HeavyLoadTest/TestRunner.cs | HeavyLoadTest/TestRunner.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using AppMetrics.Client;
namespace HeavyLoadTest
{
class TestRunner : MarshalByRefObject
{
public long Execute(string url)
{
try
{
var tracker = new Tracker(url, "HeavyLoadTest");
for (int i = 0; i < LoopsCount; i++)
{
tracker.Log("Counter", i);
tracker.Log("RandomValue", Guid.NewGuid().ToString());
tracker.Log("RandomValue2", DateTime.Now.Millisecond);
Thread.Sleep(1);
}
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
Tracker.Terminate(true);
var res = Tracker.GetServedRequestsCount();
return res;
}
private const int LoopsCount = 100000;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using AppMetrics.Client;
namespace HeavyLoadTest
{
class TestRunner : MarshalByRefObject
{
public long Execute(string url)
{
try
{
var tracker = new Tracker(url, "HeavyLoadTest");
for (int i = 0; i < LoopsCount; i++)
{
tracker.Log("RandomValue", Guid.NewGuid().ToString());
tracker.Log("RandomValue2", DateTime.Now.Millisecond);
Thread.Sleep(1);
}
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
Tracker.Terminate(true);
var res = Tracker.GetServedRequestsCount();
return res;
}
private const int LoopsCount = 1000;
}
}
| apache-2.0 | C# |
63491d3e7b3b1ef7caf7c0364c40b24938e979d2 | Update AssemblyInfo | sakapon/Tools-2017 | EventLogPicker/EventLogPicker/Properties/AssemblyInfo.cs | EventLogPicker/EventLogPicker/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("Event Log Picker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Keiho Sakapon")]
[assembly: AssemblyProduct("KTools")]
[assembly: AssemblyCopyright("© 2017 Keiho Sakapon")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("8acb46e1-b903-428d-8b78-263d043b6d66")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [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;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("EventLogPicker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EventLogPicker")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("8acb46e1-b903-428d-8b78-263d043b6d66")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
2b7bf558caa5b7e72ec94f8ec10fec3c369b2e11 | add displayFormat for Date and Amount | hatelove/MyMvcHomework,hatelove/MyMvcHomework,hatelove/MyMvcHomework | MyMoney/MyMoney/Models/ViewModels/AccountingViewModel.cs | MyMoney/MyMoney/Models/ViewModels/AccountingViewModel.cs | using MyMoney.Models.Enums;
using System;
using System.ComponentModel.DataAnnotations;
namespace MyMoney.Models.ViewModels
{
public class AccountingViewModel
{
//[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString ="{0:N0}")]
public int Amount { get; internal set; }
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}")]
public DateTime Date { get; internal set; }
public string Remark { get; internal set; }
public AccountingType Type { get; internal set; }
}
} | using System;
using MyMoney.Models.Enums;
namespace MyMoney.Models.ViewModels
{
public class AccountingViewModel
{
public int Amount { get; internal set; }
public DateTime Date { get; internal set; }
public string Remark { get; internal set; }
public AccountingType Type { get; internal set; }
}
} | mit | C# |
e4cb01518ee4b5795fdbeb577824a8a6f039b478 | add ViewModel's property Remark with DateType Attribute for MultilineText | hatelove/MyMvcHomework,hatelove/MyMvcHomework,hatelove/MyMvcHomework | MyMoney/MyMoney/Models/ViewModels/AccountingViewModel.cs | MyMoney/MyMoney/Models/ViewModels/AccountingViewModel.cs | using MyMoney.Models.CustomValidationAttributes;
using MyMoney.Models.Enums;
using System;
using System.ComponentModel.DataAnnotations;
namespace MyMoney.Models.ViewModels
{
public class AccountingViewModel
{
[Display(Name = "金額")]
[DisplayFormat(DataFormatString = "{0:N0}")]
[Range(0, int.MaxValue, ErrorMessage = "{0}需為正整數")]
[Required]
public int Amount { get; set; }
[Display(Name = "日期")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}")]
[Required]
[DateBeforeToday(ErrorMessage = "{0}不可大於今天")]
public DateTime Date { get; set; }
[Display(Name = "備註")]
[DataType(DataType.MultilineText)]
[Required]
public string Remark { get; set; }
[Display(Name = "類別")]
[Required]
public AccountingType Type { get; set; }
}
} | using MyMoney.Models.CustomValidationAttributes;
using MyMoney.Models.Enums;
using System;
using System.ComponentModel.DataAnnotations;
namespace MyMoney.Models.ViewModels
{
public class AccountingViewModel
{
[Display(Name = "金額")]
[DisplayFormat(DataFormatString = "{0:N0}")]
[Range(0, int.MaxValue, ErrorMessage = "{0}需為正整數")]
[Required]
public int Amount { get; set; }
[Display(Name = "日期")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}")]
[Required]
[DateBeforeToday(ErrorMessage = "{0}不可大於今天")]
public DateTime Date { get; set; }
[Display(Name = "備註")]
[Required]
public string Remark { get; set; }
[Display(Name = "類別")]
[Required]
public AccountingType Type { get; set; }
}
} | mit | C# |
07da8db262a091c2769a8557705286f1e8f33deb | split case now works for pulling subaccount title and info | ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing | Purchasing.Web/Views/Order/_AccountSelectTemplate.cshtml | Purchasing.Web/Views/Order/_AccountSelectTemplate.cshtml | <div class="account-container">
<select data-bind="foreach: $root.accounts, value: account, splitName: 'Account'" class="account-number" title="No Account Selected">
<option data-bind="value: id, text: text, attr: { title: title }"></option>
</select>
<span class="ui-state-default ui-corner-all ui-state-hover" style="margin:0 0.1em 0; padding-top: .4em; vertical-align: sub;">
<a href="#" title="Search Accounts" class="search-account ui-icon ui-icon-search"></a></span>
@*<select data-bind="enable: $root.shouldEnableSubAccounts(subAccounts), value: subAccount, splitName: 'SubAccount', options: subAccounts, optionsCaption: '--Sub Account--'" name="SubAccount" class="account-subaccount"></select>*@
<select data-bind="enable: $root.shouldEnableSubAccounts(subAccounts), value: subAccount, foreach: subAccounts, splitName: 'SubAccount'" name="SubAccount" class="account-subaccount">
<option data-bind="value: id, text: text, attr: { title: title }"></option>
</select>
<input data-bind="value: project, splitName: 'Project'" type="text" placeholder="Proj" class="account-projectcode" maxlength="10"/>
</div> | <div class="account-container">
<select data-bind="foreach: $root.accounts, value: account, splitName: 'Account'" class="account-number" title="No Account Selected">
<option data-bind="value: id, text: text, attr: { title: title }"></option>
</select>
<span class="ui-state-default ui-corner-all ui-state-hover" style="margin:0 0.1em 0; padding-top: .4em; vertical-align: sub;">
<a href="#" title="Search Accounts" class="search-account ui-icon ui-icon-search"></a></span>
<select data-bind="enable: $root.shouldEnableSubAccounts(subAccounts), value: subAccount, splitName: 'SubAccount', options: subAccounts, optionsCaption: '--Sub Account--'" name="SubAccount" class="account-subaccount"></select>
<input data-bind="value: project, splitName: 'Project'" type="text" placeholder="Proj" class="account-projectcode" maxlength="10"/>
</div> | mit | C# |
de52197da9fd7e26f2397103afe001fa37db7a66 | Update Assembly version | twenzel/Cake.MarkdownToPdf,twenzel/Cake.MarkdownToPdf,twenzel/Cake.MarkdownToPdf | src/Cake.MarkdownToPdf/Properties/AssemblyInfo.cs | src/Cake.MarkdownToPdf/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("Cake.MarkdownToPdf")]
[assembly: AssemblyDescription("Cake addin to convert markdown files to pdf")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cake.MarkdownToPdf")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8731fa2b-39fa-4d77-bde6-897b2d45ce4c")]
// 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("0.2.0.0")]
[assembly: AssemblyVersion("0.4.4.5")]
[assembly: AssemblyFileVersion("0.4.4.5")]
| 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("Cake.MarkdownToPdf")]
[assembly: AssemblyDescription("Cake addin to convert markdown files to pdf")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cake.MarkdownToPdf")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8731fa2b-39fa-4d77-bde6-897b2d45ce4c")]
// 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("0.2.0.0")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
| mit | C# |
58ea716ba826335df44c81c076a5c80c771b56dd | Fix for compatibility with AppVeyor | Kralizek/Nybus,Nybus-project/Nybus | src/MassTransit/MassTransit/MassTransitOptions.cs | src/MassTransit/MassTransit/MassTransitOptions.cs | using System;
using Nybus.Configuration;
using Nybus.Logging;
namespace Nybus.MassTransit
{
public class MassTransitOptions
{
public IQueueStrategy CommandQueueStrategy { get; set; } = new AutoGeneratedNameQueueStrategy();
public IErrorStrategy CommandErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IQueueStrategy EventQueueStrategy { get; set; } = new TemporaryQueueStrategy();
public IErrorStrategy EventErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IServiceBusFactory ServiceBusFactory { get; set; } = new RabbitMqServiceBusFactory(Math.Max(1, Environment.ProcessorCount));
public IContextManager ContextManager { get; set; } = new RabbitMqContextManager();
public ILoggerFactory LoggerFactory { get; set; } = Nybus.Logging.LoggerFactory.Default;
}
} | using System;
using Nybus.Configuration;
using Nybus.Logging;
namespace Nybus.MassTransit
{
public class MassTransitOptions
{
public IQueueStrategy CommandQueueStrategy { get; set; } = new AutoGeneratedNameQueueStrategy();
public IErrorStrategy CommandErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IQueueStrategy EventQueueStrategy { get; set; } = new TemporaryQueueStrategy();
public IErrorStrategy EventErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IServiceBusFactory ServiceBusFactory { get; set; } = new RabbitMqServiceBusFactory(Environment.ProcessorCount);
public IContextManager ContextManager { get; set; } = new RabbitMqContextManager();
public ILoggerFactory LoggerFactory { get; set; } = Nybus.Logging.LoggerFactory.Default;
}
} | mit | C# |
47dedee7a57372b90c11ddbeab41ff7e074e560f | Add Xamarin.iOS platform targets to MSBuildSettings PlatformTarget enumeration | cake-build/cake,gep13/cake,cake-build/cake,devlead/cake,gep13/cake,patriksvensson/cake,devlead/cake,patriksvensson/cake | src/Cake.Common/Tools/MSBuild/PlatformTarget.cs | src/Cake.Common/Tools/MSBuild/PlatformTarget.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.
namespace Cake.Common.Tools.MSBuild
{
/// <summary>
/// Represents a MSBuild platform target.
/// </summary>
public enum PlatformTarget
{
/// <summary>
/// Platform target: <c>MSIL</c> (Any CPU)
/// </summary>
MSIL = 0,
/// <summary>
/// Platform target: <c>x86</c>
/// </summary>
// ReSharper disable once InconsistentNaming
x86 = 1,
/// <summary>
/// Platform target: <c>x64</c>
/// </summary>
// ReSharper disable once InconsistentNaming
x64 = 2,
/// <summary>
/// Platform target: <c>ARM</c>
/// </summary>
// ReSharper disable once InconsistentNaming
ARM = 3,
/// <summary>
/// Platform target: <c>Win32</c>
/// </summary>
Win32 = 4,
/// <summary>
/// Platform target: <c>ARM64</c>
/// </summary>
// ReSharper disable once InconsistentNaming
ARM64 = 5,
/// <summary>
/// Platform target: <c>ARMv6</c>
/// </summary>
// ReSharper disable once InconsistentNaming
ARMv6 = 6,
/// <summary>
/// Platform target: <c>ARMv7</c>
/// </summary>
// ReSharper disable once InconsistentNaming
ARMv7 = 7,
/// <summary>
/// Platform target: <c>ARMv7s</c>
/// </summary>
// ReSharper disable once InconsistentNaming
ARMv7s = 8,
}
}
| // 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.
namespace Cake.Common.Tools.MSBuild
{
/// <summary>
/// Represents a MSBuild platform target.
/// </summary>
public enum PlatformTarget
{
/// <summary>
/// Platform target: <c>MSIL</c> (Any CPU)
/// </summary>
MSIL = 0,
/// <summary>
/// Platform target: <c>x86</c>
/// </summary>
// ReSharper disable once InconsistentNaming
x86 = 1,
/// <summary>
/// Platform target: <c>x64</c>
/// </summary>
// ReSharper disable once InconsistentNaming
x64 = 2,
/// <summary>
/// Platform target: <c>ARM</c>
/// </summary>
// ReSharper disable once InconsistentNaming
ARM = 3,
/// <summary>
/// Platform target: <c>Win32</c>
/// </summary>
Win32 = 4,
/// <summary>
/// Platform target: <c>ARM64</c>
/// </summary>
// ReSharper disable once InconsistentNaming
ARM64 = 5
}
}
| mit | C# |
f15594eb21ed2d06b95b91195e94a332d9209a3a | Update ITextFieldWriter.cs | Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Model/Interfaces/ITextFieldWriter.cs | src/Core2D/Model/Interfaces/ITextFieldWriter.cs | using System.IO;
namespace Core2D.Interfaces
{
/// <summary>
/// Defines text field writer contract.
/// </summary>
/// <typeparam name="T">The database type.</typeparam>
public interface ITextFieldWriter<T>
{
/// <summary>
/// Gets text field writer name.
/// </summary>
string Name { get; }
/// <summary>
/// Gets text field writer extension.
/// </summary>
string Extension { get; }
/// <summary>
/// Write database records to text based file format.
/// </summary>
/// <param name="stream,">The fields file stream,.</param>
/// <param name="database">The source records database.</param>
void Write(Stream stream, T database);
}
}
|
namespace Core2D.Interfaces
{
/// <summary>
/// Defines text field writer contract.
/// </summary>
/// <typeparam name="T">The database type.</typeparam>
public interface ITextFieldWriter<T>
{
/// <summary>
/// Write database records to text based file format.
/// </summary>
/// <param name="path">The fields file path.</param>
/// <param name="fs">The file system.</param>
/// <param name="database">The source records database.</param>
void Write(string path, IFileSystem fs, T database);
}
}
| mit | C# |
413a7709900f405ade52b49bd0a41b50df6039cd | Remove packages after restoring in deploy_local.csx | mrahhal/Migrator.EF6 | deploy_local.csx | deploy_local.csx | using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Linq;
var cd = Environment.CurrentDirectory;
var projectName = "Migrator.EF6.Tools";
var userName = Environment.UserName;
var userProfileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var deploymentFolder = $@"C:\D\dev\src\Local Packages";
Directory.CreateDirectory(deploymentFolder);
var nugetDirectory = Path.Combine(userProfileDirectory, ".nuget/packages");
var nugetToolsDirectory = Path.Combine(nugetDirectory, ".tools");
var nugetProjectDirectory = Path.Combine(nugetDirectory, projectName);
var nugetToolsProjectDirectory = Path.Combine(nugetToolsDirectory, projectName);
var regexFolder = new Regex(@"(.\..\..)-(.+)");
var regexFile = new Regex($@"{projectName}\.(.\..\..)-(.+).nupkg");
if (!Pack())
{
Console.WriteLine("A problem occurred while packing.");
return;
}
RemoveDevPackageFilesIn(deploymentFolder);
RemoveDevPackagesIn(nugetProjectDirectory);
RemoveDevPackagesIn(nugetToolsProjectDirectory);
var package = GetPackagePath();
if (package == null)
{
Console.WriteLine("Package file not found. A problem might have occurred with the build script.");
return;
}
var packageFileName = Path.GetFileName(package);
var deployedPackagePath = Path.Combine(deploymentFolder, packageFileName);
File.Copy(package, deployedPackagePath);
Console.WriteLine($"{packageFileName} -> {deployedPackagePath}");
//------------------------------------------------------------------------------
void RemoveDevPackagesIn(string directory)
{
var folders = Directory.EnumerateDirectories(directory);
foreach (var folder in folders)
{
var name = Path.GetFileName(folder);
if (regexFolder.IsMatch(name))
{
Directory.Delete(folder, true);
}
}
}
void RemoveDevPackageFilesIn(string directory)
{
var files = Directory.EnumerateFiles(directory);
foreach (var file in files)
{
var name = Path.GetFileName(file);
if (regexFile.IsMatch(name))
{
File.Delete(file);
}
}
}
bool Pack()
{
var process = Process.Start("powershell", "build.ps1");
process.WaitForExit();
var exitCode = process.ExitCode;
return exitCode == 0;
}
string GetPackagePath()
{
var packagesDirectory = Path.Combine(cd, "artifacts/packages");
if (!Directory.Exists(packagesDirectory))
{
return null;
}
var files = Directory.EnumerateFiles(packagesDirectory);
return files.OrderBy(f => f.Length).FirstOrDefault();
}
| using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Linq;
var cd = Environment.CurrentDirectory;
var projectName = "Migrator.EF6.Tools";
var userName = Environment.UserName;
var userProfileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var deploymentFolder = $@"C:\D\dev\src\Local Packages";
Directory.CreateDirectory(deploymentFolder);
var nugetDirectory = Path.Combine(userProfileDirectory, ".nuget/packages");
var nugetToolsDirectory = Path.Combine(nugetDirectory, ".tools");
var nugetProjectDirectory = Path.Combine(nugetDirectory, projectName);
var nugetToolsProjectDirectory = Path.Combine(nugetToolsDirectory, projectName);
var regexFolder = new Regex(@"(.\..\..)-(.+)");
var regexFile = new Regex($@"{projectName}\.(.\..\..)-(.+).nupkg");
RemoveDevPackageFilesIn(deploymentFolder);
RemoveDevPackagesIn(nugetProjectDirectory);
RemoveDevPackagesIn(nugetToolsProjectDirectory);
if (!Pack())
{
Console.WriteLine("A problem occurred while packing.");
return;
}
var package = GetPackagePath();
if (package == null)
{
Console.WriteLine("Package file not found. A problem might have occurred with the build script.");
return;
}
var packageFileName = Path.GetFileName(package);
var deployedPackagePath = Path.Combine(deploymentFolder, packageFileName);
File.Copy(package, deployedPackagePath);
Console.WriteLine($"{packageFileName} -> {deployedPackagePath}");
//------------------------------------------------------------------------------
void RemoveDevPackagesIn(string directory)
{
var folders = Directory.EnumerateDirectories(directory);
foreach (var folder in folders)
{
var name = Path.GetFileName(folder);
if (regexFolder.IsMatch(name))
{
Directory.Delete(folder, true);
}
}
}
void RemoveDevPackageFilesIn(string directory)
{
var files = Directory.EnumerateFiles(directory);
foreach (var file in files)
{
var name = Path.GetFileName(file);
if (regexFile.IsMatch(name))
{
File.Delete(file);
}
}
}
bool Pack()
{
var process = Process.Start("powershell", "build.ps1");
process.WaitForExit();
var exitCode = process.ExitCode;
return exitCode == 0;
}
string GetPackagePath()
{
var packagesDirectory = Path.Combine(cd, "artifacts/packages");
if (!Directory.Exists(packagesDirectory))
{
return null;
}
var files = Directory.EnumerateFiles(packagesDirectory);
return files.OrderBy(f => f.Length).FirstOrDefault();
}
| mit | C# |
39889c40aeac39e5780f16cbcc2ad53c9465428f | Add extra test case | scott-fleischman/algorithms-csharp | tests/Algorithms.Sort.Tests/InsertionSortTests.cs | tests/Algorithms.Sort.Tests/InsertionSortTests.cs | using System.Collections.Generic;
using NUnit.Framework;
namespace Algorithms.Sort.Tests
{
public class InsertionSortTests
{
[TestCase(new[] { 5, 2, 4, 6, 1, 3 }, new[] { 1, 2, 3, 4, 5, 6 })]
[TestCase(new[] { 31, 41, 59, 26, 41, 58 }, new[] { 26, 31, 41, 41, 58, 59 })]
public void TestSortInPlace(int[] elements, int[] expected)
{
var list = new List<int>(elements);
InsertionSort.SortInPlace(list);
Assert.That(list, Is.EqualTo(expected));
}
}
}
| using System.Collections.Generic;
using NUnit.Framework;
namespace Algorithms.Sort.Tests
{
public class InsertionSortTests
{
[Test]
public void TestSortInPlace()
{
var expected = new[] { 1, 2, 3, 4, 5, 6 };
var list = new List<int> { 5, 2, 4, 6, 1, 3 };
InsertionSort.SortInPlace(list);
Assert.That(list, Is.EqualTo(expected));
}
}
}
| mit | C# |
870d7ab98b7089a3ce4abb76401d99b36ae75fe7 | Revert making `TextureLoaderStore` ctor internal for now | smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework | osu.Framework/Graphics/Textures/TextureLoaderStore.cs | osu.Framework/Graphics/Textures/TextureLoaderStore.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;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Textures
{
/// <summary>
/// Handles the parsing of image data from standard image formats into <see cref="TextureUpload"/>s ready for GPU consumption.
/// </summary>
public class TextureLoaderStore : IResourceStore<TextureUpload>
{
private IResourceStore<byte[]> store { get; }
public TextureLoaderStore(IResourceStore<byte[]> store)
{
this.store = store;
(store as ResourceStore<byte[]>)?.AddExtension(@"png");
(store as ResourceStore<byte[]>)?.AddExtension(@"jpg");
}
public Task<TextureUpload> GetAsync(string name, CancellationToken cancellationToken = default) =>
Task.Run(() => Get(name), cancellationToken);
public TextureUpload Get(string name)
{
try
{
using (var stream = store.GetStream(name))
{
if (stream != null)
return new TextureUpload(ImageFromStream<Rgba32>(stream));
}
}
catch
{
}
return null;
}
public Stream GetStream(string name) => store.GetStream(name);
protected virtual Image<TPixel> ImageFromStream<TPixel>(Stream stream) where TPixel : unmanaged, IPixel<TPixel>
=> TextureUpload.LoadFromStream<TPixel>(stream);
public IEnumerable<string> GetAvailableResources() => store.GetAvailableResources();
#region IDisposable Support
private bool isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (isDisposed)
return;
store.Dispose();
isDisposed = true;
}
#endregion
}
}
| // 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;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Textures
{
/// <summary>
/// Handles the parsing of image data from standard image formats into <see cref="TextureUpload"/>s ready for GPU consumption.
/// </summary>
public class TextureLoaderStore : IResourceStore<TextureUpload>
{
private IResourceStore<byte[]> store { get; }
internal TextureLoaderStore(IResourceStore<byte[]> store)
{
this.store = store;
(store as ResourceStore<byte[]>)?.AddExtension(@"png");
(store as ResourceStore<byte[]>)?.AddExtension(@"jpg");
}
public Task<TextureUpload> GetAsync(string name, CancellationToken cancellationToken = default) =>
Task.Run(() => Get(name), cancellationToken);
public TextureUpload Get(string name)
{
try
{
using (var stream = store.GetStream(name))
{
if (stream != null)
return new TextureUpload(ImageFromStream<Rgba32>(stream));
}
}
catch
{
}
return null;
}
public Stream GetStream(string name) => store.GetStream(name);
protected virtual Image<TPixel> ImageFromStream<TPixel>(Stream stream) where TPixel : unmanaged, IPixel<TPixel>
=> TextureUpload.LoadFromStream<TPixel>(stream);
public IEnumerable<string> GetAvailableResources() => store.GetAvailableResources();
#region IDisposable Support
private bool isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (isDisposed)
return;
store.Dispose();
isDisposed = true;
}
#endregion
}
}
| mit | C# |
ffa0cf2d44174c870c5c0dc2173b73e9ba496a89 | Add comment detailing why this is requried | 2yangk23/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,smoogipooo/osu,EVAST9919/osu,johnneijzen/osu,NeoAdonis/osu | osu.Game/Graphics/UserInterface/DimmedLoadingLayer.cs | osu.Game/Graphics/UserInterface/DimmedLoadingLayer.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 osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Extensions.Color4Extensions;
using osuTK;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class DimmedLoadingLayer : OverlayContainer
{
private const float transition_duration = 250;
private readonly LoadingAnimation loading;
public DimmedLoadingLayer(float dimAmount = 0.5f, float iconScale = 1f)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(dimAmount),
},
loading = new LoadingAnimation { Scale = new Vector2(iconScale) },
};
}
protected override void PopIn()
{
this.FadeIn(transition_duration, Easing.OutQuint);
loading.Show();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.OutQuint);
loading.Hide();
}
protected override bool Handle(UIEvent e)
{
switch (e)
{
// blocking scroll can cause weird behaviour when this layer is used within a ScrollContainer.
case ScrollEvent _:
return false;
}
return base.Handle(e);
}
}
}
| // 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 osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Extensions.Color4Extensions;
using osuTK;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class DimmedLoadingLayer : OverlayContainer
{
private const float transition_duration = 250;
private readonly LoadingAnimation loading;
public DimmedLoadingLayer(float dimAmount = 0.5f, float iconScale = 1f)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(dimAmount),
},
loading = new LoadingAnimation { Scale = new Vector2(iconScale) },
};
}
protected override void PopIn()
{
this.FadeIn(transition_duration, Easing.OutQuint);
loading.Show();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.OutQuint);
loading.Hide();
}
protected override bool Handle(UIEvent e)
{
switch (e)
{
case ScrollEvent _:
return false;
}
return base.Handle(e);
}
}
}
| mit | C# |
bb0a7efda38f5bd4b0d82c565dd0fa37681abf19 | Fix the broken doc build. | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/Utilities/CameraEventRouter.cs | Assets/MixedRealityToolkit/Utilities/CameraEventRouter.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// A helper class to provide hooks into the Unity camera exclusive Lifecycle events
/// </summary>
public class CameraEventRouter : MonoBehaviour
{
/// <summary>
/// A callback to act upon MonoBehaviour.OnPreRender() without a script needing to exist on a Camera component
/// </summary>
public event Action<CameraEventRouter> OnCameraPreRender;
private void OnPreRender()
{
OnCameraPreRender?.Invoke(this);
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// A helper class to provide hooks into the Unity camera exclusive Lifecycle events
/// </summary>
public class CameraEventRouter : MonoBehaviour
{
/// <summary>
/// A callback to act upon <see cref="MonoBehaviour.OnPreRender()"/> without a script needing to exist on a <see cref="Camera"/> component
/// </summary>
public event Action<CameraEventRouter> OnCameraPreRender;
private void OnPreRender()
{
OnCameraPreRender?.Invoke(this);
}
}
} | mit | C# |
44aa2a4e76dc6cb857b740f8fabb34e537020c18 | Add problem 4. Photo Gallery | Peter-Georgiev/Programming.Fundamentals,Peter-Georgiev/Programming.Fundamentals | BasicSyntax-MoreExercises/04.PhotoGallery/PhotoGallery.cs | BasicSyntax-MoreExercises/04.PhotoGallery/PhotoGallery.cs | using System;
class PhotoGallery
{
static void Main()
{
int photosNumber = int.Parse(Console.ReadLine());
int day = int.Parse(Console.ReadLine());
int month = int.Parse(Console.ReadLine());
int year = int.Parse(Console.ReadLine());
int hours = int.Parse(Console.ReadLine());
int minutes = int.Parse(Console.ReadLine());
double size = double.Parse(Console.ReadLine());
int width = int.Parse(Console.ReadLine());
int height = int.Parse(Console.ReadLine());
string orientation = "square";
if (width > height)
{
orientation = "landscape";
}
else if (height > width)
{
orientation = "portrait";
}
string formatSize = "B";
if (size >= 1000000)
{
size /= 1000000d;
formatSize = "MB";
}
else if (size >= 100000)
{
size /= 1000;
formatSize = "KB";
}
Console.WriteLine($"Name: DSC_{photosNumber:D4}.jpg");
Console.WriteLine($"Date Taken: {day:D2}/{month:D2}/{year} {hours:D2}:{minutes:D2}");
Console.WriteLine($"Size: {size}{formatSize}");
Console.WriteLine($"Resolution: {width}x{height} ({orientation})");
}
} | using System;
class PhotoGallery
{
static void Main()
{
}
} | mit | C# |
649c3a8c11fc8c94489ab0cfe067e6e06e371fc8 | Increment version to 1.1.0.11 | MatthewSteeples/XeroAPI.Net,jcvandan/XeroAPI.Net,TDaphneB/XeroAPI.Net,XeroAPI/XeroAPI.Net | source/XeroApi/Properties/AssemblyInfo.cs | source/XeroApi/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.1.0.11")]
[assembly: AssemblyFileVersion("1.1.0.11")]
| 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("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.1.0.10")]
[assembly: AssemblyFileVersion("1.1.0.10")]
| mit | C# |
575de0ea038f865f40b0ef27ba523de7b994e016 | Fix tagstring | davidebbo-test/BlogConverter | BlogConverter/Program.cs | BlogConverter/Program.cs | using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlogConverter
{
class Program
{
static void Main(string[] args)
{
var root = XElement.Load(args[0]);
XNamespace ns = "http://www.w3.org/2005/Atom";
var entries = from entry in root.Elements(ns + "entry")
where entry.Element(ns + "category").Attribute("term").Value.Contains("kind#post")
select entry;
foreach (var entry in entries)
{
string title = entry.Element(ns + "title").Value;
title = Util.FixQuotes(title);
var link = entry.Elements(ns + "link").Where(e => e.Attribute("rel").Value == "alternate").FirstOrDefault();
if (link == null) continue;
string fileName = Path.GetFileNameWithoutExtension(link.Attribute("href").Value);
DateTime publishedDate = DateTime.Parse(entry.Element(ns + "published").Value);
string publishedString = publishedDate.ToString("yyyy-MM-dd");
var tags = from category in entry.Elements(ns + "category")
where category.Attribute("scheme").Value.Contains("ns#")
select category.Attribute("term").Value;
string tagString = "[" + String.Join(",", tags) + "]";
Console.WriteLine(tagString);
string content = entry.Element(ns + "content").Value;
var converter = new HtmlToMarkDownConverter(content);
string markDown = converter.Convert();
string fullFileName = String.Format("{0}-{1}.markdown", publishedString, fileName);
Console.WriteLine(fullFileName);
string contentTemplate=
@"---
layout: post
title: ""{0}""
comments: true
categories: {1}
---
{2}
";
File.WriteAllText(fullFileName, String.Format(contentTemplate, title, tagString, markDown));
}
}
}
}
| using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlogConverter
{
class Program
{
static void Main(string[] args)
{
var root = XElement.Load(args[0]);
XNamespace ns = "http://www.w3.org/2005/Atom";
var entries = from entry in root.Elements(ns + "entry")
where entry.Element(ns + "category").Attribute("term").Value.Contains("kind#post")
select entry;
foreach (var entry in entries)
{
string title = entry.Element(ns + "title").Value;
title = Util.FixQuotes(title);
var link = entry.Elements(ns + "link").Where(e => e.Attribute("rel").Value == "alternate").FirstOrDefault();
if (link == null) continue;
string fileName = Path.GetFileNameWithoutExtension(link.Attribute("href").Value);
DateTime publishedDate = DateTime.Parse(entry.Element(ns + "published").Value);
string publishedString = publishedDate.ToString("yyyy-MM-dd");
var tags = from category in entry.Elements(ns + "category")
where category.Attribute("scheme").Value.Contains("ns#")
select category.Attribute("term").Value;
string tagString = String.Join(" ", tags);
Console.WriteLine(tagString);
string content = entry.Element(ns + "content").Value;
var converter = new HtmlToMarkDownConverter(content);
string markDown = converter.Convert();
string fullFileName = String.Format("{0}-{1}.markdown", publishedString, fileName);
Console.WriteLine(fullFileName);
string contentTemplate=
@"---
layout: post
title: ""{0}""
comments: true
categories: {1}
---
{2}
";
File.WriteAllText(fullFileName, String.Format(contentTemplate, title, tagString, markDown));
}
}
}
}
| apache-2.0 | C# |
5a67218965bbbcbe96b1b4d1cc7f0fdaf36b236f | Make WaitHandle finalization-safe | jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm | stdlib/system-threading/WaitHandle.cs | stdlib/system-threading/WaitHandle.cs | namespace System.Threading
{
/// <summary>
/// A handle on which one can wait.
/// </summary>
public abstract class WaitHandle : IDisposable
{
// NOTE: this WaitHandle implementation is non-conforming.
// 'WaitOne()' and 'Dispose(bool)' are abstract instead of
// virtual.
//
// I'm not sure if that's such a big deal, though. It shouldn't
// really matter from a user's perspective and inheriting directly
// from WaitHandle in user code is usually rather useless.
protected WaitHandle()
{
isDisposed = false;
}
~WaitHandle()
{
if (!isDisposed)
{
Dispose(false);
}
}
private bool isDisposed;
public abstract bool WaitOne();
protected abstract void Dispose(bool explicitDisposing);
public virtual void Close()
{
Dispose();
}
public void Dispose()
{
isDisposed = true;
Dispose(true);
}
}
} | namespace System.Threading
{
/// <summary>
/// A handle on which one can wait.
/// </summary>
public abstract class WaitHandle : IDisposable
{
// NOTE: this WaitHandle implementation is non-conforming.
// 'WaitOne()' and 'Dispose(bool)' are abstract instead of
// virtual.
//
// I'm not sure if that's such a big deal, though. It shouldn't
// really matter from a user's perspective and inheriting directly
// from WaitHandle in user code is usually rather useless.
~WaitHandle()
{
Dispose(false);
}
public abstract bool WaitOne();
protected abstract void Dispose(bool explicitDisposing);
public virtual void Close()
{
Dispose(true);
}
public void Dispose()
{
Dispose(true);
}
}
} | mit | C# |
9dd2527ff723b727b6a946cc43c7aea95609383c | remove deprecated method | reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap | unity/demo/Assets/Scripts/Scene/UnityModelBuilder.cs | unity/demo/Assets/Scripts/Scene/UnityModelBuilder.cs | using UnityEngine;
using UtyDepend;
using UtyMap.Unity;
using Mesh = UtyMap.Unity.Mesh;
namespace Assets.Scripts.Scene
{
/// <summary>
/// Responsible for building Unity game objects from meshes and elements.
/// </summary>
internal class UnityModelBuilder
{
private readonly MaterialProvider _materialProvider;
private readonly PlaceElementBuilder _placeElementBuilder;
[Dependency]
public UnityModelBuilder(MaterialProvider materialProvider)
{
_materialProvider = materialProvider;
_placeElementBuilder = new PlaceElementBuilder(_materialProvider);
}
/// <inheritdoc />
public void BuildElement(Tile tile, Element element)
{
// TODO Add more custom builders
if (element.Styles["builders"].Contains("info"))
_placeElementBuilder.Build(tile, element).transform.parent = tile.GameObject.transform;
}
/// <inheritdoc />
public void BuildMesh(Tile tile, Mesh mesh)
{
var gameObject = new GameObject(mesh.Name);
var uMesh = new UnityEngine.Mesh();
uMesh.vertices = mesh.Vertices;
uMesh.triangles = mesh.Triangles;
uMesh.colors = mesh.Colors;
uMesh.uv = mesh.Uvs;
uMesh.uv2 = mesh.Uvs2;
uMesh.uv3 = mesh.Uvs3;
uMesh.RecalculateNormals();
gameObject.isStatic = true;
gameObject.AddComponent<MeshFilter>().mesh = uMesh;
gameObject.AddComponent<MeshRenderer>().sharedMaterial =
_materialProvider.GetSharedMaterial(@"Materials/Default");
gameObject.AddComponent<MeshCollider>();
gameObject.transform.parent = tile.GameObject.transform;
}
}
} | using UnityEngine;
using UtyDepend;
using UtyMap.Unity;
using Mesh = UtyMap.Unity.Mesh;
namespace Assets.Scripts.Scene
{
/// <summary>
/// Responsible for building Unity game objects from meshes and elements.
/// </summary>
internal class UnityModelBuilder
{
private readonly MaterialProvider _materialProvider;
private readonly PlaceElementBuilder _placeElementBuilder;
[Dependency]
public UnityModelBuilder(MaterialProvider materialProvider)
{
_materialProvider = materialProvider;
_placeElementBuilder = new PlaceElementBuilder(_materialProvider);
}
/// <inheritdoc />
public void BuildElement(Tile tile, Element element)
{
// TODO Add more custom builders
if (element.Styles["builders"].Contains("info"))
_placeElementBuilder.Build(tile, element).transform.parent = tile.GameObject.transform;
}
/// <inheritdoc />
public void BuildMesh(Tile tile, Mesh mesh)
{
EnsureTile(tile);
var gameObject = new GameObject(mesh.Name);
var uMesh = new UnityEngine.Mesh();
uMesh.vertices = mesh.Vertices;
uMesh.triangles = mesh.Triangles;
uMesh.colors = mesh.Colors;
uMesh.uv = mesh.Uvs;
uMesh.uv2 = mesh.Uvs2;
uMesh.uv3 = mesh.Uvs3;
uMesh.RecalculateNormals();
gameObject.isStatic = true;
gameObject.AddComponent<MeshFilter>().mesh = uMesh;
gameObject.AddComponent<MeshRenderer>().sharedMaterial =
_materialProvider.GetSharedMaterial(@"Materials/Default");
gameObject.AddComponent<MeshCollider>();
gameObject.transform.parent = tile.GameObject.transform;
}
}
} | apache-2.0 | C# |
c00e944eb53afad7ffe64c65bf76a7224c3497c5 | increase Title size | AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/framework,MehdyKarimpour/extensions,signumsoftware/extensions,MehdyKarimpour/extensions,signumsoftware/framework,AlejandroCano/extensions | Signum.Entities.Extensions/Excel/ExcelAttachmentEntity.cs | Signum.Entities.Extensions/Excel/ExcelAttachmentEntity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Utilities;
using Signum.Entities.Files;
using System.Linq.Expressions;
using System.ComponentModel;
using Signum.Utilities.ExpressionTrees;
using Signum.Entities.UserQueries;
using Signum.Entities.Mailing;
namespace Signum.Entities.Excel
{
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class ExcelAttachmentEntity : Entity, IAttachmentGeneratorEntity
{
[NotNullable, SqlDbType(Size = 100)]
string fileName;
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100), FileNameValidator]
public string FileName
{
get { return fileName; }
set
{
if (Set(ref fileName, value))
FileNameNode = null;
}
}
[Ignore]
internal object FileNameNode;
[SqlDbType(Size = 300)]
string title;
[StringLengthValidator(AllowNulls = true, Min = 3, Max = 300)]
public string Title
{
get { return title; }
set
{
if (Set(ref title, value))
TitleNode = null;
}
}
[Ignore]
internal object TitleNode;
[NotNullable]
[NotNullValidator]
public Lite<UserQueryEntity> UserQuery { get; set; }
[ImplementedByAll]
public Lite<Entity> Related { get; set; }
[Ignore]
public EmailTemplateEntity Template { get; set; }
static Expression<Func<ExcelAttachmentEntity, string>> ToStringExpression = @this => @this.FileName;
[ExpressionField]
public override string ToString()
{
return ToStringExpression.Evaluate(this);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Utilities;
using Signum.Entities.Files;
using System.Linq.Expressions;
using System.ComponentModel;
using Signum.Utilities.ExpressionTrees;
using Signum.Entities.UserQueries;
using Signum.Entities.Mailing;
namespace Signum.Entities.Excel
{
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class ExcelAttachmentEntity : Entity, IAttachmentGeneratorEntity
{
[NotNullable, SqlDbType(Size = 100)]
string fileName;
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100), FileNameValidator]
public string FileName
{
get { return fileName; }
set
{
if (Set(ref fileName, value))
FileNameNode = null;
}
}
[Ignore]
internal object FileNameNode;
[SqlDbType(Size = 50)]
string title;
[StringLengthValidator(AllowNulls = true, Min = 3, Max = 50)]
public string Title
{
get { return title; }
set
{
if (Set(ref title, value))
TitleNode = null;
}
}
[Ignore]
internal object TitleNode;
[NotNullable]
[NotNullValidator]
public Lite<UserQueryEntity> UserQuery { get; set; }
[ImplementedByAll]
public Lite<Entity> Related { get; set; }
[Ignore]
public EmailTemplateEntity Template { get; set; }
static Expression<Func<ExcelAttachmentEntity, string>> ToStringExpression = @this => @this.FileName;
[ExpressionField]
public override string ToString()
{
return ToStringExpression.Evaluate(this);
}
}
}
| mit | C# |
a62a175e8d05103b74c8a41890e8666e6add108a | fix clipboard error | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Controls/ChatControls/DefaultMessageBody.xaml.cs | TCC.Core/Controls/ChatControls/DefaultMessageBody.xaml.cs | using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TCC.Data;
namespace TCC.Controls.ChatControls
{
/// <summary>
/// Interaction logic for DefaultMessageBody.xaml
/// </summary>
public partial class DefaultMessageBody : UserControl
{
public DefaultMessageBody()
{
InitializeComponent();
}
private void I_Click(object sender, RoutedEventArgs e)
{
try
{
Clipboard.SetText(((ChatMessage)DataContext).ToString());
}
catch (System.Exception)
{
}
}
private void WrapPanel_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
((FrameworkElement)sender).ContextMenu.IsOpen = true;
}
}
}
| using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TCC.Data;
namespace TCC.Controls.ChatControls
{
/// <summary>
/// Interaction logic for DefaultMessageBody.xaml
/// </summary>
public partial class DefaultMessageBody : UserControl
{
public DefaultMessageBody()
{
InitializeComponent();
}
private void I_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(((ChatMessage)DataContext).ToString());
}
private void WrapPanel_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
((FrameworkElement)sender).ContextMenu.IsOpen = true;
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.