commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
54383c4e912a7b5ecb930c82b8a926a4c22c4965
|
Bump to version 1.3.
|
mono/sdb,mono/sdb
|
src/AssemblyInfo.cs
|
src/AssemblyInfo.cs
|
//
// The MIT License (MIT)
//
// Copyright (c) 2013 Alex Rønne Petersen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System.Reflection;
[assembly: AssemblyTitle("Mono.Debugger.Client")]
[assembly: AssemblyProduct("Mono")]
[assembly: AssemblyCopyright("Copyright 2013 Alex Rønne Petersen")]
[assembly: AssemblyVersion("1.3.*")]
|
//
// The MIT License (MIT)
//
// Copyright (c) 2013 Alex Rønne Petersen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System.Reflection;
[assembly: AssemblyTitle("Mono.Debugger.Client")]
[assembly: AssemblyProduct("Mono")]
[assembly: AssemblyCopyright("Copyright 2013 Alex Rønne Petersen")]
[assembly: AssemblyVersion("1.2.*")]
|
mit
|
C#
|
730f0d9311450f37c4c629032a2ba1ea08520877
|
Set svn:eol-style.
|
allquixotic/opensim-autobackup,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,Michelle-Argus/ArribasimExtract,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-tests,rryk/omp-server,RavenB/opensim,AlphaStaxLLC/taiga,RavenB/opensim,AlphaStaxLLC/taiga,TomDataworks/opensim,AlphaStaxLLC/taiga,N3X15/VoxelSim,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,Michelle-Argus/ArribasimExtract,AlphaStaxLLC/taiga,allquixotic/opensim-autobackup,cdbean/CySim,intari/OpenSimMirror,TomDataworks/opensim,QuillLittlefeather/opensim-1,justinccdev/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,intari/OpenSimMirror,ft-/arribasim-dev-tests,rryk/omp-server,AlphaStaxLLC/taiga,cdbean/CySim,ft-/arribasim-dev-extras,N3X15/VoxelSim,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,zekizeki/agentservice,ft-/opensim-optimizations-wip-tests,M-O-S-E-S/opensim,N3X15/VoxelSim,rryk/omp-server,AlexRa/opensim-mods-Alex,AlexRa/opensim-mods-Alex,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,OpenSimian/opensimulator,TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim,QuillLittlefeather/opensim-1,Michelle-Argus/ArribasimExtract,TomDataworks/opensim,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,justinccdev/opensim,AlexRa/opensim-mods-Alex,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-tests,AlphaStaxLLC/taiga,ft-/opensim-optimizations-wip-tests,N3X15/VoxelSim,TomDataworks/opensim,TomDataworks/opensim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,AlphaStaxLLC/taiga,TomDataworks/opensim,ft-/opensim-optimizations-wip-extras,justinccdev/opensim,cdbean/CySim,AlexRa/opensim-mods-Alex,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-extras,BogusCurry/arribasim-dev,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-extras,allquixotic/opensim-autobackup,rryk/omp-server,QuillLittlefeather/opensim-1,justinccdev/opensim,ft-/arribasim-dev-tests,rryk/omp-server,RavenB/opensim,AlphaStaxLLC/taiga,OpenSimian/opensimulator,cdbean/CySim,allquixotic/opensim-autobackup,N3X15/VoxelSim,OpenSimian/opensimulator,RavenB/opensim,M-O-S-E-S/opensim,intari/OpenSimMirror,bravelittlescientist/opensim-performance,zekizeki/agentservice,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip-extras,bravelittlescientist/opensim-performance,M-O-S-E-S/opensim,bravelittlescientist/opensim-performance,OpenSimian/opensimulator,RavenB/opensim,RavenB/opensim,QuillLittlefeather/opensim-1,TechplexEngineer/Aurora-Sim,zekizeki/agentservice,justinccdev/opensim,allquixotic/opensim-autobackup,Michelle-Argus/ArribasimExtract,zekizeki/agentservice,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,intari/OpenSimMirror,intari/OpenSimMirror,BogusCurry/arribasim-dev,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,AlexRa/opensim-mods-Alex,rryk/omp-server,cdbean/CySim,N3X15/VoxelSim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,OpenSimian/opensimulator,bravelittlescientist/opensim-performance,zekizeki/agentservice,ft-/opensim-optimizations-wip,AlexRa/opensim-mods-Alex,TomDataworks/opensim,N3X15/VoxelSim,ft-/opensim-optimizations-wip,M-O-S-E-S/opensim,allquixotic/opensim-autobackup,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip,BogusCurry/arribasim-dev,justinccdev/opensim,ft-/arribasim-dev-extras,bravelittlescientist/opensim-performance,cdbean/CySim,TechplexEngineer/Aurora-Sim,intari/OpenSimMirror,zekizeki/agentservice,ft-/opensim-optimizations-wip,M-O-S-E-S/opensim,N3X15/VoxelSim,bravelittlescientist/opensim-performance,OpenSimian/opensimulator,M-O-S-E-S/opensim
|
OpenSim/Grid/ScriptServer/FakeScene.cs
|
OpenSim/Grid/ScriptServer/FakeScene.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers;
using OpenSim.Region.Environment;
using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Grid.ScriptServer
{
public class FakeScene: Scene
{
public FakeScene(RegionInfo regInfo, AgentCircuitManager authen, PermissionManager permissionManager,
CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim, bool sendTasksToChild)
: base(
regInfo, authen, permissionManager, commsMan, sceneGridService, assetCach, storeManager, httpServer,
moduleLoader, dumpAssetsToFile, physicalPrim, sendTasksToChild)
{
}
// What does a scene have to do? :P
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers;
using OpenSim.Region.Environment;
using OpenSim.Region.Environment.Scenes;
namespace OpenSim.Grid.ScriptServer
{
public class FakeScene: Scene
{
public FakeScene(RegionInfo regInfo, AgentCircuitManager authen, PermissionManager permissionManager,
CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim, bool sendTasksToChild)
: base(
regInfo, authen, permissionManager, commsMan, sceneGridService, assetCach, storeManager, httpServer,
moduleLoader, dumpAssetsToFile, physicalPrim, sendTasksToChild)
{
}
// What does a scene have to do? :P
}
}
|
bsd-3-clause
|
C#
|
5ae203bfdb6be0daca906e66ed75d5d33e24081f
|
update again
|
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
|
src/Firehose.WebCore/Program.cs
|
src/Firehose.WebCore/Program.cs
|
using Firehose.Web.Infrastructure;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<NewCombinedFeedSource>();
var members = Assembly.GetCallingAssembly().GetTypes()
.Where(type => typeof(IAmACommunityMember).IsAssignableFrom(type) && !type.IsInterface);
foreach (var member in members)
builder.Services.AddSingleton(typeof(IAmACommunityMember), member);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.AllowSynchronousIO = true;
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.Run();
|
using Firehose.Web.Infrastructure;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.AllowSynchronousIO = true;
});
builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
builder.Services.AddSingleton<NewCombinedFeedSource>();
var members = Assembly.GetCallingAssembly().GetTypes()
.Where(type => typeof(IAmACommunityMember).IsAssignableFrom(type) && !type.IsInterface);
foreach (var member in members)
builder.Services.AddSingleton(typeof(IAmACommunityMember), member);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//app.UseSystemWebAdapters();
app.MapDefaultControllerRoute();
//app.MapReverseProxy();
app.Run();
|
mit
|
C#
|
9061894d18c0b9beb19d2131d34008fafcb597bf
|
Remove INotifyPropertyChanged from IMainWindowViewModel
|
Kingloo/GB-Live
|
src/Gui/IMainWindowViewModel.cs
|
src/Gui/IMainWindowViewModel.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using GBLive.GiantBomb.Interfaces;
namespace GBLive.Gui
{
public interface IMainWindowViewModel
{
bool IsLive { get; set; }
string LiveShowTitle { get; set; }
IReadOnlyCollection<IShow> Shows { get; }
Task UpdateAsync();
void OpenHomePage();
void OpenChatPage();
void StartTimer();
void StopTimer();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using GBLive.GiantBomb.Interfaces;
namespace GBLive.Gui
{
public interface IMainWindowViewModel : INotifyPropertyChanged
{
bool IsLive { get; set; }
string LiveShowTitle { get; set; }
IReadOnlyCollection<IShow> Shows { get; }
Task UpdateAsync();
void OpenHomePage();
void OpenChatPage();
void StartTimer();
void StopTimer();
}
}
|
unlicense
|
C#
|
4ac29927deb0183e9e27b42db32eaad661e1536d
|
Bump version to 8.15.0
|
KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS
|
src/SolutionInfo.cs
|
src/SolutionInfo.cs
|
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Umbraco")]
[assembly: AssemblyCopyright("Copyright © Umbraco 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// versions
// read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin
// note: do NOT change anything here manually, use the build scripts
// this is the ONLY ONE the CLR cares about for compatibility
// should change ONLY when "hard" breaking compatibility (manual change)
[assembly: AssemblyVersion("8.0.0")]
// these are FYI and changed automatically
[assembly: AssemblyFileVersion("8.15.0")]
[assembly: AssemblyInformationalVersion("8.15.0")]
|
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Umbraco")]
[assembly: AssemblyCopyright("Copyright © Umbraco 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// versions
// read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin
// note: do NOT change anything here manually, use the build scripts
// this is the ONLY ONE the CLR cares about for compatibility
// should change ONLY when "hard" breaking compatibility (manual change)
[assembly: AssemblyVersion("8.0.0")]
// these are FYI and changed automatically
[assembly: AssemblyFileVersion("8.15.0")]
[assembly: AssemblyInformationalVersion("8.15.0-rc")]
|
mit
|
C#
|
b88183f5010ec4d9638403b9766cea6f0200dd4c
|
Add support on fetching Uri with local filepath (#182)
|
milkshakesoftware/PreMailer.Net
|
PreMailer.Net/PreMailer.Net/Downloaders/WebDownloader.cs
|
PreMailer.Net/PreMailer.Net/Downloaders/WebDownloader.cs
|
using System;
using System.IO;
using System.Net;
using System.Text;
namespace PreMailer.Net.Downloaders
{
public class WebDownloader : IWebDownloader
{
private static IWebDownloader _sharedDownloader;
public static IWebDownloader SharedDownloader
{
get
{
if (_sharedDownloader == null)
{
_sharedDownloader = new WebDownloader();
}
return _sharedDownloader;
}
set
{
_sharedDownloader = value;
}
}
public string DownloadString(Uri uri)
{
var request = WebRequest.Create(uri);
using (var response = request.GetResponse())
{
switch (response)
{
case HttpWebResponse httpWebResponse:
{
var charset = httpWebResponse.CharacterSet;
var encoding = Encoding.GetEncoding(charset);
using (var stream = httpWebResponse.GetResponseStream())
using (var reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
case FileWebResponse fileWebResponse:
{
using (var stream = fileWebResponse.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
default:
throw new NotSupportedException($"The Uri type is giving a response in unsupported type '{response.GetType()}'.");
}
}
}
}
}
|
using System;
using System.IO;
using System.Net;
using System.Text;
namespace PreMailer.Net.Downloaders
{
public class WebDownloader : IWebDownloader
{
private static IWebDownloader _sharedDownloader;
public static IWebDownloader SharedDownloader
{
get
{
if (_sharedDownloader == null)
{
_sharedDownloader = new WebDownloader();
}
return _sharedDownloader;
}
set
{
_sharedDownloader = value;
}
}
public string DownloadString(Uri uri)
{
var request = WebRequest.Create(uri);
using (var response = (HttpWebResponse)request.GetResponse())
{
var charset = response.CharacterSet;
var encoding = Encoding.GetEncoding(charset);
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
}
}
}
|
mit
|
C#
|
a0d35d10ce054f1ac3221184b755129974e0c625
|
Update PixelBandGetter.cs
|
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
|
src/RasterIO/PixelBandGetter.cs
|
src/RasterIO/PixelBandGetter.cs
|
// Contributors:
// James Domingo, Green Code LLC
using Landis.SpatialModeling;
using System;
namespace Landis.RasterIO
{
/// <summary>
/// Accessor for getting a particular pixel band as another data type.
/// </summary>
public class PixelBandGetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandGetter<TRasterBand>
where TPixelBand : struct
where TRasterBand : struct
{
private Converter<TPixelBand, TRasterBand> converter;
public PixelBandGetter(PixelBand pixelBand,
Converter<TPixelBand, TRasterBand> converter)
: base(pixelBand)
{
this.converter = converter;
}
public TRasterBand GetValue()
{
return converter(pixelBand.Value);
}
}
}
|
// Copyright 2010 Green Code LLC
// All rights reserved.
//
// The copyright holders license this file under the New (3-clause) BSD
// License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is available at
//
// http://www.opensource.org/licenses/BSD-3-Clause
//
// and is included in the NOTICE.txt file distributed with this work.
//
// Contributors:
// James Domingo, Green Code LLC
using Landis.SpatialModeling;
using System;
namespace Landis.RasterIO
{
/// <summary>
/// Accessor for getting a particular pixel band as another data type.
/// </summary>
public class PixelBandGetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandGetter<TRasterBand>
where TPixelBand : struct
where TRasterBand : struct
{
private Converter<TPixelBand, TRasterBand> converter;
public PixelBandGetter(PixelBand pixelBand,
Converter<TPixelBand, TRasterBand> converter)
: base(pixelBand)
{
this.converter = converter;
}
public TRasterBand GetValue()
{
return converter(pixelBand.Value);
}
}
}
|
apache-2.0
|
C#
|
5fdb3aa087c028503ad2399c1771f39b6ea20531
|
Update PixelBandSetter.cs
|
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
|
src/RasterIO/PixelBandSetter.cs
|
src/RasterIO/PixelBandSetter.cs
|
// Contributors:
// James Domingo, Green Code LLC
using Landis.SpatialModeling;
using System;
namespace Landis.RasterIO
{
/// <summary>
/// Accessor for setting a particular pixel band with another data type.
/// </summary>
public class PixelBandSetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandSetter<TRasterBand>
where TPixelBand : struct
where TRasterBand : struct
{
private Converter<TRasterBand, TPixelBand> converter; // TRasterBand -> TPixelBand
public PixelBandSetter(PixelBand pixelBand,
Converter<TRasterBand, TPixelBand> converter)
: base(pixelBand)
{
this.converter = converter;
}
public void SetValue(TRasterBand newValue)
{
pixelBand.Value = converter(newValue);
}
}
}
|
// Copyright 2010 Green Code LLC
// All rights reserved.
//
// The copyright holders license this file under the New (3-clause) BSD
// License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is available at
//
// http://www.opensource.org/licenses/BSD-3-Clause
//
// and is included in the NOTICE.txt file distributed with this work.
//
// Contributors:
// James Domingo, Green Code LLC
using Landis.SpatialModeling;
using System;
namespace Landis.RasterIO
{
/// <summary>
/// Accessor for setting a particular pixel band with another data type.
/// </summary>
public class PixelBandSetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandSetter<TRasterBand>
where TPixelBand : struct
where TRasterBand : struct
{
private Converter<TRasterBand, TPixelBand> converter; // TRasterBand -> TPixelBand
public PixelBandSetter(PixelBand pixelBand,
Converter<TRasterBand, TPixelBand> converter)
: base(pixelBand)
{
this.converter = converter;
}
public void SetValue(TRasterBand newValue)
{
pixelBand.Value = converter(newValue);
}
}
}
|
apache-2.0
|
C#
|
75fd91e15035d84551ba6ccf3278dbc146ad5ab9
|
Refactor Add Integers Operation to use GetValues and CloneWithValues
|
ajlopez/TensorSharp
|
Src/TensorSharp/Operations/AddIntegerIntegerOperation.cs
|
Src/TensorSharp/Operations/AddIntegerIntegerOperation.cs
|
namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AddIntegerIntegerOperation : IBinaryOperation<int, int, int>
{
public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
{
int[] values1 = tensor1.GetValues();
int l = values1.Length;
int[] values2 = tensor2.GetValues();
int[] newvalues = new int[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] + values2[k];
return tensor1.CloneWithNewValues(newvalues);
}
}
}
|
namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AddIntegerIntegerOperation : IBinaryOperation<int, int, int>
{
public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
{
Tensor<int> result = new Tensor<int>();
result.SetValue(tensor1.GetValue() + tensor2.GetValue());
return result;
return result;
}
}
}
|
mit
|
C#
|
4f3c54214bf2cc5422eeb7e1a0c8bf1672e77a37
|
Add ZenMode property
|
samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays
|
TwitchPlaysAssembly/Src/Helpers/TwitchPlaysProperties.cs
|
TwitchPlaysAssembly/Src/Helpers/TwitchPlaysProperties.cs
|
public class TwitchPlaysProperties : PropertiesBehaviour
{
public TwitchPlaysProperties()
{
AddProperty("TimeMode", new Property(() => OtherModes.TimedModeOn, x => { OtherModes.TimedModeOn = (bool)x; }));
AddProperty("ZenMode", new Property(() => OtherModes.ZenModeOn, x => OtherModes.ZenModeOn = (bool) x));
AddProperty("TimeModeTimeLimit", new Property(() => TwitchPlaySettings.data.TimeModeStartingTime, SetTimeModeTimeLimit));
AddProperty("ircConnectionSendMessage", new Property(null, x => IRCConnection.Instance.SendMessage((string)x)));
AddProperty("Reward", new Property(() => TwitchPlaySettings.GetRewardBonus(), x => TwitchPlaySettings.SetRewardBonus((int) x)));
AddProperty("CauseFakeStrike", new Property(null, CauseFakeStrike));
}
private static void SetTimeModeTimeLimit(object timeLimit)
{
if (timeLimit is int intTimeLimit)
{
TwitchPlaySettings.data.TimeModeStartingTime = intTimeLimit;
TwitchPlaySettings.WriteDataToFile();
}
}
private static void CauseFakeStrike(object kmBombModule)
{
BombComponent component;
switch (kmBombModule)
{
case KMBombModule module:
component = module.GetComponentInChildren<BombComponent>();
break;
case KMNeedyModule needyModule:
component = needyModule.GetComponentInChildren<BombComponent>();
break;
default:
return;
}
if (component == null) return;
foreach (TwitchComponentHandle handle in BombMessageResponder.Instance.ComponentHandles)
{
if (handle.bombComponent != component) continue;
handle.Solver.OnFakeStrike();
break;
}
}
internal TwitchPlaysService TwitchPlaysService { get; set; }
}
|
public class TwitchPlaysProperties : PropertiesBehaviour
{
public TwitchPlaysProperties()
{
AddProperty("TimeMode", new Property(() => OtherModes.TimedModeOn, x => { OtherModes.TimedModeOn = (bool)x; }));
AddProperty("TimeModeTimeLimit", new Property(() => TwitchPlaySettings.data.TimeModeStartingTime, SetTimeModeTimeLimit));
AddProperty("ircConnectionSendMessage", new Property(null, x => IRCConnection.Instance.SendMessage((string)x)));
AddProperty("Reward", new Property(() => TwitchPlaySettings.GetRewardBonus(), x => TwitchPlaySettings.SetRewardBonus((int) x)));
AddProperty("CauseFakeStrike", new Property(null, CauseFakeStrike));
}
private static void SetTimeModeTimeLimit(object timeLimit)
{
if (timeLimit is int intTimeLimit)
{
TwitchPlaySettings.data.TimeModeStartingTime = intTimeLimit;
TwitchPlaySettings.WriteDataToFile();
}
}
private static void CauseFakeStrike(object kmBombModule)
{
BombComponent component;
switch (kmBombModule)
{
case KMBombModule module:
component = module.GetComponentInChildren<BombComponent>();
break;
case KMNeedyModule needyModule:
component = needyModule.GetComponentInChildren<BombComponent>();
break;
default:
return;
}
if (component == null) return;
foreach (TwitchComponentHandle handle in BombMessageResponder.Instance.ComponentHandles)
{
if (handle.bombComponent != component) continue;
handle.Solver.OnFakeStrike();
break;
}
}
internal TwitchPlaysService TwitchPlaysService { get; set; }
}
|
mit
|
C#
|
28ab0923098b7f64390d36af9bc2024ba26c384b
|
Fix chat messages crash the server.
|
DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
|
Server/Message/Reader/ChatMsgReader.cs
|
Server/Message/Reader/ChatMsgReader.cs
|
using LunaCommon.Message.Data.Chat;
using LunaCommon.Message.Interface;
using LunaCommon.Message.Types;
using Server.Client;
using Server.Message.Reader.Base;
using Server.System;
using System;
namespace Server.Message.Reader
{
public class ChatMsgReader : ReaderBase
{
private static readonly ChatSystemReceiver ChatSystemReceiver = new ChatSystemReceiver();
public override void HandleMessage(ClientStructure client, IClientMessageBase message)
{
var data = (ChatBaseMsgData)message.Data;
if (data.From != client.PlayerName) return;
switch (data.ChatMessageType)
{
case ChatMessageType.ListRequest:
ChatSystem.SendPlayerChatChannels(client);
//We don't use this message anymore so we can recycle it
message.Recycle();
break;
case ChatMessageType.Join:
ChatSystemReceiver.HandleJoinMessage(client, (ChatJoinMsgData)message);
break;
case ChatMessageType.Leave:
ChatSystemReceiver.HandleLeaveMessage(client, (ChatLeaveMsgData)message);
break;
case ChatMessageType.ChannelMessage:
//TODO: Is the fix from message to data correct? If so, do any of the other cases need to change? This fix was done as a quick fix to stop the message error because message is a ChatCliMsg but data is a ChatChannelMsgData.
ChatSystemReceiver.HandleChannelMessage(client, (ChatChannelMsgData)data);
break;
case ChatMessageType.PrivateMessage:
ChatSystemReceiver.HandlePrivateMessage(client, (ChatPrivateMsgData)message);
break;
case ChatMessageType.ConsoleMessage:
ChatSystemReceiver.HandleConsoleMessage(client, (ChatConsoleMsgData)message);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
|
using LunaCommon.Message.Data.Chat;
using LunaCommon.Message.Interface;
using LunaCommon.Message.Types;
using Server.Client;
using Server.Message.Reader.Base;
using Server.System;
using System;
namespace Server.Message.Reader
{
public class ChatMsgReader : ReaderBase
{
private static readonly ChatSystemReceiver ChatSystemReceiver = new ChatSystemReceiver();
public override void HandleMessage(ClientStructure client, IClientMessageBase message)
{
var data = (ChatBaseMsgData)message.Data;
if (data.From != client.PlayerName) return;
switch (data.ChatMessageType)
{
case ChatMessageType.ListRequest:
ChatSystem.SendPlayerChatChannels(client);
//We don't use this message anymore so we can recycle it
message.Recycle();
break;
case ChatMessageType.Join:
ChatSystemReceiver.HandleJoinMessage(client, (ChatJoinMsgData)message);
break;
case ChatMessageType.Leave:
ChatSystemReceiver.HandleLeaveMessage(client, (ChatLeaveMsgData)message);
break;
case ChatMessageType.ChannelMessage:
ChatSystemReceiver.HandleChannelMessage(client, (ChatChannelMsgData)message);
break;
case ChatMessageType.PrivateMessage:
ChatSystemReceiver.HandlePrivateMessage(client, (ChatPrivateMsgData)message);
break;
case ChatMessageType.ConsoleMessage:
ChatSystemReceiver.HandleConsoleMessage(client, (ChatConsoleMsgData)message);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
|
mit
|
C#
|
25e297f5bf0fcb44ba6666953548ec72d71f566c
|
Fix normalizing a vector results in a zero vector
|
ProgTrade/SharpMath
|
SharpMath/Geometry/VectorExtensions.cs
|
SharpMath/Geometry/VectorExtensions.cs
|
using SharpMath.Geometry.Exceptions;
namespace SharpMath.Geometry
{
public static class VectorExtensions
{
public static T Negate<T>(this Vector vector) where T : Vector, new()
{
var resultVector = new T();
if (vector.Dimension != resultVector.Dimension)
throw new DimensionException("The dimensions of the vectors do not equal each other.");
for (uint i = 0; i < vector.Dimension; ++i)
resultVector[i] = -vector[i];
return resultVector;
}
/// <summary>
/// Calculates the normalized <see cref="Vector"/> of this <see cref="Vector"/>.
/// </summary>
/// <returns>The normalized <see cref="Vector"/>.</returns>
public static T Normalize<T>(this Vector vector) where T : Vector, new()
{
var resultVector = new T();
if (vector.Dimension != resultVector.Dimension)
throw new DimensionException("The dimensions of the vectors do not equal each other.");
for (uint i = 0; i < vector.Dimension; ++i)
resultVector[i] = vector[i] / vector.Magnitude;
return resultVector;
}
}
}
|
namespace SharpMath.Geometry
{
public static class VectorExtensions
{
public static T Negate<T>(this Vector vector) where T : Vector, new()
{
var resultVector = new T();
for (uint i = 0; i < vector.Dimension; ++i)
resultVector[i] = -vector[i];
return resultVector;
}
/// <summary>
/// Calculates the normalized <see cref="Vector"/> of this <see cref="Vector"/>.
/// </summary>
/// <returns>The normalized <see cref="Vector"/>.</returns>
public static T Normalize<T>(this Vector vector) where T : Vector, new()
{
var resultVector = new T();
for (uint i = 0; i < vector.Dimension; ++i)
resultVector[i] /= vector.Magnitude;
return resultVector;
}
}
}
|
mit
|
C#
|
96453d8197be660721540348198819d551bf04ef
|
Remove redundant string interpolation
|
smoogipoo/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,ppy/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,ZLima12/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,ZLima12/osu,peppy/osu
|
osu.Game/Users/Drawables/DrawableFlag.cs
|
osu.Game/Users/Drawables/DrawableFlag.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Users.Drawables
{
public class DrawableFlag : Sprite, IHasTooltip
{
private readonly Country country;
public string TooltipText => country?.FullName;
public DrawableFlag(Country country)
{
this.country = country;
}
[BackgroundDependencyLoader]
private void load(TextureStore ts)
{
if (ts == null)
throw new ArgumentNullException(nameof(ts));
Texture = ts.Get($@"Flags/{country?.FlagName ?? @"__"}") ?? ts.Get(@"Flags/__");
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Users.Drawables
{
public class DrawableFlag : Sprite, IHasTooltip
{
private readonly Country country;
public string TooltipText => country?.FullName;
public DrawableFlag(Country country)
{
this.country = country;
}
[BackgroundDependencyLoader]
private void load(TextureStore ts)
{
if (ts == null)
throw new ArgumentNullException(nameof(ts));
Texture = ts.Get($@"Flags/{country?.FlagName ?? @"__"}") ?? ts.Get($@"Flags/__");
}
}
}
|
mit
|
C#
|
6c85a461512ec8b7f2fd69542e7a59dc8782efcd
|
Add test
|
sakapon/Samples-2017
|
ProxySample/TransparentHttpConsole/Program.cs
|
ProxySample/TransparentHttpConsole/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace TransparentHttpConsole
{
class Program
{
static void Main(string[] args)
{
HttpProxyTest();
ObjectMethodsTest();
}
static void HttpProxyTest()
{
var zipCloud = HttpProxy.CreateProxy<IZipCloudService>();
Console.WriteLine(zipCloud.Get("6020881"));
var cgis = HttpProxy.CreateProxy<ICgisService>();
Console.WriteLine(cgis.Get("6048301"));
Console.WriteLine(cgis.Get("501", 1));
}
static void ObjectMethodsTest()
{
var zipCloud = HttpProxy.CreateProxy<IZipCloudService>();
var h = zipCloud.GetHashCode();
var b = zipCloud.Equals(zipCloud);
var t = zipCloud.GetType();
var s = zipCloud.ToString();
}
}
// http://zipcloud.ibsnet.co.jp/doc/api
[BaseUri("http://zipcloud.ibsnet.co.jp/api/search")]
public interface IZipCloudService
{
string Get(string zipcode);
}
// http://zip.cgis.biz/
[BaseUri("http://zip.cgis.biz/xml/zip.php")]
public interface ICgisService
{
string Get(string zn);
string Get(string zn, int ver);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace TransparentHttpConsole
{
class Program
{
static void Main(string[] args)
{
var zipCloud = HttpProxy.CreateProxy<IZipCloudService>();
Console.WriteLine(zipCloud.Get("6020881"));
var cgis = HttpProxy.CreateProxy<ICgisService>();
Console.WriteLine(cgis.Get("6048301"));
Console.WriteLine(cgis.Get("501", 1));
}
}
// http://zipcloud.ibsnet.co.jp/doc/api
[BaseUri("http://zipcloud.ibsnet.co.jp/api/search")]
public interface IZipCloudService
{
string Get(string zipcode);
}
// http://zip.cgis.biz/
[BaseUri("http://zip.cgis.biz/xml/zip.php")]
public interface ICgisService
{
string Get(string zn);
string Get(string zn, int ver);
}
}
|
mit
|
C#
|
1965b7c5c825f6825c7cf882f8a36afc3c366256
|
Bump Version Numbers.
|
blackpanther989/ArchiSteamFarm,blackpanther989/ArchiSteamFarm
|
ArchiSteamFarm/SharedInfo.cs
|
ArchiSteamFarm/SharedInfo.cs
|
/*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
Copyright 2015-2016 Łukasz "JustArchi" Domeradzki
Contact: JustArchi@JustArchi.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Reflection;
namespace ArchiSteamFarm {
internal static class SharedInfo {
internal const ulong ArchiSteamID = 76561198006963719;
internal const string ASF = "ASF";
internal const string ASFDirectory = "ArchiSteamFarm";
internal const ulong ASFGroupSteamID = 103582791440160998;
internal const string ConfigDirectory = "config";
internal const string Copyright = "Copyright © ArchiSteamFarm 2015-2016";
internal const string DebugDirectory = "debug";
internal const string EventLog = ServiceName;
internal const string EventLogSource = EventLog + "Logger";
internal const string GithubReleaseURL = "https://api.github.com/repos/" + GithubRepo + "/releases"; // GitHub API is HTTPS only
internal const string GithubRepo = "Blackpanther989/ArchiSteamFarm";
internal const string GlobalConfigFileName = ASF + ".json";
internal const string GlobalDatabaseFileName = ASF + ".db";
internal const string LogFile = "log.txt";
internal const string ServiceDescription = "ASF is an application that allows you to farm steam cards using multiple steam accounts simultaneously.";
internal const string ServiceName = "ArchiSteamFarm";
internal const string StatisticsServer = "https://asf.justarchi.net";
internal const string VersionNumber = "2.1.7.9";
internal const string MyVersionNumber = "2.1.6.2";
internal static readonly Version Version = Assembly.GetEntryAssembly().GetName().Version;
}
}
|
/*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
Copyright 2015-2016 Łukasz "JustArchi" Domeradzki
Contact: JustArchi@JustArchi.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Reflection;
namespace ArchiSteamFarm {
internal static class SharedInfo {
internal const ulong ArchiSteamID = 76561198006963719;
internal const string ASF = "ASF";
internal const string ASFDirectory = "ArchiSteamFarm";
internal const ulong ASFGroupSteamID = 103582791440160998;
internal const string ConfigDirectory = "config";
internal const string Copyright = "Copyright © ArchiSteamFarm 2015-2016";
internal const string DebugDirectory = "debug";
internal const string EventLog = ServiceName;
internal const string EventLogSource = EventLog + "Logger";
internal const string GithubReleaseURL = "https://api.github.com/repos/" + GithubRepo + "/releases"; // GitHub API is HTTPS only
internal const string GithubRepo = "Blackpanther989/ArchiSteamFarm";
internal const string GlobalConfigFileName = ASF + ".json";
internal const string GlobalDatabaseFileName = ASF + ".db";
internal const string LogFile = "log.txt";
internal const string ServiceDescription = "ASF is an application that allows you to farm steam cards using multiple steam accounts simultaneously.";
internal const string ServiceName = "ArchiSteamFarm";
internal const string StatisticsServer = "https://asf.justarchi.net";
internal const string VersionNumber = "2.1.7.4";
internal const string MyVersionNumber = "2.1.6.1";
internal static readonly Version Version = Assembly.GetEntryAssembly().GetName().Version;
}
}
|
apache-2.0
|
C#
|
d2c7fef90fa1f6964c6095eaece730b3601213fc
|
Update HowToUse.cs
|
MudassarMumtaz/Cross-platform-AES-encryption,MudassarMumtaz/Cross-platform-AES-encryption,Pakhee/Cross-platform-AES-encryption,invalidred/Cross-platform-AES-encryption,Pakhee/Cross-platform-AES-encryption,MudassarMumtaz/Cross-platform-AES-encryption,invalidred/Cross-platform-AES-encryption,Pakhee/Cross-platform-AES-encryption,invalidred/Cross-platform-AES-encryption
|
C-Sharp/HowToUse.cs
|
C-Sharp/HowToUse.cs
|
public class test {
public static void Main (String []args)
{
CryptLib _crypt = new CryptLib ();
string plainText = "This is the text to be encrypted";
String iv = CryptLib.GenerateRandomIV (16); //16 bytes = 128 bits
string key = CryptLib.getHashSha256("my secret key", 31); //32 bytes = 256 bits
String cypherText = _crypt.encrypt (plainText, key, iv);
Console.WriteLine ("iv="+iv);
Console.WriteLine ("key=" + key);
Console.WriteLine("Cypher text=" + cypherText);
Console.WriteLine ("Plain text =" + _crypt.decrypt (cypherText, key, iv));
}
}
|
public class test {
public static void Main (String []args)
{
CryptLib _crypt = new CryptLib ();
string plainText = "This is the text to be encrypted";
String iv = CryptLib.GenerateRandomIV (15); //do not exceed 15
string key = CryptLib.getHashSha256("my secret key", 31); //do not exceed 31
String cypherText = _crypt.encrypt (plainText, key, iv);
Console.WriteLine ("iv="+iv);
Console.WriteLine ("key=" + key);
Console.WriteLine("Cypher text=" + cypherText);
Console.WriteLine ("Plain text =" + _crypt.decrypt (cypherText, key, iv));
}
}
|
apache-2.0
|
C#
|
9e3afb3882c51c078e899f23a9f3543c0dbf2f86
|
install as automatic startup
|
kboronka/win-service-launcher
|
demo_service/ProjectInstaller.cs
|
demo_service/ProjectInstaller.cs
|
/* Copyright (C) 2013 Kevin Boronka
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace demo_service
{
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller serviceProcessInstaller;
private ServiceInstaller serviceInstaller;
public ProjectInstaller()
{
//this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
serviceProcessInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
// Here you can set properties on serviceProcessInstaller or register event handlers
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.ServiceName = demo_service.MyServiceName;
serviceInstaller.StartType = ServiceStartMode.Automatic;
//serviceInstaller.DelayedAutoStart = true;
this.Installers.AddRange(new Installer[] { serviceProcessInstaller, serviceInstaller });
}
private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
//ServiceController serviceController = new ServiceController(serviceInstaller.ServiceName);
//ServiceHelper.ChangeStartMode(serviceController, ServiceStartMode.Automatic);
//serviceController.Start();
}
}
}
|
/* Copyright (C) 2013 Kevin Boronka
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace demo_service
{
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller serviceProcessInstaller;
private ServiceInstaller serviceInstaller;
public ProjectInstaller()
{
//this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
serviceProcessInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
// Here you can set properties on serviceProcessInstaller or register event handlers
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.ServiceName = demo_service.MyServiceName;
//serviceInstaller.StartType = ServiceStartMode.Automatic;
//serviceInstaller.DelayedAutoStart = true;
this.Installers.AddRange(new Installer[] { serviceProcessInstaller, serviceInstaller });
}
private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
//ServiceController serviceController = new ServiceController(serviceInstaller.ServiceName);
//ServiceHelper.ChangeStartMode(serviceController, ServiceStartMode.Automatic);
//serviceController.Start();
}
}
}
|
bsd-2-clause
|
C#
|
4598432aa482c22656c62838117cea95d84c054a
|
Update memory handling, add work and high ram
|
eightlittlebits/elbgb
|
elbgb.gameboy/Memory/MMU.cs
|
elbgb.gameboy/Memory/MMU.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using elbgb.gameboy.Display;
namespace elbgb.gameboy.Memory
{
class MMU //: IMemoryMappedComponent
{
public static class Registers
{
public const ushort BOOTROMLOCK = 0xFF50;
}
private GameBoy _gb;
private bool _bootRomLocked;
private byte[] _bootRom;
private byte[] _wram;
private byte[] _hram;
public MMU(GameBoy gameBoy, byte[] bootRom)
{
_gb = gameBoy;
_bootRom = bootRom;
_bootRomLocked = false;
_wram = new byte[0x2000];
_hram = new byte[0x7F];
}
public byte ReadByte(ushort address)
{
switch (address & 0xF000)
{
case 0x0000:
if (!_bootRomLocked && address < 0x100)
{
return _bootRom[address];
}
throw new NotImplementedException();
// working ram
case 0xC000:
case 0xD000:
return _wram[address & 0x1FFF];
case 0xF000:
// timer IO registers
if (address >= 0xFF04 && address <= 0xFF07)
{
return _gb.Timer.ReadByte(address);
}
// restricted area
else if (address >= 0xFEA0 && address <= 0xFEFF)
{
return 0;
}
// hi ram
else if (address >= 0xFF80 && address <= 0xFFFE)
{
return _hram[address & 0x7F];
}
else
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
public void WriteByte(ushort address, byte value)
{
switch (address & 0xF000)
{
// working ram
case 0xC000:
case 0xD000:
_wram[address & 0x1FFF] = value;
return;
// vram
case 0x8000:
case 0x9000:
_gb.PPU.WriteByte(address, value);
return;
case 0xF000:
// timer IO registers
if (address >= 0xFF04 && address <= 0xFF07)
{
_gb.Timer.WriteByte(address, value);
return;
}
// restricted area
else if (address >= 0xFEA0 && address <= 0xFEFF)
{
return;
}
// hi ram
else if (address >= 0xFF80 && address <= 0xFFFE)
{
_hram[address & 0x7F] = value;
return;
}
else if (address == Registers.BOOTROMLOCK)
{
// TODO(david): do we set a value at this location? can we read from it?
_bootRomLocked = true;
return;
}
else
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using elbgb.gameboy.Display;
namespace elbgb.gameboy.Memory
{
class MMU : IMemoryMappedComponent
{
private GameBoy _gb;
private bool _bootRomLocked;
private byte[] _bootRom;
public MMU(GameBoy gameBoy, byte[] bootRom)
{
_gb = gameBoy;
_bootRom = bootRom;
_bootRomLocked = false;
}
public byte ReadByte(ushort address)
{
if (!_bootRomLocked && address < 0x100)
{
return _bootRom[address];
}
// timer 0xFF04 - 0xFF07
else if (address >= 0xFF04 && address <= 0xFF07)
{
return _gb.Timer.ReadByte(address);
}
throw new NotImplementedException();
}
public void WriteByte(ushort address, byte value)
{
if (address == 0xFF50) // Boot ROM lockout address
{
// TODO(david): do we set a value at this location? can we read from it?
_bootRomLocked = true;
}
else if (address >= 0x8000 && address <= 0x9fff)
{
_gb.PPU.WriteByte(address, value);
}
// timer 0xFF04 - 0xFF07
else if (address >= 0xFF04 && address <= 0xFF07)
{
_gb.Timer.WriteByte(address, value);
}
else
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
1b3d37984c702b753e3dcec26a4ced7f17708c36
|
Add test for Signature equality
|
mono/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp,openmedicus/dbus-sharp,openmedicus/dbus-sharp
|
tests/SignatureTest.cs
|
tests/SignatureTest.cs
|
// Copyright 2009 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NUnit.Framework;
using NDesk.DBus;
namespace NDesk.DBus.Tests
{
[TestFixture]
public class SignatureTest
{
[Test]
public void Parse ()
{
string sigText = "as";
Signature sig = new Signature (sigText);
Assert.IsTrue (sig.IsArray);
Assert.IsFalse (sig.IsDict);
Assert.IsFalse (sig.IsPrimitive);
}
[Test]
public void Equality ()
{
string sigText = "as";
Signature a = new Signature (sigText);
Signature b = new Signature (sigText);
Assert.IsTrue (a == b);
}
}
}
|
// Copyright 2009 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using NUnit.Framework;
using NDesk.DBus;
namespace NDesk.DBus.Tests
{
[TestFixture]
public class SignatureTest
{
[Test]
public void Parse ()
{
string sigText = "as";
Signature sig = new Signature (sigText);
Assert.IsTrue (sig.IsArray);
Assert.IsFalse (sig.IsDict);
Assert.IsFalse (sig.IsPrimitive);
}
}
}
|
mit
|
C#
|
44c59af636ed1baa3eb217df97365a10746901e5
|
Fix invalidation source not being passed down
|
EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
|
osu.Framework/Layout/LayoutValue.cs
|
osu.Framework/Layout/LayoutValue.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
namespace osu.Framework.Layout
{
public class LayoutValue : LayoutMember
{
/// <summary>
/// Creates a new <see cref="LayoutValue"/>.
/// </summary>
/// <param name="invalidationType">The <see cref="Invalidation"/> flags that will invalidate this <see cref="LayoutValue"/>.</param>
/// <param name="invalidationCondition">Any extra conditions that must be satisfied before this <see cref="LayoutValue"/> is invalidated.</param>
/// <param name="invalidationSource">The source of the invalidation.</param>
public LayoutValue(Invalidation invalidationType, InvalidationConditionDelegate invalidationCondition = null, InvalidationSource invalidationSource = InvalidationSource.Default)
: base(invalidationType, invalidationCondition, invalidationSource)
{
}
/// <summary>
/// Validates this <see cref="LayoutValue"/>.
/// </summary>
public new void Validate() => base.Validate();
}
public class LayoutValue<T> : LayoutMember
{
/// <summary>
/// Creates a new <see cref="LayoutValue{T}"/>.
/// </summary>
/// <param name="invalidationType">The <see cref="Invalidation"/> flags that will invalidate this <see cref="LayoutValue{T}"/>.</param>
/// <param name="invalidationCondition">Any extra conditions that must be satisfied before this <see cref="LayoutValue{T}"/> is invalidated.</param>
/// <param name="invalidationSource">The source of the invalidation.</param>
public LayoutValue(Invalidation invalidationType, InvalidationConditionDelegate invalidationCondition = null, InvalidationSource invalidationSource = InvalidationSource.Default)
: base(invalidationType, invalidationCondition, invalidationSource)
{
}
private T value;
/// <summary>
/// The current value.
/// </summary>
/// <exception cref="InvalidOperationException">If accessed while <see cref="LayoutMember.IsValid"/> is <code>false</code>.</exception>
public T Value
{
get
{
if (!IsValid)
throw new InvalidOperationException("todo");
return value;
}
set
{
this.value = value;
Validate();
}
}
public static implicit operator T(LayoutValue<T> layoutValue) => layoutValue.Value;
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
namespace osu.Framework.Layout
{
public class LayoutValue : LayoutMember
{
/// <summary>
/// Creates a new <see cref="LayoutValue"/>.
/// </summary>
/// <param name="invalidationType">The <see cref="Invalidation"/> flags that will invalidate this <see cref="LayoutValue"/>.</param>
/// <param name="invalidationCondition">Any extra conditions that must be satisfied before this <see cref="LayoutValue"/> is invalidated.</param>
/// <param name="invalidationSource">The source of the invalidation.</param>
public LayoutValue(Invalidation invalidationType, InvalidationConditionDelegate invalidationCondition = null, InvalidationSource invalidationSource = InvalidationSource.Default)
: base(invalidationType, invalidationCondition)
{
}
/// <summary>
/// Validates this <see cref="LayoutValue"/>.
/// </summary>
public new void Validate() => base.Validate();
}
public class LayoutValue<T> : LayoutMember
{
/// <summary>
/// Creates a new <see cref="LayoutValue{T}"/>.
/// </summary>
/// <param name="invalidationType">The <see cref="Invalidation"/> flags that will invalidate this <see cref="LayoutValue{T}"/>.</param>
/// <param name="invalidationCondition">Any extra conditions that must be satisfied before this <see cref="LayoutValue{T}"/> is invalidated.</param>
/// <param name="invalidationSource">The source of the invalidation.</param>
public LayoutValue(Invalidation invalidationType, InvalidationConditionDelegate invalidationCondition = null, InvalidationSource invalidationSource = InvalidationSource.Default)
: base(invalidationType, invalidationCondition)
{
}
private T value;
/// <summary>
/// The current value.
/// </summary>
/// <exception cref="InvalidOperationException">If accessed while <see cref="LayoutMember.IsValid"/> is <code>false</code>.</exception>
public T Value
{
get
{
if (!IsValid)
throw new InvalidOperationException("todo");
return value;
}
set
{
this.value = value;
Validate();
}
}
public static implicit operator T(LayoutValue<T> layoutValue) => layoutValue.Value;
}
}
|
mit
|
C#
|
78552ade4579a69480460298b331c9338976c37b
|
Use the Count property for ICollection optimization
|
fsateler/MoreLINQ,ddpruitt/morelinq,ddpruitt/morelinq,smzinovyev/MoreLINQ,morelinq/MoreLINQ,morelinq/MoreLINQ,fsateler/MoreLINQ
|
MoreLinq/AtLeast.cs
|
MoreLinq/AtLeast.cs
|
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Returns true when the number of elements in the given sequence is greater than
/// or equal to the given integer.
/// This method throws an exception if the given integer is negative.
/// </summary>
/// <remarks>
/// The number of items streamed will be less than or equal to the given integer.
/// </remarks>
/// <typeparam name="TSource">Element type of sequence</typeparam>
/// <param name="source">The source sequence</param>
/// <param name="count">The minimum number of items a sequence must have for this
/// function to return true</param>
/// <exception cref="ArgumentNullException">source is null</exception>
/// <exception cref="ArgumentOutOfRangeException">count is negative</exception>
/// <returns><c>true</c> if the number of elements in the sequence is greater than
/// or equal to the given integer or <c>false</c> otherwise.</returns>
/// <example>
/// <code>
/// var numbers = { 123, 456, 789 };
/// var result = numbers.AtLeast(2);
/// </code>
/// The <c>result</c> variable will contain <c>true</c>.
/// </example>
public static bool AtLeast<TSource>(this IEnumerable<TSource> source, int count)
{
if (source == null) throw new ArgumentNullException("source");
if (count < 0) throw new ArgumentOutOfRangeException("count", "The count must not be negative.");
var collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count >= count;
}
return source.Take(count).Count() == count;
}
}
}
|
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Returns true when the number of elements in the given sequence is greater than
/// or equal to the given integer.
/// This method throws an exception if the given integer is negative.
/// </summary>
/// <remarks>
/// The number of items streamed will be less than or equal to the given integer.
/// </remarks>
/// <typeparam name="TSource">Element type of sequence</typeparam>
/// <param name="source">The source sequence</param>
/// <param name="count">The minimum number of items a sequence must have for this
/// function to return true</param>
/// <exception cref="ArgumentNullException">source is null</exception>
/// <exception cref="ArgumentOutOfRangeException">count is negative</exception>
/// <returns><c>true</c> if the number of elements in the sequence is greater than
/// or equal to the given integer or <c>false</c> otherwise.</returns>
/// <example>
/// <code>
/// var numbers = { 123, 456, 789 };
/// var result = numbers.AtLeast(2);
/// </code>
/// The <c>result</c> variable will contain <c>true</c>.
/// </example>
public static bool AtLeast<TSource>(this IEnumerable<TSource> source, int count)
{
if (source == null) throw new ArgumentNullException("source");
if (count < 0) throw new ArgumentOutOfRangeException("count", "The count must not be negative.");
var collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count() >= count;
}
return source.Take(count).Count() == count;
}
}
}
|
apache-2.0
|
C#
|
e56048281d35a1ceafd92b62a20e3a791486a125
|
Change TeamArea damage interval from 2 to 1
|
bunashibu/kikan
|
Assets/Scripts/TeamArea.cs
|
Assets/Scripts/TeamArea.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
namespace Bunashibu.Kikan {
public class TeamArea : Photon.MonoBehaviour, IAttacker, IPhotonBehaviour {
void Awake() {
_synchronizer = GetComponent<SkillSynchronizer>();
}
void OnTriggerStay2D(Collider2D collider) {
var targetObj = collider.gameObject;
if (targetObj.tag != "Player")
return;
var target = targetObj.GetComponent<Player>();
if (!target.PhotonView.isMine)
return;
if (target.PlayerInfo.Team == _team) {
if (target.Hp.Cur.Value == target.Hp.Max.Value)
return;
if (Time.time - _healTimestamp > _healInterval) {
_synchronizer.SyncHeal(target.PhotonView.viewID, target.Hp.Max.Value);
_healTimestamp = Time.time;
}
}
else {
if (target.State.Invincible)
return;
target.State.Invincible = true;
MonoUtility.Instance.DelaySec(1.0f, () => { target.State.Invincible = false; } );
_synchronizer.SyncAttack(photonView.viewID, target.PhotonView.viewID, _quantity, false, HitEffectType.None);
}
}
public PhotonView PhotonView => photonView;
public int Power => _quantity;
public int Critical => 0;
[SerializeField] private int _team;
[SerializeField] private int _quantity;
private SkillSynchronizer _synchronizer;
private float _healInterval = 2.0f;
private float _healTimestamp;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
namespace Bunashibu.Kikan {
public class TeamArea : Photon.MonoBehaviour, IAttacker, IPhotonBehaviour {
void Awake() {
_synchronizer = GetComponent<SkillSynchronizer>();
}
void OnTriggerStay2D(Collider2D collider) {
var targetObj = collider.gameObject;
if (targetObj.tag != "Player")
return;
var target = targetObj.GetComponent<Player>();
if (!target.PhotonView.isMine)
return;
if (target.PlayerInfo.Team == _team) {
if (target.Hp.Cur.Value == target.Hp.Max.Value)
return;
if (Time.time - _healTimestamp > _healInterval) {
_synchronizer.SyncHeal(target.PhotonView.viewID, target.Hp.Max.Value);
_healTimestamp = Time.time;
}
}
else {
if (target.State.Invincible)
return;
target.State.Invincible = true;
MonoUtility.Instance.DelaySec(2.0f, () => { target.State.Invincible = false; } );
_synchronizer.SyncAttack(photonView.viewID, target.PhotonView.viewID, _quantity, false, HitEffectType.None);
}
}
public PhotonView PhotonView => photonView;
public int Power => _quantity;
public int Critical => 0;
[SerializeField] private int _team;
[SerializeField] private int _quantity;
private SkillSynchronizer _synchronizer;
private float _healInterval = 2.0f;
private float _healTimestamp;
}
}
|
mit
|
C#
|
9497f97c4f076daa8d09b1d155b492ced6698861
|
Add layout to guidelines page.
|
mattrobineau/dotnetsignals,mattrobineau/dotnetsignals,mattrobineau/dotnetsignals,mattrobineau/dotnetsignals,mattrobineau/dotnetsignals
|
src/Stories/Views/Home/Guidelines.cshtml
|
src/Stories/Views/Home/Guidelines.cshtml
|
@{
ViewData["Title"] = "Guidelines";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<section>
<h2>What is dotnet signals?</h2>
.NET Signals is a community driven link aggregator for the sharing of knowledge in the .NET community. Our focus is to give the .NET community a place to post ideas and
knowledge as voted by the community while avoiding the clutter found in traditional sources.
<h2>Posts</h2>
<ul>
<li>Try to keep the title of the post the same as the article except to add information on vague titles,</li>
<li>Posts should be related to the .Net ecosystem or to information regarding technologies that the .Net community would find helpful or interesting,</li>
<li>Meta posts and bugs should be created on the github issues page as either discussion or bug,</li>
<li>Posts seeking help (homework, how do I do X, etc) are not suited for .NET Signals. Consider asking your questions on the .NET subreddit or stackoverflow.</li>
</ul>
<h2>Comments</h2>
<ul>
<li>Do not spam,</li>
<li>Avoid Me toos, thanks, "awesome post" comments,</li>
<li>Be professional, be polite.</li>
</ul>
</section>
|
<h2>What is dotnet signals?</h2>
.NET Signals is a community driven link aggregator for the sharing of knowledge in the .NET community. Our focus is to give the .NET community a place to post ideas and
knowledge as voted by the community while avoiding the clutter found in traditional sources.
<h2>Posts</h2>
<ul>
<li>Try to keep the title of the post the same as the article except to add information on vague titles,</li>
<li>Posts should be related to the .Net ecosystem or to information regarding technologies that the .Net community would find helpful or interesting,</li>
<li>Meta posts and bugs should be created on the github issues page as either discussion or bug,</li>
<li>Posts seeking help (homework, how do I do X, etc) are not suited for .NET Signals. Consider asking your questions on the .NET subreddit or stackoverflow.</li>
</ul>
<h2>Comments</h2>
<ul>
<li>Do not spam,</li>
<li>Avoid Me toos, thanks, "awesome post" comments,</li>
<li>Be professional, be polite.</li>
</ul>
|
mit
|
C#
|
438c3efd37181d0d66fb717e99c4d3ce90c15f65
|
Remove unused methods
|
Ackara/Daterpillar
|
src/Tests.Daterpillar/Helper/TestData.cs
|
src/Tests.Daterpillar/Helper/TestData.cs
|
using System;
using System.IO;
using System.Linq;
namespace Tests.Daterpillar.Helper
{
public static class TestData
{
public static FileInfo GetFile(string filename)
{
filename = Path.GetFileName(filename);
string ext = "*" + Path.GetExtension(filename);
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
return new DirectoryInfo(baseDirectory).GetFiles(ext, SearchOption.AllDirectories)
.First(x => x.Name == filename);
}
}
}
|
using Gigobyte.Daterpillar;
using System;
using System.IO;
using System.Linq;
namespace Tests.Daterpillar.Helper
{
public static class TestData
{
public static FileInfo GetFile(string filename)
{
filename = Path.GetFileName(filename);
string ext = "*" + Path.GetExtension(filename);
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
return new DirectoryInfo(baseDirectory).GetFiles(ext, SearchOption.AllDirectories)
.First(x => x.Name == filename);
}
public static Table CreateColumn(string name)
{
return new Table()
{
Name = name,
Comment = "This is a new table"
};
}
public static Column CreateColumn(string name, string tableName = "tb1")
{
return CreateColumn(name, new DataType("varchar", 32, 0), tableName);
}
public static Column CreateColumn(string name, DataType type, string tableName)
{
return new Column()
{
Name = name,
DataType = type,
IsNullable = false,
TableRef = new Table(tableName)
};
}
public static Index CreateIndex(string name, string tableName = "tb1", params IndexColumn[] columns)
{
return new Index()
{
TableRef = new Table(tableName),
Name = name,
Unique = false,
Table = tableName,
IndexType = IndexType.Index,
Columns = new System.Collections.Generic.List<IndexColumn>(columns)
};
}
public static ForeignKey CreateForeignKey(string name)
{
return new ForeignKey()
{
};
}
}
}
|
mit
|
C#
|
dd5b713ad9a824f5be91caddfdb039ac4e4ed1af
|
Change TransitionType to an unit enum Add [Falgs] attribute as TransitionType can have multiple values Import values from cef_transition_type_t (cef_types.h) Rename some of the values (slightly friendlier names)
|
Octopus-ITSM/CefSharp,Octopus-ITSM/CefSharp,illfang/CefSharp,twxstar/CefSharp,NumbersInternational/CefSharp,haozhouxu/CefSharp,Octopus-ITSM/CefSharp,twxstar/CefSharp,Haraguroicha/CefSharp,ITGlobal/CefSharp,ruisebastiao/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,yoder/CefSharp,AJDev77/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,joshvera/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,twxstar/CefSharp,haozhouxu/CefSharp,haozhouxu/CefSharp,twxstar/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,rover886/CefSharp,joshvera/CefSharp,AJDev77/CefSharp,VioletLife/CefSharp,ruisebastiao/CefSharp,Octopus-ITSM/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,joshvera/CefSharp,windygu/CefSharp,battewr/CefSharp,dga711/CefSharp,windygu/CefSharp,illfang/CefSharp,illfang/CefSharp,Livit/CefSharp,zhangjingpu/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,rover886/CefSharp,Livit/CefSharp,NumbersInternational/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,yoder/CefSharp,rover886/CefSharp,windygu/CefSharp,dga711/CefSharp,VioletLife/CefSharp,zhangjingpu/CefSharp,Livit/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,gregmartinhtc/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,battewr/CefSharp,VioletLife/CefSharp,VioletLife/CefSharp,ITGlobal/CefSharp
|
CefSharp/TransitionType.cs
|
CefSharp/TransitionType.cs
|
using System;
namespace CefSharp
{
[Flags]
public enum TransitionType : uint
{
/// <summary>
/// Source is a link click or the JavaScript window.open function. This is
/// also the default value for requests like sub-resource loads that are not navigations.
/// </summary>
LinkClicked = 0,
/// <summary>
/// Source is some other "explicit" navigation action such as creating a new
/// browser or using the LoadURL function. This is also the default value
/// for navigations where the actual type is unknown.
/// </summary>
Explicit = 1,
/// <summary>
/// Source is a subframe navigation. This is any content that is automatically
/// loaded in a non-toplevel frame. For example, if a page consists of several
/// frames containing ads, those ad URLs will have this transition type.
/// The user may not even realize the content in these pages is a separate
/// frame, so may not care about the URL.
/// </summary>
AutoSubFrame = 3,
/// <summary>
/// Source is a subframe navigation explicitly requested by the user that will
/// generate new navigation entries in the back/forward list. These are
/// probably more important than frames that were automatically loaded in
/// the background because the user probably cares about the fact that this
/// link was loaded.
/// </summary>
ManualSubFrame = 4,
/// <summary>
/// Source is a form submission by the user. NOTE: In some situations
/// submitting a form does not result in this transition type. This can happen
/// if the form uses a script to submit the contents.
/// </summary>
FormSubmit = 7,
/// <summary>
/// Source is a "reload" of the page via the Reload function or by re-visiting
/// the same URL. NOTE: This is distinct from the concept of whether a
/// particular load uses "reload semantics" (i.e. bypasses cached data).
/// </summary>
Reload = 8,
/// <summary>
/// General mask defining the bits used for the source values.
/// </summary>
SourceMask = 0xFF,
/// <summary>
/// Attempted to visit a URL but was blocked.
/// </summary>
Blocked = 0x00800000,
/// <summary>
/// Used the Forward or Back function to navigate among browsing history.
/// </summary>
ForwardBack = 0x01000000,
/// <summary>
/// The beginning of a navigation chain.
/// </summary>
ChainStart = 0x10000000,
/// <summary>
/// The last transition in a redirect chain.
/// </summary>
ChainEnd = 0x20000000,
/// <summary>
/// Redirects caused by JavaScript or a meta refresh tag on the page.
/// </summary>
CliendRedirect = 0x40000000,
/// <summary>
/// Redirects sent from the server by HTTP headers.
/// </summary>
ServerRedirect = 0x80000000,
/// <summary>
/// Used to test whether a transition involves a redirect.
/// </summary>
IsRedirect = 0xC0000000,
/// <summary>
/// General mask defining the bits used for the qualifiers.
/// </summary>
QualifierMask = 0xFFFFFF00
};
}
|
namespace CefSharp
{
public enum TransitionType
{
LinkClicked,
FormSubmitted,
BackForward,
Reload,
FormResubmitted,
Other
};
}
|
bsd-3-clause
|
C#
|
b84da2ca026c57645208b581a7f298a4295425ca
|
Add a couple of friend assemblies
|
arfbtwn/dbus-sharp,arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,openmedicus/dbus-sharp,mono/dbus-sharp
|
src/AssemblyInfo.cs
|
src/AssemblyInfo.cs
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
|
mit
|
C#
|
01acacd3ac13a92c2dd68092eb6dee1767437239
|
Format source
|
danielmundt/csremote
|
source/Remoting.Server/FormMain.cs
|
source/Remoting.Server/FormMain.cs
|
#region Header
// Copyright (C) 2012 Daniel Schubert
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion Header
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Text;
using System.Windows.Forms;
namespace Remoting.Server
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
CreateServer();
}
private void CreateServer()
{
try
{
HttpChannel httpChannel = new HttpChannel(80);
ChannelServices.RegisterChannel(httpChannel, false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Remoting.Interface.ICommand),
"RemotingExample/Command.soap", WellKnownObjectMode.SingleCall);
Command command = new Command();
RemotingServices.Marshal(command, "RemotingExample/Command.soap");
}
catch (SocketException)
{
}
}
}
}
|
#region Header
// Copyright (C) 2012 Daniel Schubert
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion Header
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Text;
using System.Windows.Forms;
namespace Remoting.Server
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
CreateServer();
}
private void CreateServer()
{
try
{
HttpChannel httpChannel = new HttpChannel(80);
ChannelServices.RegisterChannel(httpChannel, false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Remoting.Interface.ICommand),
"RemotingExample/Command.soap", WellKnownObjectMode.SingleCall);
Command command = new Command();
RemotingServices.Marshal(command, "RemotingExample/Command.soap");
}
catch (SocketException)
{
}
}
}
}
|
mit
|
C#
|
02283380c4b6ee648a741d695a35fa4cc5d6acf4
|
Use manual migration
|
ppy/osu,ZLima12/osu,ppy/osu,UselessToucan/osu,ZLima12/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu-new,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu
|
osu.Game/Migrations/20190525060824_SkinSettings.cs
|
osu.Game/Migrations/20190525060824_SkinSettings.cs
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace osu.Game.Migrations
{
public partial class SkinSettings : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"create table Settings_dg_tmp
(
ID INTEGER not null
constraint PK_Settings
primary key autoincrement,
Key TEXT not null,
RulesetID INTEGER,
Value TEXT,
Variant INTEGER,
SkinInfoID int
constraint Settings_SkinInfo_ID_fk
references SkinInfo
on delete restrict
);
insert into Settings_dg_tmp(ID, Key, RulesetID, Value, Variant) select ID, Key, RulesetID, Value, Variant from Settings;
drop table Settings;
alter table Settings_dg_tmp rename to Settings;
create index IX_Settings_RulesetID_Variant
on Settings (RulesetID, Variant);
create index Settings_SkinInfoID_index
on Settings (SkinInfoID);
");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Settings_SkinInfo_SkinInfoID",
table: "Settings");
migrationBuilder.DropIndex(
name: "IX_Settings_SkinInfoID",
table: "Settings");
migrationBuilder.DropColumn(
name: "SkinInfoID",
table: "Settings");
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace osu.Game.Migrations
{
public partial class SkinSettings : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "SkinInfoID",
table: "Settings",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Settings_SkinInfoID",
table: "Settings",
column: "SkinInfoID");
// unsupported by sqlite
// migrationBuilder.AddForeignKey(
// name: "FK_Settings_SkinInfo_SkinInfoID",
// table: "Settings",
// column: "SkinInfoID",
// principalTable: "SkinInfo",
// principalColumn: "ID",
// onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Settings_SkinInfo_SkinInfoID",
table: "Settings");
migrationBuilder.DropIndex(
name: "IX_Settings_SkinInfoID",
table: "Settings");
migrationBuilder.DropColumn(
name: "SkinInfoID",
table: "Settings");
}
}
}
|
mit
|
C#
|
6f3c8e9f8bf1f6190777ab513dadd20b0d5c30c0
|
Add explicit usage via attribute
|
EVAST9919/osu,DrabWeb/osu,johnneijzen/osu,naoey/osu,ZLima12/osu,DrabWeb/osu,naoey/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,ZLima12/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu,naoey/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,2yangk23/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,DrabWeb/osu,NeoAdonis/osu,smoogipoo/osu
|
osu.Game/Online/API/Requests/GetUpdatesResponse.cs
|
osu.Game/Online/API/Requests/GetUpdatesResponse.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.Chat;
namespace osu.Game.Online.API.Requests
{
public class GetUpdatesResponse
{
[JsonProperty]
public List<Channel> Presence;
[JsonProperty]
public List<Message> Messages;
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Game.Online.Chat;
namespace osu.Game.Online.API.Requests
{
public class GetUpdatesResponse
{
public List<Channel> Presence;
public List<Message> Messages;
}
}
|
mit
|
C#
|
68cda055e90a9b504e1ea04e6002520c7ef6b07b
|
Make LogLevel publicly available
|
jdno/AIChallengeFramework
|
IO/Logger.cs
|
IO/Logger.cs
|
//
// Copyright 2014 jdno
//
// 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 AIChallengeFramework
{
/// <summary>
/// This is a small logging facility that can be used for troubleshooting.
/// </summary>
public static class Logger
{
/// <summary>
/// These are the log level supported by this project.
/// </summary>
public enum Severity {
OFF = 0,
ERROR = 1,
INFO = 2,
DEBUG = 3
}
/// <summary>
/// Choose the severity you would like to have logged.
/// </summary>
public static Severity LogLevel { get; set; }
/// <summary>
/// Initialize this instance.
/// </summary>
public static void Initialize ()
{
LogLevel = Severity.ERROR;
Logger.Info ("Logger:\tInitialized.");
}
/// <summary>
/// Efficiently check if the log level is DEBUG.
/// </summary>
/// <returns><c>true</c> if is DEBUG; otherwise, <c>false</c>.</returns>
public static bool IsDebug ()
{
if (LogLevel == Severity.DEBUG) {
return true;
} else {
return false;
}
}
/// <summary>
/// Log the message only if the log level is error.
/// </summary>
/// <param name="message">Message.</param>
public static void Error (string message)
{
if (LogLevel >= Severity.ERROR)
print (message);
}
/// <summary>
/// Log the message only if the log level is info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Info (string message)
{
if (LogLevel >= Severity.INFO)
print (message);
}
/// <summary>
/// Log the message only if the log level is debug, info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Debug (string message)
{
if (LogLevel >= Severity.DEBUG)
print (message);
}
/// <summary>
/// Print the specified message.
/// </summary>
/// <param name="message">Message.</param>
private static void print (string message) {
Console.Error.WriteLine (message);
}
}
}
|
//
// Copyright 2014 jdno
//
// 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 AIChallengeFramework
{
/// <summary>
/// This is a small logging facility that can be used for troubleshooting.
/// </summary>
public static class Logger
{
/// <summary>
/// These are the log level supported by this project.
/// </summary>
public enum Severity {
OFF = 0,
ERROR = 1,
INFO = 2,
DEBUG = 3
}
/// <summary>
/// Choose the severity you would like to have logged.
/// </summary>
public static Severity LogLevel { get; private set; }
/// <summary>
/// Initialize this instance.
/// </summary>
public static void Initialize ()
{
LogLevel = Severity.ERROR;
Logger.Info ("Logger:\tInitialized.");
}
/// <summary>
/// Efficiently check if the log level is DEBUG.
/// </summary>
/// <returns><c>true</c> if is DEBUG; otherwise, <c>false</c>.</returns>
public static bool IsDebug ()
{
if (LogLevel == Severity.DEBUG) {
return true;
} else {
return false;
}
}
/// <summary>
/// Log the message only if the log level is error.
/// </summary>
/// <param name="message">Message.</param>
public static void Error (string message)
{
if (LogLevel >= Severity.ERROR)
print (message);
}
/// <summary>
/// Log the message only if the log level is info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Info (string message)
{
if (LogLevel >= Severity.INFO)
print (message);
}
/// <summary>
/// Log the message only if the log level is debug, info or error.
/// </summary>
/// <param name="message">Message.</param>
public static void Debug (string message)
{
if (LogLevel >= Severity.DEBUG)
print (message);
}
/// <summary>
/// Print the specified message.
/// </summary>
/// <param name="message">Message.</param>
private static void print (string message) {
Console.Error.WriteLine (message);
}
}
}
|
apache-2.0
|
C#
|
c303346bc33fc1f789c93cef7255a719045c3c6d
|
Halt reloading after subprocess crash if it happens too often
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
windows/TweetImpl.CefSharp/Handlers/CefRequestHandler.cs
|
windows/TweetImpl.CefSharp/Handlers/CefRequestHandler.cs
|
using System.Diagnostics;
using CefSharp;
using CefSharp.Handler;
using TweetImpl.CefSharp.Adapters;
using TweetLib.Browser.CEF.Logic;
namespace TweetImpl.CefSharp.Handlers {
sealed class CefRequestHandler : RequestHandler {
public RequestHandlerLogic<IRequest> Logic { get; }
private readonly AutoReloader? autoReloader;
public CefRequestHandler(CefLifeSpanHandler lifeSpanHandler, bool autoReload) {
this.Logic = new RequestHandlerLogic<IRequest>(CefRequestAdapter.Instance, lifeSpanHandler.Logic);
this.autoReloader = autoReload ? new AutoReloader() : null;
}
protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect) {
return Logic.OnBeforeBrowse(request, userGesture);
}
protected override bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture) {
return Logic.OnOpenUrlFromTab(targetUrl, userGesture, CefLifeSpanHandler.ConvertTargetDisposition(targetDisposition));
}
protected override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status) {
if (autoReloader?.RequestReload() == true) {
browser.Reload();
}
}
private sealed class AutoReloader {
private readonly Stopwatch lastReload = Stopwatch.StartNew();
private int rapidReloadCount;
public bool RequestReload() {
if (rapidReloadCount >= 2) {
lastReload.Stop();
return false;
}
if (lastReload.ElapsedMilliseconds < 5000) {
++rapidReloadCount;
}
else {
rapidReloadCount = 0;
}
lastReload.Restart();
return true;
}
}
}
}
|
using CefSharp;
using CefSharp.Handler;
using TweetImpl.CefSharp.Adapters;
using TweetLib.Browser.CEF.Logic;
namespace TweetImpl.CefSharp.Handlers {
sealed class CefRequestHandler : RequestHandler {
public RequestHandlerLogic<IRequest> Logic { get; }
private readonly bool autoReload;
public CefRequestHandler(CefLifeSpanHandler lifeSpanHandler, bool autoReload) {
this.Logic = new RequestHandlerLogic<IRequest>(CefRequestAdapter.Instance, lifeSpanHandler.Logic);
this.autoReload = autoReload;
}
protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect) {
return Logic.OnBeforeBrowse(request, userGesture);
}
protected override bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture) {
return Logic.OnOpenUrlFromTab(targetUrl, userGesture, CefLifeSpanHandler.ConvertTargetDisposition(targetDisposition));
}
protected override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status) {
if (autoReload) {
browser.Reload();
}
}
}
}
|
mit
|
C#
|
2a93bc84998395347341901a6df9fc0df5a265f5
|
Make mainObject an instance field
|
earalov/Skylines-ModTools
|
Debugger/ModToolsMod.cs
|
Debugger/ModToolsMod.cs
|
using System;
using ColossalFramework;
using ColossalFramework.Plugins;
using ICities;
using ModTools.Utils;
using UnityEngine;
namespace ModTools
{
public sealed class ModToolsMod : IUserMod
{
public const string ModToolsName = "ModTools";
public static GameObject MainWindowObject;
private GameObject mainObject;
public static string Version { get; } = GitVersion.GetAssemblyVersion(typeof(ModToolsMod).Assembly);
public string Name => ModToolsName;
public string Description => "Debugging toolkit for modders, version " + Version;
public void OnEnabled()
{
try
{
if (MainWindowObject != null)
{
return;
}
CODebugBase<LogChannel>.verbose = true;
CODebugBase<LogChannel>.EnableChannels(LogChannel.All);
mainObject = new GameObject(ModToolsName);
UnityEngine.Object.DontDestroyOnLoad(mainObject);
MainWindowObject = new GameObject(ModToolsName + nameof(MainWindow));
UnityEngine.Object.DontDestroyOnLoad(MainWindowObject);
var modTools = MainWindowObject.AddComponent<MainWindow>();
modTools.Initialize();
}
catch (Exception e)
{
DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, e.Message);
}
}
public void OnDisabled()
{
if (MainWindowObject != null)
{
CODebugBase<LogChannel>.verbose = false;
UnityEngine.Object.Destroy(MainWindowObject);
MainWindowObject = null;
}
if (mainObject != null)
{
CODebugBase<LogChannel>.verbose = false;
UnityEngine.Object.Destroy(mainObject);
mainObject = null;
}
}
}
}
|
using System;
using ColossalFramework;
using ColossalFramework.Plugins;
using ICities;
using ModTools.Utils;
using UnityEngine;
namespace ModTools
{
public sealed class ModToolsMod : IUserMod
{
public const string ModToolsName = "ModTools";
public static GameObject MainWindowObject;
private static GameObject mainObject;
public static string Version { get; } = GitVersion.GetAssemblyVersion(typeof(ModToolsMod).Assembly);
public string Name => ModToolsName;
public string Description => "Debugging toolkit for modders, version " + Version;
public void OnEnabled()
{
try
{
if (MainWindowObject != null)
{
return;
}
CODebugBase<LogChannel>.verbose = true;
CODebugBase<LogChannel>.EnableChannels(LogChannel.All);
mainObject = new GameObject(ModToolsName);
UnityEngine.Object.DontDestroyOnLoad(mainObject);
MainWindowObject = new GameObject(ModToolsName + nameof(MainWindow));
UnityEngine.Object.DontDestroyOnLoad(MainWindowObject);
var modTools = MainWindowObject.AddComponent<MainWindow>();
modTools.Initialize();
}
catch (Exception e)
{
DebugOutputPanel.AddMessage(PluginManager.MessageType.Error, e.Message);
}
}
public void OnDisabled()
{
if (MainWindowObject != null)
{
CODebugBase<LogChannel>.verbose = false;
UnityEngine.Object.Destroy(MainWindowObject);
MainWindowObject = null;
}
if (mainObject != null)
{
CODebugBase<LogChannel>.verbose = false;
UnityEngine.Object.Destroy(mainObject);
mainObject = null;
}
}
}
}
|
mit
|
C#
|
1ca06b2e483f2fd57dd74f5f110cd8c609a17073
|
Add handler for AppDomain.UnhandledException
|
iridinite/shiftdrive
|
Client/Program.cs
|
Client/Program.cs
|
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System;
namespace ShiftDrive {
#if WINDOWS || LINUX
public static class Program {
[STAThread]
public static void Main() {
// handler for logging crashes
AppDomain.CurrentDomain.UnhandledException += Program_UnhandledException;
// run the game
using (var game = new SDGame())
game.Run();
}
private static void Program_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
Exception ex = e.ExceptionObject as Exception;
if (ex != null)
Logger.WriteExceptionReport(ex);
}
}
#endif
}
|
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System;
namespace ShiftDrive {
#if WINDOWS || LINUX
public static class Program {
[STAThread]
public static void Main() {
#if !DEBUG
try {
#endif
using (var game = new SDGame())
game.Run();
#if !DEBUG
} catch (Exception ex) {
Logger.WriteExceptionReport(ex);
}
#endif
}
}
#endif
}
|
bsd-3-clause
|
C#
|
c9f7ce93282bffc136c2cd567735b1f13984dcd4
|
Update assembly version.
|
Dixin/EntityFramework.Functions
|
Tools/CommonAssemblyInfo.cs
|
Tools/CommonAssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyDescription("EntityFramework.Functions library implements Entity Framework code first support for stored procedures (with single result type, multiple result types, output parameter), table-valued functions (returning entity type, complex type), scalar-valued functions (composable, non-composable), aggregate functions, built-in functions, niladic functions, and model defined functions.")]
[assembly: AssemblyCompany("Dixin Yan")]
[assembly: AssemblyProduct("EntityFramework.Functions")]
[assembly: AssemblyCopyright("Dixin Yan https://weblogs.asp.net/dixin")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.3.1.0")]
[assembly: AssemblyFileVersion("1.3.1.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyDescription("EntityFramework.Functions library implements Entity Framework code first support for stored procedures (with single result type, multiple result types, output parameter), table-valued functions (returning entity type, complex type), scalar-valued functions (composable, non-composable), aggregate functions, built-in functions, niladic functions, and model defined functions.")]
[assembly: AssemblyCompany("Dixin Yan")]
[assembly: AssemblyProduct("EntityFramework.Functions")]
[assembly: AssemblyCopyright("Dixin Yan https://weblogs.asp.net/dixin")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
|
mit
|
C#
|
7b497f31590aefe9c78fc0253da50fcd161a879e
|
Make BindingPathUtilities static
|
github/VisualStudio,github/VisualStudio,github/VisualStudio
|
src/GitHub.Exports/Helpers/BindingPathUtilities.cs
|
src/GitHub.Exports/Helpers/BindingPathUtilities.cs
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using GitHub.Logging;
using Serilog;
namespace GitHub.Helpers
{
public static class BindingPathUtilities
{
static readonly ILogger log = LogManager.ForContext(typeof(BindingPathUtilities));
public static void RationalizeBindingPaths(string assemblyLocation, List<string> bindingPaths = null)
{
bindingPaths = bindingPaths ?? FindBindingPaths();
var fileName = Path.GetFileName(assemblyLocation);
bindingPaths
.Select(p => new { path = p, file = Path.Combine(p, fileName) })
.Where(pf => File.Exists(pf.file))
.Where(pf => !pf.file.Equals(assemblyLocation, StringComparison.OrdinalIgnoreCase))
.ToList()
.ForEach(pf =>
{
var loaded = IsAssemblyLoaded(pf.file);
if (loaded)
{
log.Error("Assembly has already been loaded from {Location}", pf.file);
}
log.Warning("Removing duplicate binding path {BindingPath}", pf.path);
bindingPaths.Remove(pf.path);
});
}
public static bool IsAssemblyLoaded(string assemblyLocation)
{
var prefix = Path.GetFileNameWithoutExtension(assemblyLocation) + ",";
return AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
.Where(a => a.Location.Equals(assemblyLocation, StringComparison.OrdinalIgnoreCase))
.Any();
}
public static List<string> FindBindingPaths()
{
var manager = AppDomain.CurrentDomain.DomainManager;
var property = manager.GetType().GetProperty("BindingPaths", BindingFlags.NonPublic | BindingFlags.Instance);
return (List<string>)property?.GetValue(manager);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using GitHub.Logging;
using Serilog;
namespace GitHub.Helpers
{
public class BindingPathUtilities
{
static readonly ILogger log = LogManager.ForContext<BindingPathUtilities>();
public static void RationalizeBindingPaths(string assemblyLocation, List<string> bindingPaths = null)
{
bindingPaths = bindingPaths ?? FindBindingPaths();
var fileName = Path.GetFileName(assemblyLocation);
bindingPaths
.Select(p => new { path = p, file = Path.Combine(p, fileName) })
.Where(pf => File.Exists(pf.file))
.Where(pf => !pf.file.Equals(assemblyLocation, StringComparison.OrdinalIgnoreCase))
.ToList()
.ForEach(pf =>
{
var loaded = IsAssemblyLoaded(pf.file);
if (loaded)
{
log.Error("Assembly has already been loaded from {Location}", pf.file);
}
log.Warning("Removing duplicate binding path {BindingPath}", pf.path);
bindingPaths.Remove(pf.path);
});
}
public static bool IsAssemblyLoaded(string assemblyLocation)
{
var prefix = Path.GetFileNameWithoutExtension(assemblyLocation) + ",";
return AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
.Where(a => a.Location.Equals(assemblyLocation, StringComparison.OrdinalIgnoreCase))
.Any();
}
public static List<string> FindBindingPaths()
{
var manager = AppDomain.CurrentDomain.DomainManager;
var property = manager.GetType().GetProperty("BindingPaths", BindingFlags.NonPublic | BindingFlags.Instance);
return (List<string>)property?.GetValue(manager);
}
}
}
|
mit
|
C#
|
b226a5b8f8bbcc61a21425c261042fd1814c7982
|
Change to use ScriptLinkCore.Objects namespace
|
scottolsonjr/scriptlink-core
|
Helpers.cs
|
Helpers.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ScriptLinkCore.Objects;
namespace ScriptLinkCore
{
public partial class ScriptLink
{
/// <summary>
/// Used set required fields
/// </summary>
/// <param name="optionObject"></param>
/// <param name="fieldNumber"></param>
/// <returns></returns>
public static OptionObject SetRequiredField(OptionObject optionObject, string fieldNumber)
{
OptionObject returnOptionObject = optionObject;
Boolean updated = false;
foreach (var form in returnOptionObject.Forms)
{
foreach (var currentField in form.CurrentRow.Fields)
{
if (currentField.FieldNumber == fieldNumber)
{
currentField.Required = "1";
updated = true;
}
}
}
if (updated == true)
{
foreach (var form in returnOptionObject.Forms)
{
form.CurrentRow.RowAction = "EDIT";
}
return returnOptionObject;
}
else
{
return optionObject;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NTST.ScriptLinkService.Objects;
namespace ScriptLinkCore
{
public partial class ScriptLink
{
/// <summary>
/// Used set required fields
/// </summary>
/// <param name="optionObject"></param>
/// <param name="fieldNumber"></param>
/// <returns></returns>
public static OptionObject SetRequiredField(OptionObject optionObject, string fieldNumber)
{
OptionObject returnOptionObject = optionObject;
Boolean updated = false;
foreach (var form in returnOptionObject.Forms)
{
foreach (var currentField in form.CurrentRow.Fields)
{
if (currentField.FieldNumber == fieldNumber)
{
currentField.Required = "1";
updated = true;
}
}
}
if (updated == true)
{
foreach (var form in returnOptionObject.Forms)
{
form.CurrentRow.RowAction = "EDIT";
}
return returnOptionObject;
}
else
{
return optionObject;
}
}
}
}
|
mit
|
C#
|
b9b23f4b74cad0e8e624f5743285439138dae36b
|
update version
|
ezaurum/dapper
|
Properties/AssemblyInfo.cs
|
Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper Repository")]
[assembly: AssemblyDescription("Dapper auto generated repository extension")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ezaurum")]
[assembly: AssemblyProduct("dapper extention")]
[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("c3a998b9-1a09-4589-9e91-481383acb2ec")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.1.20")]
[assembly: AssemblyFileVersion("0.0.1.20")]
[assembly: NeutralResourcesLanguageAttribute("ko-KR")]
|
using System.Reflection;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper Repository")]
[assembly: AssemblyDescription("Dapper auto generated repository extension")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ezaurum")]
[assembly: AssemblyProduct("dapper extention")]
[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("c3a998b9-1a09-4589-9e91-481383acb2ec")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.1.19")]
[assembly: AssemblyFileVersion("0.0.1.19")]
[assembly: NeutralResourcesLanguageAttribute("ko-KR")]
|
mit
|
C#
|
343efa6f5b24e5698ea37afd96298dbe41fda7b9
|
test for ValueList
|
peachpiecompiler/peachpie,peachpiecompiler/peachpie,iolevel/peachpie-concept,iolevel/peachpie-concept,peachpiecompiler/peachpie,iolevel/peachpie-concept
|
src/Tests/Peachpie.Runtime.Tests/UtilitiesTests.cs
|
src/Tests/Peachpie.Runtime.Tests/UtilitiesTests.cs
|
using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pchp.Core;
using Pchp.Core.Collections;
using Pchp.Core.Text;
namespace Peachpie.Runtime.Tests
{
[TestClass]
public class UtilitiesTests
{
[TestMethod]
public void PathUtilsTest()
{
Assert.AreEqual("php", Pchp.Core.Utilities.PathUtils.GetExtension("c:/something.path/index.php").ToString());
Assert.AreEqual("", Pchp.Core.Utilities.PathUtils.GetExtension("c:\\something.path\\index").ToString());
Assert.AreEqual("", Pchp.Core.Utilities.PathUtils.GetExtension("/something.path/index.").ToString());
Assert.AreEqual("file.txt", Pchp.Core.Utilities.PathUtils.GetFileName("/something.path/file.txt").ToString());
Assert.AreEqual("file.txt", Pchp.Core.Utilities.PathUtils.GetFileName("file.txt").ToString());
}
[TestMethod]
public void Bin2HexTest()
{
Assert.AreEqual("", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { }));
Assert.AreEqual("08", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 8 }));
Assert.AreEqual("ff", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 0xff }, "-"));
Assert.AreEqual("ff-ff", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 0xff, 0xff }, "-"));
Assert.AreEqual("ff-ff-ff", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 0xff, 0xff, 0xff }, "-"));
}
[TestMethod]
public void ValueListTest()
{
var list = new ValueList<int>();
for (int i = 0; i < 10; i++)
{
list.AddRange(new[] { 0, 1, 2, 3 });
list.Add(4);
list.Insert(list.Count, 5);
}
list.Insert(0, -1);
list.Insert(1, 1);
}
}
}
|
using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pchp.Core;
using Pchp.Core.Text;
namespace Peachpie.Runtime.Tests
{
[TestClass]
public class UtilitiesTests
{
[TestMethod]
public void PathUtilsTest()
{
Assert.AreEqual("php", Pchp.Core.Utilities.PathUtils.GetExtension("c:/something.path/index.php").ToString());
Assert.AreEqual("", Pchp.Core.Utilities.PathUtils.GetExtension("c:\\something.path\\index").ToString());
Assert.AreEqual("", Pchp.Core.Utilities.PathUtils.GetExtension("/something.path/index.").ToString());
Assert.AreEqual("file.txt", Pchp.Core.Utilities.PathUtils.GetFileName("/something.path/file.txt").ToString());
Assert.AreEqual("file.txt", Pchp.Core.Utilities.PathUtils.GetFileName("file.txt").ToString());
}
[TestMethod]
public void Bin2HexTest()
{
Assert.AreEqual("", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { }));
Assert.AreEqual("08", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 8 }));
Assert.AreEqual("ff", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 0xff }, "-"));
Assert.AreEqual("ff-ff", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 0xff, 0xff }, "-"));
Assert.AreEqual("ff-ff-ff", Pchp.Core.Utilities.StringUtils.BinToHex(new byte[] { 0xff, 0xff, 0xff }, "-"));
}
}
}
|
apache-2.0
|
C#
|
120f3b339fe3def0496d1f56c32a539e8cde9ad6
|
Use BenchmarkRunner
|
martincostello/api,martincostello/api,martincostello/api
|
tests/API.Benchmarks/Program.cs
|
tests/API.Benchmarks/Program.cs
|
// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the MIT license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Api.Benchmarks
{
using System;
using System.Threading.Tasks;
using BenchmarkDotNet.Running;
/// <summary>
/// A console application that runs performance benchmarks for the API. This class cannot be inherited.
/// </summary>
internal static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// A <see cref="Task"/> representing the asynchronous invocation of the application.
/// </returns>
internal static async Task Main(string[] args)
{
if (args?.Length == 1 && string.Equals(args[0], "--test", StringComparison.OrdinalIgnoreCase))
{
using var benchmark = new ApiBenchmarks();
await benchmark.StartServer();
await benchmark.Hash();
await benchmark.Time();
await benchmark.StopServer();
}
else
{
BenchmarkRunner.Run<ApiBenchmarks>(args: args);
}
}
}
}
|
// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the MIT license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Api.Benchmarks
{
using System;
using System.Threading.Tasks;
using BenchmarkDotNet.Running;
/// <summary>
/// A console application that runs performance benchmarks for the API. This class cannot be inherited.
/// </summary>
internal static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// A <see cref="Task"/> representing the asynchronous invocation of the application.
/// </returns>
internal static async Task Main(string[] args)
{
var switcher = BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly);
if (args?.Length == 0)
{
switcher.RunAll();
}
else if (args?.Length == 1 && string.Equals(args[0], "--test", StringComparison.OrdinalIgnoreCase))
{
using var benchmark = new ApiBenchmarks();
await benchmark.StartServer();
await benchmark.Hash();
await benchmark.Time();
await benchmark.StopServer();
}
else
{
switcher.Run(args);
}
}
}
}
|
mit
|
C#
|
f96f9e770ac23a4df2ba40d859b012c9ac177c64
|
Upgrade assembly metadata
|
Zeugma440/atldotnet
|
ATL/Properties/AssemblyInfo.cs
|
ATL/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("ATL")]
[assembly: AssemblyDescription("Audio Tools Libray .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ATL")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("1597be31-1d62-45a6-8abb-380c406238e9")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("ATL")]
[assembly: AssemblyDescription("Audio Tools Libray .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ATL")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("1597be31-1d62-45a6-8abb-380c406238e9")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
mit
|
C#
|
55c300718bf51d6eade596651df75aa670352ef8
|
Fix description
|
GeorgeHahn/SOVND
|
SOVND.Server/Channel.cs
|
SOVND.Server/Channel.cs
|
using System.Collections.Generic;
using System.Linq;
namespace SOVND.Server
{
public class Channel
{
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
// TODO Moderators
public Dictionary<string, Song> SongsByID { get; set; } = new Dictionary<string, Song>();
/// <summary>
/// Gets the song at the top of the list
/// TODO Return enumeration that counts down from the top of the list (write a sorting function and use C#'s sorting)
/// </summary>
/// <returns></returns>
public Song GetTopSong()
{
Song max = SongsByID.Values.FirstOrDefault();
foreach (var song in SongsByID.Values)
{
if (song == max)
continue;
if (song.Votes > max.Votes)
{
max = song;
} else if (song.Votes == max.Votes && song.Votetime < max.Votetime)
{
max = song;
}
}
return max;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace SOVND.Server
{
public class Channel
{
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
// TODO Moderators
public Dictionary<string, Song> SongsByID { get; set; } = new Dictionary<string, Song>();
/// <summary>
/// Gets the song at the top of the list
/// TODO Return an enum that counts down from the top of the list (write a sorting function and use C#'s sorting)
/// </summary>
/// <returns></returns>
public Song GetTopSong()
{
Song max = SongsByID.Values.FirstOrDefault();
foreach (var song in SongsByID.Values)
{
if (song == max)
continue;
if (song.Votes > max.Votes)
{
max = song;
} else if (song.Votes == max.Votes && song.Votetime < max.Votetime)
{
max = song;
}
}
return max;
}
}
}
|
epl-1.0
|
C#
|
c863b1d7331c9680a9e4dc5208382897074099fe
|
Add TODOs to the monitor tool
|
tmds/Tmds.DBus
|
Monitor.cs
|
Monitor.cs
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTest
{
public static void Main (string[] args)
{
//TODO: allow selection of bus
if (args.Length == 1) {
string arg = args[1];
switch (arg)
{
case "--system":
break;
case "--session":
break;
default:
break;
}
}
Connection conn = new Connection ();
ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
string name = "org.freedesktop.DBus";
Bus bus = conn.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.WriteLine ("NameAcquired: " + acquired_name);
};
bus.Hello ();
//hack to process the NameAcquired signal synchronously
conn.HandleSignal (conn.ReadMessage ());
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
while (true) {
Message msg = conn.ReadMessage ();
Console.WriteLine ("Message:");
Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine ("\t" + hf.Code + ": " + hf.Value);
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine ("\t" + field.Key + ": " + field.Value);
if (msg.Body != null) {
Console.WriteLine ("\tBody:");
//System.IO.MemoryStream ms = new System.IO.MemoryStream (msg.Body);
//System.IO.MemoryStream ms = msg.Body;
//TODO: this needs to be done more intelligently
foreach (DType dtype in msg.Signature.Data) {
if (dtype == DType.Invalid)
continue;
object arg;
Message.GetValue (msg.Body, dtype, out arg);
Console.WriteLine ("\t\t" + dtype + ": " + arg);
}
}
Console.WriteLine ();
}
}
}
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
public class ManagedDBusTest
{
public static void Main ()
{
Connection conn = new Connection ();
ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
string name = "org.freedesktop.DBus";
Bus bus = conn.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.WriteLine ("NameAcquired: " + acquired_name);
};
bus.Hello ();
//hack to process the NameAcquired signal synchronously
conn.HandleSignal (conn.ReadMessage ());
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn));
bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error));
while (true) {
Message msg = conn.ReadMessage ();
Console.WriteLine ("Message:");
Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType);
//foreach (HeaderField hf in msg.HeaderFields)
// Console.WriteLine ("\t" + hf.Code + ": " + hf.Value);
foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields)
Console.WriteLine ("\t" + field.Key + ": " + field.Value);
if (msg.Body != null) {
Console.WriteLine ("\tBody:");
//System.IO.MemoryStream ms = new System.IO.MemoryStream (msg.Body);
//System.IO.MemoryStream ms = msg.Body;
foreach (DType dtype in msg.Signature.Data) {
if (dtype == DType.Invalid)
continue;
object arg;
Message.GetValue (msg.Body, dtype, out arg);
Console.WriteLine ("\t\t" + dtype + ": " + arg);
}
}
Console.WriteLine ();
}
}
}
|
mit
|
C#
|
1ce8199d687e069076317d82b1cd8835a7580459
|
Hide HelenaCtrl when hit
|
bunashibu/kikan
|
Assets/Scripts/Skill/Helena/HelenaCtrl.cs
|
Assets/Scripts/Skill/Helena/HelenaCtrl.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UniRx;
namespace Bunashibu.Kikan {
[RequireComponent(typeof(SkillSynchronizer))]
public class HelenaCtrl : Skill {
void Awake() {
_synchronizer = GetComponent<SkillSynchronizer>();
_hitRistrictor = new HitRistrictor(_hitInfo);
Observable.Timer(TimeSpan.FromSeconds(_existTime))
.Where(_ => this != null)
.Subscribe(_ => {
gameObject.SetActive(false);
Observable.Timer(TimeSpan.FromSeconds(5.0f))
.Where(none => this != null)
.Subscribe(none => {
Destroy(gameObject);
});
});
}
void Update() {
if (photonView.isMine)
transform.Translate(Vector2.left * _moveSpeed * Time.deltaTime, Space.Self);
}
void OnTriggerEnter2D(Collider2D collider) {
var target = collider.gameObject.GetComponent<IPhoton>();
if (target == null)
return;
if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj))
return;
if (_hitRistrictor.ShouldRistrict(collider.gameObject))
return;
var marginTime = 0.1f;
Observable.Timer(TimeSpan.FromSeconds(marginTime))
.Where(_ => this != null)
.Subscribe(_ => {
gameObject.SetActive(false);
});
if (PhotonNetwork.isMasterClient) {
DamageCalculator.Calculate(_skillUserObj, _attackInfo);
_synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena);
_synchronizer.SyncDebuff(target.PhotonView.viewID, DebuffType.Ice, _duration);
}
}
[SerializeField] private AttackInfo _attackInfo;
[SerializeField] private HitInfo _hitInfo;
private SkillSynchronizer _synchronizer;
private HitRistrictor _hitRistrictor;
private float _duration = 2.0f;
private float _existTime = 0.6f;
private float _moveSpeed = 8.0f;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UniRx;
namespace Bunashibu.Kikan {
[RequireComponent(typeof(SkillSynchronizer))]
public class HelenaCtrl : Skill {
void Awake() {
_synchronizer = GetComponent<SkillSynchronizer>();
_hitRistrictor = new HitRistrictor(_hitInfo);
Observable.Timer(TimeSpan.FromSeconds(_existTime))
.Where(_ => this != null)
.Subscribe(_ => {
gameObject.SetActive(false);
Observable.Timer(TimeSpan.FromSeconds(5.0f))
.Where(none => this != null)
.Subscribe(none => {
Destroy(gameObject);
});
});
}
void Update() {
if (photonView.isMine)
transform.Translate(Vector2.left * _moveSpeed * Time.deltaTime, Space.Self);
}
void OnTriggerEnter2D(Collider2D collider) {
if (PhotonNetwork.isMasterClient) {
var target = collider.gameObject.GetComponent<IPhoton>();
if (target == null)
return;
if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj))
return;
if (_hitRistrictor.ShouldRistrict(collider.gameObject))
return;
DamageCalculator.Calculate(_skillUserObj, _attackInfo);
_synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena);
_synchronizer.SyncDebuff(target.PhotonView.viewID, DebuffType.Ice, _duration);
}
}
[SerializeField] private AttackInfo _attackInfo;
[SerializeField] private HitInfo _hitInfo;
private SkillSynchronizer _synchronizer;
private HitRistrictor _hitRistrictor;
private float _duration = 2.0f;
private float _existTime = 0.6f;
private float _moveSpeed = 8.0f;
}
}
|
mit
|
C#
|
9dc29b5c89645c9af44ffb233abfc2aacd676143
|
Remove AddContentButton & RemoveContentButton methods from IDetailView and add event ContentsButtonClicked
|
sakthivelnagarajan/monotouch-samples,a9upam/monotouch-samples,W3SS/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,albertoms/monotouch-samples,davidrynn/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,davidrynn/monotouch-samples,albertoms/monotouch-samples,nelzomal/monotouch-samples,albertoms/monotouch-samples,hongnguyenpro/monotouch-samples,peteryule/monotouch-samples,xamarin/monotouch-samples,robinlaide/monotouch-samples,labdogg1003/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,a9upam/monotouch-samples,haithemaraissia/monotouch-samples,iFreedive/monotouch-samples,haithemaraissia/monotouch-samples,xamarin/monotouch-samples,hongnguyenpro/monotouch-samples,sakthivelnagarajan/monotouch-samples,iFreedive/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,andypaul/monotouch-samples,kingyond/monotouch-samples,kingyond/monotouch-samples,nervevau2/monotouch-samples,markradacz/monotouch-samples,peteryule/monotouch-samples,hongnguyenpro/monotouch-samples,nervevau2/monotouch-samples,markradacz/monotouch-samples,nelzomal/monotouch-samples,kingyond/monotouch-samples,nelzomal/monotouch-samples,labdogg1003/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,a9upam/monotouch-samples,markradacz/monotouch-samples,peteryule/monotouch-samples,xamarin/monotouch-samples,sakthivelnagarajan/monotouch-samples,iFreedive/monotouch-samples,davidrynn/monotouch-samples,robinlaide/monotouch-samples,hongnguyenpro/monotouch-samples,W3SS/monotouch-samples,a9upam/monotouch-samples,andypaul/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,labdogg1003/monotouch-samples,andypaul/monotouch-samples,andypaul/monotouch-samples
|
CoreAnimation/Screens/iPad/IDetailView.cs
|
CoreAnimation/Screens/iPad/IDetailView.cs
|
using System;
using MonoTouch.UIKit;
namespace Example_CoreAnimation.Screens.iPad
{
public interface IDetailView
{
event EventHandler ContentsButtonClicked;
}
}
|
using System;
using MonoTouch.UIKit;
namespace Example_CoreAnimation.Screens.iPad
{
public interface IDetailView
{
void AddContentsButton (UIBarButtonItem button);
void RemoveContentsButton ();
}
}
|
mit
|
C#
|
e74122be78d1f932f5c044cf39658aa3cbaf01cd
|
Fix - WIP
|
Red-Folder/WebCrawl-Functions
|
WebCrawlProcess/run.csx
|
WebCrawlProcess/run.csx
|
#r "Newtonsoft.Json"
using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;
public static void Run(string request, out object outputDocument, TraceWriter log)
{
log.Info($"Started");
try
{
var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);
log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");
}
catch (Exception ex)
{
log.Info($"Failed to get object - likely wrong format: {ex.Message}");
outputDocument = null;
return;
}
var azureLogger = new AzureLogger(log);
var crawler = new Crawler(crawlRequest, azureLogger);
crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml");
var crawlResult = crawler.Crawl();
outputDocument = crawlResult;
//outputDocument = new { id = Guid.NewGuid().ToString() };
log.Info($"Finished");
}
public class AzureLogger : ILogger
{
private TraceWriter _log;
public AzureLogger(TraceWriter log)
{
_log = log;
}
public void Info(string message)
{
_log.Info(message);
}
}
|
#r "Newtonsoft.Json"
using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;
public static void Run(string request, out object outputDocument, TraceWriter log)
{
log.Info($"Started");
try
{
var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);
log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");
}
catch (Exception ex)
{
log.Info($"Failed to get object - likely wrong format: {ex.Message}");
outputDocument = null;
return;
}
//var azureLogger = new AzureLogger(log);
//var crawler = new Crawler(crawlRequest, azureLogger);
//crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml");
//var crawlResult = crawler.Crawl();
log.Info($"Finished");
//outputDocument = crawlResult;
outputDocument = new { id = Guid.NewGuid().ToString() };
}
public class AzureLogger : ILogger
{
private TraceWriter _log;
public AzureLogger(TraceWriter log)
{
_log = log;
}
public void Info(string message)
{
_log.Info(message);
}
}
|
mit
|
C#
|
ac7f8baf33be900e24ec0960faca1ce29494376e
|
Send single sample of processor performance counter to the InfluxDB.Net.
|
poxet/influxdb-collector,poxet/Influx-Capacitor
|
InfluxDB.Net.Collector.Console/Program.cs
|
InfluxDB.Net.Collector.Console/Program.cs
|
using System;
using System.Diagnostics;
using InfluxDB.Net.Models;
namespace InfluxDB.Net.Collector.Console
{
static class Program
{
private static InfluxDb _client;
static void Main(string[] args)
{
if (args.Length != 3)
{
//url: http://128.199.43.107:8086
//username: root
//Password: ?????
throw new InvalidOperationException("Three parameters needs to be provided to this application. url, username and password for the InfluxDB database.");
}
var url = args[0];
var username = args[1];
var password = args[2];
_client = new InfluxDb(url, username, password);
var pong = _client.PingAsync().Result;
System.Console.WriteLine("Ping: {0} ({1} ms)", pong.Status, pong.ResponseTime);
var version = _client.VersionAsync().Result;
System.Console.WriteLine("Version: {0}", version);
var processorCounter = GetPerformanceCounter();
System.Threading.Thread.Sleep(100);
var result = RegisterCounterValue(processorCounter);
System.Console.WriteLine(result.StatusCode);
System.Console.WriteLine("Press enter to exit...");
System.Console.ReadKey();
}
private static InfluxDbApiResponse RegisterCounterValue(PerformanceCounter processorCounter)
{
var data = processorCounter.NextValue();
System.Console.WriteLine("Processor value: {0}%", data);
var serie = new Serie.Builder("Processor")
.Columns("Total")
.Values(data)
.Build();
var result = _client.WriteAsync("QTest", TimeUnit.Milliseconds, serie);
return result.Result;
}
private static PerformanceCounter GetPerformanceCounter()
{
var processorCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
processorCounter.NextValue();
return processorCounter;
}
}
}
|
using System;
namespace InfluxDB.Net.Collector.Console
{
static class Program
{
private static InfluxDb _client;
static void Main(string[] args)
{
if (args.Length != 3)
{
//url: http://128.199.43.107:8086
//username: root
//Password: ?????
throw new InvalidOperationException("Three parameters needs to be provided to this application. url, username and password for the InfluxDB database.");
}
var url = args[0];
var username = args[1];
var password = args[2];
_client = new InfluxDb(url, username, password);
var pong = _client.PingAsync().Result;
System.Console.WriteLine("Ping: {0} ({1} ms)", pong.Status, pong.ResponseTime);
var version = _client.VersionAsync().Result;
System.Console.WriteLine("Version: {0}", version);
System.Console.WriteLine("Press any key to exit...");
System.Console.ReadKey();
}
}
}
|
mit
|
C#
|
bde0a82a85a8e9844e3296a6332c8768581a1f51
|
remove assertions that doesn't agree with Mono's ordering impl of Hashtable
|
mono/ServiceStack.Text,NServiceKit/NServiceKit.Text,gerryhigh/ServiceStack.Text,NServiceKit/NServiceKit.Text,mono/ServiceStack.Text,gerryhigh/ServiceStack.Text
|
tests/ServiceStack.Text.Tests/SpecialTypesTests.cs
|
tests/ServiceStack.Text.Tests/SpecialTypesTests.cs
|
using System;
using System.Collections;
using NUnit.Framework;
namespace ServiceStack.Text.Tests
{
[TestFixture]
public class SpecialTypesTests
: TestBase
{
[Test]
public void Can_Serialize_Version()
{
Serialize(new Version());
Serialize(Environment.Version);
}
public class JsonEntityWithPrivateGetter
{
public string Name { private get; set; }
}
public class JsonEntityWithNoProperties
{
}
[Test]
public void Can_Serialize_Type_with_no_public_getters()
{
Serialize(new JsonEntityWithPrivateGetter { Name = "Daniel" });
}
[Test]
public void Can_Serialize_Type_with_no_public_properties()
{
Serialize(new JsonEntityWithNoProperties());
}
[Test]
public void Can_Serialize_Type_with_ByteArray()
{
var test = new { Name = "Test", Data = new byte[] { 1, 2, 3, 4, 5 } };
var json = JsonSerializer.SerializeToString(test);
Assert.That(json, Is.EquivalentTo("{\"Name\":\"Test\",\"Data\":\"AQIDBAU=\"}"));
}
[Test]
public void Can_Serialize_ByteArray()
{
var test = new byte[] { 1, 2, 3, 4, 5 };
var json = JsonSerializer.SerializeToString(test);
var fromJson = JsonSerializer.DeserializeFromString<byte[]>(json);
Assert.That(test, Is.EquivalentTo(fromJson));
}
[Test]
public void Can_Serialize_HashTable()
{
var h = new Hashtable { { "A", 1 }, { "B", 2 } };
var fromJson = h.ToJson().FromJson<Hashtable>();
Assert.That(fromJson.Count, Is.EqualTo(h.Count));
Assert.That(fromJson["A"].ToString(), Is.EqualTo(h["A"].ToString()));
Assert.That(fromJson["B"].ToString(), Is.EqualTo(h["B"].ToString()));
}
}
}
|
using System;
using System.Collections;
using NUnit.Framework;
namespace ServiceStack.Text.Tests
{
[TestFixture]
public class SpecialTypesTests
: TestBase
{
[Test]
public void Can_Serialize_Version()
{
Serialize(new Version());
Serialize(Environment.Version);
}
public class JsonEntityWithPrivateGetter
{
public string Name { private get; set; }
}
public class JsonEntityWithNoProperties
{
}
[Test]
public void Can_Serialize_Type_with_no_public_getters()
{
Serialize(new JsonEntityWithPrivateGetter { Name = "Daniel" });
}
[Test]
public void Can_Serialize_Type_with_no_public_properties()
{
Serialize(new JsonEntityWithNoProperties());
}
[Test]
public void Can_Serialize_Type_with_ByteArray()
{
var test = new { Name = "Test", Data = new byte[] { 1, 2, 3, 4, 5 } };
var json = JsonSerializer.SerializeToString(test);
Assert.That(json, Is.EquivalentTo("{\"Name\":\"Test\",\"Data\":\"AQIDBAU=\"}"));
}
[Test]
public void Can_Serialize_ByteArray()
{
var test = new byte[] { 1, 2, 3, 4, 5 };
var json = JsonSerializer.SerializeToString(test);
var fromJson = JsonSerializer.DeserializeFromString<byte[]>(json);
Assert.That(test, Is.EquivalentTo(fromJson));
}
[Test]
public void Can_Serialize_HashTable()
{
var h = new Hashtable { { "A", 1 }, { "B", 2 } };
Assert.That(h.ToJson(), Is.EqualTo("{\"A\":1,\"B\":2}"));
Assert.That(JsonSerializer.SerializeToString(h, typeof(Hashtable)), Is.EqualTo("{\"A\":1,\"B\":2}"));
var fromJson = h.ToJson().FromJson<Hashtable>();
Assert.That(fromJson.Count, Is.EqualTo(h.Count));
Assert.That(fromJson["A"].ToString(), Is.EqualTo(h["A"].ToString()));
Assert.That(fromJson["B"].ToString(), Is.EqualTo(h["B"].ToString()));
}
}
}
|
bsd-3-clause
|
C#
|
6506708d87e492811204b7f7bba8a1edaf1023f1
|
fix migratorcontroller
|
GeertBellekens/Enterprise-Architect-Toolpack,GeertBellekens/Enterprise-Architect-Toolpack,GeertBellekens/Enterprise-Architect-Toolpack
|
MagicdrawMigrator/MDMigratorController.cs
|
MagicdrawMigrator/MDMigratorController.cs
|
using System.Collections.Generic;
using System.Linq;
using System;
using EAAddinFramework.Utilities;
using TSF_EA = TSF.UmlToolingFramework.Wrappers.EA;
using UML = TSF.UmlToolingFramework.UML;
using System.Windows.Forms;
namespace MagicdrawMigrator
{
/// <summary>
/// Description of MDMigratorController.
/// </summary>
public class MDMigratorController
{
List<MagicDrawCorrector> correctors {get;set;}
TSF_EA.Model model {get;set;}
public MDMigratorController()
{
correctors = new List<MagicDrawCorrector>();
model = new TSF_EA.Model();
}
public void startCorrections(string mdzipPath)
{
//create correctors
createCorrectors(mdzipPath);
//clear the log
EAOutputLogger.clearLog(this.model, correctors[0].outputName);
//start correcting
foreach (var corrector in this.correctors)
{
corrector.correct();
}
}
public void createCorrectors(string mdzipPath)
{
var mdPackage = getMagicDrawPackage();
var magicDrawReader = new MagicDrawReader(mdzipPath,this.model);
if (mdPackage !=null)
{
correctors.Add(new OCLConstraintsCorrector(magicDrawReader,model,mdPackage));
correctors.Add(new AssociationTableCorrector(magicDrawReader,model,mdPackage));
correctors.Add(new FixCallBehaviorActionCorrector(magicDrawReader,model,mdPackage));
correctors.Add(new ConvertPropertiesToAttributes(magicDrawReader,model,mdPackage));
correctors.Add(new SetStructureCorrector(magicDrawReader,model, mdPackage));
correctors.Add(new SetStatesOnObjects(magicDrawReader,model, mdPackage));
correctors.Add(new DiagramLayoutCorrector(magicDrawReader,model, mdPackage));
correctors.Add(new AddClassifiersToPartitions(magicDrawReader,model, mdPackage));
}
}
public TSF_EA.Package getMagicDrawPackage()
{
MessageBox.Show("Please select the package containing the imported Magicdraw Model","Select Magicdraw Import Package");
return this.model.getUserSelectedPackage() as TSF_EA.Package;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System;
using EAAddinFramework.Utilities;
using TSF_EA = TSF.UmlToolingFramework.Wrappers.EA;
using UML = TSF.UmlToolingFramework.UML;
using System.Windows.Forms;
namespace MagicdrawMigrator
{
/// <summary>
/// Description of MDMigratorController.
/// </summary>
public class MDMigratorController
{
List<MagicDrawCorrector> correctors {get;set;}
TSF_EA.Model model {get;set;}
public MDMigratorController()
{
correctors = new List<MagicDrawCorrector>();
model = new TSF_EA.Model();
}
public void startCorrections(string mdzipPath)
{
//create correctors
createCorrectors(mdzipPath);
//clear the log
EAOutputLogger.clearLog(this.model, correctors[0].outputName);
//start correcting
foreach (var corrector in this.correctors)
{
corrector.correct();
}
}
public void createCorrectors(string mdzipPath)
{
var mdPackage = getMagicDrawPackage();
var magicDrawReader = new MagicDrawReader(mdzipPath,this.model);
if (mdPackage !=null)
{
correctors.Add(new OCLConstraintsCorrector(magicDrawReader,model,mdPackage));
correctors.Add(new AssociationTableCorrector(magicDrawReader,model,mdPackage));
correctors.Add(new FixCallBehaviorActionCorrector(magicDrawReader,model,mdPackage));
correctors.Add(new ConvertPropertiesToAttributes(magicDrawReader,model,mdPackage));
correctors.Add(new SetStructureCorrector(magicDrawReader,model, mdPackage));
correctors.Add(new SetStatesOnObjects(magicDrawReader,model, mdPackage));
correctors.Add(new DiagramLayoutCorrector(magicDrawReader,model, mdPackage));
correctors.Add(new AddClassifiersToPartitions(magicDrawReader,model, mdPackage));
correctors.Add(new CorrectStereotypes(magicDrawReader,model, mdPackage));
correctors.Add(new CorrectTaggedValues(magicDrawReader,model, mdPackage));
}
}
public TSF_EA.Package getMagicDrawPackage()
{
MessageBox.Show("Please select the package containing the imported Magicdraw Model","Select Magicdraw Import Package");
return this.model.getUserSelectedPackage() as TSF_EA.Package;
}
}
}
|
bsd-2-clause
|
C#
|
216b1508577bdb46115197150160f1ee1de41c7f
|
Add comment about PKCS#1/same as MSAL
|
AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet
|
src/ADAL.PCL.CoreCLR/CryptographyHelper.cs
|
src/ADAL.PCL.CoreCLR/CryptographyHelper.cs
|
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
internal class CryptographyHelper : ICryptographyHelper
{
public string CreateSha256Hash(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return null;
}
using (var sha256 = SHA256.Create())
{
var inputBytes = Encoding.UTF8.GetBytes(input);
var outputBytes = sha256.ComputeHash(inputBytes);
return Convert.ToBase64String(outputBytes);
}
}
public byte[] SignWithCertificate(string message, X509Certificate2 certificate)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (certificate == null)
{
throw new ArgumentNullException(nameof(certificate));
}
var privateKey = certificate.GetRSAPrivateKey();
var messageBytes = Encoding.UTF8.GetBytes(message);
// Using PKCS#1 padding scheme – same as in MSAL:
// https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/7fe94109/src/Microsoft.Identity.Client/Platforms/netstandard1.3/CryptographyHelper.cs#L68
return privateKey.SignData(messageBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
}
}
|
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
internal class CryptographyHelper : ICryptographyHelper
{
public string CreateSha256Hash(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return null;
}
using (var sha256 = SHA256.Create())
{
var inputBytes = Encoding.UTF8.GetBytes(input);
var outputBytes = sha256.ComputeHash(inputBytes);
return Convert.ToBase64String(outputBytes);
}
}
public byte[] SignWithCertificate(string message, X509Certificate2 certificate)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (certificate == null)
{
throw new ArgumentNullException(nameof(certificate));
}
var privateKey = certificate.GetRSAPrivateKey();
var messageBytes = Encoding.UTF8.GetBytes(message);
return privateKey.SignData(messageBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
}
}
|
mit
|
C#
|
34454c45252870be04d6e646b68488ea3ce1a6d0
|
Change Lib.cs to use async/await
|
cartermp/dnx-apps
|
libs/lib1/Lib.cs
|
libs/lib1/Lib.cs
|
using System;
#if NET40
using System.Net;
#else
// Generic collections are just a part of
using System.Net.Http;
//using System.Threading.Tasks;
#endif
using System.Text.RegularExpressions;
namespace Lib
{
public class Foo
{
#if NET40
private readonly WebClient _client = new WebClient();
#else
private readonly HttpClient _client = new HttpClient();
#endif
#if NET40
public string GetDotNetCount()
{
string url = "http://www.dotnetfoundation.org/";
var uri = new Uri(url);
var result = _client.DownloadString(uri);
int dotNetCount = Regex.Matches(result, ".NET").Count;
return $"Dotnet Foundation mentions .NET {dotNetCount} times!";
}
#else
public string GetDotNetCountAsync()
{
string url = "http://www.dotnetfoundation.org/";
var result = await _client.GetStringAsync(url);
int dotNetCount = Regex.Matches(result, ".NET").Count;
return $"Dotnet Foundation mentions .NET {dotNetCount} times!";
}
#endif
}
}
|
using System;
#if NET40
using System.Net;
#else
// Generic collections are just a part of
using System.Net.Http;
#endif
using System.Text.RegularExpressions;
namespace Lib
{
public class Foo
{
#if NET40
private readonly WebClient _client = new WebClient();
#else
private readonly HttpClient _client = new HttpClient();
#endif
public string Whee()
{
string url = "http://www.dotnetfoundation.org/";
#if NET40
var uri = new Uri(url);
var result = _client.DownloadString(uri);
#else
var result = _client.GetStringAsync(url).Result;
#endif
int dotNetCount = Regex.Matches(result, ".NET").Count;
return $"Dotnet Foundation mentions .NET {dotNetCount} times!";
}
}
}
|
mit
|
C#
|
c70e5b62cc3785cf0cca3db9055a3bf637f4618c
|
Bump version to 0.1
|
Lochnair/MCServer-World-Converter
|
MCServer-World-Converter/Properties/AssemblyInfo.cs
|
MCServer-World-Converter/Properties/AssemblyInfo.cs
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Nils Andreas Svee
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.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("MCServer World Converter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MCServer-World-Converter")]
[assembly: AssemblyCopyright("Copyright © 2015 Nils Andreas Svee")]
[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("ddc0ecc5-1d1f-4a1e-aca0-ae490b13b08a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Nils Andreas Svee
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.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("MCServer World Converter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MCServer-World-Converter")]
[assembly: AssemblyCopyright("Copyright © 2015 Nils Andreas Svee")]
[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("ddc0ecc5-1d1f-4a1e-aca0-ae490b13b08a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
ae1126013b026d2c7bb17bb4165a12f6ff93ac0c
|
Improve link.
|
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
|
MitternachtWeb/Areas/Guild/Views/Warns/Index.cshtml
|
MitternachtWeb/Areas/Guild/Views/Warns/Index.cshtml
|
@model IEnumerable<Warn>
<h4>Warns</h4>
<hr />
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Reason)
</th>
<th>
@Html.DisplayNameFor(model => model.Forgiven)
</th>
<th>
@Html.DisplayNameFor(model => model.WarnedAt)
</th>
<th>
@Html.DisplayNameFor(model => model.WarnedBy)
</th>
</tr>
</thead>
<tbody>
@foreach(var warn in Model) {
<tr>
<td>
@if(!string.IsNullOrWhiteSpace(warn.AvatarUrl)) {
<img class="discord-avatar" src="@warn.AvatarUrl" alt="Avatar" />
}
</td>
<td>
<a asp-area="User" asp-controller="Warns" asp-action="Index" asp-route-userId="@warn.UserId">
@warn.Username
</a>
</td>
<td>
@Html.DisplayFor(modelItem => warn.Reason)
</td>
<td>
@{
var forgivenString = warn.Forgiven ? Html.Raw("✅") : Html.Raw("❌");
}
@if(ViewBag.PermissionForgiveWarns) {
<a asp-area="Guild" asp-controller="Warns" asp-action="ToggleForgive" asp-route-guildId="@ViewBag.GuildId" asp-route-id="@warn.Id">@forgivenString</a>
} else {
@forgivenString
}
</td>
<td>
@Html.DisplayFor(modelItem => warn.WarnedAtString)
</td>
<td>
@Html.DisplayFor(modelItem => warn.WarnedBy)
</td>
</tr>
}
</tbody>
</table>
</div>
|
@model IEnumerable<Warn>
<h4>Warns</h4>
<hr />
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Reason)
</th>
<th>
@Html.DisplayNameFor(model => model.Forgiven)
</th>
<th>
@Html.DisplayNameFor(model => model.WarnedAt)
</th>
<th>
@Html.DisplayNameFor(model => model.WarnedBy)
</th>
</tr>
</thead>
<tbody>
@foreach(var warn in Model) {
<tr>
<td>
@if(!string.IsNullOrWhiteSpace(warn.AvatarUrl)) {
<img class="discord-avatar" src="@warn.AvatarUrl" alt="Avatar" />
}
</td>
<td>
<a asp-area="User" asp-controller="Overview" asp-action="Index" asp-route-userId="@warn.UserId">
@warn.Username
</a>
</td>
<td>
@Html.DisplayFor(modelItem => warn.Reason)
</td>
<td>
@{
var forgivenString = warn.Forgiven ? Html.Raw("✅") : Html.Raw("❌");
}
@if(ViewBag.PermissionForgiveWarns) {
<a asp-area="Guild" asp-controller="Warns" asp-action="ToggleForgive" asp-route-guildId="@ViewBag.GuildId" asp-route-id="@warn.Id">@forgivenString</a>
} else {
@forgivenString
}
</td>
<td>
@Html.DisplayFor(modelItem => warn.WarnedAtString)
</td>
<td>
@Html.DisplayFor(modelItem => warn.WarnedBy)
</td>
</tr>
}
</tbody>
</table>
</div>
|
mit
|
C#
|
f923b9dbc2304a37f6f6cdb9afe16e38b6cb3ba0
|
Remove unecessary return marshalling
|
Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
|
src/Tgstation.Server.Host/NativeMethods.cs
|
src/Tgstation.Server.Host/NativeMethods.cs
|
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Tgstation.Server.Host
{
/// <summary>
/// Native methods used by the code
/// </summary>
static class NativeMethods
{
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowthreadprocessid
/// </summary>
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-findwindoww
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage
/// </summary>
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/ms633493(v=VS.85).aspx
/// </summary>
public delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-enumchildwindows
/// </summary>
[DllImport("user32")]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextw
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
/// </summary>
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createsymboliclinkw
/// </summary>
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Tgstation.Server.Host
{
/// <summary>
/// Native methods used by the code
/// </summary>
static class NativeMethods
{
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowthreadprocessid
/// </summary>
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-findwindoww
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage
/// </summary>
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/ms633493(v=VS.85).aspx
/// </summary>
public delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-enumchildwindows
/// </summary>
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextw
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
/// <summary>
/// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
/// </summary>
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
/// <summary>
/// See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createsymboliclinkw
/// </summary>
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
}
}
|
agpl-3.0
|
C#
|
c011c3cb333a70f9185fb5dab6514ff310cb2434
|
Update Program.cs
|
natintosh/Numerical-Methods
|
NumericalMethods/GuassSeidel/GuassSeidel/Program.cs
|
NumericalMethods/GuassSeidel/GuassSeidel/Program.cs
|
using System;
namespace GuassSeidel
{
class LinearAlgebraicEquation: NumericalMethods
{
public static void Main()
{
Double[,] linearEquation = new Double[,]{
{ 25, 5, 1, 106.8 },
{ 64, 8, 1, 177.2 },
{ 144, 12, 1, 292.2 } };
Double[][] matrix = new Double[][]{
new Double[] { 25, 5, 1, 106.8 },
new Double[] { 64, 8, 1, 177.2 },
new Double[] { 144, 12, 1, 292.2 }
};
DisplayMatrix(linearEquation);
Double[] bee = { 106.8, 177.2, 292.2 };
Double[] guess = { 1, 1, 1 };
Console.WriteLine("Enter the initial guess");
for (int i = 0; i < bee.Length; i++)
{
Console.Write(" A{0}: ", i + 1);
guess[i] = Convert.ToDouble(Console.ReadLine());
}
GuassSeidel guass = new GuassSeidel(matrix, bee, guess);
}
}
}
|
using System;
namespace GuassSeidel
{
class LinearAlgebraicEquation: NumericalMethods
{
public static void Main()
{
Double[,] linearEquation = new Double[,]{
{ 25, 5, 1, 106.8 },
{ 64, 8, 1, 177.2 },
{ 144, 12, 1, 292.2 } }
;
Double[][] matrix = new Double[][]{
new Double[] { 25, 5, 1, 106.8 },
new Double[] { 64, 8, 1, 177.2 },
new Double[] { 144, 12, 1, 292.2 }
};
DisplayMatrix(linearEquation);
Double[] bee = { 106.8, 177.2, 292.2 };
Double[] guess = { 1, 1, 1 };
Console.WriteLine("Enter the initial guess");
for (int i = 0; i < bee.Length; i++)
{
Console.Write(" A{0}: ", i + 1);
guess[i] = Convert.ToDouble(Console.ReadLine());
}
GuassSeidel guass = new GuassSeidel(matrix, bee, guess);
}
}
}
|
mit
|
C#
|
5eb248b8b26822a88cfd69b4ed471d2072543562
|
increment patch version,
|
jwChung/Experimentalism,jwChung/Experimentalism
|
build/CommonAssemblyInfo.cs
|
build/CommonAssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.15.4")]
[assembly: AssemblyInformationalVersion("0.15.4")]
/*
* Version 0.15.4
*
* - [FIX] Fixes excluding interfaces from verifying
* `ConstructingMemberAssertion` and `GuardClauseAssertion`.
*/
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.15.3")]
[assembly: AssemblyInformationalVersion("0.15.3")]
/*
* Version 0.15.4
*
* - [FIX] Fixes excluding interfaces from verifying
* `ConstructingMemberAssertion` and `GuardClauseAssertion`.
*/
|
mit
|
C#
|
6c7e913f03abaa02c4a7122c05bbc073413f691f
|
Remove Rigidbody from Tower
|
emazzotta/unity-tower-defense
|
Assets/Scripts/GameController.cs
|
Assets/Scripts/GameController.cs
|
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject towerBase;
public GameObject gameField;
private GameObject[,] towerBases;
private int gameFieldWidth = 0;
private int gameFieldHeight = 0;
void Start () {
this.gameFieldWidth = (int)(gameField.transform.localScale.x);
this.gameFieldHeight = (int)(gameField.transform.localScale.z);
this.towerBases = new GameObject[this.gameFieldWidth, this.gameFieldHeight];
this.initGamePlatform ();
}
void initGamePlatform() {
for (int x = 0; x < this.gameFieldWidth; x++) {
for (int z = 0; z < this.gameFieldHeight; z++) {
GameObject newTowerBase = Instantiate (towerBase);
newTowerBase.transform.position = new Vector3 (towerBase.transform.position.x+x, 0.1f, towerBase.transform.position.z-z);
this.towerBases [x, z] = newTowerBase;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject towerBase;
public GameObject gameField;
private GameObject[,] towerBases;
private int gameFieldWidth = 0;
private int gameFieldHeight = 0;
void Start () {
this.gameFieldWidth = (int)(gameField.transform.localScale.x);
this.gameFieldHeight = (int)(gameField.transform.localScale.z);
this.towerBases = new GameObject[this.gameFieldWidth, this.gameFieldHeight];
this.initGamePlatform ();
}
void initGamePlatform() {
for (int x = 0; x < this.gameFieldWidth; x++) {
for (int z = 0; z < this.gameFieldHeight; z++) {
GameObject newTowerBase = Instantiate (towerBase);
newTowerBase.AddComponent<Rigidbody> ();
newTowerBase.transform.position = new Vector3 (towerBase.transform.position.x+x, 0.1f, towerBase.transform.position.z-z);
this.towerBases [x, z] = newTowerBase;
}
}
}
}
|
mit
|
C#
|
ac42e2d6fe8c1b9a8080fe13cd055e6607dd1faa
|
add beter comment
|
ilovepi/Compiler,ilovepi/Compiler
|
compiler/frontend/Parser.cs
|
compiler/frontend/Parser.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using compiler.frontend;
namespace compiler.frontend
{
class Parser
{
public Token t;
public Lexer s;
string filename;
public void getExpected(Token expected)
{
if (t == expected)
{
next();
}
else {error();
}
}
public void error(string str)
{
//TODO: determine location in file for error messages
Console.WriteLine ("Error Parsing file: " + filename + ", " + str);
error_fatal();
}
public void error_fatal(){
//TODO: determine location in file
throw new Exception("Fatal Error Parsing file: " + filename + ". Unable to continue";
}
public void next() {
t = s.getNextToken();
}
public void Designator() {
getExpected(Token.IDENTIFIER);
getExpected(Token.OPEN_BRACKET);
Expression();
getExpected(Token.CLOSE_BRACKET);
}
public void Factor(){
if ((t == Token.IDENTIFIER) || (t == Token.IDENTIFIER))
{
next();
}
else error();
}
public void Term(){
}
public void Expression(){
}
public void Relation(){
}
public void Assign()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using compiler.frontend;
namespace compiler.frontend
{
class Parser
{
public Token t;
public Lexer s;
string filename;
public void getExpected(Token expected)
{
if (t == expected)
{
next();
}
else {error();
}
}
public void error(string str)
{
//TODO: determine location in file
Console.WriteLine ("Error Parsing file: " + filename + ", " + str);
error_fatal();
}
public void error_fatal(){
//TODO: determine location in file
throw new Exception("Fatal Error Parsing file: " + filename + ". Unable to continue";
}
public void next() {
t = s.getNextToken();
}
public void Designator() {
getExpected(Token.IDENTIFIER);
getExpected(Token.OPEN_BRACKET);
Expression();
getExpected(Token.CLOSE_BRACKET);
}
public void Factor(){
if ((t == Token.IDENTIFIER) || (t == Token.IDENTIFIER))
{
next();
}
else error();
}
public void Term(){
}
public void Expression(){
}
public void Relation(){
}
public void Assign()
{
}
}
}
|
mit
|
C#
|
fc5536f70cab90ea6d4dec805e8ac937668d53c3
|
Convert Pull to NDesk.Options.
|
hazzik/git-tfs,steveandpeggyb/Public,modulexcite/git-tfs,adbre/git-tfs,hazzik/git-tfs,hazzik/git-tfs,spraints/git-tfs,andyrooger/git-tfs,steveandpeggyb/Public,TheoAndersen/git-tfs,git-tfs/git-tfs,timotei/git-tfs,allansson/git-tfs,modulexcite/git-tfs,allansson/git-tfs,codemerlin/git-tfs,allansson/git-tfs,jeremy-sylvis-tmg/git-tfs,timotei/git-tfs,adbre/git-tfs,bleissem/git-tfs,guyboltonking/git-tfs,TheoAndersen/git-tfs,steveandpeggyb/Public,WolfVR/git-tfs,hazzik/git-tfs,TheoAndersen/git-tfs,jeremy-sylvis-tmg/git-tfs,codemerlin/git-tfs,adbre/git-tfs,pmiossec/git-tfs,codemerlin/git-tfs,guyboltonking/git-tfs,bleissem/git-tfs,vzabavnov/git-tfs,NathanLBCooper/git-tfs,irontoby/git-tfs,spraints/git-tfs,kgybels/git-tfs,WolfVR/git-tfs,irontoby/git-tfs,irontoby/git-tfs,spraints/git-tfs,guyboltonking/git-tfs,TheoAndersen/git-tfs,modulexcite/git-tfs,NathanLBCooper/git-tfs,NathanLBCooper/git-tfs,kgybels/git-tfs,PKRoma/git-tfs,WolfVR/git-tfs,bleissem/git-tfs,allansson/git-tfs,timotei/git-tfs,jeremy-sylvis-tmg/git-tfs,kgybels/git-tfs
|
GitTfs/Commands/Pull.cs
|
GitTfs/Commands/Pull.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using NDesk.Options;
using Sep.Git.Tfs.Core;
using StructureMap;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("pull")]
[Description("pull [options]")]
[RequiresValidGitRepository]
public class Pull : GitTfsCommand
{
#region GitTfsCommand Members
private readonly Fetch fetch;
private readonly Globals globals;
public OptionSet OptionSet
{
get { return fetch.OptionSet; }
}
public IEnumerable<CommandLine.OptParse.IOptionResults> ExtraOptions
{
get { return this.MakeNestedOptionResults(fetch); }
}
public Pull(Globals globals, Fetch fetch)
{
this.fetch = fetch;
this.globals = globals;
}
public int Run()
{
return Run(globals.RemoteId);
}
public int Run(string remoteId)
{
var retVal = fetch.Run(remoteId);
if (retVal == 0)
{
var remote = globals.Repository.ReadTfsRemote(remoteId);
globals.Repository.CommandNoisy("merge", remote.RemoteRef);
}
return retVal;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using NDesk.Options;
using CommandLine.OptParse;
using Sep.Git.Tfs.Core;
using StructureMap;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("pull")]
[Description("pull [options]")]
[RequiresValidGitRepository]
public class Pull : GitTfsCommand
{
#region GitTfsCommand Members
private readonly Fetch fetch;
private readonly Globals globals;
public OptionSet OptionSet
{
get { return new OptionSet(); }
}
public IEnumerable<IOptionResults> ExtraOptions
{
get { return this.MakeNestedOptionResults(fetch); }
}
public Pull(Globals globals, Fetch fetch)
{
this.fetch = fetch;
this.globals = globals;
}
public int Run()
{
return Run(globals.RemoteId);
}
public int Run(string remoteId)
{
var retVal = fetch.Run(remoteId);
if (retVal == 0)
{
var remote = globals.Repository.ReadTfsRemote(remoteId);
globals.Repository.CommandNoisy("merge", remote.RemoteRef);
}
return retVal;
}
#endregion
}
}
|
apache-2.0
|
C#
|
e55f427817773caff2a0eb05abe68f9c8e6c93db
|
Update problem004.cs
|
mvdiener/project_euler,mvdiener/project_euler
|
CSharp/problem004.cs
|
CSharp/problem004.cs
|
//A palindromic number reads the same both ways.The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
//Find the largest palindrome made from the product of two 3-digit numbers.
using System;
using System.Linq;
namespace Problem004
{
class MainClass
{
public static void Main()
{
Console.WriteLine(GetPalindromes());
}
public static int GetPalindromes()
{
int product = 0;
int largest = 0;
for (int i = 999; i > 100; i--)
{
for (int j = 999; j > 100; j--)
{
product = i * j;
if (product < largest) break;
if (isPalindrome(product))
{
if (product > largest) largest = product;
break;
}
}
}
return largest;
}
private static bool isPalindrome(int num)
{
return num.ToString() == new string(num.ToString().ToCharArray().Reverse().ToArray());
}
}
}
|
//A palindromic number reads the same both ways.The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
//Find the largest palindrome made from the product of two 3-digit numbers.
using System;
using System.Linq;
namespace Problem004
{
class MainClass
{
public static void Main()
{
Console.WriteLine(GetPalindromes());
}
public static int GetPalindromes()
{
int product = 0;
int largest = 0;
for (int i = 999; i > 100; i--)
{
for (int j = 999; j > 100; j--)
{
product = i * j;
if (product < largest) break;
if (product.ToString() == new string(product.ToString().ToCharArray().Reverse().ToArray()))
{
if (product > largest) largest = product;
break;
}
}
}
return largest;
}
}
}
|
mit
|
C#
|
70d8fe2b0e2f2442f20d4558f21686ed26e85ee4
|
Build and publish Rock.Logging nuget package
|
RockFramework/Rock.Logging
|
Rock.Logging/Properties/AssemblyInfo.cs
|
Rock.Logging/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Rock.Logging")]
[assembly: AssemblyDescription("Rock logger.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Logging")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 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("71736a4b-21bc-46f3-9bb7-f9c9a260f723")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.5")]
[assembly: AssemblyInformationalVersion("0.9.5")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Rock.Logging")]
[assembly: AssemblyDescription("Rock logger.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Logging")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 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("71736a4b-21bc-46f3-9bb7-f9c9a260f723")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.4")]
[assembly: AssemblyInformationalVersion("0.9.4")]
|
mit
|
C#
|
415c2d99c1eea99e975cb640d082af8de57fa5f5
|
Align with online sample
|
Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode
|
CSharp7/CSharp7/7.1/2.DefaultExpressions.cs
|
CSharp7/CSharp7/7.1/2.DefaultExpressions.cs
|
using System.Linq;
using static System.Console;
namespace CSharp7
{
public sealed class DefaultExpressions
{
public DefaultExpressions()
{
int? DoSomeWorkAndGetResult(int a = default, string s = default)
{
if (s == default && s is default)
{
return default;
}
switch(a)
{
case (default): break;
default: break;
}
int? result = default;
var array = new[] { default, a, s.Length };
if (array.Sum() > 0)
{
result = array.Sum();
}
return result;
}
WriteLine(DoSomeWorkAndGetResult(default, string.Empty));
}
}
}
|
using System.Linq;
using static System.Console;
namespace CSharp7
{
public sealed class DefaultExpressions
{
public DefaultExpressions()
{
int? DoSomeWorkAndGetResult(int a = default, string s = default)
{
if (s == default || s is default)
{
return default;
}
switch(a)
{
case (default): break;
default: break;
}
int? result = default;
var array = new[] { default, a, s.Length };
if (array.Sum() > 0)
{
result = array.Sum();
}
return result;
}
WriteLine(DoSomeWorkAndGetResult(default, string.Empty));
}
}
}
|
mit
|
C#
|
060c74c3cc73dcb56f557242c871480b4d1f2bdc
|
use trygetvalue instead of checking Contains
|
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
|
TCC.Core/Data/Databases/DatabaseBase.cs
|
TCC.Core/Data/Databases/DatabaseBase.cs
|
using System.IO;
using FoglioUtils;
namespace TCC.Data.Databases
{
public abstract class DatabaseBase
{
protected string Language;
protected abstract string FolderName { get; }
protected abstract string Extension { get; }
public string RelativePath => $"{FolderName}/{FolderName}-{Language}.{Extension}";
protected string FullPath => Path.Combine(App.DataPath, RelativePath);
public virtual bool Exists => File.Exists(FullPath);
public bool IsUpToDate => outdatedCount == 0 && Exists;
protected int outdatedCount;
public abstract void Load();
public virtual void CheckVersion(string customAbsPath = null, string customRelPath = null)
{
if (!Exists) return;
var localHash = HashUtils.GenerateFileHash(customAbsPath ?? FullPath);
if (UpdateManager.DatabaseHashes.Count == 0) return;
if (!UpdateManager.DatabaseHashes.TryGetValue(customRelPath ?? RelativePath, out var remoteHash)) return;
if (remoteHash == localHash) return;
Log.CW($"Hash mismatch for {customRelPath ?? RelativePath}");
outdatedCount++;
}
public DatabaseBase(string lang)
{
Language = lang;
}
public virtual void Update(string custom = null)
{
UpdateManager.UpdateDatabase(custom ?? RelativePath);
}
}
}
|
using System.IO;
using FoglioUtils;
namespace TCC.Data.Databases
{
public abstract class DatabaseBase
{
protected string Language;
protected abstract string FolderName { get; }
protected abstract string Extension { get; }
public string RelativePath => $"{FolderName}/{FolderName}-{Language}.{Extension}";
protected string FullPath => Path.Combine(App.DataPath, RelativePath);
public virtual bool Exists => File.Exists(FullPath);
public bool IsUpToDate => outdatedCount == 0 && Exists;
protected int outdatedCount;
public abstract void Load();
public virtual void CheckVersion(string customAbsPath = null, string customRelPath = null)
{
if (!Exists) return;
var localHash = HashUtils.GenerateFileHash(customAbsPath ?? FullPath);
if (UpdateManager.DatabaseHashes.Count == 0) return;
if (!UpdateManager.DatabaseHashes.ContainsKey(customRelPath ?? RelativePath)) return;
if (UpdateManager.DatabaseHashes[customRelPath ?? RelativePath] == localHash) return;
Log.CW($"Hash mismatch for {customRelPath ?? RelativePath}");
outdatedCount++;
}
public DatabaseBase(string lang)
{
Language = lang;
}
public virtual void Update(string custom = null)
{
UpdateManager.UpdateDatabase(custom ?? RelativePath);
}
}
}
|
mit
|
C#
|
a343d1977e19fbcb76e0065cdb5f63492f6f7473
|
Duplicate loop count arg check in NestedLoops
|
fsateler/MoreLINQ,smzinovyev/MoreLINQ,Agbar/MoreLINQ,Agbar/MoreLINQ,fsateler/MoreLINQ,morelinq/MoreLINQ,morelinq/MoreLINQ,ddpruitt/morelinq,ddpruitt/morelinq
|
MoreLinq/NestedLoops.cs
|
MoreLinq/NestedLoops.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace MoreLinq
{
public static partial class MoreEnumerable
{
// This extension methods were developed (primarily) to support the
// implementation of the Permutations() extension methods. However,
// it is of sufficient generality and usefulness to be elevated to
// public extension methods in its own right.
/// <summary>
/// Produces a sequence from an action based on the dynamic generation of N nested loops
/// who iteration counts are defined by <paramref name="loopCounts"/>.
/// </summary>
/// <param name="action">Action delegate for which to produce a nested loop sequence</param>
/// <param name="loopCounts">A sequence of loop repetition counts</param>
/// <returns>A sequence of Action representing the expansion of a set of nested loops</returns>
public static IEnumerable<Action> NestedLoops(this Action action, IEnumerable<int> loopCounts)
{
loopCounts.ThrowIfNull("loopCounts");
using (var iter = loopCounts.GetEnumerator())
{
var loopCount = NextLoopCount(iter);
if (loopCount == null)
return Enumerable.Empty<Action>(); // null loop
var loop = Enumerable.Repeat(action, loopCount.Value);
while ((loopCount = NextLoopCount(iter)) != null)
loop = loop.Repeat(loopCount.Value);
return loop;
}
}
private static int? NextLoopCount(IEnumerator<int> iter)
{
if (!iter.MoveNext())
return null;
if (iter.Current < 0)
throw new ArgumentException("All loop counts must be >= 0", "loopCounts");
return iter.Current;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace MoreLinq
{
public static partial class MoreEnumerable
{
// This extension methods were developed (primarily) to support the
// implementation of the Permutations() extension methods. However,
// it is of sufficient generality and usefulness to be elevated to
// public extension methods in its own right.
/// <summary>
/// Produces a sequence from an action based on the dynamic generation of N nested loops
/// who iteration counts are defined by <paramref name="loopCounts"/>.
/// </summary>
/// <param name="action">Action delegate for which to produce a nested loop sequence</param>
/// <param name="loopCounts">A sequence of loop repetition counts</param>
/// <returns>A sequence of Action representing the expansion of a set of nested loops</returns>
public static IEnumerable<Action> NestedLoops(this Action action, IEnumerable<int> loopCounts)
{
loopCounts.ThrowIfNull("loopCounts");
using (var iter = loopCounts.GetEnumerator())
{
if (!iter.MoveNext())
return Enumerable.Empty<Action>(); // null loop
if (iter.Current < 0)
throw new ArgumentException("All loop counts must be >= 0", "loopCounts");
var loop = Enumerable.Repeat(action, iter.Current);
while (iter.MoveNext())
{
if (iter.Current < 0)
throw new ArgumentException("All loop counts must be >= 0", "loopCounts");
loop = loop.Repeat(iter.Current);
}
return loop;
}
}
}
}
|
apache-2.0
|
C#
|
8921cdc9e16b4c5dc64d16079d5f17bc85f4c7a3
|
Reimplement WindowsGameWindow.SetIconFromStream using reflection
|
Tom94/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework
|
osu.Framework/Platform/Windows/WindowsGameWindow.cs
|
osu.Framework/Platform/Windows/WindowsGameWindow.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using osuTK.Input;
using System.Linq;
using System.Drawing;
using osu.Framework.Logging;
namespace osu.Framework.Platform.Windows
{
internal class WindowsGameWindow : DesktopGameWindow
{
private const int seticon_message = 0x0080;
private object smallIcon;
private object largeIcon;
protected override void OnKeyDown(object sender, KeyboardKeyEventArgs e)
{
if (e.Key == Key.F4 && e.Alt)
{
Implementation.Exit();
return;
}
base.OnKeyDown(sender, e);
}
public override void SetIconFromStream(Stream stream)
{
if (WindowInfo.Handle == IntPtr.Zero)
throw new InvalidOperationException("Window must be created before an icon can be set.");
var secondStream = new MemoryStream();
stream.CopyTo(secondStream);
stream.Position = 0;
secondStream.Position = 0;
try
{
// get the type info with reflection, since Icon won't be available to Xamarin
var drawingAssembly = typeof(Point).Assembly;
Type iconType = drawingAssembly.ExportedTypes.Single(x => x.Name == "Icon");
ConstructorInfo cons = iconType.GetConstructor(new Type[] { typeof(Stream), typeof(int), typeof(int) });
PropertyInfo handleProp = iconType.GetProperties().Single(x => x.Name == "Handle");
// create icons and get their handles
smallIcon = cons.Invoke(new object[] { stream, 24, 24 });
largeIcon = cons.Invoke(new object[] { secondStream, 256, 256 });
IntPtr smallIconHandle = (IntPtr)handleProp.GetValue(smallIcon);
IntPtr largeIconHandle = (IntPtr)handleProp.GetValue(largeIcon);
// pass the handles through to SendMessage
SendMessage(WindowInfo.Handle, seticon_message, (IntPtr)0, smallIconHandle);
SendMessage(WindowInfo.Handle, seticon_message, (IntPtr)1, largeIconHandle);
}
catch
{
Logger.Log("Failed to set window icon from Stream.", LoggingTarget.Runtime, LogLevel.Important);
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.IO;
using System.Runtime.InteropServices;
using osuTK.Input;
namespace osu.Framework.Platform.Windows
{
internal class WindowsGameWindow : DesktopGameWindow
{
private const int seticon_message = 0x0080;
// FIXME
//private Icon smallIcon;
//private Icon largeIcon;
protected override void OnKeyDown(object sender, KeyboardKeyEventArgs e)
{
if (e.Key == Key.F4 && e.Alt)
{
Implementation.Exit();
return;
}
base.OnKeyDown(sender, e);
}
public override void SetIconFromStream(Stream stream)
{
if (WindowInfo.Handle == IntPtr.Zero)
throw new InvalidOperationException("Window must be created before an icon can be set.");
var secondStream = new MemoryStream();
stream.CopyTo(secondStream);
stream.Position = 0;
secondStream.Position = 0;
// FIXME
//smallIcon = new Icon(stream, 24, 24);
//largeIcon = new Icon(secondStream, 256, 256);
//SendMessage(WindowInfo.Handle, seticon_message, (IntPtr)0, smallIcon.Handle);
//SendMessage(WindowInfo.Handle, seticon_message, (IntPtr)1, largeIcon.Handle);
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
}
}
|
mit
|
C#
|
a1b63652e44c5bcf462cf08b29129415aeb1d4dd
|
allow comment out UserConnections
|
AlejandroCano/framework,avifatal/framework,signumsoftware/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework
|
Signum.Engine/Connection/UserConnections.cs
|
Signum.Engine/Connection/UserConnections.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Engine;
using System.Data.SqlClient;
using System.Diagnostics;
using Signum.Engine.Maps;
using Signum.Utilities;
using Signum.Engine.Properties;
namespace Signum.Engine
{
public static class UserConnections
{
public static string FileName = @"C:\UserConnections.txt";
static Dictionary<string, string> replacements = null;
public static Dictionary<string, string> LoadReplacements()
{
if (!File.Exists(FileName))
return new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
Debug.WriteLine("UserConnection's file found on {0}".Formato(FileName));
Debug.WriteLine("{0}".Formato(File.ReadAllText(FileName)));
return File.ReadAllLines(FileName).Where(s=>s.HasText() && !s.StartsWith("-") && !s.StartsWith("/")).Select(s => s.Split('>')).ToDictionary(a => a[0], a => a[1]);
}
public static string Replace(string connectionString)
{
if (replacements == null)
replacements = LoadReplacements();
string schemaName = new SqlConnection(connectionString).Database;
return replacements.TryGetC(schemaName) ?? connectionString;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Engine;
using System.Data.SqlClient;
using System.Diagnostics;
using Signum.Engine.Maps;
using Signum.Utilities;
using Signum.Engine.Properties;
namespace Signum.Engine
{
public static class UserConnections
{
public static string FileName = @"C:\UserConnections.txt";
static Dictionary<string, string> replacements = null;
public static Dictionary<string, string> LoadReplacements()
{
if (!File.Exists(FileName))
return new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
Debug.WriteLine("UserConnection's file found on {0}".Formato(FileName));
Debug.WriteLine("{0}".Formato(File.ReadAllText(FileName)));
return File.ReadAllLines(FileName).Select(s => s.Split('>')).ToDictionary(a => a[0], a => a[1]);
}
public static string Replace(string connectionString)
{
if (replacements == null)
replacements = LoadReplacements();
string schemaName = new SqlConnection(connectionString).Database;
return replacements.TryGetC(schemaName) ?? connectionString;
}
}
}
|
mit
|
C#
|
1bd44529dd31302a62a55d424135c316233d5384
|
add full-stop to mod description for consistency
|
ppy/osu,2yangk23/osu,johnneijzen/osu,smoogipoo/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,UselessToucan/osu
|
osu.Game/Rulesets/Mods/ModDifficultyAdjust.cs
|
osu.Game/Rulesets/Mods/ModDifficultyAdjust.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using System;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModDifficultyAdjust : Mod, IApplicableToDifficulty
{
public override string Name => @"Difficulty Adjust";
public override string Description => @"Override a beatmap's difficulty settings.";
public override string Acronym => "DA";
public override ModType Type => ModType.Conversion;
public override IconUsage Icon => FontAwesome.Solid.Hammer;
public override double ScoreMultiplier => 1.0;
public override Type[] IncompatibleMods => new[] { typeof(ModEasy), typeof(ModHardRock) };
public virtual BindableNumber<float> DrainRate { get; }
public virtual BindableNumber<float> CircleSize { get; }
public virtual BindableNumber<float> ApproachRate { get; }
public virtual BindableNumber<float> OverallDifficulty { get; }
private BeatmapDifficulty difficulty;
public virtual void ApplyToDifficulty(BeatmapDifficulty difficulty)
{
if (this.difficulty == null || this.difficulty.ID != difficulty.ID)
{
this.difficulty = difficulty;
if (DrainRate != null)
DrainRate.Value = DrainRate.Default = difficulty.DrainRate;
if (CircleSize != null)
CircleSize.Value = CircleSize.Default = difficulty.CircleSize;
if (ApproachRate != null)
ApproachRate.Value = ApproachRate.Default = difficulty.ApproachRate;
if (OverallDifficulty != null)
OverallDifficulty.Value = OverallDifficulty.Default = difficulty.OverallDifficulty;
}
else
{
difficulty.DrainRate = DrainRate?.Value ?? difficulty.DrainRate;
difficulty.CircleSize = CircleSize?.Value ?? difficulty.CircleSize;
difficulty.ApproachRate = ApproachRate?.Value ?? difficulty.ApproachRate;
difficulty.OverallDifficulty = OverallDifficulty?.Value ?? difficulty.OverallDifficulty;
}
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using System;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModDifficultyAdjust : Mod, IApplicableToDifficulty
{
public override string Name => @"Difficulty Adjust";
public override string Description => @"Override a beatmap's difficulty settings";
public override string Acronym => "DA";
public override ModType Type => ModType.Conversion;
public override IconUsage Icon => FontAwesome.Solid.Hammer;
public override double ScoreMultiplier => 1.0;
public override Type[] IncompatibleMods => new[] { typeof(ModEasy), typeof(ModHardRock) };
public virtual BindableNumber<float> DrainRate { get; }
public virtual BindableNumber<float> CircleSize { get; }
public virtual BindableNumber<float> ApproachRate { get; }
public virtual BindableNumber<float> OverallDifficulty { get; }
private BeatmapDifficulty difficulty;
public virtual void ApplyToDifficulty(BeatmapDifficulty difficulty)
{
if (this.difficulty == null || this.difficulty.ID != difficulty.ID)
{
this.difficulty = difficulty;
if (DrainRate != null)
DrainRate.Value = DrainRate.Default = difficulty.DrainRate;
if (CircleSize != null)
CircleSize.Value = CircleSize.Default = difficulty.CircleSize;
if (ApproachRate != null)
ApproachRate.Value = ApproachRate.Default = difficulty.ApproachRate;
if (OverallDifficulty != null)
OverallDifficulty.Value = OverallDifficulty.Default = difficulty.OverallDifficulty;
}
else
{
difficulty.DrainRate = DrainRate?.Value ?? difficulty.DrainRate;
difficulty.CircleSize = CircleSize?.Value ?? difficulty.CircleSize;
difficulty.ApproachRate = ApproachRate?.Value ?? difficulty.ApproachRate;
difficulty.OverallDifficulty = OverallDifficulty?.Value ?? difficulty.OverallDifficulty;
}
}
}
}
|
mit
|
C#
|
45348ae4071f7d519f4e4d7ca881d3ce64897461
|
Fix quoting for Unity log file
|
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
|
source/Nuke.Common/Tools/Unity/UnityBaseSettings.cs
|
source/Nuke.Common/Tools/Unity/UnityBaseSettings.cs
|
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using Nuke.Common.Tooling;
using Nuke.Common.Utilities;
namespace Nuke.Common.Tools.Unity
{
public partial class UnityBaseSettings
{
public override Action<OutputType, string> ProcessCustomLogger => UnityTasks.UnityLogger;
public string GetProcessToolPath()
{
return UnityTasks.GetToolPath(HubVersion);
}
public string GetLogFile()
{
return (LogFile ?? NukeBuild.RootDirectory / "unity.log").DoubleQuoteIfNeeded();
}
}
}
|
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using Nuke.Common.Tooling;
namespace Nuke.Common.Tools.Unity
{
public partial class UnityBaseSettings
{
public override Action<OutputType, string> ProcessCustomLogger => UnityTasks.UnityLogger;
public string GetProcessToolPath()
{
return UnityTasks.GetToolPath(HubVersion);
}
public string GetLogFile()
{
// TODO SK
return LogFile ?? NukeBuild.RootDirectory / "unity.log";
}
}
}
|
mit
|
C#
|
31f6f99f314300008b5c9cb1173da8b30f2bafe2
|
Modify unit of work extension to provide a way to supply app's own unit of work type
|
volak/Aggregates.NET,volak/Aggregates.NET
|
src/Aggregates.NET.NServiceBus/ContextExtensions.cs
|
src/Aggregates.NET.NServiceBus/ContextExtensions.cs
|
using Aggregates.Contracts;
using Aggregates.Messages;
using NServiceBus;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Aggregates
{
public static class ContextExtensions
{
public static IRepository<T> For<T>(this IMessageHandlerContext context) where T : IEntity
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().For<T>();
}
public static IPocoRepository<T> Poco<T>(this IMessageHandlerContext context) where T : class, new()
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().Poco<T>();
}
public static Task<TResponse> Query<TQuery, TResponse>(this IMessageHandlerContext context, TQuery query) where TQuery : IQuery<TResponse>
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().Query<TQuery, TResponse>(query, container.Resolve<IUnitOfWork>());
}
public static Task<TResponse> Query<TQuery, TResponse>(this IMessageHandlerContext context, Action<TQuery> query) where TQuery : IQuery<TResponse>
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().Query<TQuery, TResponse>(query, container.Resolve<IUnitOfWork>());
}
public static TUnitOfWork App<TUnitOfWork>(this IMessageHandlerContext context) where TUnitOfWork : class, IUnitOfWork
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<TUnitOfWork>();
}
}
}
|
using Aggregates.Contracts;
using Aggregates.Messages;
using NServiceBus;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Aggregates
{
public static class ContextExtensions
{
public static IRepository<T> For<T>(this IMessageHandlerContext context) where T : IEntity
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().For<T>();
}
public static IPocoRepository<T> Poco<T>(this IMessageHandlerContext context) where T : class, new()
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().Poco<T>();
}
public static Task<TResponse> Query<TQuery, TResponse>(this IMessageHandlerContext context, TQuery query) where TQuery : IQuery<TResponse>
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().Query<TQuery, TResponse>(query, container.Resolve<IUnitOfWork>());
}
public static Task<TResponse> Query<TQuery, TResponse>(this IMessageHandlerContext context, Action<TQuery> query) where TQuery : IQuery<TResponse>
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IDomainUnitOfWork>().Query<TQuery, TResponse>(query, container.Resolve<IUnitOfWork>());
}
public static IUnitOfWork UnitOfWork(this IMessageHandlerContext context)
{
var container = context.Extensions.Get<IContainer>();
return container.Resolve<IUnitOfWork>();
}
}
}
|
mit
|
C#
|
b7c0e517fc9d7b4076f757d41925da2f2cd7eda3
|
Add MemberCloneResult contains member
|
Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver
|
src/AsmResolver.DotNet/Cloning/MemberCloneResult.cs
|
src/AsmResolver.DotNet/Cloning/MemberCloneResult.cs
|
using System;
using System.Collections.Generic;
namespace AsmResolver.DotNet.Cloning
{
/// <summary>
/// Provides information about the result of a metadata cloning procedure.
/// </summary>
public class MemberCloneResult
{
private readonly IDictionary<IMemberDescriptor, IMemberDescriptor> clonedMembers;
/// <summary>
/// Creates a new instance of the <see cref="MemberCloneResult"/> class.
/// </summary>
/// <param name="clonedMembers">The cloned members.</param>
/// <exception cref="ArgumentNullException">Occurs when <paramref name="clonedMembers"/> is null.</exception>
public MemberCloneResult(IDictionary<IMemberDescriptor, IMemberDescriptor> clonedMembers)
{
this.clonedMembers = clonedMembers ?? throw new ArgumentNullException(nameof(clonedMembers));
ClonedMembers = new List<IMemberDescriptor>(clonedMembers.Values);
OriginalMembers = new List<IMemberDescriptor>(clonedMembers.Keys);
}
/// <summary>
/// Gets a collection of all cloned members.
/// </summary>
public ICollection<IMemberDescriptor> ClonedMembers
{
get;
}
/// <summary>
/// Gets a collection of all original members.
/// </summary>
public ICollection<IMemberDescriptor> OriginalMembers
{
get;
}
/// <summary>
/// Verifies if the <paramref name="originalMember"/> is cloned by the <see cref="MemberCloner"/>.
/// </summary>
/// <param name="originalMember">The original <see cref="IMemberDescriptor"/></param>
/// <returns><c>true</c> if the provided member was cloned, <c>false</c> otherwise.</returns>
public bool ContainsClonedMember(IMemberDescriptor originalMember) => clonedMembers.ContainsKey(originalMember);
/// <summary>
/// Gets the cloned <see cref="IMemberDescriptor"/> by its original <see cref="IMemberDescriptor"/>.
/// </summary>
/// <param name="originalMember">Original <see cref="IMemberDescriptor"/></param>
/// <exception cref="ArgumentOutOfRangeException">Occurs when <paramref name="originalMember"/> is not a member of <see cref="OriginalMembers"/></exception>
/// <returns>Cloned <see cref="IMemberDescriptor"/></returns>
public IMemberDescriptor GetClonedMember(IMemberDescriptor originalMember)
{
if (clonedMembers.ContainsKey(originalMember))
throw new ArgumentOutOfRangeException(nameof(originalMember));
return clonedMembers[originalMember];
}
}
}
|
using System;
using System.Collections.Generic;
namespace AsmResolver.DotNet.Cloning
{
/// <summary>
/// Provides information about the result of a metadata cloning procedure.
/// </summary>
public class MemberCloneResult
{
private readonly IDictionary<IMemberDescriptor, IMemberDescriptor> clonedMembers;
/// <summary>
/// Creates a new instance of the <see cref="MemberCloneResult"/> class.
/// </summary>
/// <param name="clonedMembers">The cloned members.</param>
public MemberCloneResult(IDictionary<IMemberDescriptor, IMemberDescriptor> clonedMembers)
{
this.clonedMembers = clonedMembers;
ClonedMembers = new List<IMemberDescriptor>(clonedMembers.Values);
OriginalMembers = new List<IMemberDescriptor>(clonedMembers.Keys);
}
/// <summary>
/// Gets a collection of all cloned members.
/// </summary>
public ICollection<IMemberDescriptor> ClonedMembers
{
get;
}
/// <summary>
/// Gets a collection of all original members.
/// </summary>
public ICollection<IMemberDescriptor> OriginalMembers
{
get;
}
/// <summary>
/// Gets the cloned <see cref="IMemberDescriptor"/> by its original <see cref="IMemberDescriptor"/>.
/// </summary>
/// <param name="originalMember">Original <see cref="IMemberDescriptor"/></param>
/// <exception cref="ArgumentOutOfRangeException">Occurs when <paramref name="originalMember"/> is not a member of <see cref="OriginalMembers"/></exception>
/// <returns>Cloned <see cref="IMemberDescriptor"/></returns>
public IMemberDescriptor GetClonedMember(IMemberDescriptor originalMember)
{
if (clonedMembers.ContainsKey(originalMember))
throw new ArgumentOutOfRangeException(nameof(originalMember));
return clonedMembers[originalMember];
}
}
}
|
mit
|
C#
|
8a14fed787692597a1141aa334f52758e12450fa
|
Replace Windows directory separator \ with URI path separator /
|
jochenvangasse/Klondike,jochenvangasse/Klondike,jochenvangasse/Klondike,fhchina/Klondike,fhchina/Klondike,themotleyfool/Klondike,Stift/Klondike,fhchina/Klondike,Stift/Klondike,davidvmckay/Klondike,Stift/Klondike,davidvmckay/Klondike,themotleyfool/Klondike,davidvmckay/Klondike,themotleyfool/Klondike
|
src/Klondike.SelfHost/SelfHostVirtualPathUtility.cs
|
src/Klondike.SelfHost/SelfHostVirtualPathUtility.cs
|
using System;
using System.IO;
using System.Net;
using Autofac;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NuGet.Lucene.Web;
using NuGet.Lucene.Web.Formatters;
using Owin;
namespace Klondike.SelfHost
{
public class SelfHostVirtualPathUtility : IVirtualPathUtility
{
readonly string virtualPathRoot;
readonly string webRoot;
public SelfHostVirtualPathUtility(string webRoot, string virtualPathRoot)
{
if (string.IsNullOrEmpty(webRoot))
{
throw new ArgumentException("webRoot must not be null or blank", "webRoot");
}
if (!Path.IsPathRooted(webRoot))
{
throw new ArgumentException("webRoot must be an absolute path", "webRoot");
}
if (!Directory.Exists(webRoot))
{
throw new ArgumentException("Directory does not exist", "webRoot");
}
if (virtualPathRoot == null)
{
virtualPathRoot = "";
}
if (virtualPathRoot.Length > 0 && !virtualPathRoot.StartsWith("/"))
{
throw new ArgumentException("virtualPathRoot must be blank or start with /", "virtualPathRoot");
}
this.webRoot = webRoot.TrimEnd('\\', '/');
this.virtualPathRoot = virtualPathRoot.TrimEnd('\\', '/');
}
public string MapPath(string virtualPath)
{
if (virtualPath.StartsWith("~/"))
{
virtualPath = virtualPath.Substring(1).TrimStart('/');
}
return Path.Combine(webRoot, virtualPath);
}
public string ToAbsolute(string virtualPath)
{
var physicalPath = MapPath(virtualPath);
if (!physicalPath.StartsWith(webRoot))
{
throw new InvalidOperationException("Path is not rooted in document root");
}
var relativePath = physicalPath.Substring(webRoot.Length);
return virtualPathRoot + relativePath.Replace('\\', '/');
}
}
}
|
using System;
using System.IO;
using System.Net;
using Autofac;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NuGet.Lucene.Web;
using NuGet.Lucene.Web.Formatters;
using Owin;
namespace Klondike.SelfHost
{
public class SelfHostVirtualPathUtility : IVirtualPathUtility
{
readonly string virtualPathRoot;
readonly string webRoot;
public SelfHostVirtualPathUtility(string webRoot, string virtualPathRoot)
{
if (string.IsNullOrEmpty(webRoot))
{
throw new ArgumentException("webRoot must not be null or blank", "webRoot");
}
if (!Path.IsPathRooted(webRoot))
{
throw new ArgumentException("webRoot must be an absolute path", "webRoot");
}
if (!Directory.Exists(webRoot))
{
throw new ArgumentException("Directory does not exist", "webRoot");
}
if (virtualPathRoot == null)
{
virtualPathRoot = "";
}
if (virtualPathRoot.Length > 0 && !virtualPathRoot.StartsWith("/"))
{
throw new ArgumentException("virtualPathRoot must be blank or start with /", "virtualPathRoot");
}
this.webRoot = webRoot.TrimEnd('\\', '/');
this.virtualPathRoot = virtualPathRoot.TrimEnd('\\', '/');
}
public string MapPath(string virtualPath)
{
if (virtualPath.StartsWith("~/"))
{
virtualPath = virtualPath.Substring(1).TrimStart('/');
}
return Path.Combine(webRoot, virtualPath);
}
public string ToAbsolute(string virtualPath)
{
var physicalPath = MapPath(virtualPath);
if (!physicalPath.StartsWith(webRoot))
{
throw new InvalidOperationException("Path is not rooted in document root");
}
var relativePath = physicalPath.Substring(webRoot.Length);
return virtualPathRoot + relativePath;
}
}
}
|
apache-2.0
|
C#
|
8c16df83b21db42d0d7babcf2f80291960e43bb3
|
Handle exiting if bot is destroyed by consuming resources.
|
MarjieVolk/Backfire
|
Assets/Nanobot.cs
|
Assets/Nanobot.cs
|
using UnityEngine;
using System.Collections;
public class Nanobot : MonoBehaviour, TimestepManager.TimestepListener {
BulletGridGenerator currentLevel;
public NanobotSchematic schematic;
public int price;
public string id;
// Use this for initialization
void Start() {
currentLevel = FindObjectOfType<BulletGridGenerator>();
GameObject.FindObjectOfType<TimestepManager>().addListener(this);
schematic = GameObject.Instantiate(schematic);
}
public void notifyTimestep() {
GridPosition position = gameObject.GetComponent<GridPositionComponent>().position;
BulletGridGenerator.GameCell cell = currentLevel.getCellAt(position);
cell.Cell.GetComponent<Cell>().Eat(1, false);
if (cell.Nanobot == null) {
// TODO: Trigger animation for nanobot death.
return;
}
for (int x = 0; x < schematic.getTransformation().Length; x++) {
if (schematic.getTransformation()[x] != null) {
for (int y = 0; y < schematic.getTransformation()[x].Length; y++) {
if (schematic.getTransformation()[x][y] != null) {
currentLevel.moveBotAnimated(position, schematic.getTransformation()[x][y], new GridPosition(x - 1, y - 1), 5, false);
}
}
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class Nanobot : MonoBehaviour, TimestepManager.TimestepListener {
BulletGridGenerator currentLevel;
public NanobotSchematic schematic;
public int price;
public string id;
// Use this for initialization
void Start() {
currentLevel = FindObjectOfType<BulletGridGenerator>();
GameObject.FindObjectOfType<TimestepManager>().addListener(this);
schematic = GameObject.Instantiate(schematic);
}
public void notifyTimestep() {
currentLevel.getCellAt(gameObject.GetComponent<GridPositionComponent>().position).Cell.GetComponent<Cell>().Eat(1, false);
for (int x = 0; x < schematic.getTransformation().Length; x++) {
if (schematic.getTransformation()[x] != null) {
for (int y = 0; y < schematic.getTransformation()[x].Length; y++) {
if (schematic.getTransformation()[x][y] != null) {
currentLevel.moveBotAnimated(gameObject.GetComponent<GridPositionComponent>().position, schematic.getTransformation()[x][y], new GridPosition(x - 1, y - 1), 5, false);
}
}
}
}
}
}
|
mit
|
C#
|
acbd73e0c808664cf7c39788e559ee199ceb3da1
|
Add support for XamMac assembly as well
|
mono/guiunit
|
src/framework/GuiUnit/MonoMacMainLoopIntegration.cs
|
src/framework/GuiUnit/MonoMacMainLoopIntegration.cs
|
using System;
using System.Linq;
namespace GuiUnit
{
public class MonoMacMainLoopIntegration : IMainLoopIntegration
{
Type Application {
get; set;
}
object SharedApplication {
get; set;
}
public MonoMacMainLoopIntegration ()
{
Application =
Type.GetType ("AppKit.NSApplication, Xamarin.Mac") ??
Type.GetType ("MonoMac.AppKit.NSApplication, XamMac") ??
Type.GetType ("MonoMac.AppKit.NSApplication, MonoMac");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
var initMethod = Application.GetMethod ("Init", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
initMethod.Invoke (null, null);
var sharedAppProperty = Application.GetProperty ("SharedApplication", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SharedApplication = sharedAppProperty.GetValue (null, null);
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var potentialMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var invokeOnMainThreadMethod = potentialMethods.First (m => m.Name == "InvokeOnMainThread" && m.GetParameters ().Length == 1);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (SharedApplication, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (SharedApplication, null);
}
public void Shutdown ()
{
Application.GetMethod ("Terminate").Invoke (SharedApplication, new [] { SharedApplication });
}
}
}
|
using System;
using System.Linq;
namespace GuiUnit
{
public class MonoMacMainLoopIntegration : IMainLoopIntegration
{
Type Application {
get; set;
}
object SharedApplication {
get; set;
}
public MonoMacMainLoopIntegration ()
{
Application = Type.GetType ("MonoMac.AppKit.NSApplication, MonoMac");
if (Application == null)
Application = Type.GetType ("AppKit.NSApplication, Xamarin.Mac");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
var initMethod = Application.GetMethod ("Init", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
initMethod.Invoke (null, null);
var sharedAppProperty = Application.GetProperty ("SharedApplication", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SharedApplication = sharedAppProperty.GetValue (null, null);
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var potentialMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var invokeOnMainThreadMethod = potentialMethods.First (m => m.Name == "InvokeOnMainThread" && m.GetParameters ().Length == 1);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (SharedApplication, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (SharedApplication, null);
}
public void Shutdown ()
{
Application.GetMethod ("Terminate").Invoke (SharedApplication, new [] { SharedApplication });
}
}
}
|
mit
|
C#
|
e5656f35e1d5b60f6651f81cf624614dabf4eaf3
|
Refactor `PlansPage`
|
atata-framework/atata-sample-app-tests
|
test/AtataSampleApp.UITests.Components/PlansPage.cs
|
test/AtataSampleApp.UITests.Components/PlansPage.cs
|
using Atata;
namespace AtataSampleApp.UITests;
using _ = PlansPage;
[Url("plans")]
[VerifyTitle]
[VerifyH1]
[VerifyContent("Please choose your payment plan")]
public class PlansPage : AppPage<_>
{
public ControlList<PlanItem, _> PlanItems { get; private set; }
[ControlDefinition("div", ContainingClass = "plan-item", ComponentTypeName = "plan item")]
public class PlanItem : Control<_>
{
public H3<_> Title { get; private set; }
[FindByClass]
public Currency<_> Price { get; private set; }
[FindByClass("projects-num")]
public Number<_> NumberOfProjects { get; private set; }
public ControlList<TextListItem<_>, _> Features { get; private set; }
}
}
|
using Atata;
namespace AtataSampleApp.UITests;
using _ = PlansPage;
[Url("plans")]
[VerifyTitle]
[VerifyH1]
[VerifyContent("Please choose your payment plan")]
public class PlansPage : AppPage<_>
{
public ControlList<PlanItem, _> PlanItems { get; private set; }
[ControlDefinition("div", ContainingClass = "plan-item", ComponentTypeName = "plan item")]
public class PlanItem : Control<_>
{
public H3<_> Title { get; private set; }
[FindByClass]
public Currency<_> Price { get; private set; }
[FindByClass("projects-num")]
public Number<_> NumberOfProjects { get; private set; }
[ControlDefinition("li", ComponentTypeName = "feature")]
public ControlList<Text<_>, _> Features { get; private set; }
}
}
|
apache-2.0
|
C#
|
ba72e0d75a5aab80b5e00fb622623d63cec3f4ea
|
update customer in controller
|
QuantumHive/HiLaarIsch,QuantumHive/HiLaarIsch
|
HiLaarIsch.WebApp/Controllers/CustomersController.cs
|
HiLaarIsch.WebApp/Controllers/CustomersController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HiLaarIsch.Contract.Commands;
using HiLaarIsch.Contract.DTOs;
using HiLaarIsch.Contract.Queries;
using QuantumHive.Core;
namespace HiLaarIsch.Controllers
{
[Authorize]
[RoutePrefix("customers")]
public class CustomersController : Controller
{
private readonly IQueryProcessor queryProcessor;
private readonly ICommandHandler<CreateModelCommand<CustomerModel>> createHandler;
private readonly ICommandHandler<UpdateModelCommand<CustomerModel>> updateHandler;
public CustomersController(
IQueryProcessor queryProcessor,
ICommandHandler<CreateModelCommand<CustomerModel>> createHandler,
ICommandHandler<UpdateModelCommand<CustomerModel>> updateHandler)
{
this.queryProcessor = queryProcessor;
this.createHandler = createHandler;
this.updateHandler = updateHandler;
}
[Route("~/")]
[HttpGet, Route]
public ActionResult Index()
{
var customers = this.queryProcessor.Process(new GetAllModelsQuery<CustomerView>());
return this.View(customers);
}
[HttpGet, Route("new")]
public ActionResult New()
{
return this.View(new CustomerModel());
}
[HttpPost, Route("new")]
[ValidateAntiForgeryToken]
public ActionResult New(CustomerModel model)
{
this.createHandler.Handle(new CreateModelCommand<CustomerModel>(model));
return this.Redirect("/"); //TODO: clean redirect
}
[HttpGet, Route("edit/{customerId}")]
public ActionResult Edit(Guid customerId)
{
var model = this.queryProcessor.Process(new GetModelByIdQuery<CustomerModel>(customerId));
return this.View(model);
}
[HttpPost, Route("edit")]
public ActionResult Edit(CustomerModel model)
{
this.updateHandler.Handle(new UpdateModelCommand<CustomerModel>(model, model.Id));
return this.Redirect("/"); //TODO: clean redirect
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HiLaarIsch.Contract.Commands;
using HiLaarIsch.Contract.DTOs;
using HiLaarIsch.Contract.Queries;
using QuantumHive.Core;
namespace HiLaarIsch.Controllers
{
[Authorize]
[RoutePrefix("customers")]
public class CustomersController : Controller
{
private readonly IQueryProcessor queryProcessor;
private readonly ICommandHandler<CreateModelCommand<CustomerModel>> createHandler;
public CustomersController(
IQueryProcessor queryProcessor,
ICommandHandler<CreateModelCommand<CustomerModel>> createHandler)
{
this.queryProcessor = queryProcessor;
this.createHandler = createHandler;
}
[Route("~/")]
[HttpGet, Route]
public ActionResult Index()
{
var customers = this.queryProcessor.Process(new GetAllModelsQuery<CustomerView>());
return this.View(customers);
}
[HttpGet, Route("new")]
public ActionResult New()
{
return this.View(new CustomerModel());
}
[HttpPost, Route("new")]
[ValidateAntiForgeryToken]
public ActionResult New(CustomerModel model)
{
this.createHandler.Handle(new CreateModelCommand<CustomerModel>(model));
return this.Redirect("/"); //TODO: clean redirect
}
[HttpGet, Route("edit/{customerId}")]
public ActionResult Edit(Guid customerId)
{
var model = this.queryProcessor.Process(new GetModelByIdQuery<CustomerModel>(customerId));
return this.View(model);
}
[HttpPost, Route("edit")]
public ActionResult Edit(CustomerModel model)
{
//TODO: edit command handler
return this.Redirect("/"); //TODO: clean redirect
}
}
}
|
mit
|
C#
|
93b4e77ca0e23f38b92f7fd3519eb4049ff5fd26
|
correct keypath value
|
dgarage/NBXplorer,dgarage/NBXplorer
|
NBXplorer.Client/NBXplorerNetworkProvider.Althash.cs
|
NBXplorer.Client/NBXplorerNetworkProvider.Althash.cs
|
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
namespace NBXplorer
{
public partial class NBXplorerNetworkProvider
{
private void InitAlthash(ChainName networkType)
{
Add(new NBXplorerNetwork(NBitcoin.Altcoins.Althash.Instance, networkType)
{
MinRPCVersion = 169900,
CoinType = networkType == ChainName.Mainnet ? new KeyPath("172'") : new KeyPath("1'")
});
}
public NBXplorerNetwork GetALTHASH()
{
return GetFromCryptoCode(NBitcoin.Altcoins.Althash.Instance.CryptoCode);
}
}
}
|
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
namespace NBXplorer
{
public partial class NBXplorerNetworkProvider
{
private void InitAlthash(ChainName networkType)
{
Add(new NBXplorerNetwork(NBitcoin.Altcoins.Althash.Instance, networkType)
{
MinRPCVersion = 169900,
CoinType = networkType == ChainName.Mainnet ? new KeyPath("88'") : new KeyPath("0'")
});
}
public NBXplorerNetwork GetALTHASH()
{
return GetFromCryptoCode(NBitcoin.Altcoins.Althash.Instance.CryptoCode);
}
}
}
|
mit
|
C#
|
7fd00f9142ec4951374ab188dd2069e5816948bd
|
Fix RadioButtonCellView.Toggled event
|
TheBrainTech/xwt,hamekoz/xwt,lytico/xwt,cra0zy/xwt,hwthomas/xwt,antmicro/xwt,mono/xwt
|
Xwt.XamMac/Xwt.Mac.CellViews/RadioButtonTableCell.cs
|
Xwt.XamMac/Xwt.Mac.CellViews/RadioButtonTableCell.cs
|
//
// RadioButtonTableCell.cs
//
// Author:
// Vsevolod Kukol <sevoku@microsoft.com>
//
// Copyright (c) 2016 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.AppKit;
#else
using AppKit;
#endif
namespace Xwt.Mac
{
class RadioButtonTableCell: NSButtonCell, ICellRenderer
{
public RadioButtonTableCell ()
{
SetButtonType (NSButtonType.Radio);
AllowsMixedState = false;
Activated += HandleActivated;
Title = "";
}
public override NSCellStateValue State {
get {
return base.State;
}
set {
if (base.State != value)
stateChanging = true;
base.State = value;
}
}
bool stateChanging;
void HandleActivated (object sender, EventArgs e)
{
if (State == NSCellStateValue.On && stateChanging) {
var cellView = Frontend;
CellContainer.SetCurrentEventRow ();
Frontend.Load (CellContainer);
if (cellView.Editable && !cellView.RaiseToggled ()) {
if (cellView.ActiveField != null)
CellContainer.SetValue (cellView.ActiveField, State != NSCellStateValue.Off);
} else
base.State = NSCellStateValue.Off;
}
stateChanging = false;
}
public RadioButtonTableCell (IntPtr p): base (p)
{
}
IRadioButtonCellViewFrontend Frontend {
get { return (IRadioButtonCellViewFrontend)Backend.Frontend; }
}
public CellViewBackend Backend { get; set; }
public CompositeCell CellContainer { get; set; }
public void Fill ()
{
var cellView = Frontend;
base.State = cellView.Active ? NSCellStateValue.On : NSCellStateValue.Off;
Editable = cellView.Editable;
}
public void CopyFrom (object other)
{
var ob = (RadioButtonTableCell)other;
Backend = ob.Backend;
}
}
}
|
//
// RadioButtonTableCell.cs
//
// Author:
// Vsevolod Kukol <sevoku@microsoft.com>
//
// Copyright (c) 2016 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.AppKit;
#else
using AppKit;
#endif
namespace Xwt.Mac
{
class RadioButtonTableCell: NSButtonCell, ICellRenderer
{
public RadioButtonTableCell ()
{
SetButtonType (NSButtonType.Radio);
AllowsMixedState = false;
Activated += HandleActivated;
Title = "";
}
void HandleActivated (object sender, EventArgs e)
{
var cellView = Frontend;
CellContainer.SetCurrentEventRow ();
if (cellView.Editable && !cellView.RaiseToggled () && cellView.ActiveField != null) {
CellContainer.SetValue (cellView.ActiveField, State != NSCellStateValue.Off);
}
}
public RadioButtonTableCell (IntPtr p): base (p)
{
}
IRadioButtonCellViewFrontend Frontend {
get { return (IRadioButtonCellViewFrontend)Backend.Frontend; }
}
public CellViewBackend Backend { get; set; }
public CompositeCell CellContainer { get; set; }
public void Fill ()
{
var cellView = Frontend;
State = cellView.Active ? NSCellStateValue.On : NSCellStateValue.Off;
Editable = cellView.Editable;
}
public void CopyFrom (object other)
{
var ob = (RadioButtonTableCell)other;
Backend = ob.Backend;
}
}
}
|
mit
|
C#
|
346778a112d401fb780e729b917fd2a728300918
|
Change format on default logger formatter.
|
jirkapenzes/SimpleLogger,Maxwolf/SimpleLogger,Maxwolf/Lumberjack
|
SimpleLogger/Logging/Formatters/DefaultLoggerFormatter.cs
|
SimpleLogger/Logging/Formatters/DefaultLoggerFormatter.cs
|
namespace SimpleLogger.Logging.Formatters
{
internal class DefaultLoggerFormatter : ILoggerFormatter
{
public string ApplyFormat(LogMessage logMessage)
{
return string.Format("{0:dd.MM.yyyy HH:mm}: {1} [line: {2} {3} -> {4}()]: {5}",
logMessage.DateTime, logMessage.Level, logMessage.LineNumber, logMessage.CallingClass,
logMessage.CallingMethod, logMessage.Text);
}
}
}
|
namespace SimpleLogger.Logging.Formatters
{
internal class DefaultLoggerFormatter : ILoggerFormatter
{
public string ApplyFormat(LogMessage logMessage)
{
return string.Format("{0:dd.MM.yyyy HH:mm}: {1} ln: {2} [{3} -> {4}()]: {5}",
logMessage.DateTime, logMessage.Level, logMessage.LineNumber, logMessage.CallingClass,
logMessage.CallingMethod, logMessage.Text);
}
}
}
|
mit
|
C#
|
515414c6973e4053a643aea6804c26e7a61c2362
|
Update ChildNode.cs
|
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
|
src/Draw2D.Skia/Bounds/ChildNode.cs
|
src/Draw2D.Skia/Bounds/ChildNode.cs
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Draw2D.ViewModels;
using SkiaSharp;
namespace Draw2D.Bounds
{
public readonly struct ChildNode : IDisposable
{
public readonly IBaseShape Shape;
public readonly string StyleId;
public readonly double dX;
public readonly double dY;
public readonly double Scale;
public readonly SKPath Geometry;
public readonly SKRect Bounds;
public ChildNode(IBaseShape shape, string styleId, double dx, double dy, double scale, SKPath geometry)
{
this.Shape = shape;
this.StyleId = styleId;
this.dX = dx;
this.dY = dy;
this.Scale = scale;
this.Geometry = geometry;
geometry.GetBounds(out this.Bounds);
}
public bool Contains(float x, float y, ContainsMode mode)
{
if (mode == ContainsMode.Geometry)
{
return Geometry.Contains(x, y);
}
else if (mode == ContainsMode.Bounds)
{
return Bounds.Contains(x, y);
}
return false;
}
public bool Intersects(SKPath geometry)
{
using (var result = this.Geometry.Op(geometry, SKPathOp.Intersect))
{
return result?.IsEmpty == false;
}
}
public bool Intersects(ref SKRect rect)
{
return this.Bounds.IntersectsWith(rect);
}
public void Dispose()
{
Geometry?.Dispose();
}
}
}
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Draw2D.ViewModels;
using Draw2D.ViewModels.Containers;
using Draw2D.ViewModels.Shapes;
using SkiaSharp;
namespace Draw2D.Bounds
{
public readonly struct ChildNode : IDisposable
{
public readonly IBaseShape Shape;
public readonly string StyleId;
public readonly double dX;
public readonly double dY;
public readonly double Scale;
public readonly SKPath Geometry;
public readonly SKRect Bounds;
public ChildNode(IBaseShape shape, string styleId, double dx, double dy, double scale, SKPath geometry)
{
this.Shape = shape;
this.StyleId = styleId;
this.dX = dx;
this.dY = dy;
this.Scale = scale;
this.Geometry = geometry;
geometry.GetBounds(out this.Bounds);
}
public bool Contains(float x, float y, ContainsMode mode)
{
if (mode == ContainsMode.Geometry)
{
return Geometry.Contains(x, y);
}
else if (mode == ContainsMode.Bounds)
{
return Bounds.Contains(x, y);
}
return false;
}
public bool Intersects(SKPath geometry)
{
using (var result = this.Geometry.Op(geometry, SKPathOp.Intersect))
{
return result?.IsEmpty == false;
}
}
public bool Intersects(ref SKRect rect)
{
return this.Bounds.IntersectsWith(rect);
}
public void Dispose()
{
Geometry?.Dispose();
}
}
}
|
mit
|
C#
|
ddacdb92a64391636fa7acd9c4359e441321c40a
|
Fix 8.1 app
|
onovotny/MiFare
|
src/MiFare.Shared.UAP/CardReader.cs
|
src/MiFare.Shared.UAP/CardReader.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.SmartCards;
#if WINDOWS_UAP
using Windows.Foundation.Metadata;
#endif
namespace MiFare
{
public static class CardReader
{
public static async Task<SmartCardReader> FindAsync(Func<DeviceInformationCollection, DeviceInformation> selector = null)
{
#if WINDOWS_UAP
// Make sure we have the API we need
if (!ApiInformation.IsTypePresent(typeof(SmartCardConnection).FullName))
return null;
#endif
var devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc));
// There is a bug on some devices that were updated to WP8.1 where an NFC SmartCardReader is
// enumerated despite that the device does not support it. As a workaround, we can do an additonal check
// to ensure the device truly does support it.
var workaroundDetect = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{50DD5230-BA8A-11D1-BF5D-0000F805F530}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
if (workaroundDetect.Count == 0 || devices.Count == 0)
{
return null;
}
#if WINDOWS_UAP
// See if one of the reader names contains a -CL
if (devices.Count > 1 && selector == null)
{
var di = devices.SingleOrDefault(d => d.Id.Contains("-CL"));
if (di != null)
return await SmartCardReader.FromIdAsync(di.Id);
}
#endif
var func = selector ?? (d => d.First());
var dev = func(devices);
if (dev == null) return null;
var reader = await SmartCardReader.FromIdAsync(dev.Id);
return reader;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.SmartCards;
#if WINDOWS_UAP
using Windows.Foundation.Metadata;
#endif
namespace MiFare
{
public static class CardReader
{
public static async Task<SmartCardReader> FindAsync(Func<DeviceInformationCollection, DeviceInformation> selector = null)
{
#if WINDOWS_UAP
// Make sure we have the API we need
if (!ApiInformation.IsTypePresent(typeof(SmartCardConnection).FullName))
return null;
#endif
var devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Generic));
// There is a bug on some devices that were updated to WP8.1 where an NFC SmartCardReader is
// enumerated despite that the device does not support it. As a workaround, we can do an additonal check
// to ensure the device truly does support it.
var workaroundDetect = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{50DD5230-BA8A-11D1-BF5D-0000F805F530}\" AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
if (workaroundDetect.Count == 0 || devices.Count == 0)
{
return null;
}
#if WINDOWS_UAP
// See if one of the reader names contains a -CL
if (devices.Count > 1 && selector == null)
{
var di = devices.SingleOrDefault(d => d.Id.Contains("-CL"));
if (di != null)
return await SmartCardReader.FromIdAsync(di.Id);
}
#endif
var func = selector ?? (d => d.First());
var dev = func(devices);
if (dev == null) return null;
var reader = await SmartCardReader.FromIdAsync(dev.Id);
return reader;
}
}
}
|
mit
|
C#
|
4222500e0fdf4e4c15afb218bb7c06e724dc43e5
|
increase the timeout
|
AutoMapper/AutoMapper,AutoMapper/AutoMapper
|
src/IntegrationTests/LocalDbContext.cs
|
src/IntegrationTests/LocalDbContext.cs
|
using Microsoft.EntityFrameworkCore;
namespace AutoMapper.IntegrationTests;
public abstract class LocalDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(
@$"Data Source=(localdb)\mssqllocaldb;Integrated Security=True;MultipleActiveResultSets=True;Database={GetType()};Connection Timeout=300");
}
|
using Microsoft.EntityFrameworkCore;
namespace AutoMapper.IntegrationTests;
public abstract class LocalDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(
@$"Data Source=(localdb)\mssqllocaldb;Integrated Security=True;MultipleActiveResultSets=True;Database={GetType()};Connection Timeout=160");
}
|
mit
|
C#
|
bf67c6bfeaace152644b0b2e5dcdb3812645a789
|
Revise expected resource name after fixing default namespace
|
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
|
src/ScriptBuilder/ResourceReader.cs
|
src/ScriptBuilder/ResourceReader.cs
|
using System.IO;
using System.Reflection;
using NServiceBus.Persistence.Sql.ScriptBuilder;
static class ResourceReader
{
static Assembly assembly = typeof(ResourceReader).GetTypeInfo().Assembly;
public static string ReadResource(BuildSqlDialect sqlDialect, string prefix)
{
var text = $"NServiceBus.Persistence.Sql.ScriptBuilder.{prefix}_{sqlDialect}.sql";
using (var stream = assembly.GetManifestResourceStream(text))
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
|
using System.IO;
using System.Reflection;
using NServiceBus.Persistence.Sql.ScriptBuilder;
static class ResourceReader
{
static Assembly assembly = typeof(ResourceReader).GetTypeInfo().Assembly;
public static string ReadResource(BuildSqlDialect sqlDialect, string prefix)
{
var text = $"NServiceBus.Persistence.Sql.{prefix}_{sqlDialect}.sql";
using (var stream = assembly.GetManifestResourceStream(text))
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
|
mit
|
C#
|
5c01d9eb091cb64f6a4c8eab2514c34b2b7ae94e
|
Add .map ext to SetupMiddleware #286
|
FanrayMedia/Fanray,FanrayMedia/Fanray,FanrayMedia/Fanray
|
src/Fan.Web/Infrastructure/SetupMiddleware.cs
|
src/Fan.Web/Infrastructure/SetupMiddleware.cs
|
using Fan.Settings;
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Fan.Web.Infrastructure
{
/// <summary>
/// Middleware to setup the site.
/// </summary>
public class SetupMiddleware
{
private readonly RequestDelegate _next;
public SetupMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// Invoke middleware to test if setup needs to happen.
/// </summary>
/// <param name="context">The HTTP context</param>
/// <param name="settingService">The settings service</param>
/// <returns>Task</returns>
public async Task Invoke(HttpContext context, ISettingService settingService)
{
var coreSettings = await settingService.GetSettingsAsync<CoreSettings>();
if (!coreSettings.SetupDone)
{
var setupUrl = $"{context.Request.Scheme}://{context.Request.Host}/setup";
var currentUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}";
// don't redirect to setup if url is setup itself or certain types of files
string[] exts = { ".ico", ".js", ".css", ".map" };
if (!currentUrl.Equals(setupUrl, StringComparison.OrdinalIgnoreCase) &&
!exts.Any(ext=> currentUrl.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
{
context.Response.Redirect(setupUrl);
return;
}
}
// no need to setup
await _next(context);
}
}
}
|
using Fan.Settings;
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Fan.Web.Infrastructure
{
/// <summary>
/// Middleware to setup the site.
/// </summary>
public class SetupMiddleware
{
private readonly RequestDelegate _next;
public SetupMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// Invoke middleware to test if setup needs to happen.
/// </summary>
/// <param name="context">The HTTP context</param>
/// <param name="settingService">The settings service</param>
/// <returns>Task</returns>
public async Task Invoke(HttpContext context, ISettingService settingService)
{
var coreSettings = await settingService.GetSettingsAsync<CoreSettings>();
if (!coreSettings.SetupDone)
{
var setupUrl = $"{context.Request.Scheme}://{context.Request.Host}/setup";
var currentUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}";
// skip setup page itself and ico, js, css files
string[] exts = { ".ico", ".js", ".css" };
if (!currentUrl.Equals(setupUrl, StringComparison.OrdinalIgnoreCase) &&
!exts.Any(ext=> currentUrl.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
{
context.Response.Redirect(setupUrl);
return;
}
}
// no need to setup
await _next(context);
}
}
}
|
apache-2.0
|
C#
|
e83f6afdcf6d67a75efb12e2d178ae8fae989a58
|
Add language declaration to layout
|
billboga/fav-rocks
|
src/FavRocks.Site/Views/Shared/_Layout.cshtml
|
src/FavRocks.Site/Views/Shared/_Layout.cshtml
|
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"]–FAV Rocks</title>
<link rel="shortcut icon" href="~/favicon.ico" />
<environment names="Development">
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
@RenderSection("styles", required: false)
</head>
<body>
<header>
<div id="title-container">
<a id="title" asp-controller="Home" asp-action="Index">FAV \m/</a>
<a id="about" asp-controller="About">About</a>
</div>
<h3 id="tagline">The most accessible and efficient favicon editor</h3>
</header>
<hr />
@RenderBody()
<hr />
<footer>
<p>© @DateTimeOffset.Now.Year, <a href="https://www.billboga.com/">Bill Boga</a>.
</footer>
@RenderSection("scripts", required: false)
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"]–FAV Rocks</title>
<link rel="shortcut icon" href="~/favicon.ico" />
<environment names="Development">
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
@RenderSection("styles", required: false)
</head>
<body>
<header>
<div id="title-container">
<a id="title" asp-controller="Home" asp-action="Index">FAV \m/</a>
<a id="about" asp-controller="About">About</a>
</div>
<h3 id="tagline">The most accessible and efficient favicon editor</h3>
</header>
<hr />
@RenderBody()
<hr />
<footer>
<p>© @DateTimeOffset.Now.Year, <a href="https://www.billboga.com/">Bill Boga</a>.
</footer>
@RenderSection("scripts", required: false)
</body>
</html>
|
mit
|
C#
|
260194537dd87f5da2d3be64afa083b404c34f62
|
Fix build
|
janssenr/MyParcelApi.Net
|
src/MyParcelApi.Tests/DeliveryOptionsTests.cs
|
src/MyParcelApi.Tests/DeliveryOptionsTests.cs
|
using System;
using System.Configuration;
using MyParcelApi.Net;
using MyParcelApi.Net.Models;
using NUnit.Framework;
namespace MyParcelApi.Tests
{
[TestFixture]
public class DeliveryOptionsTests
{
private MyParcelApiClient _client;
[SetUp]
public void SetUp()
{
var apiKey = ConfigurationManager.AppSettings["ApiKey"];
_client = new MyParcelApiClient(apiKey);
}
[Test]
public void GetDeliveryOptionsForPostalCodeAndNumberAndCarrier()
{
var response = _client.GetDeliveryOptions("NL", "2132WT", "66", Platform.MyParcel, Carrier.PostNl);
response.Wait();
Assert.IsNotNull(response);
Assert.IsNotNull(response.Result);
Assert.IsTrue(response.Result.DeliveryOptions.Length > 0);
Assert.IsTrue(response.Result.PickupOptions.Length > 0);
}
[Test]
public void GetDeliveryOptionsForPostalCodeAndNumberAndCarrierAndCutoffTimeAndDropoffDaysAndDropoffDelayAndDeliverydaysWindowAndDeliveryType()
{
var response = _client.GetDeliveryOptions("NL", "2132WT", "66", Platform.MyParcel, Carrier.PostNl, cutoffTime: new TimeSpan(16, 0, 0), dropoffDays: new [] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }, dropoffDelay: 0, deliverydaysWindow: 2, excludeDeliveryType: new[] { DeliveryType.Morning });
response.Wait();
Assert.IsNotNull(response);
Assert.IsNotNull(response.Result);
Assert.IsTrue(response.Result.DeliveryOptions.Length > 0);
Assert.IsTrue(response.Result.PickupOptions.Length > 0);
}
}
}
|
using System;
using System.Configuration;
using MyParcelApi.Net;
using MyParcelApi.Net.Models;
using NUnit.Framework;
namespace MyParcelApi.Tests
{
[TestFixture]
public class DeliveryOptionsTests
{
private MyParcelApiClient _client;
[SetUp]
public void SetUp()
{
var apiKey = ConfigurationManager.AppSettings["ApiKey"];
_client = new MyParcelApiClient(apiKey);
}
[Test]
public void GetDeliveryOptionsForPostalCodeAndNumberAndCarrier()
{
var response = _client.GetDeliveryOptions("NL", "2132WT", "66", Carrier.PostNl);
response.Wait();
Assert.IsNotNull(response);
Assert.IsNotNull(response.Result);
Assert.IsTrue(response.Result.DeliveryOptions.Length > 0);
Assert.IsTrue(response.Result.PickupOptions.Length > 0);
}
[Test]
public void GetDeliveryOptionsForPostalCodeAndNumberAndCarrierAndCutoffTimeAndDropoffDaysAndDropoffDelayAndDeliverydaysWindowAndDeliveryType()
{
var response = _client.GetDeliveryOptions("NL", "2132WT", "66", Carrier.PostNl, cutoffTime: new TimeSpan(16, 0, 0), dropoffDays: new [] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }, dropoffDelay: 0, deliverydaysWindow: 2, excludeDeliveryType: new[] { DeliveryType.Morning });
response.Wait();
Assert.IsNotNull(response);
Assert.IsNotNull(response.Result);
Assert.IsTrue(response.Result.DeliveryOptions.Length > 0);
Assert.IsTrue(response.Result.PickupOptions.Length > 0);
}
}
}
|
mit
|
C#
|
f33c71b0824f8a329442f7272acce95a2c3f3963
|
Set port 7400 and use default WebHost builder
|
barnardos-au/Neo4jManager
|
src/Neo4jManager/Neo4jManager.Host/Program.cs
|
src/Neo4jManager/Neo4jManager.Host/Program.cs
|
using System.IO;
using System.Net;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace Neo4jManager.Host
{
public class Program
{
public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => options.Listen(IPAddress.Loopback, 7400))
.ConfigureServices(services => services.AddAutofac())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
|
using System.IO;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
namespace Neo4jManager.Host
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services => services.AddAutofac())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
|
mit
|
C#
|
3ba0d0ff07eceafdd954ee3642917900ca5d8b5e
|
Add search link. Closes #37
|
sixteencolors/Pablo.Gallery,sixteencolors/Pablo.Gallery,sixteencolors/Pablo.Gallery,sixteencolors/Pablo.Gallery
|
src/Pablo.Gallery/Views/Shared/_Layout.cshtml
|
src/Pablo.Gallery/Views/Shared/_Layout.cshtml
|
@using System.Web.Configuration
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewBag.Title - @WebConfigurationManager.AppSettings["ApplicationNameLong"]</title>
@Styles.Render("~/Content/css")
</head>
<body>
@{
var controllerName = ViewContext.Controller.GetType().Name;
var suffix = "Controller";
if (controllerName.EndsWith(suffix)) {
controllerName = controllerName.Substring(0, controllerName.Length - suffix.Length);
}
var viewName = System.IO.Path.GetFileNameWithoutExtension(((RazorView)Html.ViewContext.View).ViewPath);
var pageClass = string.Format("page-{0}-{1}", controllerName, viewName).ToLowerInvariant();
ViewBag.ShowNav = ViewBag.ShowNav ?? true;
}
@if (ViewBag.ShowNav) {
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink(WebConfigurationManager.AppSettings["ApplicationNameLong"], "Index", "Home", null, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Packs", "Index", "Year")</li>
<li>@Html.ActionLink("Search", "Index", "File")</li>
@if (User.IsInRole("admin")) {
<li>@Html.ActionLink("Scanner", "Index", "Scanner")</li>
}
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
}
@RenderSection("SecondaryHeader", required: false)
<div class="container body-content @pageClass">
@RenderBody()
<div style="clear:both"></div>
</div>
@if (ViewBag.ShowNav) {
<footer>
<div class="container">@WebConfigurationManager.AppSettings["ApplicationNameShort"] Pablo Gallery</div>
</footer>
}
@Scripts.Render("~/bundles/js")
@Html.PageScripts()
@RenderSection("scripts", required: false)
</body>
</html>
|
@using System.Web.Configuration
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewBag.Title - @WebConfigurationManager.AppSettings["ApplicationNameLong"]</title>
@Styles.Render("~/Content/css")
</head>
<body>
@{
var controllerName = ViewContext.Controller.GetType().Name;
var suffix = "Controller";
if (controllerName.EndsWith(suffix)) {
controllerName = controllerName.Substring(0, controllerName.Length - suffix.Length);
}
var viewName = System.IO.Path.GetFileNameWithoutExtension(((RazorView)Html.ViewContext.View).ViewPath);
var pageClass = string.Format("page-{0}-{1}", controllerName, viewName).ToLowerInvariant();
ViewBag.ShowNav = ViewBag.ShowNav ?? true;
}
@if (ViewBag.ShowNav) {
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink(WebConfigurationManager.AppSettings["ApplicationNameLong"], "Index", "Home", null, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Packs", "Index", "Year")</li>
@if (User.IsInRole("admin")) {
<li>@Html.ActionLink("Scanner", "Index", "Scanner")</li>
}
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
}
@RenderSection("SecondaryHeader", required: false)
<div class="container body-content @pageClass">
@RenderBody()
<div style="clear:both"></div>
</div>
@if (ViewBag.ShowNav) {
<footer>
<div class="container">@WebConfigurationManager.AppSettings["ApplicationNameShort"] Pablo Gallery</div>
</footer>
}
@Scripts.Render("~/bundles/js")
@Html.PageScripts()
@RenderSection("scripts", required: false)
</body>
</html>
|
mit
|
C#
|
6a82406caf76ec1033b4f72303fe4e1f9e8dacd8
|
Update ProfilerHelper
|
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
|
src/WeihanLi.Common/Helpers/ProfilerHelper.cs
|
src/WeihanLi.Common/Helpers/ProfilerHelper.cs
|
using System.Diagnostics;
namespace WeihanLi.Common.Helpers;
public sealed class ProfilerStopper : IDisposable
{
private readonly IProfiler _profiler;
private readonly Action<TimeSpan> _profileAction;
public ProfilerStopper(IProfiler profiler, Action<TimeSpan> profileAction)
{
_profiler = profiler ?? throw new ArgumentNullException(nameof(profiler));
_profileAction = profileAction ?? throw new ArgumentNullException(nameof(profileAction));
}
public void Dispose()
{
_profiler.Stop();
_profileAction(_profiler.Elapsed);
}
}
public sealed class StopwatchStopper : IDisposable
{
private readonly Stopwatch _stopwatch;
private readonly Action<TimeSpan> _profileAction;
public StopwatchStopper(Stopwatch stopwatch, Action<TimeSpan> profileAction)
{
_stopwatch = stopwatch ?? throw new ArgumentNullException(nameof(stopwatch));
_profileAction = profileAction ?? throw new ArgumentNullException(nameof(profileAction));
}
public void Dispose()
{
_stopwatch.Stop();
_profileAction(_stopwatch.Elapsed);
}
}
public static class ProfilerHelper
{
public static StopwatchStopper Profile(this Stopwatch watch, Action<TimeSpan> profilerAction)
{
Guard.NotNull(watch, nameof(watch)).Restart();
return new StopwatchStopper(watch, profilerAction);
}
public static ProfilerStopper StartNew(this IProfiler profiler, Action<TimeSpan> profilerAction)
{
Guard.NotNull(profiler, nameof(profiler)).Restart();
return new ProfilerStopper(profiler, profilerAction);
}
public static readonly double TicksPerTimestamp = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
/// <summary>
/// GetElapsedTime
/// </summary>
/// <param name="startTimestamp">startTimestamp, get by Stopwatch.GetTimestamp()</param>
/// <returns>elapsed timespan</returns>
public static TimeSpan GetElapsedTime(long startTimestamp) =>
#if NET7_0_OR_GREATER
Stopwatch.GetElapsedTime(startTimestamp)
#else
GetElapsedTime(startTimestamp, Stopwatch.GetTimestamp())
#endif
;
/// <summary>
/// GetElapsedTime
/// </summary>
/// <param name="startTimestamp">startTimestamp, get by Stopwatch.GetTimestamp()</param>
/// <param name="endTimestamp">endTimestamp, get by Stopwatch.GetTimestamp</param>
/// <returns>elapsed timespan</returns>
public static TimeSpan GetElapsedTime(long startTimestamp, long endTimestamp)
{
#if NET7_0_OR_GREATER
return Stopwatch.GetElapsedTime(startTimestamp, endTimestamp);
#else
var ticks = (long)((endTimestamp - startTimestamp) * TicksPerTimestamp);
return new TimeSpan(ticks);
#endif
}
}
|
using System.Diagnostics;
namespace WeihanLi.Common.Helpers;
public sealed class ProfilerStopper : IDisposable
{
private readonly IProfiler _profiler;
private readonly Action<TimeSpan> _profileAction;
public ProfilerStopper(IProfiler profiler, Action<TimeSpan> profileAction)
{
_profiler = profiler ?? throw new ArgumentNullException(nameof(profiler));
_profileAction = profileAction ?? throw new ArgumentNullException(nameof(profileAction));
}
public void Dispose()
{
_profiler.Stop();
_profileAction(_profiler.Elapsed);
}
}
public sealed class StopwatchStopper : IDisposable
{
private readonly Stopwatch _stopwatch;
private readonly Action<TimeSpan> _profileAction;
public StopwatchStopper(Stopwatch stopwatch, Action<TimeSpan> profileAction)
{
_stopwatch = stopwatch ?? throw new ArgumentNullException(nameof(stopwatch));
_profileAction = profileAction ?? throw new ArgumentNullException(nameof(profileAction));
}
public void Dispose()
{
_stopwatch.Stop();
_profileAction(_stopwatch.Elapsed);
}
}
public static class ProfilerHelper
{
public static StopwatchStopper Profile(this Stopwatch watch, Action<TimeSpan> profilerAction)
{
Guard.NotNull(watch, nameof(watch)).Restart();
return new StopwatchStopper(watch, profilerAction);
}
public static ProfilerStopper StartNew(this IProfiler profiler, Action<TimeSpan> profilerAction)
{
Guard.NotNull(profiler, nameof(profiler)).Restart();
return new ProfilerStopper(profiler, profilerAction);
}
public static readonly double TicksPerTimestamp = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
/// <summary>
/// GetElapsedTime
/// </summary>
/// <param name="startTimestamp">startTimestamp, get by Stopwatch.GetTimestamp()</param>
/// <returns>elapsed timespan</returns>
public static TimeSpan GetElapsedTime(long startTimestamp) =>
GetElapsedTime(startTimestamp, Stopwatch.GetTimestamp());
/// <summary>
/// GetElapsedTime
/// </summary>
/// <param name="startTimestamp">startTimestamp, get by Stopwatch.GetTimestamp()</param>
/// <param name="endTimestamp">endTimestamp, get by Stopwatch.GetTimestamp</param>
/// <returns>elapsed timespan</returns>
public static TimeSpan GetElapsedTime(long startTimestamp, long endTimestamp)
{
var ticks = (long)((endTimestamp - startTimestamp) * TicksPerTimestamp);
return new TimeSpan(ticks);
}
}
|
mit
|
C#
|
8afac251209cf0940d5338993bbc26394a5098ce
|
Add params modifier on override
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
csharp/extractor/Semmle.Util/LoggerUtils.cs
|
csharp/extractor/Semmle.Util/LoggerUtils.cs
|
using System;
using System.IO;
using System.Diagnostics;
namespace Semmle.Util
{
/// <summary>
/// Utility stream writer that prefixes the current PID to some writes.
/// Useful to disambiguate logs belonging to different extractor processes
/// that end up in the same place (csharp.log). Does a best-effort attempt
/// (i.e. only overrides one of the overloaded methods, calling the others
/// may print without a prefix).
/// </summary>
public sealed class PidStreamWriter : StreamWriter
{
/// <summary>
/// Constructs with output stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
public PidStreamWriter(Stream stream) : base(stream) { }
private readonly string prefix = "[" + Process.GetCurrentProcess().Id + "] ";
public override void WriteLine(string? value)
{
lock (mutex)
{
base.WriteLine(prefix + value);
}
}
public override void WriteLine(string? format, params object?[] args)
{
WriteLine(format is null ? format : String.Format(format, args));
}
private readonly object mutex = new object();
}
}
|
using System;
using System.IO;
using System.Diagnostics;
namespace Semmle.Util
{
/// <summary>
/// Utility stream writer that prefixes the current PID to some writes.
/// Useful to disambiguate logs belonging to different extractor processes
/// that end up in the same place (csharp.log). Does a best-effort attempt
/// (i.e. only overrides one of the overloaded methods, calling the others
/// may print without a prefix).
/// </summary>
public sealed class PidStreamWriter : StreamWriter
{
/// <summary>
/// Constructs with output stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
public PidStreamWriter(Stream stream) : base(stream) { }
private readonly string prefix = "[" + Process.GetCurrentProcess().Id + "] ";
public override void WriteLine(string? value)
{
lock (mutex)
{
base.WriteLine(prefix + value);
}
}
public override void WriteLine(string? value, object?[] args)
{
WriteLine(value is null ? value : String.Format(value, args));
}
private readonly object mutex = new object();
}
}
|
mit
|
C#
|
2c1e9b4d0fa5a0b49a7a9b97b07292f2f1fb4117
|
Fix some details of the event object
|
haithemaraissia/XamarinStripe,xamarin/XamarinStripe
|
XamarinStripe/StripeEvent.cs
|
XamarinStripe/StripeEvent.cs
|
/*
* Copyright 2012 Xamarin, 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace Xamarin.Payments.Stripe {
public class StripeEvent : StripeObject {
[JsonProperty (PropertyName = "livemode")]
public bool LiveMode { get; set; }
[JsonProperty (PropertyName = "created")]
[JsonConverter (typeof (UnixDateTimeConverter))]
public DateTime? Created { get; set; }
[JsonProperty (PropertyName = "type")]
public string Type { get; set; }
[JsonProperty (PropertyName= "data")]
public EventData Data { get; set; }
public class EventData {
[JsonProperty (PropertyName = "object")]
[JsonConverter (typeof (StripeObjectConverter))]
public StripeObject Object { get; set; }
[JsonProperty (PropertyName = "previous_attributes")]
public JObject PreviousAttributes { get; set; }
}
}
}
|
/*
* Copyright 2012 Xamarin, 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Dynamic;
using Newtonsoft.Json.Linq;
namespace Xamarin.Payments.Stripe {
public class StripeEvent : StripeObject {
[JsonProperty (PropertyName = "livemode")]
bool LiveMode { get; set; }
[JsonProperty (PropertyName = "created")]
[JsonConverter (typeof (UnixDateTimeConverter))]
public DateTime? Created { get; set; }
[JsonProperty (PropertyName = "type")]
public string type { get; set; }
[JsonProperty (PropertyName= "data")]
public EventData Data { get; set; }
public class EventData {
[JsonProperty (PropertyName = "object")]
[JsonConverter (typeof (StripeObjectConverter))]
public StripeObject Object { get; set; }
}
}
}
|
apache-2.0
|
C#
|
28be1e96f493480b00de219a8b75d79c4a1a565d
|
Make JSON SQL builders public
|
henkmollema/Dommel
|
src/Dommel.Json/IJsonSqlBuilder.cs
|
src/Dommel.Json/IJsonSqlBuilder.cs
|
namespace Dommel.Json
{
/// <summary>
/// Extends the <see cref="DommelMapper.ISqlBuilder"/> with support for
/// creating JSON value expressions.
/// </summary>
public interface IJsonSqlBuilder : DommelMapper.ISqlBuilder
{
/// <summary>
/// Creates a JSON value expression for the specified <paramref name="column"/> and <paramref name="path"/>.
/// </summary>
/// <param name="column">The column which contains the JSON data.</param>
/// <param name="path">The path of the JSON value to query.</param>
/// <returns>A JSON value expression.</returns>
string JsonValue(string column, string path);
}
/// <summary>
/// JSON SQL builder for SQL server.
/// </summary>
public class SqlServerSqlBuilder : DommelMapper.SqlServerSqlBuilder, IJsonSqlBuilder
{
/// <inheritdoc />
public string JsonValue(string column, string path) => $"JSON_VALUE({column}, '$.{path}')";
}
/// <summary>
/// JSON SQL builder for MySQL.
/// </summary>
public class MySqlSqlBuilder : DommelMapper.MySqlSqlBuilder, IJsonSqlBuilder
{
/// <inheritdoc />
public string JsonValue(string column, string path) => $"{column}->'$.{path}'";
}
/// <summary>
/// JSON SQL builder for PostgreSQL.
/// </summary>
public class PostgresSqlBuiler : DommelMapper.PostgresSqlBuilder, IJsonSqlBuilder
{
/// <inheritdoc />
public string JsonValue(string column, string path) => $"{column}->>'{path}'";
}
/// <summary>
/// JSON SQL builder for SQLite.
/// </summary>
public class SqliteSqlBuilder : DommelMapper.SqliteSqlBuilder, IJsonSqlBuilder
{
/// <inheritdoc />
public string JsonValue(string column, string path) => $"JSON_EXTRACT({column}, '$.{path}')";
}
/// <summary>
/// JSON SQL builder for SQL Server CE.
/// </summary>
public class SqlServerCeSqlBuilder : DommelMapper.SqlServerCeSqlBuilder, IJsonSqlBuilder
{
/// <inheritdoc />
public string JsonValue(string column, string path) => $"JSON_VALUE({column}, '$.{path}')";
}
}
|
namespace Dommel.Json
{
/// <summary>
/// Extends the <see cref="DommelMapper.ISqlBuilder"/> with support for
/// creating JSON value expressions.
/// </summary>
public interface IJsonSqlBuilder : DommelMapper.ISqlBuilder
{
/// <summary>
/// Creates a JSON value expression for the specified <paramref name="column"/> and <paramref name="path"/>.
/// </summary>
/// <param name="column">The column which contains the JSON data.</param>
/// <param name="path">The path of the JSON value to query.</param>
/// <returns>A JSON value expression.</returns>
string JsonValue(string column, string path);
}
internal class SqlServerSqlBuilder : DommelMapper.SqlServerSqlBuilder, IJsonSqlBuilder
{
public string JsonValue(string column, string path) => $"JSON_VALUE({column}, '$.{path}')";
}
internal class MySqlSqlBuilder : DommelMapper.MySqlSqlBuilder, IJsonSqlBuilder
{
public string JsonValue(string column, string path) => $"{column}->'$.{path}'";
}
internal class PostgresSqlBuiler : DommelMapper.PostgresSqlBuilder, IJsonSqlBuilder
{
public string JsonValue(string column, string path) => $"{column}->>'{path}'";
}
internal class SqliteSqlBuilder : DommelMapper.SqliteSqlBuilder, IJsonSqlBuilder
{
public string JsonValue(string column, string path) => $"JSON_EXTRACT({column}, '$.{path}')";
}
internal class SqlServerCeSqlBuilder : DommelMapper.SqlServerCeSqlBuilder, IJsonSqlBuilder
{
public string JsonValue(string column, string path) => $"JSON_VALUE({column}, '$.{path}')";
}
}
|
mit
|
C#
|
40e29673e39796f20a773d670726317cadc8d48b
|
allow users to leave a closed room
|
mogulTest1/Project13171106,mzdv/JabbR,mogultest2/Project92109,mogultest2/Project13171008,mogulTest1/Project13161127,mogulTest1/Project13161127,M-Zuber/JabbR,mogulTest1/ProjectJabbr01,mogultest2/Project13231008,M-Zuber/JabbR,timgranstrom/JabbR,mogulTest1/Project91105,e10/JabbR,MogulTestOrg1008/Project13221008,mogulTest1/Project13231212,mogulTest1/Project13171024,MogulTestOrg9221/Project92108,mogulTest1/Project13171106,mogultest2/Project13171210,mogulTest1/Project91409,Org1106/Project13221113,aapttester/jack12051317,v-mohua/TestProject91001,fuzeman/vox,mogulTest1/Project91404,lukehoban/JabbR,MogulTestOrg/JabbrApp,fuzeman/vox,mogulTest1/Project13231205,mogulTest1/Project13171205,mogulTest1/MogulVerifyIssue5,mogulTest1/Project91009,ClarkL/test09jabbr,mogulTest1/Project13171109,mogulTest1/ProjectfoIssue6,mogulTest1/ProjectfoIssue6,timgranstrom/JabbR,mogulTest1/Project13171205,mogultest2/Project13171010,mogulTest1/Project13231212,mogulTest1/Project13231213,mogulTest1/Project13171109,MogulTestOrg911/Project91104,huanglitest/JabbRTest2,ClarkL/1323on17jabbr-,yadyn/JabbR,mogulTest1/Project13231109,ClarkL/test09jabbr,mogulTest1/Project13171113,LookLikeAPro/JabbR,mogultest2/Project92105,mogulTest1/Project13171009,clarktestkudu1029/test08jabbr,kudutest/FaizJabbr,Createfor1322/jessica0122-1322,ClarkL/1323on17jabbr-,mogulTest1/Project13171009,aapttester/jack12051317,mogulTest1/Project91409,meebey/JabbR,mogulTest1/Project91009,mogultest2/Project92104,18098924759/JabbR,mogultest2/Project13231008,Org1106/Project13221106,mogulTest1/Project13231109,ClarkL/new09,huanglitest/JabbRTest2,mogultest2/Project13171210,MogulTestOrg914/Project91407,mogultest2/Project13171010,fuzeman/vox,mogultest2/Project92104,ajayanandgit/JabbR,lukehoban/JabbR,MogulTestOrg2/JabbrApp,LookLikeAPro/JabbR,18098924759/JabbR,mogulTest1/ProjectVerify912,Org1106/Project13221113,SonOfSam/JabbR,KuduApps/TestDeploy123,CrankyTRex/JabbRMirror,kudutest/FaizJabbr,MogulTestOrg9221/Project92108,ClarkL/1317on17jabbr,test0925/test0925,mogulTest1/Project13231113,CrankyTRex/JabbRMirror,meebey/JabbR,mogulTest1/MogulVerifyIssue5,mogulTest1/Project91101,mogulTest1/Project13231113,mogultest2/Project92105,mogulTest1/ProjectVerify912,ajayanandgit/JabbR,KuduApps/TestDeploy123,MogulTestOrg1008/Project13221008,huanglitest/JabbRTest2,LookLikeAPro/JabbR,mogulTest1/ProjectJabbr01,ClarkL/1317on17jabbr,mogulTest1/Project91105,mogulTest1/Project13231106,borisyankov/JabbR,mogulTest1/Project13231106,Createfor1322/jessica0122-1322,mogulTest1/Project90301,MogulTestOrg/JabbrApp,meebey/JabbR,ClarkL/new1317,mogulTest1/Project13231205,MogulTestOrg911/Project91104,mogulTest1/Project90301,clarktestkudu1029/test08jabbr,MogulTestOrg914/Project91407,test0925/test0925,AAPT/jean0226case1322,mogultest2/Project92109,borisyankov/JabbR,yadyn/JabbR,mogulTest1/Project13231213,mogulTest1/Project13171113,MogulTestOrg2/JabbrApp,Org1106/Project13221106,JabbR/JabbR,mogultest2/Project13171008,mogulTest1/Project91404,mzdv/JabbR,ClarkL/new09,ClarkL/new1317,e10/JabbR,v-mohua/TestProject91001,mogulTest1/Project13171024,CrankyTRex/JabbRMirror,yadyn/JabbR,JabbR/JabbR,mogulTest1/Project91101,lukehoban/JabbR,SonOfSam/JabbR,AAPT/jean0226case1322,borisyankov/JabbR
|
JabbR/Commands/LeaveCommand.cs
|
JabbR/Commands/LeaveCommand.cs
|
using System.Web;
using JabbR.Models;
namespace JabbR.Commands
{
[Command("leave", "")]
public class LeaveCommand : UserCommand
{
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args)
{
ChatRoom room = null;
if (args.Length == 0)
{
room = context.Repository.VerifyUserRoom(context.Cache, callingUser, callerContext.RoomName);
}
else
{
string roomName = HttpUtility.HtmlDecode(args[0]);
room = context.Repository.VerifyRoom(roomName, mustBeOpen: false);
}
context.Service.LeaveRoom(callingUser, room);
context.NotificationService.LeaveRoom(callingUser, room);
context.Repository.CommitChanges();
}
}
}
|
using System.Web;
using JabbR.Models;
namespace JabbR.Commands
{
[Command("leave", "")]
public class LeaveCommand : UserCommand
{
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args)
{
ChatRoom room = null;
if (args.Length == 0)
{
room = context.Repository.VerifyUserRoom(context.Cache, callingUser, callerContext.RoomName);
}
else
{
string roomName = HttpUtility.HtmlDecode(args[0]);
room = context.Repository.VerifyRoom(roomName);
}
context.Service.LeaveRoom(callingUser, room);
context.NotificationService.LeaveRoom(callingUser, room);
context.Repository.CommitChanges();
}
}
}
|
mit
|
C#
|
3f2c1338d565848a811ae640ed5e5542cde8ea0e
|
remove unused using statements
|
peasy/Samples,peasy/Peasy.NET,ahanusa/Peasy.NET,peasy/Samples,peasy/Samples,ahanusa/facile.net
|
Orders.com.BLL/OrderService.cs
|
Orders.com.BLL/OrderService.cs
|
using Facile.Core;
using Orders.com.Core.DataProxy;
using Orders.com.Core.Domain;
using Orders.com.Core.QueryData;
using System;
using System.Collections.Generic;
namespace Orders.com.BLL
{
public class OrderService : OrdersDotComServiceBase<Order>
{
private InventoryItemService _inventoryService;
private OrderItemService _orderItemService;
public OrderService(IOrderDataProxy dataProxy, OrderItemService orderItemService, InventoryItemService inventoryService) : base(dataProxy)
{
_inventoryService = inventoryService;
_orderItemService = orderItemService;
}
protected override void OnBeforeInsertCommandExecuted(Order entity)
{
entity.OrderDate = DateTime.Now;
}
public ICommand<IEnumerable<OrderInfo>> GetAllCommand(int start, int pageSize)
{
var proxy = DataProxy as IOrderDataProxy;
return new ServiceCommand<IEnumerable<OrderInfo>>
(
executeMethod: () => proxy.GetAll(start, pageSize),
executeAsyncMethod: () => proxy.GetAllAsync(start, pageSize)
);
}
public override ICommand DeleteCommand(long id)
{
//TODO: create a DeleteOrderCommand that takes OrderService and OrderItemService, and return that command here
return base.DeleteCommand(id);
}
}
}
|
using Facile.Core;
using Orders.com.BLL.Rules;
using Orders.com.Core.DataProxy;
using Orders.com.Core.Domain;
using Orders.com.Core.Extensions;
using Orders.com.Core.QueryData;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Orders.com.BLL
{
public class OrderService : OrdersDotComServiceBase<Order>
{
private InventoryItemService _inventoryService;
private OrderItemService _orderItemService;
public OrderService(IOrderDataProxy dataProxy, OrderItemService orderItemService, InventoryItemService inventoryService) : base(dataProxy)
{
_inventoryService = inventoryService;
_orderItemService = orderItemService;
}
protected override void OnBeforeInsertCommandExecuted(Order entity)
{
entity.OrderDate = DateTime.Now;
}
public ICommand<IEnumerable<OrderInfo>> GetAllCommand(int start, int pageSize)
{
var proxy = DataProxy as IOrderDataProxy;
return new ServiceCommand<IEnumerable<OrderInfo>>
(
executeMethod: () => proxy.GetAll(start, pageSize),
executeAsyncMethod: () => proxy.GetAllAsync(start, pageSize)
);
}
public override ICommand DeleteCommand(long id)
{
//TODO: create a DeleteOrderCommand that takes OrderService and OrderItemService, and return that command here
return base.DeleteCommand(id);
}
}
}
|
mit
|
C#
|
087fb87572a9a2a6da13e4cf9e9962225230c45d
|
Update version
|
Solybum/Libraries
|
ByteArray/ByteArray/Properties/AssemblyInfo.cs
|
ByteArray/ByteArray/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ByteArray")]
[assembly: AssemblyDescription("Wrapper to ease data type conversions to and from byte arrays")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ByteArray")]
[assembly: AssemblyCopyright("Copyright © Soleil Rojas 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0022ee24-1361-41c8-982b-5b0215834234")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ByteArray")]
[assembly: AssemblyDescription("Wrapper to ease data type conversions to and from byte arrays")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ByteArray")]
[assembly: AssemblyCopyright("Copyright © Soleil Rojas 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0022ee24-1361-41c8-982b-5b0215834234")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
mit
|
C#
|
24d3b0b342fe49901ce3664691d39b1bdb5e4f89
|
remove unused function from utils.cs
|
smurfpandey/sendgrid-csharp-net40,dubrovkinmaxim/sendgrid-csharp,brcaswell/sendgrid-csharp,sumeshthomas/sendgrid-csharp,pandeysoni/sendgrid-csharp,sumeshthomas/sendgrid-csharp,kenlefeb/sendgrid-csharp,dubrovkinmaxim/sendgrid-csharp,smurfpandey/sendgrid-csharp-net40,sendgrid/sendgrid-csharp,FriskyLingo/sendgrid-csharp,sendgrid/sendgrid-csharp,pandeysoni/sendgrid-csharp,kenlefeb/sendgrid-csharp,FriskyLingo/sendgrid-csharp,brcaswell/sendgrid-csharp,sendgrid/sendgrid-csharp
|
SendGrid/SendGridMail/Utils.cs
|
SendGrid/SendGridMail/Utils.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.Serialization.Json;
using System.Text;
namespace SendGridMail
{
public class Utils
{
public static string Serialize<T>(T obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
var jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
return jsonData;
}
}
public static string SerializeDictionary(IDictionary<String, String> dic)
{
return "{"+String.Join(",",dic.Select(kvp => Serialize(kvp.Key) + ":" + Serialize(kvp.Value)))+"}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.Serialization.Json;
using System.Text;
namespace SendGridMail
{
public class Utils
{
public static string Serialize<T>(T obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
var jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
return jsonData;
}
}
public static string SerializeDictionary(IDictionary<String, String> dic)
{
return "{"+String.Join(",",dic.Select(kvp => Serialize(kvp.Key) + ":" + Serialize(kvp.Value)))+"}";
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}
|
mit
|
C#
|
a47de530585cc60209761caa6f96d4288323e14e
|
copy documentation from solr wiki
|
chang892886597/SolrNet,erandr/SolrNet,vyzvam/SolrNet,mausch/SolrNet,yonglehou/SolrNet,Laoujin/SolrNet,erandr/SolrNet,doss78/SolrNet,18098924759/SolrNet,doss78/SolrNet,vladen/SolrNet,vyzvam/SolrNet,vmanral/SolrNet,yonglehou/SolrNet,vyzvam/SolrNet,yonglehou/SolrNet,MetSystem/SolrNet,tombeany/SolrNet,SolrNet/SolrNet,18098924759/SolrNet,mausch/SolrNet,MetSystem/SolrNet,tombeany/SolrNet,chang892886597/SolrNet,erandr/SolrNet,Laoujin/SolrNet,erandr/SolrNet,chang892886597/SolrNet,vmanral/SolrNet,mausch/SolrNet,18098924759/SolrNet,drakeh/SolrNet,drakeh/SolrNet,vladen/SolrNet,Laoujin/SolrNet,doss78/SolrNet,vmanral/SolrNet,MetSystem/SolrNet,drakeh/SolrNet,vladen/SolrNet,SolrNet/SolrNet,tombeany/SolrNet,vladen/SolrNet
|
SolrNet/SolrFacetFieldQuery.cs
|
SolrNet/SolrFacetFieldQuery.cs
|
using System.Collections.Generic;
namespace SolrNet {
public class SolrFacetFieldQuery : ISolrFacetQuery {
private readonly string field;
public SolrFacetFieldQuery(string field) {
this.field = field;
}
/// <summary>
/// Limits the terms on which to facet to those starting with the given string prefix.
/// </summary>
public string Prefix { get; set; }
/// <summary>
/// Set to true, this parameter indicates that constraints should be sorted by their count.
/// If false, facets will be in their natural index order (unicode).
/// For terms in the ascii range, this will be alphabetically sorted.
/// The default is true if Limit is greater than 0, false otherwise.
/// </summary>
public bool? Sort { get; set; }
/// <summary>
/// This param indicates the maximum number of constraint counts that should be returned for the facet fields.
/// A negative value means unlimited.
/// The default value is 100.
/// </summary>
public int? Limit { get; set; }
/// <summary>
/// This param indicates an offset into the list of constraints to allow paging.
/// The default value is 0.
/// </summary>
public int? Offset { get; set; }
/// <summary>
/// This param indicates the minimum counts for facet fields should be included in the response.
/// The default value is 0.
/// </summary>
public int? MinCount { get; set; }
/// <summary>
/// Set to true this param indicates that in addition to the Term based constraints of a facet field, a count of all matching results which have no value for the field should be computed
/// Default is false
/// </summary>
public bool? Missing { get; set; }
/// <summary>
/// This param indicates the minimum document frequency (number of documents matching a term) for which the filterCache should be used when determining the constraint count for that term.
/// This is only used during the term enumeration method of faceting (field type faceting on multi-valued or full-text fields).
/// A value greater than zero will decrease memory usage of the filterCache, but increase the query time.
/// When faceting on a field with a very large number of terms, and you wish to decrease memory usage, try a low value of 25 to 50 first.
/// The default value is 0, causing the filterCache to be used for all terms in the field.
/// </summary>
public int? EnumCacheMinDf { get; set; }
public IEnumerable<KeyValuePair<string, string>> Query {
get {
var r = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("facet.field", field)
};
if (Prefix != null)
r.Add(new KeyValuePair<string, string>("facet.prefix", Prefix));
if (Sort.HasValue)
r.Add(new KeyValuePair<string, string>("facet.sort", Sort.ToString().ToLowerInvariant()));
if (Limit.HasValue)
r.Add(new KeyValuePair<string, string>("facet.limit", Limit.ToString()));
if (Offset.HasValue)
r.Add(new KeyValuePair<string, string>("facet.offset", Offset.ToString()));
if (MinCount.HasValue)
r.Add(new KeyValuePair<string, string>("facet.mincount", MinCount.ToString()));
if (EnumCacheMinDf.HasValue)
r.Add(new KeyValuePair<string, string>("facet.enum.cache.minDf", EnumCacheMinDf.ToString()));
return r;
}
}
}
}
|
using System.Collections.Generic;
namespace SolrNet {
public class SolrFacetFieldQuery : ISolrFacetQuery {
private readonly string field;
public SolrFacetFieldQuery(string field) {
this.field = field;
}
public string Prefix { get; set; }
public bool? Sort { get; set; }
public int? Limit { get; set; }
public int? Offset { get; set; }
public int? MinCount { get; set; }
public bool? Missing { get; set; }
public int? EnumCacheMinDf { get; set; }
public IEnumerable<KeyValuePair<string, string>> Query {
get {
var r = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("facet.field", field)
};
if (Prefix != null)
r.Add(new KeyValuePair<string, string>("facet.prefix", Prefix));
if (Sort.HasValue)
r.Add(new KeyValuePair<string, string>("facet.sort", Sort.ToString().ToLowerInvariant()));
if (Limit.HasValue)
r.Add(new KeyValuePair<string, string>("facet.limit", Limit.ToString()));
if (Offset.HasValue)
r.Add(new KeyValuePair<string, string>("facet.offset", Offset.ToString()));
if (MinCount.HasValue)
r.Add(new KeyValuePair<string, string>("facet.mincount", MinCount.ToString()));
if (EnumCacheMinDf.HasValue)
r.Add(new KeyValuePair<string, string>("facet.enum.cache.minDf", EnumCacheMinDf.ToString()));
return r;
}
}
}
}
|
apache-2.0
|
C#
|
a950f2034eceaff0d2ffd48046e45e52324c9994
|
Set OptimizeJoins default value to false.
|
jogibear9988/linq2db,genusP/linq2db,jogibear9988/linq2db,lvaleriu/linq2db,linq2db/linq2db,sdanyliv/linq2db,MaceWindu/linq2db,lvaleriu/linq2db,linq2db/linq2db,ronnyek/linq2db,sdanyliv/linq2db,genusP/linq2db,MaceWindu/linq2db,LinqToDB4iSeries/linq2db,enginekit/linq2db,LinqToDB4iSeries/linq2db
|
Source/Common/Configuration.cs
|
Source/Common/Configuration.cs
|
using System;
namespace LinqToDB.Common
{
public static class Configuration
{
public static bool IsStructIsScalarType = true;
public static bool AvoidSpecificDataProviderAPI;
public static class Linq
{
public static bool PreloadGroups;
public static bool IgnoreEmptyUpdate;
public static bool AllowMultipleQuery;
public static bool GenerateExpressionTest;
public static bool TraceMapperExpression;
public static bool DoNotClearOrderBys;
public static bool OptimizeJoins;
/// <summary>
/// If set to true unllable fields would be checked for IS NULL when comparasion type is NotEqual
/// <example>
/// public class MyEntity
/// {
/// public int? Value;
/// }
///
/// db.MyEntity.Where(e => e.Value != 10)
///
/// Would be converted to
///
/// SELECT Value FROM MyEntity WHERE Value IS NULL OR Value != 10
/// </example>
/// </summary>
public static bool CheckNullForNotEquals = true;
/// <summary>
/// Prevents to use constructions like q.GroupBy(_ => _.SomeValue) which leads to unexpected behaviour.
/// </summary>
/// <remarks>
/// https://github.com/linq2db/linq2db/issues/365
/// </remarks>
public static bool GuardGrouping = false;
/// <summary>
/// Experimental
/// Used to optimize big logical operations with great number of operands like expr1.and.axpr2...and.exprN into to one <see cref="LinqToDB.Expressions.BinaryAggregateExpression"/>.
/// This saves from deep recursion in visitors.
/// <remarks>
/// Default: <value>false</value>
/// Switched off in 1.8.2 as unstable
/// </remarks>
/// </summary>
/// <remarks>
/// See:
/// https://github.com/linq2db/linq2db/issues/447
/// https://github.com/linq2db/linq2db/pull/563
/// </remarks>
public static bool UseBinaryAggregateExpression = false;
}
public static class LinqService
{
public static bool SerializeAssemblyQualifiedName;
public static bool ThrowUnresolvedTypeException;
}
}
}
|
using System;
namespace LinqToDB.Common
{
public static class Configuration
{
public static bool IsStructIsScalarType = true;
public static bool AvoidSpecificDataProviderAPI;
public static class Linq
{
public static bool PreloadGroups;
public static bool IgnoreEmptyUpdate;
public static bool AllowMultipleQuery;
public static bool GenerateExpressionTest;
public static bool TraceMapperExpression;
public static bool DoNotClearOrderBys;
public static bool OptimizeJoins = true;
/// <summary>
/// If set to true unllable fields would be checked for IS NULL when comparasion type is NotEqual
/// <example>
/// public class MyEntity
/// {
/// public int? Value;
/// }
///
/// db.MyEntity.Where(e => e.Value != 10)
///
/// Would be converted to
///
/// SELECT Value FROM MyEntity WHERE Value IS NULL OR Value != 10
/// </example>
/// </summary>
public static bool CheckNullForNotEquals = true;
/// <summary>
/// Prevents to use constructions like q.GroupBy(_ => _.SomeValue) which leads to unexpected behaviour.
/// </summary>
/// <remarks>
/// https://github.com/linq2db/linq2db/issues/365
/// </remarks>
public static bool GuardGrouping = false;
/// <summary>
/// Experimental
/// Used to optimize big logical operations with great number of operands like expr1.and.axpr2...and.exprN into to one <see cref="LinqToDB.Expressions.BinaryAggregateExpression"/>.
/// This saves from deep recursion in visitors.
/// <remarks>
/// Default: <value>false</value>
/// Switched off in 1.8.2 as unstable
/// </remarks>
/// </summary>
/// <remarks>
/// See:
/// https://github.com/linq2db/linq2db/issues/447
/// https://github.com/linq2db/linq2db/pull/563
/// </remarks>
public static bool UseBinaryAggregateExpression = false;
}
public static class LinqService
{
public static bool SerializeAssemblyQualifiedName;
public static bool ThrowUnresolvedTypeException;
}
}
}
|
mit
|
C#
|
e1cf91bee7c92d1bdc58e21ed9e06bdf0ea9f636
|
Add renderable Point
|
Weingartner/SolidworksAddinFramework
|
SolidworksAddinFramework/OpenGl/IRenderable.cs
|
SolidworksAddinFramework/OpenGl/IRenderable.cs
|
using System;
using System.Numerics;
using OpenTK.Graphics.OpenGL;
using SolidWorks.Interop.sldworks;
using MGL = SolidworksAddinFramework.OpenGl.ModernOpenGl;
using OpenTK.Graphics.OpenGL;
namespace SolidworksAddinFramework.OpenGl
{
public interface IRenderable
{
void Render(DateTime time);
void ApplyTransform(Matrix4x4 transform);
}
public class Point : IRenderable
{
public Point(Vector3 location)
{
Location = location;
}
private Vector3 Location { get; }
public void Render(DateTime time)
{
using (MGL.Begin(PrimitiveType.Points))
{
Location.GLVertex3();
}
}
public void ApplyTransform(Matrix4x4 transform)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Numerics;
using SolidWorks.Interop.sldworks;
namespace SolidworksAddinFramework.OpenGl
{
public interface IRenderable
{
void Render(DateTime time);
void ApplyTransform(Matrix4x4 transform);
}
}
|
mit
|
C#
|
a37de93ccbcc0f6a4421bfa85a16ababa2b02ca2
|
Enable all tests again.
|
CosmosOS/Cosmos,zarlo/Cosmos,fanoI/Cosmos,trivalik/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,fanoI/Cosmos,jp2masa/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,tgiphil/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,trivalik/Cosmos,trivalik/Cosmos,zarlo/Cosmos,tgiphil/Cosmos
|
Tests/Cosmos.TestRunner.Core/TestKernelSets.cs
|
Tests/Cosmos.TestRunner.Core/TestKernelSets.cs
|
using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
yield return typeof(SimpleStructsAndArraysTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
//yield return typeof(FrotzKernel.Kernel);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
//yield return typeof(VGACompilerCrash.Kernel);
////yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
//yield return typeof(SimpleStructsAndArraysTest.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
//yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
yield return typeof(FrotzKernel.Kernel);
}
}
}
|
bsd-3-clause
|
C#
|
9cebf31541c54789aac436d2990659569bb458b6
|
Use a flag to indicate if the shader stage has been successfully compiled.
|
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
|
ChamberLib.OpenTK/ShaderStage.cs
|
ChamberLib.OpenTK/ShaderStage.cs
|
using System;
using OpenTK.Graphics.OpenGL;
using System.Diagnostics;
using ChamberLib.Content;
using _OpenTK = global::OpenTK;
namespace ChamberLib.OpenTK
{
public class ShaderStage : IShaderStage
{
public ShaderStage(ShaderContent content)
: this(content.Source, content.Type, content.Name)
{
}
public ShaderStage(string source, ShaderType shaderType, string name)
{
Source = source;
ShaderType = shaderType;
Name = name;
}
public string Name { get; protected set; }
public int ShaderID { get; protected set; }
public string Source { get; protected set; }
public ShaderType ShaderType { get; protected set; }
public bool IsCompiled { get; protected set; }
public void MakeReady()
{
GLHelper.CheckError();
if (ShaderID == 0)
{
ShaderID = GL.CreateShader(ShaderType.ToOpenTK());
GLHelper.CheckError();
IsCompiled = false;
}
if (!IsCompiled)
{
GL.ShaderSource(ShaderID, Source);
GLHelper.CheckError();
GL.CompileShader(ShaderID);
GLHelper.CheckError();
int result;
GL.GetShader(ShaderID, ShaderParameter.CompileStatus, out result);
Debug.WriteLine("{1} compile status: {0}", result, ShaderType);
GLHelper.CheckError();
Debug.WriteLine("{0} info:", ShaderType);
Debug.WriteLine(GL.GetShaderInfoLog(ShaderID));
GLHelper.CheckError();
IsCompiled = (result == 1);
}
}
}
}
|
using System;
using OpenTK.Graphics.OpenGL;
using System.Diagnostics;
using ChamberLib.Content;
namespace ChamberLib.OpenTK
{
public class ShaderStage : IShaderStage
{
public ShaderStage(ShaderContent content)
: this(content.Source, content.Type, content.Name)
{
}
public ShaderStage(string source, ShaderType shaderType, string name)
{
Source = source;
ShaderType = shaderType;
Name = name;
}
public string Name { get; protected set; }
public int ShaderID { get; protected set; }
public string Source { get; protected set; }
public ShaderType ShaderType { get; protected set; }
public void MakeReady()
{
if (ShaderID != 0) return;
GLHelper.CheckError();
ShaderID = GL.CreateShader(ShaderType.ToOpenTK());
GLHelper.CheckError();
GL.ShaderSource(ShaderID, Source);
GLHelper.CheckError();
GL.CompileShader(ShaderID);
GLHelper.CheckError();
int result;
GL.GetShader(ShaderID, ShaderParameter.CompileStatus, out result);
Debug.WriteLine("{1} compile status: {0}", result, ShaderType);
GLHelper.CheckError();
Debug.WriteLine("{0} info:", ShaderType);
Debug.WriteLine(GL.GetShaderInfoLog(ShaderID));
GLHelper.CheckError();
}
}
}
|
lgpl-2.1
|
C#
|
e3fb60d250538abe4ab4cfb785d5c9d76e89ffc9
|
fix gc alloc
|
Elringus/SpriteGlow,Elringus/SpriteGlow
|
Assets/SpriteGlow/SpriteGlowMaterial.cs
|
Assets/SpriteGlow/SpriteGlowMaterial.cs
|
using System.Collections.Generic;
using UnityEngine;
namespace SpriteGlow
{
public class SpriteGlowMaterial : Material
{
public Texture SpriteTexture { get { return mainTexture; } }
public bool DrawOutside { get { return IsKeywordEnabled(OUTSIDE_MATERIAL_KEYWORD); } }
public bool InstancingEnabled { get { return enableInstancing; } }
private const string OUTLINE_SHADER_NAME = "Sprites/Outline";
private const string OUTSIDE_MATERIAL_KEYWORD = "SPRITE_OUTLINE_OUTSIDE";
private static readonly Shader OUTLINE_SHADER = Shader.Find(OUTLINE_SHADER_NAME);
private static List<SpriteGlowMaterial> sharedMaterials = new List<SpriteGlowMaterial>();
public SpriteGlowMaterial (Texture spriteTexture, bool drawOutside = false, bool instancingEnabled = false)
: base(OUTLINE_SHADER)
{
if (!OUTLINE_SHADER) Debug.LogError(string.Format("{0} shader not found. Make sure the shader is included to the build.", OUTLINE_SHADER_NAME));
mainTexture = spriteTexture;
if (drawOutside) EnableKeyword(OUTSIDE_MATERIAL_KEYWORD);
if (instancingEnabled) enableInstancing = true;
}
public static Material GetSharedFor (SpriteGlowEffect spriteGlow)
{
for (int i = 0; i < sharedMaterials.Count; i++)
{
if (sharedMaterials[i].SpriteTexture == spriteGlow.Renderer.sprite.texture &&
sharedMaterials[i].DrawOutside == spriteGlow.DrawOutside &&
sharedMaterials[i].InstancingEnabled == spriteGlow.EnableInstancing)
return sharedMaterials[i];
}
var material = new SpriteGlowMaterial(spriteGlow.Renderer.sprite.texture, spriteGlow.DrawOutside, spriteGlow.EnableInstancing);
material.hideFlags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor | HideFlags.NotEditable;
sharedMaterials.Add(material);
return material;
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
namespace SpriteGlow
{
public class SpriteGlowMaterial : Material
{
public Texture SpriteTexture { get { return mainTexture; } }
public bool DrawOutside { get { return IsKeywordEnabled(OUTSIDE_MATERIAL_KEYWORD); } }
public bool InstancingEnabled { get { return enableInstancing; } }
private const string OUTLINE_SHADER_NAME = "Sprites/Outline";
private const string OUTSIDE_MATERIAL_KEYWORD = "SPRITE_OUTLINE_OUTSIDE";
private static readonly Shader OUTLINE_SHADER = Shader.Find(OUTLINE_SHADER_NAME);
private static List<SpriteGlowMaterial> sharedMaterials = new List<SpriteGlowMaterial>();
public SpriteGlowMaterial (Texture spriteTexture, bool drawOutside = false, bool instancingEnabled = false)
: base(OUTLINE_SHADER)
{
if (!OUTLINE_SHADER) Debug.LogError(string.Format("{0} shader not found. Make sure the shader is included to the build.", OUTLINE_SHADER_NAME));
mainTexture = spriteTexture;
if (drawOutside) EnableKeyword(OUTSIDE_MATERIAL_KEYWORD);
if (instancingEnabled) enableInstancing = true;
}
public static Material GetSharedFor (SpriteGlowEffect spriteGlow)
{
var material = sharedMaterials.Find(m =>
m.SpriteTexture == spriteGlow.Renderer.sprite.texture &&
m.DrawOutside == spriteGlow.DrawOutside &&
m.InstancingEnabled == spriteGlow.EnableInstancing);
if (!material)
{
material = new SpriteGlowMaterial(spriteGlow.Renderer.sprite.texture, spriteGlow.DrawOutside, spriteGlow.EnableInstancing);
material.hideFlags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor | HideFlags.NotEditable;
sharedMaterials.Add(material);
}
return material;
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.