doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
7aa947a8-c190-4c67-9677-6c4c37b14aaf | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel.DataAnnotations;
namespace VotingApplication.Web.Api.Models.DBViewModels
{
public class PollCreationRequestModel
{
[Required]
public string Name { get; set; }
[Required]
public string Creator { get; set; }
[Required]
public string VotingStrategy { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(1, int.MaxValue)]
public int MaxPoints { get; set; }
[Range(1, int.MaxValue)]
public int MaxPerVote { get; set; }
public long TemplateId { get; set; }
public bool InviteOnly { get; set; }
public bool NamedVoting { get; set; }
public bool RequireAuth { get; set; }
public bool Expires { get; set; }
public DateTimeOffset ExpiryDate { get; set; }
public bool OptionAdding { get; set; }
}
}```
Fix expiry date on create new poll | ```c#
using System;
using System.ComponentModel.DataAnnotations;
namespace VotingApplication.Web.Api.Models.DBViewModels
{
public class PollCreationRequestModel
{
[Required]
public string Name { get; set; }
[Required]
public string Creator { get; set; }
[Required]
public string VotingStrategy { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(1, int.MaxValue)]
public int MaxPoints { get; set; }
[Range(1, int.MaxValue)]
public int MaxPerVote { get; set; }
public long TemplateId { get; set; }
public bool InviteOnly { get; set; }
public bool NamedVoting { get; set; }
public bool RequireAuth { get; set; }
public bool Expires { get; set; }
public DateTimeOffset? ExpiryDate { get; set; }
public bool OptionAdding { get; set; }
}
}``` |
fecdb4d6-ec72-4839-baea-00f535293abd | {
"language": "C#"
} | ```c#
#region
using System;
using Tabster.Core.Plugins;
#endregion
namespace TextFile
{
public class TextFilePlugin : ITabsterPlugin
{
#region Implementation of ITabsterPlugin
public string Author
{
get { return "Nate Shoffner"; }
}
public string Copyright
{
get { return "Copyright © Nate Shoffner 2014"; }
}
public string Description
{
get { return "Supports importing and exporting to/from text (.txt) files. "; }
}
public string DisplayName
{
get { return "Textfile support"; }
}
public Version Version
{
get { return new Version("1.0"); }
}
public Uri Website
{
get { return new Uri("http://nateshoffner.com"); }
}
public void Activate()
{
// not implemented
}
public void Deactivate()
{
// not implemented
}
public Type[] Types
{
get { return new[] {typeof (TextFileExporter), typeof (TextFileImporter)}; }
}
#endregion
}
}```
Add Initialize() method to ITabsterPlugin | ```c#
#region
using System;
using Tabster.Core.Plugins;
#endregion
namespace TextFile
{
public class TextFilePlugin : ITabsterPlugin
{
#region Implementation of ITabsterPlugin
public string Author
{
get { return "Nate Shoffner"; }
}
public string Copyright
{
get { return "Copyright © Nate Shoffner 2014"; }
}
public string Description
{
get { return "Supports importing and exporting to/from text (.txt) files. "; }
}
public string DisplayName
{
get { return "Textfile support"; }
}
public Version Version
{
get { return new Version("1.0"); }
}
public Uri Website
{
get { return new Uri("http://nateshoffner.com"); }
}
public void Activate()
{
// not implemented
}
public void Deactivate()
{
// not implemented
}
public void Initialize()
{
// not implemented
}
public Type[] Types
{
get { return new[] {typeof (TextFileExporter), typeof (TextFileImporter)}; }
}
#endregion
}
}``` |
9eb403d2-0ef2-4b2f-a891-f4b09747f238 | {
"language": "C#"
} | ```c#
using Core;
using StructureMap;
using System;
using Xunit;
namespace Tests
{
public class ValidationTests
{
[Fact]
public void VerifyValidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
container.AssertConfigurationIsValid();
}
[Fact]
public void VerifyInvalidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<BrokenService>();
});
Assert.Throws<StructureMapConfigurationException>(
() => container.AssertConfigurationIsValid());
}
public class BrokenService : IService
{
public string Id { get; private set; }
[ValidationMethod]
public void BrokenMethod()
{
throw new ApplicationException();
}
}
}
}
```
Add AssertConfigurationIsValid test for missing ctor parameter | ```c#
using Core;
using StructureMap;
using System;
using Xunit;
namespace Tests
{
public class ValidationTests
{
[Fact]
public void MissingRequiredConstructorArgument()
{
var container = new Container(x =>
{
x.For<IService>().Use<ServiceWithCtorArg>();
});
Assert.Throws<StructureMapConfigurationException>(
() => container.AssertConfigurationIsValid());
}
[Fact]
public void VerifyValidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
container.AssertConfigurationIsValid();
}
[Fact]
public void VerifyInvalidConfiguration()
{
var container = new Container(x =>
{
x.For<IService>().Use<BrokenService>();
});
Assert.Throws<StructureMapConfigurationException>(
() => container.AssertConfigurationIsValid());
}
public class BrokenService : IService
{
public string Id { get; private set; }
[ValidationMethod]
public void BrokenMethod()
{
throw new ApplicationException();
}
}
}
}
``` |
828a8a90-e2aa-42db-92b7-ac4d5a6b0efa | {
"language": "C#"
} | ```c#
@page
@model Disable2faModel
@{
ViewData["Title"] = "Disable two-factor authentication (2FA)";
ViewData["ActivePage"] = "TwoFactorAuthentication";
}
<h2>@ViewData["Title"]</h2>
<div class="alert alert-warning" role="alert">
<p>
<span class="glyphicon glyphicon-warning-sign"></span>
<strong>This action only disables 2FA.</strong>
</p>
<p>
Disabling 2FA does not change the keys used in authenticator apps. If you wish to change the key
used in an authenticator app you should <a href="./ResetAuthenticator">reset your authenticator keys.</a>
</p>
</div>
<div>
<form method="post" class="form-group">
<button class="btn btn-danger" type="submit">Disable 2FA</button>
</form>
</div>
```
Use anchor tag helper instead of hard coded href | ```c#
@page
@model Disable2faModel
@{
ViewData["Title"] = "Disable two-factor authentication (2FA)";
ViewData["ActivePage"] = "TwoFactorAuthentication";
}
<h2>@ViewData["Title"]</h2>
<div class="alert alert-warning" role="alert">
<p>
<span class="glyphicon glyphicon-warning-sign"></span>
<strong>This action only disables 2FA.</strong>
</p>
<p>
Disabling 2FA does not change the keys used in authenticator apps. If you wish to change the key
used in an authenticator app you should <a asp-page="./ResetAuthenticator">reset your authenticator keys.</a>
</p>
</div>
<div>
<form method="post" class="form-group">
<button class="btn btn-danger" type="submit">Disable 2FA</button>
</form>
</div>
``` |
241dbe5f-219f-47d4-a8e7-6c0ced08eaa9 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsCheckbox : SettingsItem<bool>
{
private OsuCheckbox checkbox;
protected override Drawable CreateControl() => checkbox = new OsuCheckbox();
public override string LabelText
{
set => checkbox.LabelText = value;
}
}
}
```
Fix settings checkboxes not being searchable | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsCheckbox : SettingsItem<bool>
{
private OsuCheckbox checkbox;
private string labelText;
protected override Drawable CreateControl() => checkbox = new OsuCheckbox();
public override string LabelText
{
get => labelText;
set => checkbox.LabelText = labelText = value;
}
}
}
``` |
24ba7c6c-bb2b-4efe-9cba-edd103f8e019 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using YaTools.Yaml;
using Raven;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Storage;
using Raven.Database;
namespace Craftitude
{
public class RepositoryCache : IDisposable
{
internal EmbeddableDocumentStore _db;
internal Cache _cache;
internal RepositoryCache(Cache cache, string cacheId)
{
_cache = cache;
_db = new EmbeddableDocumentStore()
{
DataDirectory = Path.Combine(_cache._path, cacheId)
};
if (!Directory.Exists(_db.DataDirectory))
Directory.CreateDirectory(_db.DataDirectory);
_db.Initialize();
}
public void Dispose()
{
if (!_db.WasDisposed)
_db.Dispose();
}
public void SavePackage(string id, Package package)
{
using (var session = _db.OpenSession())
{
session.Store(package, id);
}
}
}
}
```
Allow deletion and reading of saved package information. | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using YaTools.Yaml;
using Raven;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Storage;
using Raven.Database;
namespace Craftitude
{
public class RepositoryCache : IDisposable
{
internal EmbeddableDocumentStore _db;
internal Cache _cache;
internal RepositoryCache(Cache cache, string cacheId)
{
_cache = cache;
_db = new EmbeddableDocumentStore()
{
DataDirectory = Path.Combine(_cache._path, cacheId)
};
if (!Directory.Exists(_db.DataDirectory))
Directory.CreateDirectory(_db.DataDirectory);
_db.Initialize();
}
public void Dispose()
{
if (!_db.WasDisposed)
_db.Dispose();
}
public void DeletePackage(string id, Package package)
{
using (var session = _db.OpenSession())
{
session.Delete(package);
session.SaveChanges();
}
}
public void SavePackage(string id, Package package)
{
using (var session = _db.OpenSession())
{
session.Store(package, id);
session.SaveChanges();
}
}
public Package[] GetPackages(params string[] IDs)
{
using (var session = _db.OpenSession())
{
return session.Load<Package>(IDs);
}
}
public Package GetPackage(string ID)
{
using (var session = _db.OpenSession())
{
return session.Load<Package>(ID);
}
}
}
}
``` |
216defd9-956e-43ea-b8c5-44845c77b6db | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Mappings
{
public interface IMapping<T>
{
void print();
T get_pos(ICoordinate coord);
bool pos_exists(ICoordinate coord);
bool add_to_pos(T addition, ICoordinate coord);
bool remove_from_pos(ICoordinate coord);
}
public interface IMapUpdatable
{
bool can_move(ICoordinate startCoord, ICoordinate endCoord);
bool move(ICoordinate startCoord, ICoordinate endCoord);
}
public interface IMapUpdateReadable<T>
{
void print();
T get_pos(ICoordinate coord);
bool pos_exists(ICoordinate coord);
}
}
```
Split apart and made generic the interfaces for maps following interface segregation and CQRS | ```c#
using Engine.Mappings.Coordinates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Mappings
{
public interface IMapWriteable<T>
{
bool can_move(ICoordinate<T> startCoord, ICoordinate<T> endCoord);
bool move(ICoordinate<T> startCoord, ICoordinate<T> endCoord);
}
public interface IMapReadable<T, S>
{
void print();
S get_pos(ICoordinate<T> coord);
bool pos_exists(ICoordinate<T> coord);
}
}
``` |
34435ce6-987d-46d6-b1a4-51dce4001e06 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WinSerHost
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private ServiceHost host;
protected override void OnStart(string[] args)
{
if (host != null)
{
host.Close();
}
host = new ServiceHost(typeof(BankAService.BankAService));
host.Open();
}
protected override void OnStop()
{
if (host != null)
{
host.Close();
}
host = null;
}
}
}
```
Add command in the comment. | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WinSerHost
{
// For this service to work correctly,
// we must run the following command in Admin mode,
// netsh http add urlacl url=http://+:9889/BankA user="NT AUTHORITY\NETWORKSERVICE"
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private ServiceHost host;
protected override void OnStart(string[] args)
{
if (host != null)
{
host.Close();
}
host = new ServiceHost(typeof(BankAService.BankAService));
host.Open();
}
protected override void OnStop()
{
if (host != null)
{
host.Close();
}
host = null;
}
}
}
``` |
179c9b29-e6ab-4754-95d1-8b6d89e461b8 | {
"language": "C#"
} | ```c#
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("ZeroLog.Tests")]
[assembly: InternalsVisibleTo("ZeroLog.Benchmarks")]
```
Use SkipLocalsInit on .NET 5 | ```c#
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("ZeroLog.Tests")]
[assembly: InternalsVisibleTo("ZeroLog.Benchmarks")]
#if NETCOREAPP && !NETCOREAPP2_1
[module: SkipLocalsInit]
#endif
``` |
2a206e31-01d3-41de-9905-30981ae228ca | {
"language": "C#"
} | ```c#
using SnakeApp.Graphics;
using System;
namespace SnakeApp.Models
{
public class Food
{
public Food()
{
DateCreated = DateTime.Now;
}
public Food(byte score, Point position, byte secondsToLive) : this()
{
Score = score;
Position = position;
SecondsToLive = secondsToLive;
}
public Point Position { get; private set; }
public DateTime DateCreated { get; private set; }
public byte Score { get; private set; }
public bool DrawnAsRotten { get; set; }
public bool IsConsumed { get; set; }
public byte SecondsToLive { get; set; }
}
}```
Make the food TTL setter private. | ```c#
using SnakeApp.Graphics;
using System;
namespace SnakeApp.Models
{
public class Food
{
public Food()
{
DateCreated = DateTime.Now;
}
public Food(byte score, Point position, byte secondsToLive) : this()
{
Score = score;
Position = position;
SecondsToLive = secondsToLive;
}
public Point Position { get; private set; }
public DateTime DateCreated { get; private set; }
public byte Score { get; private set; }
public byte SecondsToLive { get; private set; }
public bool DrawnAsRotten { get; set; }
public bool IsConsumed { get; set; }
}
}``` |
ed306984-395c-47b9-9972-97e0fd9d40c2 | {
"language": "C#"
} | ```c#
namespace Gu.Wpf.Geometry.UiTests
{
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public class MainWindowTests
{
[Test]
public void ClickAllTabs()
{
// Just a smoke test so that we do not explode.
using (var app = Application.Launch("Gu.Wpf.Geometry.Demo.exe"))
{
var window = app.MainWindow;
var tab = window.FindTabControl();
foreach (var tabItem in tab.Items)
{
_ = tabItem.Select();
}
}
}
}
}
```
Add timeout waiting for MainWindow. | ```c#
namespace Gu.Wpf.Geometry.UiTests
{
using System;
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public class MainWindowTests
{
[Test]
public void ClickAllTabs()
{
// Just a smoke test so that we do not explode.
using (var app = Application.Launch("Gu.Wpf.Geometry.Demo.exe"))
{
app.WaitForMainWindow(TimeSpan.FromSeconds(10));
var window = app.MainWindow;
var tab = window.FindTabControl();
foreach (var tabItem in tab.Items)
{
_ = tabItem.Select();
}
}
}
}
}
``` |
b351d2af-5220-4844-8dd8-b1828f9d29c3 | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="ListaOperatoriResult.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.API.Models.Classi.Autenticazione;
using SO115App.Models.Classi.Condivise;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Models.Servizi.CQRS.Queries.GestioneUtente.ListaOperatori
{
public class ListaOperatoriResult
{
public Paginazione Pagination { get; set; }
public List<Utente> DataArray { get; set; }
}
}
```
Add - Aggiunta proprietà lista sedi alla result degli utenti nella gestione utenti | ```c#
//-----------------------------------------------------------------------
// <copyright file="ListaOperatoriResult.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.API.Models.Classi.Autenticazione;
using SO115App.Models.Classi.Condivise;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Models.Servizi.CQRS.Queries.GestioneUtente.ListaOperatori
{
public class ListaOperatoriResult
{
public Paginazione Pagination { get; set; }
public List<Utente> DataArray { get; set; }
public List<string> ListaSediPresenti { get; set; }
}
}
``` |
be0371c8-0f73-4b08-af29-0137a8e36ffd | {
"language": "C#"
} | ```c#
// Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace Google.Cloud.Firestore.Admin.V1.SmokeTests
{
public sealed class FirestoreAdminSmokeTest
{
private const string ProjectEnvironmentVariable = "FIRESTORE_TEST_PROJECT";
public static int Main(string[] args)
{
string projectId = Environment.GetEnvironmentVariable(ProjectEnvironmentVariable);
if (string.IsNullOrEmpty(projectId))
{
Console.WriteLine($"Environment variable {ProjectEnvironmentVariable} must be set.");
return 1;
}
// Create client
FirestoreAdminClient client = FirestoreAdminClient.Create();
// Initialize request argument
ParentName parentName = new ParentName(projectId, "(default)", "collection");
// Call API method
var indexes = client.ListIndexes(parentName);
// Show the result
foreach (var index in indexes)
{
Console.WriteLine(index);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
```
Fix manual smoke test for Google.Cloud.Firestore.Admin.V1 | ```c#
// Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace Google.Cloud.Firestore.Admin.V1.SmokeTests
{
public sealed class FirestoreAdminSmokeTest
{
private const string ProjectEnvironmentVariable = "FIRESTORE_TEST_PROJECT";
public static int Main(string[] args)
{
string projectId = Environment.GetEnvironmentVariable(ProjectEnvironmentVariable);
if (string.IsNullOrEmpty(projectId))
{
Console.WriteLine($"Environment variable {ProjectEnvironmentVariable} must be set.");
return 1;
}
// Create client
FirestoreAdminClient client = FirestoreAdminClient.Create();
// Initialize request argument
CollectionGroupName collectionGroupName = CollectionGroupName.FromProjectDatabaseCollection(projectId, "(default)", "collection");
// Call API method
var indexes = client.ListIndexes(collectionGroupName);
// Show the result
foreach (var index in indexes)
{
Console.WriteLine(index);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
``` |
d85a8dc8-4c90-4cbc-8698-9fb7a4fa82c9 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouthOfEvilController : MonoBehaviour {
public List<EvilEyeScript> evilEyes;
public int mouthOfEvilHealth = 12;
private int hitsLeftInPhase;
public int maxHitsPerPhase = 4;
public bool isInPhase = false;
void Awake () {
foreach(EvilEyeScript eye in evilEyes){
eye.isActive = false;
}
hitsLeftInPhase = 4;
isInPhase = false;
}
// Update is called once per frame
void Update () {
}
}
```
Add non-complete boss controller script | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouthOfEvilController : MonoBehaviour {
public List<EvilEyeScript> evilEyes;
public int mouthOfEvilHealth = 12;
private int hitsLeftInPhase;
public int maxHitsPerPhase = 4;
public bool isInPhase = false;
public int totalPhases;
public int currentPhase;
public bool isBossFightActive = false;
void Awake () {
foreach(EvilEyeScript eye in evilEyes){
eye.isActive = false;
}
hitsLeftInPhase = 4;
isInPhase = false;
}
// Update is called once per frame
void Update () {
if(isBossFightActive){
if(hitsLeftInPhase <= 0){
IteratePhase();
}
}
}
private void IteratePhase(){
currentPhase++;
return;
}
//stolen from: https://forum.unity.com/threads/make-a-sprite-flash.224086/
IEnumerator FlashSprites(SpriteRenderer[] sprites, int numTimes, float delay, bool disable = false) {
// number of times to loop
for (int loop = 0; loop < numTimes; loop++) {
// cycle through all sprites
for (int i = 0; i < sprites.Length; i++) {
if (disable) {
// for disabling
sprites[i].enabled = false;
} else {
// for changing the alpha
sprites[i].color = new Color(sprites[i].color.r, sprites[i].color.g, sprites[i].color.b, 0.5f);
}
}
// delay specified amount
yield return new WaitForSeconds(delay);
// cycle through all sprites
for (int i = 0; i < sprites.Length; i++) {
if (disable) {
// for disabling
sprites[i].enabled = true;
} else {
// for changing the alpha
sprites[i].color = new Color(sprites[i].color.r, sprites[i].color.g, sprites[i].color.b, 1);
}
}
// delay specified amount
yield return new WaitForSeconds(delay);
}
}
}
``` |
741c3db9-508e-441e-8fb4-9b5dfec02205 | {
"language": "C#"
} | ```c#
using System;
namespace PropertyChanged
{
/// <summary>
/// Include a <see cref="Type"/> for notification.
/// The INotifyPropertyChanged interface is added to the type.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ImplementPropertyChangedAttribute : Attribute
{
}
}```
Improve the interface documentation for the attribute | ```c#
using System;
namespace PropertyChanged
{
/// <summary>
/// Specifies that PropertyChanged Notification will be added to a class.
/// PropertyChanged.Fody will weave the <c>INotifyPropertyChanged</c> interface and implementation into the class.
/// When the value of a property changes, the PropertyChanged notification will be raised automatically
/// See https://github.com/Fody/PropertyChanged for more information.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ImplementPropertyChangedAttribute : Attribute
{
}
}
``` |
b5fa5026-e5be-4830-9f50-68eac6aa3ec8 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using NBi.Xml.Constraints;
using NBi.Xml.Systems;
using NBi.NUnit.Builder.Helper;
using NBi.Core.Configuration;
using NBi.Core.Injection;
using NBi.Core.Variable;
using NBi.Core.Scalar.Resolver;
namespace NBi.NUnit.Builder
{
abstract class AbstractScalarBuilder : AbstractTestCaseBuilder
{
protected AbstractSystemUnderTestXml SystemUnderTestXml { get; set; }
protected ScalarHelper Helper { get; private set; }
public override void Setup(AbstractSystemUnderTestXml sutXml, AbstractConstraintXml ctrXml, IConfiguration config, IDictionary<string, ITestVariable> variables, ServiceLocator serviceLocator)
{
base.Setup(sutXml, ctrXml, config, variables, serviceLocator);
Helper = new ScalarHelper(ServiceLocator, Variables);
}
protected override void BaseSetup(AbstractSystemUnderTestXml sutXml, AbstractConstraintXml ctrXml)
{
if (!(sutXml is ScalarXml))
throw new ArgumentException("System-under-test must be a 'ScalarXml'");
SystemUnderTestXml = sutXml;
}
protected override void BaseBuild()
{
if (SystemUnderTestXml is ScalarXml)
SystemUnderTest = InstantiateSystemUnderTest((ScalarXml)SystemUnderTestXml);
}
protected virtual IScalarResolver<decimal> InstantiateSystemUnderTest(ScalarXml scalarXml) => Helper.InstantiateResolver<decimal>(scalarXml);
}
}
```
Fix issue with Scalar testing where default connection-strings where not forwarded | ```c#
using System;
using System.Collections.Generic;
using NBi.Xml.Constraints;
using NBi.Xml.Systems;
using NBi.NUnit.Builder.Helper;
using NBi.Core.Configuration;
using NBi.Core.Injection;
using NBi.Core.Variable;
using NBi.Core.Scalar.Resolver;
using NBi.Xml.Settings;
namespace NBi.NUnit.Builder
{
abstract class AbstractScalarBuilder : AbstractTestCaseBuilder
{
protected ScalarXml SystemUnderTestXml { get; set; }
public override void Setup(AbstractSystemUnderTestXml sutXml, AbstractConstraintXml ctrXml, IConfiguration config, IDictionary<string, ITestVariable> variables, ServiceLocator serviceLocator)
=> base.Setup(sutXml, ctrXml, config, variables, serviceLocator);
protected override void BaseSetup(AbstractSystemUnderTestXml sutXml, AbstractConstraintXml ctrXml)
=> SystemUnderTestXml = sutXml as ScalarXml
?? throw new ArgumentException("System-under-test must be a 'ScalarXml'");
protected override void BaseBuild()
=> SystemUnderTest = InstantiateSystemUnderTest(SystemUnderTestXml);
protected virtual IScalarResolver<decimal> InstantiateSystemUnderTest(ScalarXml scalarXml)
=> new ScalarHelper(ServiceLocator, scalarXml.Settings, SettingsXml.DefaultScope.SystemUnderTest, Variables).InstantiateResolver<decimal>(scalarXml);
}
}
``` |
0aa431be-c925-497d-8044-007ba6330845 | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Dump<T>(this T value) {
value.Inspect(title: "Dump");
}
public static void Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
}
}
```
Return object from Dump/Inspect extension methods. | ```c#
using System.ComponentModel;
using System.Text;
using SharpLab.Runtime.Internal;
public static class SharpLabObjectExtensions {
// LinqPad/etc compatibility only
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Dump<T>(this T value)
=> value.Inspect(title: "Dump");
public static T Inspect<T>(this T value, string title = "Inspect") {
var builder = new StringBuilder();
ObjectAppender.Append(builder, value);
var data = new SimpleInspectionResult(title, builder);
Output.Write(data);
return value;
}
}
``` |
3c94e2c7-6e1b-4c44-8e37-568f42524869 | {
"language": "C#"
} | ```c#
using System;
namespace AppHarbor.Commands
{
public class AddConfigCommand : ICommand
{
public AddConfigCommand()
{
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
```
Initialize AppConfigCommand with an IApplicationConfiguration | ```c#
using System;
namespace AppHarbor.Commands
{
public class AddConfigCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
public AddConfigCommand(IApplicationConfiguration applicationConfiguration)
{
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
``` |
6ec9523b-4d41-4f3a-86c9-bb129220f302 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Mapping;
namespace FluentNHibernate.AutoMap
{
public class AutoMapper
{
private readonly List<IAutoMapper> _mappingRules;
public AutoMapper(Conventions conventions)
{
_mappingRules = new List<IAutoMapper>
{
new AutoMapIdentity(conventions),
new AutoMapVersion(conventions),
new AutoMapColumn(conventions),
new AutoMapManyToOne(conventions),
new AutoMapOneToMany(conventions),
};
}
public AutoMap<T> MergeMap<T>(AutoMap<T> map)
{
foreach (var property in typeof(T).GetProperties())
{
if (!property.PropertyType.IsEnum)
{
foreach (var rule in _mappingRules)
{
if (rule.MapsProperty(property))
{
if (map.PropertiesMapped.Count(p => p.Name == property.Name) == 0)
{
rule.Map(map, property);
break;
}
}
}
}
}
return map;
}
public AutoMap<T> Map<T>()
{
var classMap = (AutoMap<T>)Activator.CreateInstance(typeof(AutoMap<T>));
return MergeMap(classMap);
}
}
}```
Change automapper to whitelist classes rather than blacklist enums. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Mapping;
namespace FluentNHibernate.AutoMap
{
public class AutoMapper
{
private readonly List<IAutoMapper> _mappingRules;
public AutoMapper(Conventions conventions)
{
_mappingRules = new List<IAutoMapper>
{
new AutoMapIdentity(conventions),
new AutoMapVersion(conventions),
new AutoMapColumn(conventions),
new AutoMapManyToOne(conventions),
new AutoMapOneToMany(conventions),
};
}
public AutoMap<T> MergeMap<T>(AutoMap<T> map)
{
foreach (var property in typeof(T).GetProperties())
{
if (property.PropertyType.IsClass)
{
foreach (var rule in _mappingRules)
{
if (rule.MapsProperty(property))
{
if (map.PropertiesMapped.Count(p => p.Name == property.Name) == 0)
{
rule.Map(map, property);
break;
}
}
}
}
}
return map;
}
public AutoMap<T> Map<T>()
{
var classMap = (AutoMap<T>)Activator.CreateInstance(typeof(AutoMap<T>));
return MergeMap(classMap);
}
}
}``` |
5a4c02e2-0cf7-44bd-b916-f57d31f85ef0 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[SerializeField]
private GameObject _prefab;
private Stack<GameObject> _pool;
public GameObject prefab
{
set {
_prefab = value;
}
}
//TODO: Add possibility to differentiate between prefabs
public GameObject GetGameObject()
{
if (_pool != null)
{
if (_pool.Count > 0)
return _pool.Pop();
else
return GameObject.Instantiate<GameObject>(_prefab);
}
else
{
_pool = new Stack<GameObject>();
return GameObject.Instantiate<GameObject>(_prefab);
}
}
public void Put(GameObject obj)
{
if (_pool == null)
_pool = new Stack<GameObject>();
_pool.Push(obj);
}
}
```
Restructure to start implementing category based pool. | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[SerializeField]
private GameObject _defaultPrefab;
#region Public methods and properties
public GameObject defaultPrefab
{
set
{
_defaultPrefab = value;
}
}
//TODO: Add possibility to differentiate between prefabs
public AudioObject GetFreeAudioObject(GameObject prefab = null)
{
return null;
}
#endregion
}
[System.Serializable]
public class PrefabBasedPool
{
public GameObject prefab;
public List<AudioObject> audioObjects;
}
``` |
b9d6808e-972e-408d-bb41-f7594db46f2d | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Mono.Options;
namespace Menora
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
var config = "TempConfig.json";
var help = false;
var minimize = false;
var optionSet = new OptionSet();
optionSet
.Add("c=|config=", "Change configuration file path", (v) => config = v)
.Add("m|minimize", "Start minimized", (v) => minimize = true)
.Add("h|help", "Display help and exit", (v) => help = true)
.Parse(args);
if (help)
{
using (var writer = new StringWriter())
{
writer.WriteLine(Application.ProductName);
writer.WriteLine();
optionSet.WriteOptionDescriptions(writer);
MessageBox.Show(writer.ToString(), Application.ProductName);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(config, minimize));
}
}
}
```
Change default configuration file name. | ```c#
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Mono.Options;
namespace Menora
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
var config = "Menora.json";
var help = false;
var minimize = false;
var optionSet = new OptionSet();
optionSet
.Add("c=|config=", "Change configuration file path", (v) => config = v)
.Add("m|minimize", "Start minimized", (v) => minimize = true)
.Add("h|help", "Display help and exit", (v) => help = true)
.Parse(args);
if (help)
{
using (var writer = new StringWriter())
{
writer.WriteLine(Application.ProductName);
writer.WriteLine();
optionSet.WriteOptionDescriptions(writer);
MessageBox.Show(writer.ToString(), Application.ProductName);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(config, minimize));
}
}
}
``` |
05fe798e-2443-4195-bfc7-2f6fdff34a30 | {
"language": "C#"
} | ```c#
namespace Playground.Leetcode
{
using System;
using System.Collections.Generic;
public static class CombinationSum
{
// Problem number 377. https://leetcode.com/problems/combination-sum-iv/
public static int CombinationSum4(int[] nums, int target)
{
//Array.Sort(nums);
var count = 0;
var countOfInterimSums = new Dictionary<int, int>();
count = Helper(nums, target, countOfInterimSums);
return count;
}
private static int Helper(
int[] nums,
int target,
Dictionary<int, int> cache)
{
if (target == 0)
{
return 1;
}
if (cache.ContainsKey(target))
{
return cache[target];
}
var count = 0;
foreach (var n in nums)
{
if (n > target)
{
}
else
{
var innerCount = Helper(nums, target - n, cache);
if (innerCount != 0)
{
count += innerCount;
}
}
}
cache[target] = count;
return count;
}
}
}```
Remove unnecessary using and comment. | ```c#
namespace Playground.Leetcode
{
using System.Collections.Generic;
public static class CombinationSum
{
// Problem number 377. https://leetcode.com/problems/combination-sum-iv/
public static int CombinationSum4(int[] nums, int target)
{
var count = 0;
var countOfInterimSums = new Dictionary<int, int>();
count = Helper(nums, target, countOfInterimSums);
return count;
}
private static int Helper(
int[] nums,
int target,
Dictionary<int, int> cache)
{
if (target == 0)
{
return 1;
}
if (cache.ContainsKey(target))
{
return cache[target];
}
var count = 0;
foreach (var n in nums)
{
if (n > target)
{
}
else
{
var innerCount = Helper(nums, target - n, cache);
if (innerCount != 0)
{
count += innerCount;
}
}
}
cache[target] = count;
return count;
}
}
}``` |
a655ef21-14a2-4f5c-932c-dfbd3e1d300f | {
"language": "C#"
} | ```c#
using System;
namespace RepositoryExceptions.Persistence
{
/// <summary>
/// New exception introduced
/// </summary>
public class UserNotFoundException : Exception
{
public UserNotFoundException() : base()
{
}
public UserNotFoundException(string message) : base(message)
{
}
}
}
```
Make new exception inherit from known type. Tests ok. | ```c#
using System;
namespace RepositoryExceptions.Persistence
{
/// <summary>
/// New exception introduced
/// </summary>
public class UserNotFoundException : EntityNotFoundException
{
public UserNotFoundException() : base()
{
}
public UserNotFoundException(string message) : base(message)
{
}
}
}
``` |
6288ea38-40b2-40d2-8f9c-0949f7c1c633 | {
"language": "C#"
} | ```c#
namespace Paydock_dotnet_sdk.Models
{
public class ChargeRequestStripeConnect : ChargeRequestBase
{
public MetaData meta;
}
public class MetaData
{
public string stripe_direct_account_id;
public string stripe_destination_account_id;
public string stripe_transfer_group;
public Transfer[] stripe_transfer;
}
public class Transfer
{
public decimal amount;
public string currency;
public string destination;
}
}```
Update stripe connect objects based on changes to the API | ```c#
namespace Paydock_dotnet_sdk.Models
{
public class ChargeRequestStripeConnect : ChargeRequestBase
{
public MetaData meta;
public Transfer[] transfer;
}
public class MetaData
{
public string stripe_direct_account_id;
public decimal stripe_application_fee;
public string stripe_destination_account_id;
public decimal stripe_destination_amount;
}
public class Transfer
{
public string stripe_transfer_group;
public TransferItems[] items;
public class TransferItems
{
public decimal amount;
public string currency;
public string destination;
}
}
}``` |
55fe7586-2bdf-4d9e-873f-fbdde8eea342 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Html.Abstractions
{
/// <summary>
/// A builder for HTML content.
/// </summary>
public interface IHtmlContentBuilder : IHtmlContent
{
/// <summary>
/// Appends an <see cref="IHtmlContent"/> instance.
/// </summary>
/// <param name="content">The <see cref="IHtmlContent"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(IHtmlContent content);
/// <summary>
/// Appends a <see cref="string"/> value. The value is treated as unencoded as-provided, and will be HTML
/// encoded before writing to output.
/// </summary>
/// <param name="content">The <see cref="string"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(string unencoded);
/// <summary>
/// Clears the content.
/// </summary>
void Clear();
}
}
```
Add AppendEncoded to the builder | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Html.Abstractions
{
/// <summary>
/// A builder for HTML content.
/// </summary>
public interface IHtmlContentBuilder : IHtmlContent
{
/// <summary>
/// Appends an <see cref="IHtmlContent"/> instance.
/// </summary>
/// <param name="content">The <see cref="IHtmlContent"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(IHtmlContent content);
/// <summary>
/// Appends a <see cref="string"/> value. The value is treated as unencoded as-provided, and will be HTML
/// encoded before writing to output.
/// </summary>
/// <param name="content">The <see cref="string"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder Append(string unencoded);
/// <summary>
/// Appends an HTML encoded <see cref="string"/> value. The value is treated as HTML encoded as-provided, and
/// no further encoding will be performed.
/// </summary>
/// <param name="content">The HTML encoded <see cref="string"/> to append.</param>
/// <returns>The <see cref="IHtmlContentBuilder"/>.</returns>
IHtmlContentBuilder AppendEncoded(string encoded);
/// <summary>
/// Clears the content.
/// </summary>
void Clear();
}
}
``` |
478aa15b-16d8-4aee-ab07-604b989d8b10 | {
"language": "C#"
} | ```c#
using SOVND.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace SOVND.Client.Views
{
/// <summary>
/// Interaction logic for NewChannel.xaml
/// </summary>
public partial class NewChannel : Window
{
public NewChannel()
{
InitializeComponent();
DataContext = new NewChannelViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(((NewChannelViewModel) DataContext).Register())
this.Close();
}
}
}
```
Return name of channel so we can subscribe to it | ```c#
using SOVND.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace SOVND.Client.Views
{
/// <summary>
/// Interaction logic for NewChannel.xaml
/// </summary>
public partial class NewChannel : Window
{
public string ChannelName { get; private set; }
public NewChannel()
{
InitializeComponent();
DataContext = new NewChannelViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (((NewChannelViewModel) DataContext).Register())
{
ChannelName = ((NewChannelViewModel) DataContext).Name;
this.Close();
}
}
}
}
``` |
f6878f96-69fb-4f57-8125-161ebaaf7884 | {
"language": "C#"
} | ```c#
namespace Downlink.GitHub
{
public class GitHubCredentials
{
public GitHubCredentials(string apiToken, string repoId)
{
Token = apiToken;
var segs = repoId.Split('/');
if (segs.Length != 2) throw new System.InvalidOperationException("Could not parse repository name");
Owner = segs[0];
Repo = segs[1];
}
public string Owner { get; }
public string Repo { get; }
public string Token { get; }
}
}
```
Fix bug in GitHub backend | ```c#
namespace Downlink.GitHub
{
public class GitHubCredentials
{
public GitHubCredentials(string apiToken, string repoId)
{
Token = apiToken;
var segs = repoId.Split('/');
if (segs.Length != 0) return;
if (segs.Length != 2) throw new System.InvalidOperationException("Could not parse repository name");
Owner = segs[0];
Repo = segs[1];
}
public string Owner { get; }
public string Repo { get; }
public string Token { get; }
}
}
``` |
6824db6b-1a05-4d92-818c-ef3bb214dcdb | {
"language": "C#"
} | ```c#
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("Obvs.RabbitMQ")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Obvs.RabbitMQ")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1712ac7-e84e-400d-9cbb-c3b8945377c6")]
// 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")]
```
Add author to assembly properties | ```c#
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("Obvs.RabbitMQ")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Christopher Read")]
[assembly: AssemblyProduct("Obvs.RabbitMQ")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1712ac7-e84e-400d-9cbb-c3b8945377c6")]
// 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")]
``` |
c84c941d-327f-4aa6-8543-b20d0ce83f06 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace AspNetCoreMvc
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
```
Use command line args when configuring the server | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace AspNetCoreMvc
{
public class Program
{
public static void Main (string[] args)
{
BuildWebHost (args).Run ();
}
public static IWebHost BuildWebHost (string[] args) =>
WebHost.CreateDefaultBuilder (args)
.UseConfiguration (new ConfigurationBuilder ().AddCommandLine (args).Build ())
.UseStartup<Startup> ()
.Build ();
}
}
``` |
694ff2e7-6a1c-493f-b00e-51e2884aaf99 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace LSDStay
{
public static class PSXFinder
{
public static Process FindPSX()
{
Process psx = Process.GetProcessesByName("psxfin").FirstOrDefault();
}
}
}
```
Add methods for opening and closing PSX handle | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace LSDStay
{
public static class PSXFinder
{
public static Process FindPSX()
{
Process psx = Process.GetProcessesByName("psxfin").FirstOrDefault();
return psx;
}
public static IntPtr OpenPSX(Process psx)
{
int PID = psx.Id;
IntPtr psxHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID);
}
public static void ClosePSX(IntPtr processHandle)
{
int result = Memory.CloseHandle(processHandle);
if (result == 0)
{
Console.WriteLine("ERROR: Could not close psx handle");
}
}
}
}
``` |
063a3780-fd2b-4dfb-8556-721233799c44 | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.Moq 3.0.1")]
```
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.Moq 3.0.1")]
``` |
c95af5e7-89f0-4c4e-85b9-44128f1339d0 | {
"language": "C#"
} | ```c#
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Threading.Tasks;
namespace Blogifier.Core.Services
{
public class MailKitService : IEmailService
{
private readonly IDataService _db;
public MailKitService(IDataService db)
{
_db = db;
}
public async Task<string> SendEmail(string fromName, string fromEmail, string toEmail, string subject, string content)
{
try
{
var mailKit = await _db.CustomFields.GetMailKitModel();
var message = new MimeMessage();
message.From.Add(new MailboxAddress(fromName, fromEmail));
message.To.Add(new MailboxAddress(toEmail));
message.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = content;
message.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(mailKit.EmailServer, mailKit.Port, mailKit.Options);
client.Authenticate(mailKit.EmailAddress, mailKit.EmailPassword);
client.Send(message);
client.Disconnect(true);
return await Task.FromResult("");
}
catch (Exception ex)
{
return await Task.FromResult(ex.Message);
}
}
}
}
```
Resolve a problem with Obsolete controller | ```c#
using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Threading.Tasks;
namespace Blogifier.Core.Services
{
public class MailKitService : IEmailService
{
private readonly IDataService _db;
public MailKitService(IDataService db)
{
_db = db;
}
public async Task<string> SendEmail(string fromName, string fromEmail, string toEmail, string subject, string content)
{
try
{
var mailKit = await _db.CustomFields.GetMailKitModel();
var message = new MimeMessage();
message.From.Add(new MailboxAddress(fromName, fromEmail));
message.To.Add(new MailboxAddress(fromName, toEmail));
message.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = content;
message.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(mailKit.EmailServer, mailKit.Port, mailKit.Options);
client.Authenticate(mailKit.EmailAddress, mailKit.EmailPassword);
client.Send(message);
client.Disconnect(true);
return await Task.FromResult("");
}
catch (Exception ex)
{
return await Task.FromResult(ex.Message);
}
}
}
}
``` |
ec676187-6ffb-4c03-a265-264abb6a1d04 | {
"language": "C#"
} | ```c#
using System;
using Bit.Core.Domains;
using System.Collections.Generic;
using Newtonsoft.Json;
using Bit.Core.Enums;
namespace Bit.Api.Models
{
public class DomainsResponseModel : ResponseModel
{
public DomainsResponseModel(User user)
: base("domains")
{
if(user == null)
{
throw new ArgumentNullException(nameof(user));
}
EquivalentDomains = user.EquivalentDomains != null ?
JsonConvert.DeserializeObject<List<List<string>>>(user.EquivalentDomains) : null;
GlobalEquivalentDomains = Core.Utilities.EquivalentDomains.Global;
ExcludedGlobalEquivalentDomains = user.ExcludedGlobalEquivalentDomains != null ?
JsonConvert.DeserializeObject<List<GlobalEquivalentDomainsType>>(user.ExcludedGlobalEquivalentDomains) : null;
}
public IEnumerable<IEnumerable<string>> EquivalentDomains { get; set; }
public IDictionary<GlobalEquivalentDomainsType, IEnumerable<string>> GlobalEquivalentDomains { get; set; }
public IEnumerable<GlobalEquivalentDomainsType> ExcludedGlobalEquivalentDomains { get; set; }
}
}
```
Rework models for global domains | ```c#
using System;
using Bit.Core.Domains;
using System.Collections.Generic;
using Newtonsoft.Json;
using Bit.Core.Enums;
using System.Linq;
namespace Bit.Api.Models
{
public class DomainsResponseModel : ResponseModel
{
public DomainsResponseModel(User user)
: base("domains")
{
if(user == null)
{
throw new ArgumentNullException(nameof(user));
}
EquivalentDomains = user.EquivalentDomains != null ?
JsonConvert.DeserializeObject<List<List<string>>>(user.EquivalentDomains) : null;
var excludedGlobalEquivalentDomains = user.ExcludedGlobalEquivalentDomains != null ?
JsonConvert.DeserializeObject<List<GlobalEquivalentDomainsType>>(user.ExcludedGlobalEquivalentDomains) : null;
var globalDomains = new List<GlobalDomains>();
foreach(var domain in Core.Utilities.EquivalentDomains.Global)
{
globalDomains.Add(new GlobalDomains(domain.Key, domain.Value, excludedGlobalEquivalentDomains));
}
GlobalEquivalentDomains = !globalDomains.Any() ? null : globalDomains;
}
public IEnumerable<IEnumerable<string>> EquivalentDomains { get; set; }
public IEnumerable<GlobalDomains> GlobalEquivalentDomains { get; set; }
public class GlobalDomains
{
public GlobalDomains(
GlobalEquivalentDomainsType globalDomain,
IEnumerable<string> domains,
IEnumerable<GlobalEquivalentDomainsType> excludedDomains)
{
Type = globalDomain;
Domains = domains;
Excluded = excludedDomains?.Contains(globalDomain) ?? false;
}
public GlobalEquivalentDomainsType Type { get; set; }
public IEnumerable<string> Domains { get; set; }
public bool Excluded { get; set; }
}
}
}
``` |
978e4215-0515-4f25-a89b-07704d1d7015 | {
"language": "C#"
} | ```c#
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("AxosoftAPI.NET")]
[assembly: AssemblyDescription(".NET wrapper for the Axosoft API v4")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Axosoft")]
[assembly: AssemblyProduct("AxosoftAPI.NET")]
[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("e9dab9c2-a84d-4572-9bc2-93347b5cdc8a")]
// 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("4.0.3.0")]
[assembly: AssemblyFileVersion("4.0.3.0")]
```
Change project version based on lateset NuGet package. | ```c#
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("AxosoftAPI.NET")]
[assembly: AssemblyDescription(".NET wrapper for the Axosoft API v4")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Axosoft")]
[assembly: AssemblyProduct("AxosoftAPI.NET")]
[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("e9dab9c2-a84d-4572-9bc2-93347b5cdc8a")]
// 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("4.0.4.0")]
[assembly: AssemblyFileVersion("4.0.4.0")]
``` |
71820d2e-42ee-4094-83af-277606e45df8 | {
"language": "C#"
} | ```c#
namespace CertiPay.Common.Testing
{
using ApprovalTests;
using Newtonsoft.Json;
using Ploeh.AutoFixture;
public static class TestExtensions
{
private static readonly Fixture _fixture = new Fixture { };
/// <summary>
/// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object
/// </summary>
public static void VerifyMe(this object obj)
{
var json = JsonConvert.SerializeObject(obj);
Approvals.VerifyJson(json);
}
public static T AutoGenerate<T>()
{
return _fixture.Create<T>();
}
}
}```
Update comments on test extensions | ```c#
namespace CertiPay.Common.Testing
{
using ApprovalTests;
using Newtonsoft.Json;
using Ploeh.AutoFixture;
public static class TestExtensions
{
private static readonly Fixture _fixture = new Fixture { };
/// <summary>
/// Runs ApprovalTests's VerifyJson against a JSON.net serialized representation of the provided object
/// </summary>
public static void VerifyMe(this object obj)
{
var json = JsonConvert.SerializeObject(obj);
Approvals.VerifyJson(json);
}
/// <summary>
/// Returns an auto-initialized instance of the type T, filled via mock
/// data via AutoFixture.
///
/// This will not work for interfaces, only concrete types.
/// </summary>
public static T AutoGenerate<T>()
{
return _fixture.Create<T>();
}
}
}``` |
868de19e-9d03-48a9-b173-2a9761aa671a | {
"language": "C#"
} | ```c#
using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyDocs.Common.Contract.Service
{
public interface IPageExtractor
{
IEnumerable<string> SupportedExtensions { get; }
Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document);
}
public class PageExtractorList : IPageExtractor
{
private readonly List<IPageExtractor> extractors;
public PageExtractorList(IEnumerable<IPageExtractor> extractors)
{
this.extractors = extractors.ToList();
}
public IEnumerable<string> SupportedExtensions
{
get { return extractors.SelectMany(e => e.SupportedExtensions); }
}
public async Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document)
{
var extension = Path.GetExtension(file.Name);
return await extractors
.Single(e => e.SupportedExtensions.Contains(extension))
.ExtractPages(file, document);
}
}
}
```
Use interfaces instead of concrete types in file definition | ```c#
using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyDocs.Common.Contract.Service
{
public interface IPageExtractor
{
IEnumerable<string> SupportedExtensions { get; }
Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document);
}
public class PageExtractorList : IPageExtractor
{
private readonly IList<IPageExtractor> extractors;
public PageExtractorList(IEnumerable<IPageExtractor> extractors)
{
this.extractors = extractors.ToList();
}
public IEnumerable<string> SupportedExtensions
{
get { return extractors.SelectMany(e => e.SupportedExtensions); }
}
public async Task<IEnumerable<IFile>> ExtractPages(IFile file, Document document)
{
var extension = Path.GetExtension(file.Name);
return await extractors
.Single(e => e.SupportedExtensions.Contains(extension))
.ExtractPages(file, document);
}
}
}
``` |
ae9aafad-1856-4d55-ae3b-1b10339147dc | {
"language": "C#"
} | ```c#
using System;
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
public static DateTime Yesterday(this DateTime date)
{
return date.AddDays(-1);
}
public static int Age(this DateTime date)
{
var now = DateTime.Now;
var age = now.Year - date.Year;
if (now.Month > date.Month || (now.Month == date.Month && now.Day < date.Month))
age -= 1;
return age;
}
public static int AgeInDays(this DateTime date)
{
TimeSpan ts = DateTime.Now - date;
return ts.Duration().Days;
}
}
}
```
Adjust rule for Age Calc. | ```c#
using System;
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
public static DateTime Yesterday(this DateTime date)
{
return date.AddDays(-1);
}
public static int Age(this DateTime date)
{
var now = DateTime.Now;
var age = now.Year - date.Year;
if (now.Month > date.Month || (now.Month == date.Month && now.Day <= date.Day))
age -= 1;
return age;
}
public static int AgeInDays(this DateTime date)
{
TimeSpan ts = DateTime.Now - date;
return ts.Duration().Days;
}
}
}
``` |
4bda7af5-9a2f-470b-9444-19f0bb521def | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class TriggerDestroy : MonoBehaviour
{
public Transform owner;
public float ensureDestroyAfter = 5f;
void Update()
{
ensureDestroyAfter -= Time.deltaTime;
}
void OnTriggerEnter(Collider other)
{
if (other.transform.name != owner.name)
{
return;
}
Destroy(gameObject);
}
}
```
Fix safety measures. Destroy missing. | ```c#
using UnityEngine;
using System.Collections;
public class TriggerDestroy : MonoBehaviour
{
public Transform owner;
public float ensureDestroyAfter = 2f;
void Update()
{
ensureDestroyAfter -= Time.deltaTime;
if (ensureDestroyAfter <= 0) {
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.name != owner.name)
{
return;
}
Destroy(gameObject);
}
}
``` |
62f443ad-bece-4311-b618-2b024f29c283 | {
"language": "C#"
} | ```c#
#region Apache License 2.0
// Copyright 2015 Thaddeus Ryker
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Reflection;
using Fasterflect;
namespace Org.Edgerunner.DotSerialize.Utilities
{
public static class FieldInfoExtensions
{
#region Static Methods
public static PropertyInfo GetEncapsulatingAutoProperty(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
if (!string.IsNullOrEmpty(propertyName))
return info.DeclaringType.Property(propertyName);
return null;
}
public static bool IsBackingField(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
return !string.IsNullOrEmpty(propertyName);
}
#endregion
}
}```
Improve accuracy of IsBackingField extension method. | ```c#
#region Apache License 2.0
// Copyright 2015 Thaddeus Ryker
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Fasterflect;
namespace Org.Edgerunner.DotSerialize.Utilities
{
public static class FieldInfoExtensions
{
#region Static Methods
public static PropertyInfo GetEncapsulatingAutoProperty(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
if (!string.IsNullOrEmpty(propertyName))
return info.DeclaringType.Property(propertyName);
return null;
}
public static bool IsBackingField(this FieldInfo info)
{
var propertyName = NamingUtils.GetAutoPropertyName(info.Name);
if (string.IsNullOrEmpty(propertyName))
return false;
return info.HasAttribute<CompilerGeneratedAttribute>();
}
#endregion
}
}``` |
12763ca0-c733-49ca-bc22-4ef395120c47 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using ClearMeasure.NumberCruncher;
using ClearMeasure.NumberCruncher.PrinterFormatters;
namespace TheTesst
{
class Program
{
static void Main(string[] args)
{
var formatter = new DefaultPrinterFormatter(() => new FileResultStore(), new NumberToWord(), new FizzBuzz());
var printer = new ConsolePrinter();
var cruncher = new Cruncher(formatter, printer);
var data = new List<int>() { 2, 3, 15, 7, 30, 104, 35465 };
cruncher.Execute(data);
Console.ReadLine();
}
}
}```
Use StringBuilderResultStore in the console application | ```c#
using System;
using System.Collections.Generic;
using ClearMeasure.NumberCruncher;
using ClearMeasure.NumberCruncher.PrinterFormatters;
namespace TheTesst
{
class Program
{
static void Main(string[] args)
{
var formatter = new DefaultPrinterFormatter(() => new StringBuilderResultStore(), new NumberToWord(), new FizzBuzz());
var printer = new ConsolePrinter();
var cruncher = new Cruncher(formatter, printer);
var data = new List<int>() { 2, 3, 15, 7, 30, 104, 35465 };
cruncher.Execute(data);
Console.ReadLine();
}
}
}
``` |
16cd1e1c-f112-4e2e-a347-ebdc4eb6e41b | {
"language": "C#"
} | ```c#
namespace Moya.Exceptions
{
using System;
public class MoyaException : Exception
{
public MoyaException(String message) : base(message)
{
}
}
}```
Add xml documentation to moya exceptions | ```c#
namespace Moya.Exceptions
{
using System;
/// <summary>
/// Represents errors that occur during execution of Moya.
/// </summary>
public class MoyaException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="MoyaException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">A message describing the error.</param>
public MoyaException(String message) : base(message)
{
}
}
}``` |
55c65060-6cc0-4099-b5c1-3eb8a6641de3 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace ExtendedControls
{
public class StatusStripCustom : StatusStrip
{
public const int WM_NCHITTEST = 0x84;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int WM_NCLBUTTONUP = 0xA2;
public const int HT_CLIENT = 0x1;
public const int HT_BOTTOMRIGHT = 0x11;
public const int HT_TRANSPARENT = -1;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST && (int)m.Result == HT_BOTTOMRIGHT)
{
// Tell the system to test the parent
m.Result = (IntPtr)HT_TRANSPARENT;
}
}
}
}
```
Work around faulty StatusStrip implementations | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace ExtendedControls
{
public class StatusStripCustom : StatusStrip
{
public const int WM_NCHITTEST = 0x84;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int WM_NCLBUTTONUP = 0xA2;
public const int HT_CLIENT = 0x1;
public const int HT_BOTTOMRIGHT = 0x11;
public const int HT_TRANSPARENT = -1;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST)
{
if ((int)m.Result == HT_BOTTOMRIGHT)
{
// Tell the system to test the parent
m.Result = (IntPtr)HT_TRANSPARENT;
}
else if ((int)m.Result == HT_CLIENT)
{
// Work around the implementation returning HT_CLIENT instead of HT_BOTTOMRIGHT
int x = unchecked((short)((uint)m.LParam & 0xFFFF));
int y = unchecked((short)((uint)m.LParam >> 16));
Point p = PointToClient(new Point(x, y));
if (p.X >= this.ClientSize.Width - this.ClientSize.Height)
{
// Tell the system to test the parent
m.Result = (IntPtr)HT_TRANSPARENT;
}
}
}
}
}
}
``` |
e0bc4629-9386-4da0-84eb-72e2121de5ee | {
"language": "C#"
} | ```c#
namespace ErikLieben.Data.Repository
{
using System.Collections.Generic;
public interface IRepository<T> : IEnumerable<T>
where T : class
{
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item to add.</param>
void Add(T item);
/// <summary>
/// Deletes the specified item.
/// </summary>
/// <param name="item">The item to delete.</param>
void Delete(T item);
/// <summary>
/// Updates the specified item.
/// </summary>
/// <param name="item">The item to update.</param>
void Update(T item);
IEnumerable<T> Find(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
}
}
```
Add find first or default | ```c#
namespace ErikLieben.Data.Repository
{
using System.Collections.Generic;
public interface IRepository<T> : IEnumerable<T>
where T : class
{
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item to add.</param>
void Add(T item);
/// <summary>
/// Deletes the specified item.
/// </summary>
/// <param name="item">The item to delete.</param>
void Delete(T item);
/// <summary>
/// Updates the specified item.
/// </summary>
/// <param name="item">The item to update.</param>
void Update(T item);
IEnumerable<T> Find(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
T FindFirstOrDefault(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
}
}
``` |
9eeb168f-c27b-4839-9a9f-b2e4d1571deb | {
"language": "C#"
} | ```c#
using MobileKidsIdApp.ViewModels;
using Xamarin.Forms;
namespace MobileKidsIdApp.Views
{
public class MainPage : TabbedPage
{
private ApplicationBase CurrentApp => Application.Current as ApplicationBase;
public MainPage()
{
Page childListPage = CurrentApp.CreatePage<ChildProfileListPage, ChildProfileListViewModel>(true).Result;
Page instructionsPage = CurrentApp.CreatePage<InstructionIndexPage, InstructionIndexViewModel>(true).Result;
if (childListPage is NavigationPage childNavPage)
{
childNavPage.Title = "My Kids";
// TODO: set icon
}
if (instructionsPage is NavigationPage instructionNavPage)
{
instructionNavPage.Title = "Content";
// TODO: set icon
}
Children.Add(childListPage);
Children.Add(instructionsPage);
// TODO: Add "logout" ability
}
}
}
```
Set tabs on Android to be on the bottom | ```c#
using MobileKidsIdApp.ViewModels;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
namespace MobileKidsIdApp.Views
{
public class MainPage : Xamarin.Forms.TabbedPage
{
private ApplicationBase CurrentApp => Xamarin.Forms.Application.Current as ApplicationBase;
public MainPage()
{
On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
Xamarin.Forms.Page childListPage = CurrentApp.CreatePage<ChildProfileListPage, ChildProfileListViewModel>(true).Result;
Xamarin.Forms.Page instructionsPage = CurrentApp.CreatePage<InstructionIndexPage, InstructionIndexViewModel>(true).Result;
if (childListPage is Xamarin.Forms.NavigationPage childNavPage)
{
childNavPage.Title = "My Kids";
// TODO: set icon
}
if (instructionsPage is Xamarin.Forms.NavigationPage instructionNavPage)
{
instructionNavPage.Title = "Content";
// TODO: set icon
}
Children.Add(childListPage);
Children.Add(instructionsPage);
// TODO: Add "logout" ability
}
}
}
``` |
aac2fff3-7538-422f-a897-bfc27db1768f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
// TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
_requestRuntimes.Discover();
_requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
_requestHandlers.Discover();
}
public async Task Begin(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.Begin(context);
}
}
public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
{
foreach (var requestHandler in _requestHandlers)
{
if (requestHandler.WillHandle(context))
{
handeler = requestHandler;
return true;
}
}
handeler = null;
return false;
}
public async Task End(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.End(context);
}
}
}
}```
Add Request Authorizer to master request runtime | ```c#
using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
using System.Threading.Tasks;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers;
private readonly IDiscoverableCollection<IRequestAuthorizer> _requestAuthorizers;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
// TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware
_requestAuthorizers = serviceProvider.GetService<IDiscoverableCollection<IRequestAuthorizer>>();
_requestAuthorizers.Discover();
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
_requestRuntimes.Discover();
_requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>();
_requestHandlers.Discover();
}
public bool Authorized(IHttpContext context)
{
foreach (var requestAuthorizer in _requestAuthorizers)
{
var allowed = requestAuthorizer.AllowUser(context);
if (!allowed)
{
return false;
}
}
return true;
}
public async Task Begin(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.Begin(context);
}
}
public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler)
{
foreach (var requestHandler in _requestHandlers)
{
if (requestHandler.WillHandle(context))
{
handeler = requestHandler;
return true;
}
}
handeler = null;
return false;
}
public async Task End(IHttpContext context)
{
foreach (var requestRuntime in _requestRuntimes)
{
await requestRuntime.End(context);
}
}
}
}``` |
d057a1cf-b2bc-4bc4-a501-08cb0606830e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;
using DereTore.Applications.StarlightDirector.Components;
using DereTore.Applications.StarlightDirector.Entities.Serialization;
namespace DereTore.Applications.StarlightDirector.Entities {
public sealed class CompiledScore {
public CompiledScore() {
Notes = new InternalList<CompiledNote>();
}
public InternalList<CompiledNote> Notes { get; }
public string GetCsvString() {
var tempFileName = Path.GetTempFileName();
using (var stream = File.Open(tempFileName, FileMode.Create, FileAccess.Write)) {
using (var writer = new StreamWriter(stream, Encoding.UTF8)) {
var config = new CsvConfiguration();
config.RegisterClassMap<ScoreCsvMap>();
config.HasHeaderRecord = true;
config.TrimFields = false;
using (var csv = new CsvWriter(writer, config)) {
var newList = new List<CompiledNote>(Notes);
newList.Sort(CompiledNote.IDComparison);
csv.WriteRecords(newList);
}
}
}
// BUG: WTF? Why can't all the data be written into a MemoryStream right after the csv.WriteRecords() call, but a FileStream?
var text = File.ReadAllText(tempFileName, Encoding.UTF8);
File.Delete(tempFileName);
return text;
}
}
}
```
Use Unix line feed for score exportation. | ```c#
using System.Collections.Generic;
using System.IO;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;
using DereTore.Applications.StarlightDirector.Components;
using DereTore.Applications.StarlightDirector.Entities.Serialization;
namespace DereTore.Applications.StarlightDirector.Entities {
public sealed class CompiledScore {
public CompiledScore() {
Notes = new InternalList<CompiledNote>();
}
public InternalList<CompiledNote> Notes { get; }
public string GetCsvString() {
var tempFileName = Path.GetTempFileName();
using (var stream = File.Open(tempFileName, FileMode.Create, FileAccess.Write)) {
using (var writer = new StreamWriter(stream, Encoding.UTF8)) {
var config = new CsvConfiguration();
config.RegisterClassMap<ScoreCsvMap>();
config.HasHeaderRecord = true;
config.TrimFields = false;
using (var csv = new CsvWriter(writer, config)) {
var newList = new List<CompiledNote>(Notes);
newList.Sort(CompiledNote.IDComparison);
csv.WriteRecords(newList);
}
}
}
// BUG: WTF? Why can't all the data be written into a MemoryStream right after the csv.WriteRecords() call, but a FileStream?
var text = File.ReadAllText(tempFileName, Encoding.UTF8);
text = text.Replace("\r\n", "\n");
File.Delete(tempFileName);
return text;
}
}
}
``` |
ca67616c-06d6-4a8f-b769-be98df2c0625 | {
"language": "C#"
} | ```c#
// Plugboard.cs
// <copyright file="Plugboard.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.Linq;
namespace EnigmaUtilities.Components
{
/// <summary>
/// An implementation of the plug board component for the enigma machine.
/// </summary>
public class Plugboard : Component
{
/// <summary>
/// Initializes a new instance of the <see cref="Plugboard" /> class.
/// </summary>
/// <param name="plugs"> The plugs to be used. </param>
public Plugboard(string[] plugs)
{
// Turn each plug connection into an encryption element in the dictionary
this.EncryptionKeys = new Dictionary<char, char>();
foreach (string plug in plugs)
{
// Add both ways round so its not required to look backwards across the plugboard during the encryption
this.EncryptionKeys.Add(plug[0], plug[1]);
this.EncryptionKeys.Add(plug[1], plug[0]);
}
}
/// <summary>
/// Encrypts a letter with the current plug board settings.
/// </summary>
/// <param name="c"> The character to encrypt. </param>
/// <returns> The encrypted character. </returns>
public override char Encrypt(char c)
{
return this.EncryptionKeys.Keys.Contains(c) ? this.EncryptionKeys[c] : c;
}
}
}
```
Stop errors if invalid plugboard settings and inputted into the constructor The constructor would throw errors if the length of a string in the string array of settings was of length 1 or 0. Now it only adds plug settings with a length of 2 or above | ```c#
// Plugboard.cs
// <copyright file="Plugboard.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.Linq;
namespace EnigmaUtilities.Components
{
/// <summary>
/// An implementation of the plug board component for the enigma machine.
/// </summary>
public class Plugboard : Component
{
/// <summary>
/// Initializes a new instance of the <see cref="Plugboard" /> class.
/// </summary>
/// <param name="plugs"> The plugs to be used. </param>
public Plugboard(string[] plugs)
{
// Turn each plug connection into an encryption element in the dictionary
this.EncryptionKeys = new Dictionary<char, char>();
foreach (string plug in plugs)
{
// Only add to plugboard if its and length that won't create errors (2 or above)
if (plug.Length >= 2)
{
// Add both ways round so its not required to look backwards across the plugboard during the encryption
this.EncryptionKeys.Add(plug[0], plug[1]);
this.EncryptionKeys.Add(plug[1], plug[0]);
}
}
}
/// <summary>
/// Encrypts a letter with the current plug board settings.
/// </summary>
/// <param name="c"> The character to encrypt. </param>
/// <returns> The encrypted character. </returns>
public override char Encrypt(char c)
{
return this.EncryptionKeys.Keys.Contains(c) ? this.EncryptionKeys[c] : c;
}
}
}
``` |
eae841ed-c6cb-415d-827b-0db3777a5c09 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.iOS.ListUsbDevices
{
internal static class Program
{
private static bool ourFinished;
private static int Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: ios-list-usb-devices dllFolderPath sleepInMs");
Console.WriteLine(" Type 'stop' to finish");
return -1;
}
var thread = new Thread(ThreadFunc);
thread.Start(args);
while (true)
{
if (Console.ReadLine()?.Equals("stop", StringComparison.OrdinalIgnoreCase) == true)
{
ourFinished = true;
break;
}
}
thread.Join();
return 0;
}
private static void ThreadFunc(object state)
{
var args = (string[]) state;
var sleepTimeMs = int.Parse(args[1]);
using (var api = new ListDevices(args[0]))
{
while (!ourFinished)
{
var devices = api.GetDevices();
Console.WriteLine($"{devices.Count}");
foreach (var device in devices)
Console.WriteLine($"{device.productId:X} {device.udid}");
Thread.Sleep(sleepTimeMs);
}
}
}
}
}```
Fix listing iOS devices on Windows | ```c#
using System;
using System.Net.Sockets;
using System.Threading;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.iOS.ListUsbDevices
{
internal static class Program
{
private static bool ourFinished;
private static int Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: ios-list-usb-devices dllFolderPath sleepInMs");
Console.WriteLine(" Type 'stop' to finish");
return -1;
}
InitialiseWinSock();
var thread = new Thread(ThreadFunc);
thread.Start(args);
while (true)
{
if (Console.ReadLine()?.Equals("stop", StringComparison.OrdinalIgnoreCase) == true)
{
ourFinished = true;
break;
}
}
thread.Join();
return 0;
}
private static void InitialiseWinSock()
{
// Small hack to force WinSock to initialise on Windows. If we don't do this, the C based socket APIs in the
// native dll will fail, because no-one has bothered to initialise sockets.
try
{
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
socket.Dispose();
}
catch (Exception e)
{
Console.WriteLine("Failed to create socket (force initialising WinSock on Windows)");
Console.WriteLine(e);
}
}
private static void ThreadFunc(object state)
{
var args = (string[]) state;
var sleepTimeMs = int.Parse(args[1]);
using (var api = new ListDevices(args[0]))
{
while (!ourFinished)
{
var devices = api.GetDevices();
Console.WriteLine($"{devices.Count}");
foreach (var device in devices)
Console.WriteLine($"{device.productId:X} {device.udid}");
Thread.Sleep(sleepTimeMs);
}
}
}
}
}
``` |
cf2a3fe3-3192-4dab-b80a-620c976d7c0d | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace Daisy.SaveAsDAISY.Addins.Word2007 {
public partial class ExceptionReport : Form {
private Exception ExceptionRaised { get; }
public ExceptionReport(Exception raised) {
InitializeComponent();
this.ExceptionRaised = raised;
this.ExceptionMessage.Text = raised.Message + "\r\nStacktrace:\r\n" + raised.StackTrace;
}
private void SendReport_Click(object sender, EventArgs e) {
StringBuilder message = new StringBuilder("The following exception was reported by a user using the saveAsDaisy addin:\r\n");
message.AppendLine(this.ExceptionRaised.Message);
message.AppendLine();
message.Append(this.ExceptionRaised.StackTrace);
string mailto = string.Format(
"mailto:{0}?Subject={1}&Body={2}",
"daisy-pipeline@mail.daisy.org",
"Unhandled exception report in the SaveAsDAISY addin",
message.ToString()
);
mailto = Uri.EscapeUriString(mailto);
//MessageBox.Show(message.ToString());
Process.Start(mailto);
}
}
}
```
Improve exception report to also get inner exceptions if possible | ```c#
using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace Daisy.SaveAsDAISY.Addins.Word2007 {
public partial class ExceptionReport : Form {
private Exception ExceptionRaised { get; }
public ExceptionReport(Exception raised) {
InitializeComponent();
this.ExceptionRaised = raised;
this.ExceptionMessage.Text = raised.Message + "\r\nStacktrace:\r\n" + raised.StackTrace;
}
private void SendReport_Click(object sender, EventArgs evt) {
StringBuilder message = new StringBuilder("The following exception was reported by a user using the saveAsDaisy addin:\r\n");
message.AppendLine(this.ExceptionRaised.Message);
message.AppendLine();
message.Append(this.ExceptionRaised.StackTrace);
Exception e = ExceptionRaised;
while (e.InnerException != null) {
e = e.InnerException;
message.AppendLine(" - Inner exception : " + e.Message);
message.AppendLine();
message.Append(this.ExceptionRaised.StackTrace);
}
string mailto = string.Format(
"mailto:{0}?Subject={1}&Body={2}",
"daisy-pipeline@mail.daisy.org",
"Unhandled exception report in the SaveAsDAISY addin",
message.ToString()
);
mailto = Uri.EscapeUriString(mailto);
//MessageBox.Show(message.ToString());
Process.Start(mailto);
}
}
}
``` |
71888530-c9e9-402d-9d08-74a4954788de | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace kafka4net.Metadata
{
class BrokerMeta
{
public int NodeId;
public string Host;
public int Port;
// Not serialized, just a link to connection associated with this broker
internal Connection Conn;
public override string ToString()
{
return string.Format("{0}:{1} Id:{2}", Host, Port, NodeId);
}
#region comparer
public static readonly IEqualityComparer<BrokerMeta> NodeIdComparer = new ComparerImpl();
class ComparerImpl : IEqualityComparer<BrokerMeta>
{
public bool Equals(BrokerMeta x, BrokerMeta y)
{
return x.NodeId == y.NodeId;
}
public int GetHashCode(BrokerMeta obj)
{
return obj.NodeId;
}
}
#endregion
}
}
```
Fix comparer. Seed node all have NodeId=-99, so need to compare their fields. | ```c#
using System;
using System.Collections.Generic;
namespace kafka4net.Metadata
{
class BrokerMeta
{
public int NodeId;
public string Host;
public int Port;
// Not serialized, just a link to connection associated with this broker
internal Connection Conn;
public override string ToString()
{
return string.Format("{0}:{1} Id:{2}", Host, Port, NodeId);
}
#region comparer
public static readonly IEqualityComparer<BrokerMeta> NodeIdComparer = new ComparerImpl();
class ComparerImpl : IEqualityComparer<BrokerMeta>
{
public bool Equals(BrokerMeta x, BrokerMeta y)
{
if(x.NodeId != -99 || y.NodeId != -99)
return x.NodeId == y.NodeId;
// If those are non-resolved seed brokers, do property comparison, because they all have NodeId==-99
return string.Equals(x.Host, y.Host, StringComparison.OrdinalIgnoreCase) && x.Port == y.Port;
}
public int GetHashCode(BrokerMeta obj)
{
return obj.NodeId;
}
}
#endregion
}
}
``` |
4449401c-fe2e-4b14-a7ae-3025824a4987 | {
"language": "C#"
} | ```c#
using System.Drawing;
public struct FBAdSize {
SizeF size;
}
public struct FBAdStarRating {
float value;
int scale;
}
```
Fix the access level on the size and rating structs | ```c#
using System.Drawing;
public struct FBAdSize {
public SizeF size;
}
public struct FBAdStarRating {
public float value;
public int scale;
}
``` |
d807e20b-01bd-4be0-b7a3-bd24ab749d28 | {
"language": "C#"
} | ```c#
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
Console.WriteLine("Bigsby Gates was here!");
Console.WriteLine("Bigsby Trovalds was here!");
}
}
}
```
Add Bigsby Jobs was here | ```c#
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
Console.WriteLine("Bigsby Gates was here!");
Console.WriteLine("Bigsby Trovalds was here!");
Console.WriteLine("Bigsby Jobs was here!");
}
}
}
``` |
6a241cc0-4ad4-43aa-b259-27acf5f020e0 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.SPOT;
namespace IntervalTimer
{
public class IntervalReachedEventArgs : EventArgs
{
public String Message { get; set; }
public IntervalReachedEventArgs(String message)
{
Message = message;
}
}
}
```
Change IntervalReached event to contain duration position. | ```c#
using System;
using Microsoft.SPOT;
namespace IntervalTimer
{
public class IntervalReachedEventArgs : EventArgs
{
public int DurationNumber { get; set; }
public IntervalReachedEventArgs(int durationNumber)
{
DurationNumber = durationNumber;
}
}
}
``` |
14ae9e70-4d87-4019-a051-3f2fbcca0d66 | {
"language": "C#"
} | ```c#
// 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.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield
{
[SettingSource("Roll speed", "Speed at which things rotate")]
public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(1)
{
MinValue = 0.1,
MaxValue = 20,
Precision = 0.1,
};
public override string Name => "Barrel Roll";
public override string Acronym => "BR";
public override double ScoreMultiplier => 1;
public void Update(Playfield playfield)
{
playfield.Rotation = (float)(playfield.Time.Current / 1000 * SpinSpeed.Value);
}
}
}
```
Scale the playfield to avoid off-screen objects | ```c#
// 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.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield, IApplicableToDrawableRuleset<OsuHitObject>
{
[SettingSource("Roll speed", "Speed at which things rotate")]
public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(1)
{
MinValue = 0.1,
MaxValue = 20,
Precision = 0.1,
};
public override string Name => "Barrel Roll";
public override string Acronym => "BR";
public override double ScoreMultiplier => 1;
public void Update(Playfield playfield)
{
playfield.Rotation = (float)(playfield.Time.Current / 1000 * SpinSpeed.Value);
}
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
// scale the playfield to allow all hitobjects to stay within the visible region.
drawableRuleset.Playfield.Scale = new Vector2(OsuPlayfield.BASE_SIZE.Y / OsuPlayfield.BASE_SIZE.X);
}
}
}
``` |
2a233803-ecfc-4241-adc2-46cd87389700 | {
"language": "C#"
} | ```c#
using System.Dynamic;
using System.Xml.Serialization;
using com.esendex.sdk.core;
using com.esendex.sdk.messaging;
using com.esendex.sdk.utilities;
using NUnit.Framework;
namespace com.esendex.sdk.test.messaging
{
[TestFixture]
public class SmsMessageSerializationTests
{
[Test]
public void WhenCharacterSetIsDefaultItIsNotSerialised()
{
var message = new SmsMessage();
var serialiser = new XmlSerialiser();
var serialisedMessage = serialiser.Serialise(message);
Assert.That(serialisedMessage, Is.Not.StringContaining("characterset"));
}
[Test]
public void WhenCharacterSetIsSetShouldBeSerialised([Values(CharacterSet.Auto, CharacterSet.GSM, CharacterSet.Unicode)] CharacterSet characterSet)
{
var message = new SmsMessage();
message.CharacterSet = characterSet;
var serialiser = new XmlSerialiser();
var serialisedMessage = serialiser.Serialise(message);
Assert.That(serialiser.Deserialise<SmsMessage>(serialisedMessage).CharacterSet, Is.EqualTo(characterSet));
}
}
}```
Make characterset serialisation test explicit | ```c#
using com.esendex.sdk.core;
using com.esendex.sdk.messaging;
using com.esendex.sdk.utilities;
using NUnit.Framework;
namespace com.esendex.sdk.test.messaging
{
[TestFixture]
public class SmsMessageSerializationTests
{
[TestCase(CharacterSet.Auto, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>Auto</characterset></message>")]
[TestCase(CharacterSet.GSM, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>GSM</characterset></message>")]
[TestCase(CharacterSet.Unicode, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>Unicode</characterset></message>")]
[TestCase(CharacterSet.Default, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity></message>")]
public void WhenSmsMessageIsSerializedThenTheCharacterSetIsSerialisedAsExpected(CharacterSet characterSet, string expectedXml)
{
var message = new SmsMessage {CharacterSet = characterSet};
var serialiser = new XmlSerialiser();
var serialisedMessage = serialiser.Serialise(message);
Assert.That(serialisedMessage, Is.EqualTo(expectedXml));
}
}
}``` |
3124b1f1-368a-42b7-b467-930de3c55080 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
/**
* Use Keyboard to switch between all scenes in build
* Wraps from last Scene back to first and vice versa
*/
namespace mmm {
public class SceneSwitcher : MonoBehaviour {
public KeyCode keyNext = KeyCode.Equals;
public KeyCode keyPrevious = KeyCode.Minus;
void Update () {
// Trigger Scene Switch with Keyboard Commands
if (Input.GetKeyDown(keyNext))
{
// Increment Scene
int nextLevel = Application.loadedLevel;
nextLevel++;
if (nextLevel >= Application.levelCount)
{
nextLevel = 0;
}
Application.LoadLevel(nextLevel);
}
if (Input.GetKeyDown(keyPrevious))
{
// Decrement Scene
int nextLevel = Application.loadedLevel;
nextLevel--;
if (nextLevel < 0)
{
nextLevel = Application.levelCount;
}
Application.LoadLevel(nextLevel);
}
}
}
}```
Fix for Scene Switcher negative wraparound | ```c#
using UnityEngine;
using System.Collections;
/**
* Use Keyboard to switch between all scenes in build
* Wraps from last Scene back to first and vice versa
*/
namespace mmm {
public class SceneSwitcher : MonoBehaviour {
public KeyCode keyNext = KeyCode.Equals;
public KeyCode keyPrevious = KeyCode.Minus;
void Update () {
// Trigger Scene Switch with Keyboard Commands
if (Input.GetKeyDown(keyNext))
{
// Increment Scene
int nextLevel = Application.loadedLevel;
nextLevel++;
if (nextLevel >= Application.levelCount)
{
nextLevel = 0;
}
Application.LoadLevel(nextLevel);
}
if (Input.GetKeyDown(keyPrevious))
{
// Decrement Scene
int nextLevel = Application.loadedLevel;
nextLevel--;
if (nextLevel < 0)
{
nextLevel = Application.levelCount - 1;
}
Application.LoadLevel(nextLevel);
}
}
}
}``` |
8d18df48-a158-4185-933d-3bcd7d8e96a7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace QueueDataGraphic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<string> TestList = new List<string>();
TestList.Add("Channel1");
TestList.Add("Channel2");
TestList.Add("Channel3");
CSharpFiles.QueueDataGraphic QueueDataGraphic1 = new CSharpFiles.QueueDataGraphic(TestList);
for(int Loopnum = 0; Loopnum < 500; Loopnum++)
{
QueueDataGraphic1.AddData("Channel1", Loopnum*2);
}
panel1.Paint += new PaintEventHandler(QueueDataGraphic1.DrawGraph);
panel1.Refresh();
}
}
}
```
Call SetWidth and SetHeight method | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace QueueDataGraphic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<string> TestList = new List<string>();
TestList.Add("Channel1");
TestList.Add("Channel2");
TestList.Add("Channel3");
CSharpFiles.QueueDataGraphic QueueDataGraphic1 = new CSharpFiles.QueueDataGraphic(TestList);
for(int Loopnum = 0; Loopnum < 500; Loopnum++)
{
QueueDataGraphic1.AddData("Channel1", Loopnum*2);
}
QueueDataGraphic1.SetWidth(panel1.Size.Width);
QueueDataGraphic1.SetHeight(panel1.Size.Height);
panel1.Paint += new PaintEventHandler(QueueDataGraphic1.DrawGraph);
panel1.Refresh();
}
}
}
``` |
57aa22e0-d018-4419-8177-79d7695bb482 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyDescription ("Clide.Vsix")]
[assembly: InternalsVisibleTo ("Clide.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d9776e258bdf5f7c38f3c880404b9861ebbd235d8198315cdfda0f0c25b18608bdfd03e34bac9d0ec95766e8c3928140c6eda581a9448066af7dfaf88d3b6cb71d45a094011209ff6e76713151b4f2ce469cd2886285f1bf565b7fa63dada9d2e9573b743d26daa608b4d0fdebc9daa907a52727448316816f9c05c6e5529b9f")]```
Remove duplicate attribute that fails the build | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo ("Clide.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d9776e258bdf5f7c38f3c880404b9861ebbd235d8198315cdfda0f0c25b18608bdfd03e34bac9d0ec95766e8c3928140c6eda581a9448066af7dfaf88d3b6cb71d45a094011209ff6e76713151b4f2ce469cd2886285f1bf565b7fa63dada9d2e9573b743d26daa608b4d0fdebc9daa907a52727448316816f9c05c6e5529b9f")]``` |
66c098cc-cdb0-42c8-93e6-347861965cbf | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ControlDisplay : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private SpriteRenderer controlRenderer;
[SerializeField]
private Text controlText;
#pragma warning restore 0649
public void setControlScheme(MicrogameTraits.ControlScheme controlScheme)
{
//TODO re-enable command warnings?
controlRenderer.sprite = GameController.instance.getControlSprite(controlScheme);
controlText.text = TextHelper.getLocalizedTextNoWarnings("control." + controlScheme.ToString().ToLower(), getDefaultControlString(controlScheme));
}
string getDefaultControlString(MicrogameTraits.ControlScheme controlScheme)
{
switch (controlScheme)
{
case (MicrogameTraits.ControlScheme.Key):
return "USE DA KEYZ";
case (MicrogameTraits.ControlScheme.Mouse):
return "USE DA MOUSE";
default:
return "USE SOMETHING";
}
}
}
```
Fix incorrect control display key | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ControlDisplay : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private SpriteRenderer controlRenderer;
[SerializeField]
private Text controlText;
#pragma warning restore 0649
public void setControlScheme(MicrogameTraits.ControlScheme controlScheme)
{
//TODO re-enable command warnings?
controlRenderer.sprite = GameController.instance.getControlSprite(controlScheme);
controlText.text = TextHelper.getLocalizedTextNoWarnings("stage.control." + controlScheme.ToString().ToLower(), getDefaultControlString(controlScheme));
}
string getDefaultControlString(MicrogameTraits.ControlScheme controlScheme)
{
switch (controlScheme)
{
case (MicrogameTraits.ControlScheme.Key):
return "USE DA KEYZ";
case (MicrogameTraits.ControlScheme.Mouse):
return "USE DA MOUSE";
default:
return "USE SOMETHING";
}
}
}
``` |
50aad3e6-1eb3-4685-b959-bf34e328e01c | {
"language": "C#"
} | ```c#
// <copyright file="ViewResolver.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// 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.Collections.Generic;
namespace Stormpath.Owin.Common.Views.Precompiled
{
public static class ViewResolver
{
private static readonly Dictionary<string, Func<IView>> LookupTable =
new Dictionary<string, Func<IView>>(StringComparer.OrdinalIgnoreCase)
{
["change"] = () => new Change(),
["forgot"] = () => new Forgot(),
["login"] = () => new Login(),
["register"] = () => new Register(),
["verify"] = () => new Verify(),
};
public static IView GetView(string name)
{
Func<IView> foundViewFactory = null;
LookupTable.TryGetValue(name, out foundViewFactory);
return foundViewFactory == null
? null
: foundViewFactory();
}
}
}
```
Fix incorrect default view names | ```c#
// <copyright file="ViewResolver.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// 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.Collections.Generic;
namespace Stormpath.Owin.Common.Views.Precompiled
{
public static class ViewResolver
{
private static readonly Dictionary<string, Func<IView>> LookupTable =
new Dictionary<string, Func<IView>>(StringComparer.OrdinalIgnoreCase)
{
["change-password"] = () => new Change(),
["forgot-password"] = () => new Forgot(),
["login"] = () => new Login(),
["register"] = () => new Register(),
["verify"] = () => new Verify(),
};
public static IView GetView(string name)
{
Func<IView> foundViewFactory = null;
LookupTable.TryGetValue(name, out foundViewFactory);
return foundViewFactory == null
? null
: foundViewFactory();
}
}
}
``` |
0fd0e5f5-080c-473c-a72f-4220e03fe56d | {
"language": "C#"
} | ```c#
/*********************************************************************************
* SettingsTextBox.UIActions.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using System;
namespace Sandra.UI.WF
{
public partial class SettingsTextBox
{
public const string SettingsTextBoxUIActionPrefix = nameof(RichTextBoxBase) + ".";
public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.Save,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
});
public UIActionState TrySaveToFile(bool perform)
{
if (ReadOnly) return UIActionVisibility.Hidden;
return UIActionVisibility.Enabled;
}
}
}
```
Implement TrySaveToFile() by using File.WriteAllText(). | ```c#
/*********************************************************************************
* SettingsTextBox.UIActions.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using System;
using System.IO;
namespace Sandra.UI.WF
{
public partial class SettingsTextBox
{
public const string SettingsTextBoxUIActionPrefix = nameof(RichTextBoxBase) + ".";
public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.Save,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
});
public UIActionState TrySaveToFile(bool perform)
{
if (ReadOnly) return UIActionVisibility.Hidden;
if (perform) File.WriteAllText(settingsFile.AbsoluteFilePath, Text);
return UIActionVisibility.Enabled;
}
}
}
``` |
c178cb7d-6f5c-4378-b52b-72709522ee84 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public GlimpseServerWebOptions()
{
AllowedUserRoles = new List<string>();
}
public bool AllowRemote { get; set; }
public IList<string> AllowedUserRoles { get; }
}
}```
Revert "Add option for allowed user roles" | ```c#
using System;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public bool AllowRemote { get; set; }
}
}``` |
9df26a28-135f-455b-9f81-49773d7b8f0a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using UniProgramGen.Data;
namespace UniProgramGen
{
public partial class ResultsTab : UserControl
{
public ResultsTab()
{
InitializeComponent();
}
private List<Teacher> teachers;
private List<Room> rooms;
private List<Group> groups;
private List<Subject> subjects;
internal void InitializeBindingSources(
BindingSource teachersBS,
BindingSource roomsBS,
BindingSource groupsBS,
BindingSource subjectsBS)
{
teachers = (List<Teacher>)teachersBS.DataSource;
rooms = (List<Room>)roomsBS.DataSource;
groups = (List<Group>)groupsBS.DataSource;
subjects = (List<Subject>)subjectsBS.DataSource;
listBoxTeachers.DataSource = teachersBS;
listBoxRooms.DataSource = roomsBS;
listBoxGroups.DataSource = groupsBS;
}
private void buttonGenerate_Click(object sender, EventArgs e)
{
//new Generator.ProgramGenerator().GenerateProgram();
}
}
}
```
Add dumping of solution based on dummy data | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using UniProgramGen.Data;
namespace UniProgramGen
{
public partial class ResultsTab : UserControl
{
public ResultsTab()
{
InitializeComponent();
}
private List<Teacher> teachers;
private List<Room> rooms;
private List<Group> groups;
private List<Subject> subjects;
internal void InitializeBindingSources(
BindingSource teachersBS,
BindingSource roomsBS,
BindingSource groupsBS,
BindingSource subjectsBS)
{
teachers = (List<Teacher>)teachersBS.DataSource;
rooms = (List<Room>)roomsBS.DataSource;
groups = (List<Group>)groupsBS.DataSource;
subjects = (List<Subject>)subjectsBS.DataSource;
listBoxTeachers.DataSource = teachersBS;
listBoxRooms.DataSource = roomsBS;
listBoxGroups.DataSource = groupsBS;
}
private void buttonGenerate_Click(object sender, EventArgs e)
{
DumpExampleSolution();
return;
var generator = new Generator.ProgramGenerator();
var program = generator.GenerateProgram(rooms, subjects, teachers, groups);
}
private void DumpExampleSolution()
{
Data.DBManager db = new DBManager();
db.getTestData();
var program = new Generator.ProgramGenerator().GenerateProgram(db.rooms, db.subjects, db.teachers, db.groups);
var firstSolution = program.First();
string firstSolutionJson = Newtonsoft.Json.JsonConvert.SerializeObject(firstSolution);
System.IO.File.WriteAllText("../../datafiles/example_solution.json", firstSolutionJson);
}
}
}
``` |
dd439e87-8ccf-4990-9f35-382e89215a08 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace template_designer
{
public class JsonToDictionaryConverter
{
public static Dictionary<string, object> DeserializeJsonToDictionary(string json)
{
var jObject = JObject.Parse(json);
var dict = ParseObject(jObject);
return dict;
}
private static Dictionary<string, object> ParseObject(JObject jObject)
{
var dict = new Dictionary<string, object>();
foreach (var property in jObject.Properties())
{
if (property.Value.Type == JTokenType.Array)
{
dict.Add(property.Name, ParseArray(property.Value.ToObject<JArray>()));
}
else if (property.Value.Type == JTokenType.Object)
{
dict.Add(property.Name, ParseObject(property.Value.ToObject<JObject>()));
}
else
{
dict.Add(property.Name, property.Value.ToString());
}
}
return dict;
}
private static List<object> ParseArray(JArray value)
{
var list = new List<object>();
foreach (var child in value.Children())
{
if (child.Type == JTokenType.Array)
{
list.Add(ParseArray(child.ToObject<JArray>()));
}
else if (child.Type == JTokenType.Object)
{
list.Add(ParseObject(child.ToObject<JObject>()));
}
else
{
list.Add(child.ToString());
}
}
return list;
}
}
}```
Improve json conversion: support more types + cleanup code | ```c#
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace template_designer
{
public class JsonToDictionaryConverter
{
public static Dictionary<string, object> DeserializeJsonToDictionary(string json)
{
var jObject = JObject.Parse(json);
return ParseJObject(jObject);
}
private static Dictionary<string, object> ParseJObject(JObject jObject)
{
return jObject.Properties().ToDictionary(property => property.Name, property => ParseValue(property.Value));
}
private static object ParseValue(JToken value)
{
switch (value.Type)
{
case JTokenType.Array:
return ParseJArray(value.ToObject<JArray>());
case JTokenType.Object:
return ParseJObject(value.ToObject<JObject>());
case JTokenType.Boolean:
return value.ToObject<bool>();
case JTokenType.Integer:
return value.ToObject<int>();
case JTokenType.Float:
return value.ToObject<float>();
default:
return value.ToString();
}
}
private static List<object> ParseJArray(JArray value)
{
return value.Children().Select(ParseValue).ToList();
}
}
}``` |
e83a693a-51a3-47b9-afd4-c1bc64efd8ab | {
"language": "C#"
} | ```c#
// 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 Microsoft.CodeAnalysis.CodeStyle
{
internal partial class CodeStyleOption2<T>
{
public static explicit operator CodeStyleOption<T>(CodeStyleOption2<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption<T>(option.Value, (NotificationOption)option.Notification);
}
public static explicit operator CodeStyleOption2<T>(CodeStyleOption<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption2<T>(option.Value, (NotificationOption2)option.Notification);
}
}
}
```
Switch back to implicit operators for conversions to and from CodeStyleOption and CodeStyleOption2 respectively. These are needed to prevent InvalidCastException when user invokes `optionSet.WithChangedOption(..., new CodeStyleOption<bool>(...))` and any of our internal code base tries to fetch the option value with `optionSet.GetOption<T>(...)` where T is ` CodeStyleOption2<bool>`, and this helper attempts a direct cast from object to `T`. | ```c#
// 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 Microsoft.CodeAnalysis.CodeStyle
{
internal partial class CodeStyleOption2<T>
{
public static implicit operator CodeStyleOption<T>(CodeStyleOption2<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption<T>(option.Value, (NotificationOption)option.Notification);
}
public static implicit operator CodeStyleOption2<T>(CodeStyleOption<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption2<T>(option.Value, (NotificationOption2)option.Notification);
}
}
}
``` |
f1c9ee28-2e97-40cf-bbcf-965f4cab1c1a | {
"language": "C#"
} | ```c#
using Plantain;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("Plantain/Trigger/Propagator")]
public class TriggerPropagator : Trigger {
/// <summary>
/// A list of GameObjects that will have the current GameObject's triggers passed on to.
/// </summary>
public List<GameObject> targets;
/// <summary>
/// Used to prevent infinite propagation by allowing only 1 pass on.
/// </summary>
protected bool procced = false;
public void PerformTrigger(TriggerOption tOption) {
if(!procced && isActive) {
procced = true;
foreach(GameObject gameObj in targets) {
gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
}
procced = false;
}
}
void OnDrawGizmos() {
TriggerGizmos("Propagator");
Gizmos.color = Color.cyan;
GizmoTargetedObjects(targets);
}
}
```
Add option for only 1 hop propagation | ```c#
using Plantain;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("Plantain/Trigger/Propagator")]
public class TriggerPropagator : Trigger {
/// <summary>
/// Prevent a trigger from hopping any further than the targeted objects.
/// </summary>
public bool preventPropigation = false;
/// <summary>
/// A list of GameObjects that will have the current GameObject's triggers passed on to.
/// </summary>
public List<GameObject> targets;
/// <summary>
/// Used to prevent propigation for infinite loops, among other senarios.
/// </summary>
protected bool procced = false;
public void PerformTrigger(TriggerOption tOption) {
if(!procced && isActive) {
procced = true;
foreach(GameObject gameObj in targets) {
if(preventPropigation) {
TriggerPropagator[] propagators = gameObj.GetComponents<TriggerPropagator>();
foreach(TriggerPropagator propigator in propagators) {
propigator.procced = true;
}
gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
foreach(TriggerPropagator propigator in propagators) {
propigator.procced = false;
}
} else {
gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
}
}
procced = false;
}
}
void OnDrawGizmos() {
TriggerGizmos("Propagator");
Gizmos.color = Color.cyan;
GizmoTargetedObjects(targets);
}
}
``` |
88c50921-bbd2-416f-b199-7d010726f352 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Samesound
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
}
```
Add Database initializer to Global | ```c#
using Samesound.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Samesound
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<SamesoundContext>(null);
}
}
}
``` |
3167526a-9bef-439a-a8e4-13d8c6129820 | {
"language": "C#"
} | ```c#
@using Microsoft.AspNet.Identity
<div class="row">
<div class="col-md-6">
<h1>
@ViewBag.Title
<small>
@ViewBag.Lead
</small>
</h1>
</div>
<div class="col-md-6">
<ul class="nav nav-pills pull-right">
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<li><a href="/">Home</a></li>
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
}
}
else
{
<li><a href="/">Home</a></li>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
}
</ul>
</div>
</div>
<br /><br />
```
Fix logout form input button | ```c#
@using Microsoft.AspNet.Identity
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
}
<div class="row">
<div class="col-md-6">
<h1>
@ViewBag.Title
<small>
@ViewBag.Lead
</small>
</h1>
</div>
<div class="col-md-6">
<ul class="nav nav-pills pull-right">
@if (Request.IsAuthenticated)
{
<li><a href="/">Home</a></li>
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li>
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
</li>
}
else
{
<li><a href="/">Home</a></li>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
}
</ul>
</div>
</div>
<br /><br />
``` |
3c591329-cac9-45cf-b282-ed4fd8a026db | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace TcpSocketDataSender
{
public class TcpSocketManager : IDisposable
{
private TcpClient _tcpClient;
BinaryWriter _writer = null;
public int ServerPort = 7839;
public string ServerIp = "127.0.0.1";
public bool AutoReconnect = false;
public bool Connect()
{
if (_writer != null)
return true;
_tcpClient = new TcpClient();
try
{
_tcpClient.Connect(IPAddress.Parse(ServerIp), ServerPort);
_writer = new BinaryWriter(_tcpClient.GetStream());
}
catch (SocketException)
{
//No server avaliable, or it is busy/full.
return false;
}
return true;
}
public void Write(string data)
{
bool written = false;
try
{
if (_tcpClient?.Connected ?? false)
{
_writer?.Write(data);
written = true;
}
}
catch (IOException)
{
//connection most likely closed
_writer?.Dispose();
_writer = null;
((IDisposable)_tcpClient)?.Dispose();
}
if (!written && AutoReconnect)
{
if(Connect())
Write(data);
}
}
public void Dispose()
{
((IDisposable)_tcpClient)?.Dispose();
_writer?.Dispose();
}
}
}```
Make tcpSocketManager writes async to avoid blocking everything else | ```c#
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace TcpSocketDataSender
{
public class TcpSocketManager : IDisposable
{
private TcpClient _tcpClient;
BinaryWriter _writer = null;
public int ServerPort = 7839;
public string ServerIp = "127.0.0.1";
public bool AutoReconnect = false;
public async Task<bool> Connect()
{
if (_writer != null)
return true;
_tcpClient = new TcpClient();
try
{
await _tcpClient.ConnectAsync(IPAddress.Parse(ServerIp), ServerPort);
_writer = new BinaryWriter(_tcpClient.GetStream());
}
catch (SocketException)
{
//No server avaliable, or it is busy/full.
return false;
}
return true;
}
public async Task Write(string data)
{
bool written = false;
try
{
if (_tcpClient?.Connected ?? false)
{
_writer?.Write(data);
written = true;
}
}
catch (IOException)
{
//connection most likely closed
_writer?.Dispose();
_writer = null;
((IDisposable)_tcpClient)?.Dispose();
}
if (!written && AutoReconnect)
{
if(await Connect())
await Write(data);
}
}
public void Dispose()
{
((IDisposable)_tcpClient)?.Dispose();
_writer?.Dispose();
}
}
}``` |
9e76347a-06d1-423d-8063-47624a31c6f4 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
{
private readonly ISkin skin;
public LegacyAccuracyCounter(ISkin skin)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.75f);
Margin = new MarginPadding(10);
this.skin = skin;
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText() =>
new LegacySpriteText(skin, "score" /*, true*/)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
protected override void Update()
{
base.Update();
if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
{
// for now align with the score counter. eventually this will be user customisable.
Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
}
}
}
}
```
Adjust accuracy display to match stable | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
{
private readonly ISkin skin;
public LegacyAccuracyCounter(ISkin skin)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.6f);
Margin = new MarginPadding(10);
this.skin = skin;
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText() =>
new LegacySpriteText(skin, "score" /*, true*/)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
protected override void Update()
{
base.Update();
if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
{
// for now align with the score counter. eventually this will be user customisable.
Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
}
}
}
}
``` |
7a62e3b8-f301-4248-8aad-7eba1e565681 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Linq;
namespace Cams
{
class Program
{
static void Main(string[] args)
{
string rawDir = Path.Combine(Settings.Path, "raw");
string processedDir = Path.Combine(Settings.Path, "processed");
var cameras = Directory.GetDirectories(rawDir).Select(BuildCamera);
foreach (var cam in cameras)
cam.Process(processedDir);
var dates = Directory.GetDirectories(processedDir).Select(p => new VideoDate(p));
foreach (var date in dates)
date.Summarize();
#if DEBUG
Console.ReadKey();
#endif
}
static Camera BuildCamera(string path)
{
bool isAmcrest = File.Exists(Path.Combine(path, "DVRWorkDirectory"));
if (isAmcrest)
return new AmcrestCamera(path);
return new FoscamCamera(path);
}
}
}
```
Add message to exit in debug mode | ```c#
using System;
using System.IO;
using System.Linq;
namespace Cams
{
class Program
{
static void Main(string[] args)
{
string rawDir = Path.Combine(Settings.Path, "raw");
string processedDir = Path.Combine(Settings.Path, "processed");
var cameras = Directory.GetDirectories(rawDir).Select(BuildCamera);
foreach (var cam in cameras)
cam.Process(processedDir);
var dates = Directory.GetDirectories(processedDir).Select(p => new VideoDate(p));
foreach (var date in dates)
date.Summarize();
#if DEBUG
Console.WriteLine();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
#endif
}
static Camera BuildCamera(string path)
{
bool isAmcrest = File.Exists(Path.Combine(path, "DVRWorkDirectory"));
if (isAmcrest)
return new AmcrestCamera(path);
return new FoscamCamera(path);
}
}
}
``` |
ef4b144b-2269-4c55-9ac9-58980aa3f6aa | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("GitHubFeeds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bradley Grainger")]
[assembly: AssemblyProduct("GitHubFeeds")]
[assembly: AssemblyCopyright("Copyright 2012 Bradley Grainger")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
```
Allow compiler to set assembly version. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("GitHubFeeds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bradley Grainger")]
[assembly: AssemblyProduct("GitHubFeeds")]
[assembly: AssemblyCopyright("Copyright 2012 Bradley Grainger")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.*")]
``` |
5e37ed81-d363-49eb-961f-1fe63d8f25d3 | {
"language": "C#"
} | ```c#
<div ng-controller="CreateBasicPageController">
<div>
<h2>Regular Poller?</h2>
Register for more config options. It's free!
</div>
<form name="quickPollForm">
<div id="question-block">
Your Question <br />
<input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />
</div>
<div id="quickpoll-block">
<button type="submit" class="inactive-btn shadowed" ng-click="createPoll(pollQuestion)" ng-disabled="quickPollForm.$invalid">Quick Poll</button>
</div>
</form>
<h3 class="centered-text horizontal-ruled">or</h3>
<div id="register-block">
<button class="active-btn shadowed" ng-click="openLoginDialog()">Sign In</button>
<button class="active-btn shadowed" ng-click="openRegisterDialog()">Register</button>
</div>
</div>
```
Return now submits quick poll | ```c#
<div ng-controller="CreateBasicPageController">
<div>
<h2>Regular Poller?</h2>
Register for more config options. It's free!
</div>
<form name="quickPollForm" ng-submit="createPoll(pollQuestion)">
<div id="question-block">
Your Question <br />
<input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />
</div>
<div id="quickpoll-block">
<button type="submit" class="inactive-btn shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button>
</div>
</form>
<h3 class="centered-text horizontal-ruled">or</h3>
<div id="register-block">
<button class="active-btn shadowed" ng-click="openLoginDialog()">Sign In</button>
<button class="active-btn shadowed" ng-click="openRegisterDialog()">Register</button>
</div>
</div>
``` |
0cd521e8-70ce-4680-a1d9-5451cd55042a | {
"language": "C#"
} | ```c#
```
Add UserVoice widget to global footer. | ```c#
@using GiveCRM.Web.Infrastructure
@if (ConfigurationSettings.IsUserVoiceIntegrationEnabled)
{
<script type="text/javascript">
var uvOptions = { };
(function() {
var uv = document.createElement('script');
uv.type = 'text/javascript';
uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/XMFifLxGL4npm6SHybYvtw.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(uv, s);
})();
</script>
}``` |
2a65f6ef-28e7-4f2c-b867-9c8c7a0bd7ae | {
"language": "C#"
} | ```c#
@if (Request.IsAuthenticated) {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> @Session["DisplayName"]<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Profile", "Profile", "User")</li>
<li class="divider"></li>
<li>@Html.ActionLink("Log Out", "Logout", "User")</li>
</ul>
} else {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> Log In<span class="caret"></span> </a>
<ul class="dropdown-menu">
<li><a href="@ViewBag.GoogleLoginUrl" id="googleLoginLink">Log in with Google</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="facebookLoginLink">Log in with Facebook</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="twitterLoginLink">Log in with Twitter</a></li>
<li><a data-toggle="modal" href="#openIdLogin">Log in with an OpenID</a></li>
<li class="divider"></li>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
</ul>
}```
Fix Log Out link so it works everywhere. | ```c#
@if (Request.IsAuthenticated) {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> @Session["DisplayName"]<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Profile", "Profile", "User")</li>
<li class="divider"></li>
<li>@Html.ActionLink("Log Out", "Logout", "User", new { Area = string.Empty }, htmlAttributes: null)</li>
</ul>
} else {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> Log In<span class="caret"></span> </a>
<ul class="dropdown-menu">
<li><a href="@ViewBag.GoogleLoginUrl" id="googleLoginLink">Log in with Google</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="facebookLoginLink">Log in with Facebook</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="twitterLoginLink">Log in with Twitter</a></li>
<li><a data-toggle="modal" href="#openIdLogin">Log in with an OpenID</a></li>
<li class="divider"></li>
<li>@Html.ActionLink("Register", "Register", "Account", htmlAttributes: new { id = "registerLink" })</li>
</ul>
}``` |
35529edf-6a03-4730-96d0-67ba69ad1b9f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fitSharp.Machine.Engine;
using fitSharp.Machine.Model;
using NUnit.Framework;
using fitSharp.Samples.Fit;
using fitSharp.Fit.Operators;
namespace fitSharp.Test.NUnit.Fit {
public class ParseOperatorTest<ParseOperatorType>
where ParseOperatorType : CellOperator, ParseOperator<Cell>, new() {
ParseOperatorType parser;
public ParseOperatorTest() {
// Parse operators are stateless, so no need to use SetUp.
parser = new ParseOperatorType { Processor = Builder.CellProcessor() };
}
protected bool CanParse<T>(string cellContent) {
return parser.CanParse(typeof(T), TypedValue.Void, new CellTreeLeaf(cellContent));
}
protected T Parse<T>(string cellContent) where T : class {
return Parse<T>(cellContent, TypedValue.Void);
}
protected T Parse<T>(string cellContent, TypedValue instance) where T : class {
TypedValue result = parser.Parse(typeof(string), TypedValue.Void, new CellTreeLeaf(cellContent));
return result.GetValueAs<T>();
}
}
}
```
Refactor Expose parse operator to deriving tests. Use [SetUp] attribute to recreate parser for every test. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fitSharp.Machine.Engine;
using fitSharp.Machine.Model;
using NUnit.Framework;
using fitSharp.Samples.Fit;
using fitSharp.Fit.Operators;
namespace fitSharp.Test.NUnit.Fit {
public class ParseOperatorTest<ParseOperatorType>
where ParseOperatorType : CellOperator, ParseOperator<Cell>, new() {
public ParseOperatorType Parser { get; private set; }
[SetUp]
public void SetUp() {
// Parse operators are stateless, but the processor may be mutated
// by Parse(), so recreate for every test
Parser = new ParseOperatorType { Processor = Builder.CellProcessor() };
}
protected bool CanParse<T>(string cellContent) {
return Parser.CanParse(typeof(T), TypedValue.Void, new CellTreeLeaf(cellContent));
}
protected T Parse<T>(string cellContent) where T : class {
return Parse<T>(cellContent, TypedValue.Void);
}
protected T Parse<T>(string cellContent, TypedValue instance) where T : class {
TypedValue result = Parser.Parse(typeof(string), TypedValue.Void, new CellTreeLeaf(cellContent));
return result.GetValueAs<T>();
}
}
}
``` |
8dd34303-c537-4925-bf73-a480f1b1bd9f | {
"language": "C#"
} | ```c#
using System;
using System.Data;
namespace Gigobyte.Daterpillar.Data
{
public class SQLiteSchemaAggregator : SchemaAggregatorBase
{
public SQLiteSchemaAggregator(IDbConnection connection) : base(connection)
{
}
protected override string GetColumnInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetForeignKeyInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetIndexColumnsQuery(string indexIdentifier)
{
throw new NotImplementedException();
}
protected override string GetIndexInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetTableInfoQuery()
{
throw new NotImplementedException();
}
}
}```
Add implementation details to SQLiteSchema Aggregator | ```c#
using System;
using System.Data;
using Gigobyte.Daterpillar.Transformation;
using System.Text.RegularExpressions;
namespace Gigobyte.Daterpillar.Data
{
public class SQLiteSchemaAggregator : SchemaAggregatorBase
{
public SQLiteSchemaAggregator(IDbConnection connection) : base(connection)
{
}
protected override void LoadColumnInformationIntoSchema(Table table, DataTable columnInfo)
{
foreach (DataRow row in columnInfo.Rows)
{
string temp;
string typeName = Convert.ToString(row[ColumnName.Type]);
typeName = (typeName == "INTEGER" ? "int" : typeName.ToLower());
temp = _dataTypeRegex.Match(typeName)?.Groups["scale"]?.Value;
int scale = Convert.ToInt32((string.IsNullOrEmpty(temp) ? "0" : temp));
temp = _dataTypeRegex.Match(typeName)?.Groups["precision"]?.Value;
int precision = Convert.ToInt32((string.IsNullOrEmpty(temp) ? "0" : temp));
string defaultValue = Convert.ToString(row["dflt_value"]);
var newColumn = new Column();
newColumn.Name = Convert.ToString(row[ColumnName.Name]);
newColumn.DataType = new DataType(typeName, scale, precision);
//newColumn.AutoIncrement = Convert.ToBoolean(row[ColumnName.Auto]);
newColumn.IsNullable = !Convert.ToBoolean(row["notnull"]);
if (!string.IsNullOrEmpty(defaultValue)) newColumn.Modifiers.Add(defaultValue);
table.Columns.Add(newColumn);
}
}
protected override void LoadForeignKeyInformationIntoSchema(Table table, DataTable foreignKeyInfo)
{
base.LoadForeignKeyInformationIntoSchema(table, foreignKeyInfo);
}
protected override string GetColumnInfoQuery(string tableName)
{
return $"PRAGMA table_info('{tableName}');";
}
protected override string GetForeignKeyInfoQuery(string tableName)
{
return $"PRAGMA foreign_key_list('{tableName}');";
}
protected override string GetIndexColumnsQuery(string indexIdentifier)
{
throw new NotImplementedException();
}
protected override string GetIndexInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetTableInfoQuery()
{
return $"select sm.tbl_name AS [Name], '' AS [Comment] from sqlite_master sm WHERE sm.sql IS NOT NULL AND sm.name <> 'sqlite_sequence' AND sm.type = 'table';";
}
#region Private Members
private Regex _dataTypeRegex = new Regex(@"\((?<scale>\d+),? ?(?<precision>\d+)\)", RegexOptions.Compiled);
#endregion
}
}``` |
ce114dea-337c-4671-ae9e-c6391414ce9b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace Psistats.App
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
// Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainScreen2());
}
static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("CurrentDomain: Whoops! Please contact the developers with the following"
+ " information:\n\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
public static void Application_ThreadException (object sender, System.Threading.ThreadExceptionEventArgs e)
{
DialogResult result = DialogResult.Abort;
try
{
result = MessageBox.Show("Application: Whoops! Please contact the developers with the"
+ " following information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
"Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
if (result == DialogResult.Abort)
{
Application.Exit();
}
}
}
}
}
```
Fix last remaining critical issue in sonar | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace Psistats.App
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainScreen2());
}
static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("CurrentDomain: Whoops! Please contact the developers with the following"
+ " information:\n\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
public static void Application_ThreadException (object sender, System.Threading.ThreadExceptionEventArgs e)
{
DialogResult result = DialogResult.Abort;
try
{
result = MessageBox.Show("Application: Whoops! Please contact the developers with the"
+ " following information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
"Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
if (result == DialogResult.Abort)
{
Application.Exit();
}
}
}
}
}
``` |
c1033523-9cfa-4472-a1e3-a77967dbce92 | {
"language": "C#"
} | ```c#
using System.Reflection;
using Xunit;
namespace System.Text.Utf8.Tests
{
public class TypeConstraintsTests
{
[Fact]
public void Utf8StringIsAStruct()
{
var utf8String = "anyString"u8;
Assert.True(utf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodeUnitsEnumeratorIsAStruct()
{
var utf8String = "anyString"u8;
var utf8CodeUnitsEnumerator = utf8String.GetEnumerator();
Assert.True(utf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumerableIsAStruct()
{
var utf8String = "anyString"u8;
Assert.True(utf8String.CodePoints.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumeratorIsAStruct()
{
var utf8String = "anyString"u8;
var utf8CodePointEnumerator = utf8String.CodePoints.GetEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringReverseCodePointEnumeratorIsAStruct()
{
var utf8String = "anyString"u8;
var utf8CodePointEnumerator = utf8String.CodePoints.GetReverseEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
}
}
```
Replace hard coded string with field in utf8string tests where the value is irrelevant | ```c#
using System.Reflection;
using Xunit;
namespace System.Text.Utf8.Tests
{
public class TypeConstraintsTests
{
private Utf8String _anyUtf8String;
public TypeConstraintsTests()
{
_anyUtf8String = "anyString"u8;
}
[Fact]
public void Utf8StringIsAStruct()
{
Assert.True(_anyUtf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodeUnitsEnumeratorIsAStruct()
{
var utf8CodeUnitsEnumerator = _anyUtf8String.GetEnumerator();
Assert.True(_anyUtf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumerableIsAStruct()
{
Assert.True(_anyUtf8String.CodePoints.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumeratorIsAStruct()
{
var utf8CodePointEnumerator = _anyUtf8String.CodePoints.GetEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringReverseCodePointEnumeratorIsAStruct()
{
var utf8CodePointEnumerator = _anyUtf8String.CodePoints.GetReverseEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
}
}
``` |
1d7fb0dd-f827-4b11-9514-e7844bbad392 | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.SignalR")]
[assembly: AssemblyDescription("")]
```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.SignalR")]
``` |
ce5b3d18-1ca3-43d7-b1ac-770399741b18 | {
"language": "C#"
} | ```c#
using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;
namespace Cake.Terraform
{
public class TerraformApplyRunner : TerraformRunner<TerraformApplySettings>
{
public TerraformApplyRunner(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools)
: base(fileSystem, environment, processRunner, tools)
{
}
public void Run(TerraformApplySettings settings)
{
var builder = new ProcessArgumentBuilder()
.Append("apply");
// Order of AutoApprove and Plan are important.
if (settings.AutoApprove)
{
builder.Append("-auto-approve");
}
// Use Plan if it exists.
if (settings.Plan != null)
{
builder.Append(settings.Plan);
}
if (!string.IsNullOrEmpty(settings.InputVariablesFile))
{
builder.AppendSwitchQuoted("-var-file", $"{settings.InputVariablesFile}");
}
if (settings.InputVariables != null)
{
foreach (var inputVariable in settings.InputVariables)
{
builder.AppendSwitchQuoted("-var", $"{inputVariable.Key}={inputVariable.Value}");
}
}
Run(settings, builder);
}
}
}```
Use fullpath for Plan in Apply command | ```c#
using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;
namespace Cake.Terraform
{
public class TerraformApplyRunner : TerraformRunner<TerraformApplySettings>
{
public TerraformApplyRunner(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools)
: base(fileSystem, environment, processRunner, tools)
{
}
public void Run(TerraformApplySettings settings)
{
var builder = new ProcessArgumentBuilder()
.Append("apply");
// Order of AutoApprove and Plan are important.
if (settings.AutoApprove)
{
builder.Append("-auto-approve");
}
// Use Plan if it exists.
if (settings.Plan != null)
{
builder.Append(settings.Plan.FullPath);
}
if (!string.IsNullOrEmpty(settings.InputVariablesFile))
{
builder.AppendSwitchQuoted("-var-file", $"{settings.InputVariablesFile}");
}
if (settings.InputVariables != null)
{
foreach (var inputVariable in settings.InputVariables)
{
builder.AppendSwitchQuoted("-var", $"{inputVariable.Key}={inputVariable.Value}");
}
}
Run(settings, builder);
}
}
}``` |
2e1ce52d-8af7-43e3-b923-5ed1c3e9d6d5 | {
"language": "C#"
} | ```c#
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
namespace IronAHK.Scripting
{
partial class Parser : ICodeParser
{
Dictionary<string, CodeMemberMethod> methods;
Type core;
const string mainScope = "";
CodeEntryPointMethod main;
/// <summary>
/// Return a DOM representation of a script.
/// </summary>
public CodeCompileUnit CompileUnit
{
get
{
CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace space = new CodeNamespace(core.Namespace + ".Instance");
unit.Namespaces.Add(space);
var container = new CodeTypeDeclaration("Program");
container.BaseTypes.Add(core.BaseType);
//container.BaseTypes.Add(core);
container.Attributes = MemberAttributes.Private;
space.Types.Add(container);
foreach (CodeMemberMethod method in methods.Values)
container.Members.Add(method);
return unit;
}
}
public Parser()
{
main = new CodeEntryPointMethod();
main.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(STAThreadAttribute))));
methods = new Dictionary<string, CodeMemberMethod>();
methods.Add(mainScope, main);
core = typeof(Script);
internalID = 0;
}
public CodeCompileUnit Parse(TextReader codeStream)
{
var lines = Read(codeStream, null);
Compile(lines);
return CompileUnit;
}
}
}
```
Set correct base type for script instances. | ```c#
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
namespace IronAHK.Scripting
{
partial class Parser : ICodeParser
{
Dictionary<string, CodeMemberMethod> methods;
Type core;
const string mainScope = "";
CodeEntryPointMethod main;
/// <summary>
/// Return a DOM representation of a script.
/// </summary>
public CodeCompileUnit CompileUnit
{
get
{
CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace space = new CodeNamespace(core.Namespace + ".Instance");
unit.Namespaces.Add(space);
var container = new CodeTypeDeclaration("Program");
container.BaseTypes.Add(typeof(Script));
container.Attributes = MemberAttributes.Private;
space.Types.Add(container);
foreach (CodeMemberMethod method in methods.Values)
container.Members.Add(method);
return unit;
}
}
public Parser()
{
main = new CodeEntryPointMethod();
main.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(STAThreadAttribute))));
methods = new Dictionary<string, CodeMemberMethod>();
methods.Add(mainScope, main);
core = typeof(Script);
internalID = 0;
}
public CodeCompileUnit Parse(TextReader codeStream)
{
var lines = Read(codeStream, null);
Compile(lines);
return CompileUnit;
}
}
}
``` |
e67cec48-3963-4d00-9905-87e9438f25bc | {
"language": "C#"
} | ```c#
@using CkanDotNet.Api.Model
@model Package
<div class="container">
<h2 class="container-title">Rate this Package</h2>
<div class="container-content">
@Html.Partial("~/Views/Shared/_Rating.cshtml", Model, new ViewDataDictionary { { "editable", true } })
</div>
</div>
```
Change ui text "Package" to "Dataset" | ```c#
@using CkanDotNet.Api.Model
@model Package
<div class="container">
<h2 class="container-title">Rate this Dataset</h2>
<div class="container-content">
@Html.Partial("~/Views/Shared/_Rating.cshtml", Model, new ViewDataDictionary { { "editable", true } })
</div>
</div>
``` |
7dea68db-16b7-4d35-92ad-26ae74f51b73 | {
"language": "C#"
} | ```c#
using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class LineBreakParser : IParser<LineBreak>
{
public string StartsWithChars { get { return "\\ \n"; } }
public LineBreak Parse(ParserContext context, Subject subject)
{
if (!this.CanParse(subject)) return null;
string[] groups;
if (subject.IsMatch(@" +\n", 0, out groups))
{
subject.Advance(groups[0].Length);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith("\\\n", 0))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith(" \n", 0))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
else if (subject.Char == '\n')
{
subject.Advance();
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
return null;
}
}
}
```
Use Regex in stead of string | ```c#
using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class LineBreakParser : IParser<LineBreak>
{
private static readonly Regex _startsWithDoubleSpaceNewLine = RegexUtils.Create(@"\G +\n");
public string StartsWithChars { get { return "\\ \n"; } }
public LineBreak Parse(ParserContext context, Subject subject)
{
if (!this.CanParse(subject)) return null;
string[] groups;
if (subject.IsMatch(_startsWithDoubleSpaceNewLine, 0, out groups))
{
subject.Advance(groups[0].Length);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith("\\\n"))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith(" \n"))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
else if (subject.Char == '\n')
{
subject.Advance();
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
return null;
}
}
}
``` |
7a2b630e-4a9a-40eb-b2ca-4ec9fefde8b1 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace Stripe
{
public class StripeCustomerListOptions : StripeListOptions
{
[JsonProperty("created")]
public StripeDateFilter Created { get; set; }
}
}```
Add the ability to list customers via email address | ```c#
using Newtonsoft.Json;
namespace Stripe
{
public class StripeCustomerListOptions : StripeListOptions
{
[JsonProperty("created")]
public StripeDateFilter Created { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
}
}``` |
708a57b1-d974-4fad-b714-2bd36fd7a9ac | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using Arango.Client.Protocol;
namespace Arango.Client
{
public static class ArangoClient
{
private static List<Connection> _connections = new List<Connection>();
public static string DriverName
{
get { return "ArangoDB-NET"; }
}
public static string DriverVersion
{
get { return "0.7.0"; }
}
public static ArangoSettings Settings { get; set; }
static ArangoClient()
{
Settings = new ArangoSettings();
}
public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias)
{
var connection = new Connection(hostname, port, isSecured, userName, password, alias);
_connections.Add(connection);
}
internal static Connection GetConnection(string alias)
{
return _connections.Where(connection => connection.Alias == alias).FirstOrDefault();
}
}
}
```
Make driver name and version static properties constants and use dictionary structure for connections to simplify their retrieval. | ```c#
using System.Collections.Generic;
using System.Linq;
using Arango.Client.Protocol;
namespace Arango.Client
{
public static class ArangoClient
{
private static Dictionary<string, Connection> _connections = new Dictionary<string, Connection>();
public const string DriverName = "ArangoDB-NET";
public const string DriverVersion = "0.7.0";
public static ArangoSettings Settings { get; set; }
static ArangoClient()
{
Settings = new ArangoSettings();
}
public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias)
{
_connections.Add(
alias,
new Connection(hostname, port, isSecured, userName, password, alias)
);
}
internal static Connection GetConnection(string alias)
{
return _connections[alias];
}
}
}
``` |
22b7f25d-5d9b-4d88-bb7a-ebc801710b61 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BlogTemplate.Models;
namespace BlogTemplate.Pages
{
public class PostModel : PageModel
{
private Blog _blog;
public PostModel(Blog blog)
{
_blog = blog;
}
public Post Post { get; set; }
public void OnGet()
{
string slug = RouteData.Values["slug"].ToString();
Post = _blog.Posts.FirstOrDefault(p => p.Slug == slug);
}
}
}
```
Read in post data from the data store | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BlogTemplate.Models;
namespace BlogTemplate.Pages
{
public class PostModel : PageModel
{
private Blog _blog;
public PostModel(Blog blog)
{
_blog = blog;
}
public Post Post { get; set; }
public void OnGet()
{
string slug = RouteData.Values["slug"].ToString();
Post = _blog.Posts.FirstOrDefault(p => p.Slug == slug);
BlogDataStore dataStore = new BlogDataStore();
Post = dataStore.GetPost(slug);
if(Post == null)
{
RedirectToPage("/Index");
}
}
}
}
``` |
33c3690d-e145-4730-a26b-303115ffd01d | {
"language": "C#"
} | ```c#
namespace food_tracker {
public class NutritionItem {
public string name { get; set; }
public double calories { get; set; }
public double carbohydrates { get; set; }
public double sugars { get; set; }
public double fats { get; set; }
public double saturatedFats { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
public NutritionItem(string name, double calories, double carbohydrates, double sugars, double fats, double satFat, double protein, double salt, double fibre) {
this.name = name;
this.calories = calories;
this.carbohydrates = carbohydrates;
this.sugars = sugars;
this.fats = fats;
this.saturatedFats = satFat;
this.protein = protein;
this.salt = salt;
this.fibre = fibre;
}
}
}
```
Add defulat constructor and add day as an attribute | ```c#
using System.ComponentModel.DataAnnotations;
namespace food_tracker {
public class NutritionItem {
[Key]
public int NutritionItemId { get; set; }
public string name { get; set; }
public string dayId { get; set; }
public double calories { get; set; }
public double carbohydrates { get; set; }
public double sugars { get; set; }
public double fats { get; set; }
public double saturatedFats { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
public NutritionItem() { }
public NutritionItem(string name, string day, double calories, double carbohydrates, double sugars, double fats, double satFat, double protein, double salt, double fibre) {
this.name = name;
this.dayId = day;
this.calories = calories;
this.carbohydrates = carbohydrates;
this.sugars = sugars;
this.fats = fats;
this.saturatedFats = satFat;
this.protein = protein;
this.salt = salt;
this.fibre = fibre;
}
}
}
``` |
71143900-13ba-411e-b377-b81d318b1ec5 | {
"language": "C#"
} | ```c#
using Bugsnag.Payload;
namespace Bugsnag
{
public interface IClient
{
void Notify(System.Exception exception, Request request = null);
void Notify(System.Exception exception, Severity severity, Request request = null);
void Notify(System.Exception exception, HandledState severity, Request request = null);
void Notify(Report report);
IBreadcrumbs Breadcrumbs { get; }
ISessionTracker SessionTracking { get; }
IConfiguration Configuration { get; }
}
}
```
Add before notify to client interface | ```c#
using Bugsnag.Payload;
namespace Bugsnag
{
public interface IClient
{
void Notify(System.Exception exception, Request request = null);
void Notify(System.Exception exception, Severity severity, Request request = null);
void Notify(System.Exception exception, HandledState severity, Request request = null);
void Notify(Report report);
IBreadcrumbs Breadcrumbs { get; }
ISessionTracker SessionTracking { get; }
IConfiguration Configuration { get; }
void BeforeNotify(Middleware middleware);
}
}
``` |
d6a4720f-f6cc-41bb-a08b-270da3e26a4e | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
namespace SPAD.neXt.Interfaces.Base
{
public interface ISPADBackgroundThread
{
string WorkerName { get; }
bool IsRunning { get; }
TimeSpan Interval { get; }
bool ScheduleOnTimeout { get; }
EventWaitHandle SignalHandle { get; }
EventWaitHandle StopHandle { get; }
bool IsPaused { get; }
bool IsActive();
void Signal();
void Start();
void Start(uint waitInterval);
void Start(uint waitInterval, object argument);
void Pause();
void Continue();
bool CanContinue();
void Stop();
void Abort();
void SetImmuneToPreStop(bool v);
void SetArgument(object argument);
void SetContinousMode(bool mode);
void SetIntervall(TimeSpan newInterval);
void SetScheduleOnTimeout(bool mode);
}
public interface ISPADBackgroundWorker
{
void BackgroundProcessingStart(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingContinue(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingStop(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingDoWork(ISPADBackgroundThread workerThread, object argument);
}
}
```
Add support to set thread priority | ```c#
using System;
using System.Threading;
namespace SPAD.neXt.Interfaces.Base
{
public interface ISPADBackgroundThread
{
string WorkerName { get; }
bool IsRunning { get; }
TimeSpan Interval { get; }
bool ScheduleOnTimeout { get; }
EventWaitHandle SignalHandle { get; }
EventWaitHandle StopHandle { get; }
bool IsPaused { get; }
bool IsActive();
void Signal();
void Start();
void Start(uint waitInterval);
void Start(uint waitInterval, object argument);
void Pause();
void Continue();
bool CanContinue();
void Stop();
void Abort();
void SetImmuneToPreStop(bool v);
void SetArgument(object argument);
void SetContinousMode(bool mode);
void SetIntervall(TimeSpan newInterval);
void SetScheduleOnTimeout(bool mode);
void SetPriority(ThreadPriority priority);
}
public interface ISPADBackgroundWorker
{
void BackgroundProcessingStart(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingContinue(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingStop(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingDoWork(ISPADBackgroundThread workerThread, object argument);
}
}
``` |
564d84db-dc6e-4b6e-83a7-9de447ef40b9 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3449735700206298d, 151, "diffcalc-test")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(2.7879104989252959d, 151, "diffcalc-test")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new ManiaModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
```
Update max combo test value | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3449735700206298d, 242, "diffcalc-test")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(2.7879104989252959d, 242, "diffcalc-test")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new ManiaModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
``` |
14073370-cdde-4a2c-a3d3-65054bb9142e | {
"language": "C#"
} | ```c#
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("DataStats")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DataStats")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("26b9df58-5fa9-42e5-95b0-444a259a3e68")]
// 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")]
```
Update build properties with correct data | ```c#
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("DataStats")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("J.D. Sandifer")]
[assembly: AssemblyProduct("DataStats")]
[assembly: AssemblyCopyright("© 2016 J.D. Sandifer")]
[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("26b9df58-5fa9-42e5-95b0-444a259a3e68")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
``` |
898aa0ee-b14e-4d45-ba60-dc020404f8ca | {
"language": "C#"
} | ```c#
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("OWLib")]
[assembly: AssemblyDescription("Common Overwatch Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OWLib")]
[assembly: AssemblyCopyright("Copyright © 2016-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(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("353c0d05-c505-4df4-909e-624fd94a7d3b")]
// 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.10.0.0")]
[assembly: AssemblyFileVersion("1.10.0.0")]
```
Add unknown file version placeholder | ```c#
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("OWLib")]
[assembly: AssemblyDescription("Common Overwatch Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OWLib")]
[assembly: AssemblyCopyright("Copyright © 2016-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(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("353c0d05-c505-4df4-909e-624fd94a7d3b")]
// 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.10.0.0")]
[assembly: AssemblyFileVersion("1.10.0.0")]
[assembly: AssemblyInformationalVersion("unknown")]
``` |
e6386ac2-791a-4263-bd13-e054b42413d5 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetResponse : IResponse
{
private readonly HttpRequestBase _request;
private readonly HttpResponseBase _response;
public AspNetResponse(HttpRequestBase request, HttpResponseBase response)
{
_request = request;
_response = response;
}
public bool Buffer
{
get
{
return _response.Buffer;
}
set
{
_response.Buffer = value;
_response.Buffer = value;
_response.BufferOutput = value;
if (!value)
{
// This forces the IIS compression module to leave this response alone.
// If we don't do this, it will buffer the response to suit its own compression
// logic, resulting in partial messages being sent to the client.
_request.Headers.Remove("Accept-Encoding");
_response.CacheControl = "no-cache";
_response.AddHeader("Connection", "keep-alive");
}
}
}
public bool IsClientConnected
{
get
{
return _response.IsClientConnected;
}
}
public string ContentType
{
get
{
return _response.ContentType;
}
set
{
_response.ContentType = value;
}
}
public Task WriteAsync(string data)
{
_response.Write(data);
return TaskAsyncHelper.Empty;
}
}
}
```
Remove duplicate line (copy paste bug). | ```c#
using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetResponse : IResponse
{
private readonly HttpRequestBase _request;
private readonly HttpResponseBase _response;
public AspNetResponse(HttpRequestBase request, HttpResponseBase response)
{
_request = request;
_response = response;
}
public bool Buffer
{
get
{
return _response.Buffer;
}
set
{
_response.Buffer = value;
_response.BufferOutput = value;
if (!value)
{
// This forces the IIS compression module to leave this response alone.
// If we don't do this, it will buffer the response to suit its own compression
// logic, resulting in partial messages being sent to the client.
_request.Headers.Remove("Accept-Encoding");
_response.CacheControl = "no-cache";
_response.AddHeader("Connection", "keep-alive");
}
}
}
public bool IsClientConnected
{
get
{
return _response.IsClientConnected;
}
}
public string ContentType
{
get
{
return _response.ContentType;
}
set
{
_response.ContentType = value;
}
}
public Task WriteAsync(string data)
{
_response.Write(data);
return TaskAsyncHelper.Empty;
}
}
}
``` |
2ea23c41-0a34-4f00-9073-3d88447bd60b | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace DevelopmentInProgress.DipState
{
public interface IDipState
{
int Id { get; }
string Name { get; }
bool IsDirty { get; }
bool InitialiseWithParent { get; }
DipStateType Type { get; }
DipStateStatus Status { get; }
IDipState Parent { get; }
IDipState Antecedent { get; }
IDipState Transition { get; set; }
List<IDipState> Transitions { get; }
List<IDipState> Dependencies { get; }
List<IDipState> SubStates { get; }
List<StateAction> Actions { get; }
List<LogEntry> Log { get; }
bool CanComplete();
void Reset();
}
}```
Add additional methods to interface | ```c#
using System;
using System.Collections.Generic;
namespace DevelopmentInProgress.DipState
{
public interface IDipState
{
int Id { get; }
string Name { get; }
bool IsDirty { get; }
bool InitialiseWithParent { get; }
DipStateType Type { get; }
DipStateStatus Status { get; }
IDipState Parent { get; }
IDipState Antecedent { get; }
IDipState Transition { get; set; }
List<IDipState> Transitions { get; }
List<IDipState> Dependencies { get; }
List<IDipState> SubStates { get; }
List<StateAction> Actions { get; }
List<LogEntry> Log { get; }
bool CanComplete();
void Reset();
DipState AddTransition(IDipState transition);
DipState AddDependency(IDipState dependency);
DipState AddSubState(IDipState subState);
DipState AddAction(DipStateActionType actionType, Action<IDipState> action);
}
}``` |
d35dc049-1720-468e-ae6e-1df4bdcf6698 | {
"language": "C#"
} | ```c#
using System.IO;
namespace LINQToTreeHelpers.FutureUtils
{
/// <summary>
/// Future TFile - really just a normal TFile, but gets written out in the future...
/// </summary>
public class FutureTFile : FutureTDirectory
{
private static ROOTNET.Interface.NTFile CreateOpenFile(string name)
{
var f = ROOTNET.NTFile.Open(name, "RECREATE");
return f;
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(FileInfo outputRootFile)
: base(CreateOpenFile(outputRootFile.FullName))
{
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(string outputRootFile)
: base(CreateOpenFile(outputRootFile))
{
}
/// <summary>
/// Close this file. Resolves all futures, writes the directories, and closes the file
/// </summary>
public void Close()
{
//
// Write out this guy and close it!
//
Write();
Directory.Close();
}
}
}
```
Make sure file is open before getting on with it. | ```c#
using System;
using System.IO;
namespace LINQToTreeHelpers.FutureUtils
{
/// <summary>
/// Future TFile - really just a normal TFile, but gets written out in the future...
/// </summary>
public class FutureTFile : FutureTDirectory
{
private static ROOTNET.Interface.NTFile CreateOpenFile(string name)
{
var f = ROOTNET.NTFile.Open(name, "RECREATE");
if (!f.IsOpen())
{
throw new InvalidOperationException(string.Format("Unable to create file '{0}'. It could be the file is locked by another process (like ROOT!!??)", name));
}
return f;
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(FileInfo outputRootFile)
: base(CreateOpenFile(outputRootFile.FullName))
{
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(string outputRootFile)
: base(CreateOpenFile(outputRootFile))
{
}
/// <summary>
/// Close this file. Resolves all futures, writes the directories, and closes the file
/// </summary>
public void Close()
{
//
// Write out this guy and close it!
//
Write();
Directory.Close();
}
}
}
``` |
501afef9-8721-411f-b02b-e9f9385c46f2 | {
"language": "C#"
} | ```c#
using Discord;
using Discord.Commands;
using Discord.Rest;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SoraBot.Data.Configurations;
namespace SoraBot.Bot.Extensions
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddSoraBot(this IServiceCollection services)
{
services.AddSingleton(
provider => new DiscordSocketClient(new DiscordSocketConfig()
{
AlwaysDownloadUsers = false,
LogLevel = LogSeverity.Debug,
MessageCacheSize = 0, // Let's have this disabled for now.
TotalShards = provider.GetService<IOptions<SoraBotConfig>>().Value.TotalShards,
ShardId = 0 // TODO make this configurable
}));
services.AddSingleton(new DiscordRestClient(new DiscordRestConfig()
{
LogLevel = LogSeverity.Debug
}));
services.AddSingleton(_ =>
{
var service = new CommandService(new CommandServiceConfig()
{
LogLevel = LogSeverity.Debug,
DefaultRunMode = RunMode.Sync,
CaseSensitiveCommands = false,
SeparatorChar = ' '
});
// Here i could add type readers or programatically added commands etc
return services;
});
services.AddSingleton<DiscordSerilogAdapter>();
services.AddHostedService<SoraBot>();
return services;
}
}
}```
Fix issue with misspelled commandservice | ```c#
using Discord;
using Discord.Commands;
using Discord.Rest;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SoraBot.Data.Configurations;
namespace SoraBot.Bot.Extensions
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddSoraBot(this IServiceCollection services)
{
services.AddSingleton(
provider => new DiscordSocketClient(new DiscordSocketConfig()
{
AlwaysDownloadUsers = false,
LogLevel = LogSeverity.Debug,
MessageCacheSize = 0, // Let's have this disabled for now.
TotalShards = provider.GetService<IOptions<SoraBotConfig>>().Value.TotalShards,
ShardId = 0 // TODO make this configurable
}));
services.AddSingleton(new DiscordRestClient(new DiscordRestConfig()
{
LogLevel = LogSeverity.Debug
}));
services.AddSingleton(_ =>
{
var service = new CommandService(new CommandServiceConfig()
{
LogLevel = LogSeverity.Debug,
DefaultRunMode = RunMode.Sync,
CaseSensitiveCommands = false,
SeparatorChar = ' '
});
// Here i could add type readers or programatically added commands etc
return service;
});
services.AddSingleton<DiscordSerilogAdapter>();
services.AddHostedService<SoraBot>();
return services;
}
}
}``` |
f70a5a2a-b207-4535-9c23-0a3893a1f21e | {
"language": "C#"
} | ```c#
namespace MyStudio.ViewModels
{
using Catel;
using Catel.MVVM;
using MyStudio.Models;
using MyStudio.Services;
public class RibbonViewModel : ViewModelBase
{
private StudioStateModel model;
private ICommandsService commandsService;
public RibbonViewModel(StudioStateModel model,
ICommandsService commandsService)
{
Argument.IsNotNull(() => model);
Argument.IsNotNull(() => commandsService);
this.model = model;
this.commandsService = commandsService;
}
public Command StartCommand
{
get
{
return this.commandsService.StartCommand;
}
}
}
}
```
Fix for win7 null reference exception on start | ```c#
namespace MyStudio.ViewModels
{
using Catel;
using Catel.MVVM;
using MyStudio.Models;
using MyStudio.Services;
public class RibbonViewModel : ViewModelBase
{
private StudioStateModel model;
private ICommandsService commandsService;
public RibbonViewModel(StudioStateModel model,
ICommandsService commandsService)
{
Argument.IsNotNull(() => model);
Argument.IsNotNull(() => commandsService);
this.model = model;
this.commandsService = commandsService;
}
public Command StartCommand
{
get
{
return this.commandsService != null ? this.commandsService.StartCommand : null;
}
}
}
}
``` |
8b9b8d51-3ff4-4491-9191-e61c812cd4c8 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using ServiceFabric.Utilities;
namespace SceneSkope.ServiceFabric.EventHubs
{
public static class EventHubConfiguration
{
public static async Task<EventHubClient> GetEventHubClientAsync(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var inputConnectionString = await GetEventHubConnectionString(sectionName, onFailure, ct).ConfigureAwait(false);
return EventHubClient.CreateFromConnectionString(inputConnectionString);
}
private static async Task<string> GetEventHubConnectionString(string sectionName, Action<string> onFailure, CancellationToken ct)
{
return (await GetEventHubConnectionStringBuilder(sectionName, onFailure, ct).ConfigureAwait(false)).ToString();
}
private static async Task<EventHubsConnectionStringBuilder> GetEventHubConnectionStringBuilder(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var configuration = new FabricConfigurationProvider(sectionName);
if (!configuration.HasConfiguration)
{
await configuration.RejectConfigurationAsync($"No {sectionName} section", onFailure, ct).ConfigureAwait(false);
}
return new EventHubsConnectionStringBuilder(
new Uri(await configuration.TryReadConfigurationAsync("EndpointAddress", onFailure, ct).ConfigureAwait(false)),
await configuration.TryReadConfigurationAsync("EntityPath", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKeyName", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKey", onFailure, ct).ConfigureAwait(false)
);
}
}
}
```
Make the api changes public! | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using ServiceFabric.Utilities;
namespace SceneSkope.ServiceFabric.EventHubs
{
public static class EventHubConfiguration
{
public static async Task<EventHubClient> GetEventHubClientAsync(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var inputConnectionString = await GetEventHubConnectionString(sectionName, onFailure, ct).ConfigureAwait(false);
return EventHubClient.CreateFromConnectionString(inputConnectionString);
}
public static async Task<string> GetEventHubConnectionString(string sectionName, Action<string> onFailure, CancellationToken ct)
{
return (await GetEventHubConnectionStringBuilder(sectionName, onFailure, ct).ConfigureAwait(false)).ToString();
}
public static async Task<EventHubsConnectionStringBuilder> GetEventHubConnectionStringBuilder(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var configuration = new FabricConfigurationProvider(sectionName);
if (!configuration.HasConfiguration)
{
await configuration.RejectConfigurationAsync($"No {sectionName} section", onFailure, ct).ConfigureAwait(false);
}
return new EventHubsConnectionStringBuilder(
new Uri(await configuration.TryReadConfigurationAsync("EndpointAddress", onFailure, ct).ConfigureAwait(false)),
await configuration.TryReadConfigurationAsync("EntityPath", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKeyName", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKey", onFailure, ct).ConfigureAwait(false)
);
}
}
}
``` |
8710af52-5c00-4ab0-aa58-0ccbe7f112a9 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.IO
{
public class DllResourceStoreTest
{
[Test]
public async Task TestSuccessfulAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp3");
Assert.That(stream, Is.Not.Null);
}
[Test]
public async Task TestFailedAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp5");
Assert.That(stream, Is.Null);
}
}
}
```
Fix CI complaining about no `ConfigureAwait()` | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.IO
{
public class DllResourceStoreTest
{
[Test]
public async Task TestSuccessfulAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp3").ConfigureAwait(false);
Assert.That(stream, Is.Not.Null);
}
[Test]
public async Task TestFailedAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp5").ConfigureAwait(false);
Assert.That(stream, Is.Null);
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.