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 |
---|---|---|---|---|---|---|---|---|
e97c8637a13bf911e55030681884c8301a67e1dd
|
update version
|
HouseBreaker/Shameless
|
Shameless/Properties/AssemblyInfo.cs
|
Shameless/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("Shameless")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shameless")]
[assembly: AssemblyCopyright("Copyright © Housey 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c103c186-94f8-486f-ad20-4f636bdbfd6c")]
// 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.8.7.0")]
[assembly: AssemblyFileVersion("1.8.7.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("Shameless")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shameless")]
[assembly: AssemblyCopyright("Copyright © Housey 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c103c186-94f8-486f-ad20-4f636bdbfd6c")]
// 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.8.6.0")]
[assembly: AssemblyFileVersion("1.8.6.0")]
|
mit
|
C#
|
4817d8aee3c78a7d65b01b67190c8cbe0110c624
|
Update index.cshtml
|
Aleksandrovskaya/apmathclouddif
|
site/index.cshtml
|
site/index.cshtml
|
@{
double t_0 = 0;
double t_end = 150;
double step = 0.1;
int N = Convert.ToInt32((t_end-t_0)/step) + 1;
String data = "";
bool show_chart = false;
if (IsPost){
show_chart = true;
var number = Request["text1"];
double xd = number.AsInt();
double t = 0;
double x1 = 0;
double x2 = 0;
double x3 = 0;
double currentx1 = 0;
double currentx2 = 0;
double currentx3 = 0;
for (int i=0; i < N; ++i){
t = t_0 + step * i;
currentx1 = x1 + step* (-0.1252*x1 + -0.004637*(x2-xd)+-0.002198*x3);
currentx2 = x2 + step*x1 ;
currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd));
x1 = currentx1;
x2 = currentx2;
x3 = currentx3;
data += "[" +t+"," + x2+"]";
if( i < N - 1){
data += ",";
}
}
}
}
<html>
<head>
<meta charset="utf-8">
<title>MathBox</title>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'pitch'],
@data
]);
var options = {
title: 'pitch',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form action="" method="post" align="center">
<p><label for="text1">Input Angle</label><br>
<input type="text" name="text1" /></p>
<p><input type="submit" value=" Show " /></p>
</form>
@if (show_chart)
{
<div id="curve_chart" style="width: 900px; height: 500px"></div>
}
else
{
<p></p>
}
</body>
</html>
|
@{
double t_0 = 0;
double t_end = 150;
double step = 0.1;
int N = Convert.ToInt32((t_end-t_0)/step) + 1;
String data = "";
bool show_chart = false;
if (IsPost){
show_chart = true;
var number = Request["text1"];
double xd = number.AsInt();
double t = 0;
double x1 = 0;
double x2 = 0;
double x3 = 0;
double currentx1 = 0;
double currentx2 = 0;
double currentx3 = 0;
for (int i=0; i < N; ++i){
t = t_0 + step * i;
currentx1 = x1 + step* (-0.1252*x1 + -0.004637*(x2-xd)+-0.002198*x3);
currentx2 = x2 + step*x1 ;
currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd));
x1 = currentx1;
x2 = currentx2;
x3 = currentx3;
data += "[" +t+"," + x2+"]";
if( i < N - 1){
data += ",";
}
}
}
}
<html>
<head>
<meta charset="utf-8">
<title>MathBox</title>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'pitch'],
@data
]);
var options = {
title: 'pitch',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form action="" method="post" align="center">
<p><label for="text1">Input Angle</label><br>
<input type="text" name="text1" /></p>
<p><input type="submit" value=" Show " /></p>
</form>
@if (show_chart)
{
<div id="curve_chart" style="width: 1200px; height: 500px"></div>
}
else
{
<p></p>
}
</body>
</html>
|
mit
|
C#
|
762b8bbbc88cdf99c0b56dd3f983ee87397d0c79
|
fix messed up chem dispenser code which regressed somehow
|
Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation
|
UnityProject/Assets/Prefabs/GUI/Resources/ChemistryDispenser.cs
|
UnityProject/Assets/Prefabs/GUI/Resources/ChemistryDispenser.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Main component for chemistry dispenser.
/// </summary>
public class ChemistryDispenser : NBHandApplyInteractable {
public ReagentContainer Container;
public ObjectBehaviour objectse;
public delegate void ChangeEvent ();
public static event ChangeEvent changeEvent;
private void UpdateGUI()
{
// Change event runs updateAll in ChemistryGUI
if(changeEvent!=null)
{
changeEvent();
}
}
protected override bool WillInteract(HandApply interaction, NetworkSide side)
{
if (!base.WillInteract(interaction, side)) return false;
//only interaction that works is using a reagent container on this
if (!Validations.HasComponent<ReagentContainer>(interaction.HandObject)) return false;
return true;
}
protected override void ServerPerformInteraction(HandApply interaction)
{
//put the reagant container inside me
Container = interaction.HandObject.GetComponent<ReagentContainer>();
objectse = interaction.HandObject.GetComponentInChildren<ObjectBehaviour> ();
var slot = InventoryManager.GetSlotFromOriginatorHand(interaction.Performer, interaction.HandSlot.SlotName);
InventoryManager.UpdateInvSlot(true, "", interaction.HandObject, slot.UUID);
UpdateGUI();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Main component for chemistry dispenser.
/// </summary>
public class ChemistryDispenser : NBHandApplyInteractable {
public ReagentContainer Container;
public ObjectBehaviour objectse;
public delegate void ChangeEvent ();
public static event ChangeEvent changeEvent;
private void UpdateGUI()
{
// Change event runs updateAll in ChemistryGUI
if(changeEvent!=null)
{
changeEvent();
}
}
protected override InteractionValidationChain<HandApply> InteractionValidationChain()
{
return CommonValidationChains.CAN_APPLY_HAND_CONSCIOUS
.WithValidation(DoesUsedObjectHaveComponent<ReagentContainer>.DOES);
}
protected override void ServerPerformInteraction(HandApply interaction)
{
//put the reagant container inside me
Container = interaction.UsedObject.GetComponent<ReagentContainer>();
objectse = interaction.UsedObject.GetComponentInChildren<ObjectBehaviour> ();
var slot = InventoryManager.GetSlotFromOriginatorHand(interaction.Performer, interaction.HandSlot.SlotName);
InventoryManager.UpdateInvSlot(true, "", interaction.UsedObject, slot.UUID);
UpdateGUI();
}
}
|
agpl-3.0
|
C#
|
34c871534c4503b3f584f6d578ce30771984401a
|
Clean up Health CHeck
|
BrighterCommand/Brighter,BrighterCommand/Brighter,BrighterCommand/Brighter
|
Paramore.Brighter.ServiceActivator.Extensions.HealthChecks/BrighterServiceActivatorHealthCheck.cs
|
Paramore.Brighter.ServiceActivator.Extensions.HealthChecks/BrighterServiceActivatorHealthCheck.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Paramore.Brighter.ServiceActivator.Extensions.HealthChecks;
public class BrighterServiceActivatorHealthCheck : IHealthCheck
{
private readonly IDispatcher _dispatcher;
public BrighterServiceActivatorHealthCheck(IDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new())
{
var expectedConsumers = ((Dispatcher)_dispatcher).Connections.Sum(c => c.NoOfPeformers);
var activeConsumers = _dispatcher.Consumers.Count();
if (expectedConsumers != activeConsumers)
{
var status = activeConsumers > 0 ? HealthStatus.Degraded : HealthStatus.Unhealthy;
return Task.FromResult(new HealthCheckResult(status,
GenerateUnhealthyMessage()));
}
return Task.FromResult(HealthCheckResult.Healthy($"{activeConsumers} healthy consumers."));
}
private string GenerateUnhealthyMessage()
{
var config = ((Dispatcher)_dispatcher).Connections;
var unhealthyHosts = new List<string>();
foreach (var cfg in config)
{
var sub = _dispatcher.Consumers.Where(c => c.SubscriptionName == cfg.Name).ToArray();
if(sub.Count() != cfg?.NoOfPeformers)
unhealthyHosts.Add($"{cfg.Name} has {sub.Count()} of {cfg.NoOfPeformers} expected consumers");
}
return string.Join(';', unhealthyHosts);
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Paramore.Brighter.ServiceActivator.Extensions.HealthChecks;
public class BrighterServiceActivatorHealthCheck : IHealthCheck
{
private readonly IDispatcher _dispatcher;
public BrighterServiceActivatorHealthCheck(IDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new())
{
var expectedConsumers = ((Dispatcher)_dispatcher).Connections.Sum(c => c.NoOfPeformers);
var activeConsumers = _dispatcher.Consumers.Count();
if (expectedConsumers != activeConsumers)
{
var status = HealthStatus.Degraded;
if (activeConsumers < 1)
{
status = HealthStatus.Unhealthy;
}
return Task.FromResult(new HealthCheckResult(status,
GenerateUnhealthyMessage()));
}
return Task.FromResult(HealthCheckResult.Healthy($"{activeConsumers} healthy consumers."));
}
private string GenerateUnhealthyMessage()
{
var config = ((Dispatcher)_dispatcher).Connections;
var unhealthyHosts = new List<string>();
foreach (var cfg in config)
{
var sub = _dispatcher.Consumers.Where(c => c.SubscriptionName == cfg.Name).ToArray();
if(sub.Count() != cfg?.NoOfPeformers)
unhealthyHosts.Add($"{cfg.Name} has {sub.Count()} of {cfg.NoOfPeformers} expected consumers");
}
return string.Join(';', unhealthyHosts);
}
}
|
mit
|
C#
|
d728c1beb27dfd3a31f9ad084d1c4094b27b65f9
|
refactor LSL_EventTests.TestStateEntryEvent into single method to test compile
|
ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,OpenSimian/opensimulator,ft-/arribasim-dev-tests,justinccdev/opensim,justinccdev/opensim,TomDataworks/opensim,OpenSimian/opensimulator,OpenSimian/opensimulator,M-O-S-E-S/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,OpenSimian/opensimulator,M-O-S-E-S/opensim,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,justinccdev/opensim,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,ft-/arribasim-dev-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,TomDataworks/opensim,BogusCurry/arribasim-dev,QuillLittlefeather/opensim-1,RavenB/opensim,justinccdev/opensim,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip,RavenB/opensim,OpenSimian/opensimulator,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,justinccdev/opensim,M-O-S-E-S/opensim,ft-/arribasim-dev-tests,TomDataworks/opensim,M-O-S-E-S/opensim,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-tests,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip,TomDataworks/opensim,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,RavenB/opensim,RavenB/opensim,BogusCurry/arribasim-dev,TomDataworks/opensim,RavenB/opensim,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,QuillLittlefeather/opensim-1,RavenB/opensim,RavenB/opensim,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-extras,justinccdev/opensim,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,M-O-S-E-S/opensim,TomDataworks/opensim,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip
|
OpenSim/Region/ScriptEngine/Shared/CodeTools/Tests/LSL_EventTests.cs
|
OpenSim/Region/ScriptEngine/Shared/CodeTools/Tests/LSL_EventTests.cs
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.Text.RegularExpressions;
using NUnit.Framework;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
public class LSL_EventTests : OpenSimTestCase
{
CSCodeGenerator m_cg = new CSCodeGenerator();
[Test]
public void TestStateEntryEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestCompile("default { state_entry() {} }", false);
TestCompile("default { state_entry(integer n) {} }", true);
}
private void TestCompile(string script, bool expectException)
{
bool gotException = false;
try
{
m_cg.Convert(script);
}
catch (Exception)
{
gotException = true;
}
Assert.That(gotException, Is.EqualTo(expectException));
}
}
}
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.Text.RegularExpressions;
using NUnit.Framework;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
public class LSL_EventTests : OpenSimTestCase
{
[Test]
public void TestStateEntryEvent()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
CSCodeGenerator cg = new CSCodeGenerator();
cg.Convert("default { state_entry() {} }");
{
bool gotException = false;
try
{
cg.Convert("default { state_entry(integer n) {} }");
}
catch (Exception )
{
gotException = true;
}
Assert.That(gotException, Is.True);
}
}
}
}
|
bsd-3-clause
|
C#
|
325c3ebc780bd48dbd3997c5acbadce15c389d6a
|
Add input binder to allow for comma-separated list inputs for API routes
|
mtcairneyleeming/latin
|
api/CommaDelimitedArrayModelBinder.cs
|
api/CommaDelimitedArrayModelBinder.cs
|
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace api
{
public class CommaDelimitedArrayModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext.ModelMetadata.IsEnumerableType)
{
var key = bindingContext.ModelName;
var value = bindingContext.ValueProvider.GetValue(key).ToString();
if (!string.IsNullOrWhiteSpace(value))
{
var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
var converter = TypeDescriptor.GetConverter(elementType);
var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => converter.ConvertFromString(x.Trim()))
.ToArray();
var typedValues = Array.CreateInstance(elementType, values.Length);
values.CopyTo(typedValues, 0);
bindingContext.Result = ModelBindingResult.Success(typedValues);
}
else
{
Console.WriteLine("string was empty");
// change this line to null if you prefer nulls to empty arrays
bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0));
}
return Task.CompletedTask;
}
Console.WriteLine("Not enumerable");
return Task.CompletedTask;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace api
{
public class CommaDelimitedArrayModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext.ModelMetadata.IsEnumerableType)
{
var key = bindingContext.ModelName;
var value = bindingContext.ValueProvider.GetValue(key).ToString();
if (!string.IsNullOrWhiteSpace(value))
{
var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
var converter = TypeDescriptor.GetConverter(elementType);
var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => converter.ConvertFromString(x.Trim()))
.ToArray();
var typedValues = Array.CreateInstance(elementType, values.Length);
values.CopyTo(typedValues, 0);
bindingContext.Result = ModelBindingResult.Success(typedValues);
}
else
{
Console.WriteLine("string was empty");
// change this line to null if you prefer nulls to empty arrays
bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0));
}
return Task.CompletedTask;
}
Console.WriteLine("Not enumerable");
return Task.CompletedTask;
}
}
}
|
mit
|
C#
|
aff21c989744dd5e4fb40d9b943c8c20ce450b08
|
Update Program.cs
|
vanjikumaran/VizhiMozhi
|
SrilankanTamilFingerSpelling/SrilankanTamilFingerSpelling/Program.cs
|
SrilankanTamilFingerSpelling/SrilankanTamilFingerSpelling/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace SrilankanTamilFingerSpelling
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new GUI.frmSplashScreen());
Application.Run(new GUI.frmMainInterFace());
}
private static void ShowAssemblies(object sender, AssemblyLoadEventArgs e)
{
// Store name of assembly in the queue
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace SrilankanTamilFingerSpelling
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new GUI.frmWebCamGUI());
//Application.Run(new GUI.frmTrainingSession());
// Application.Run(new GUI.frmRegognition());
// Application.Run(new GUI.frmMDIParent());
Application.Run(new GUI.frmSplashScreen());
// Application.Run(new GUI.frmMDIParent());
Application.Run(new GUI.frmMainInterFace());
}
private static void ShowAssemblies(object sender, AssemblyLoadEventArgs e)
{
// Store name of assembly in the queue
}
}
}
|
apache-2.0
|
C#
|
08f3c8f246b6472cf05bd6728962e56e28b41f8c
|
Modify WhatDoIHave to show expected result
|
kendaleiv/di-servicelocation-structuremap,kendaleiv/di-servicelocation-structuremap,kendaleiv/di-servicelocation-structuremap
|
Tests/TroubleshootingTests.cs
|
Tests/TroubleshootingTests.cs
|
using Core;
using StructureMap;
using Xunit;
namespace Tests
{
public class TroubleshootingTests
{
[Fact]
public void ShowBuildPlan()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
var buildPlan = container.Model.For<IService>()
.Default
.DescribeBuildPlan();
var expectedBuildPlan =
@"PluginType: Core.IService
Lifecycle: Transient
new Service()
";
Assert.Equal(expectedBuildPlan, buildPlan);
}
[Fact]
public void WhatDoIHave()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
var whatDoIHave = container.WhatDoIHave();
var expectedWhatDoIHave = @"
===================================================================================================
PluginType Namespace Lifecycle Description Name
---------------------------------------------------------------------------------------------------
Func<TResult> System Transient Open Generic Template for Func<> (Default)
---------------------------------------------------------------------------------------------------
Func<T, TResult> System Transient Open Generic Template for Func<,> (Default)
---------------------------------------------------------------------------------------------------
IContainer StructureMap Singleton Object: StructureMap.Container (Default)
---------------------------------------------------------------------------------------------------
IService Core Transient Core.Service (Default)
---------------------------------------------------------------------------------------------------
Lazy<T> System Transient Open Generic Template for Func<> (Default)
===================================================================================================";
Assert.Equal(expectedWhatDoIHave, whatDoIHave);
}
}
}
|
using Core;
using StructureMap;
using System.Diagnostics;
using Xunit;
namespace Tests
{
public class TroubleshootingTests
{
[Fact]
public void ShowBuildPlan()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
var buildPlan = container.Model.For<IService>()
.Default
.DescribeBuildPlan();
var expectedBuildPlan =
@"PluginType: Core.IService
Lifecycle: Transient
new Service()
";
Assert.Equal(expectedBuildPlan, buildPlan);
}
[Fact]
public void WhatDoIHave()
{
var container = new Container(x =>
{
x.For<IService>().Use<Service>();
});
var whatDoIHave = container.WhatDoIHave();
Trace.Write(whatDoIHave);
}
}
}
|
mit
|
C#
|
941966230556a90c7a01eafe12fc5204103b9d3d
|
Fix serialization
|
FireCube-/HarvesterBot
|
TexasHoldEm/GeneReadWriter.cs
|
TexasHoldEm/GeneReadWriter.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
[Serializable]
public static class GeneReadWriter {
public static Gene readGene(string path) {
using (Stream stream = File.Open(path, FileMode.Open)) {
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (Gene) binaryFormatter.Deserialize(stream);
}
}
public static void writeGene(string path, Gene gene) {
using (Stream stream = File.Open(path, FileMode.Create)) {
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, gene);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
public static class GeneReadWriter {
public static Gene readGene(string path) {
using (Stream stream = File.Open(path, FileMode.Open)) {
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (Gene) binaryFormatter.Deserialize(stream);
}
}
public static void writeGene(string path, Gene gene) {
using (Stream stream = File.Open(path, FileMode.Create)) {
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, gene);
}
}
}
|
mit
|
C#
|
f6e2958d60f89f59d1852ed9d5c2f53841662013
|
add logging
|
NDark/ndinfrastructure,NDark/ndinfrastructure
|
Unity/UnityTools/UnityFind.cs
|
Unity/UnityTools/UnityFind.cs
|
/**
MIT License
Copyright (c) 2017 NDark
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.
*/
/**
@file UnityFind.cs
@author NDark
@date 20170812 . file started.
*/
using UnityEngine;
public static class UnityFind
{
public static GameObject GameObjectFind( GameObject _Obj , string _Name )
{
if( null != _Obj )
{
var trans = _Obj.transform.Find( _Name );
if( null == trans )
{
Debug.LogError( "GameObjectFind() null == trans _Name=" + _Name );
}
else
{
return trans.gameObject ;
}
}
return null ;
}
public static T ComponentFind<T>( Transform _Root , string _Name )
{
var trans = _Root.Find( _Name );
if( null == trans )
{
Debug.LogError( "ComponentFind() null == trans _Name=" + _Name );
return default(T) ;
}
var c = trans.gameObject.GetComponent<T>();
if( null == c )
{
Debug.LogError( "ComponentFind() null == component _Name=" + _Name ) ;
return default(T) ;
}
return c;
}
}
|
/**
MIT License
Copyright (c) 2017 NDark
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.
*/
/**
@file UnityFind.cs
@author NDark
@date 20170812 . file started.
*/
using UnityEngine;
public static class UnityFind
{
public static GameObject GameObjectFind( GameObject _Obj , string _Name )
{
if( null != _Obj )
{
var trans = _Obj.transform.Find( _Name );
if( null != trans )
{
return trans.gameObject ;
}
}
return null ;
}
public static T ComponentFind<T>( Transform _Root , string _Name )
{
var trans = _Root.Find( _Name );
if( null == trans )
{
Debug.LogError( "ComponentFind() null == trans _Name=" + _Name );
return default(T) ;
}
var c = trans.gameObject.GetComponent<T>();
if( null == c )
{
Debug.LogError( "ComponentFind() null == component _Name=" + _Name ) ;
return default(T) ;
}
return c;
}
}
|
mit
|
C#
|
de60b2cf0c469cec9d84422c251bf5adcfb4d901
|
Update AverageCurrencyConversionCompositionStrategy.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Finance/AverageCurrencyConversionCompositionStrategy.cs
|
TIKSN.Core/Finance/AverageCurrencyConversionCompositionStrategy.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TIKSN.Finance.Helpers;
namespace TIKSN.Finance
{
public class AverageCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy
{
public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters,
CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, baseMoney.Currency,
counterCurrency, asOn, cancellationToken);
var amounts = new List<decimal>();
foreach (var converter in filteredConverters)
{
var convertedMoney =
await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken);
if (convertedMoney.Currency != counterCurrency)
{
throw new Exception("Converted into wrong currency.");
}
amounts.Add(convertedMoney.Amount);
}
var amount = amounts.Average();
return new Money(counterCurrency, amount);
}
public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair,
DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, pair, asOn, cancellationToken);
var rates = new List<decimal>();
foreach (var converter in filteredConverters)
{
var rate = await converter.GetExchangeRateAsync(pair, asOn, cancellationToken);
rates.Add(rate);
}
return rates.Average();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TIKSN.Finance.Helpers;
namespace TIKSN.Finance
{
public class AverageCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy
{
public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, baseMoney.Currency, counterCurrency, asOn, cancellationToken);
var amounts = new List<decimal>();
foreach (var converter in filteredConverters)
{
var convertedMoney = await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken);
if (convertedMoney.Currency != counterCurrency)
throw new Exception("Converted into wrong currency.");
amounts.Add(convertedMoney.Amount);
}
var amount = amounts.Average();
return new Money(counterCurrency, amount);
}
public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = await CurrencyHelper.FilterConverters(converters, pair, asOn, cancellationToken);
var rates = new List<decimal>();
foreach (var converter in filteredConverters)
{
var rate = await converter.GetExchangeRateAsync(pair, asOn, cancellationToken);
rates.Add(rate);
}
return rates.Average();
}
}
}
|
mit
|
C#
|
af5c1eed67db378e373d02f30bef58b914642949
|
Update SampleDataController.cs
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/ProjectTemplates/Web.Spa.ProjectTemplates/content/React-CSharp/Controllers/SampleDataController.cs
|
src/ProjectTemplates/Web.Spa.ProjectTemplates/content/React-CSharp/Controllers/SampleDataController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if (IndividualLocalAuth)
using Microsoft.AspNetCore.Authorization;
#endif
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Company.WebApplication1.Controllers
{
#if (IndividualLocalAuth)
[Authorize]
#endif
[Route("api/[controller]")]
public class SampleDataController : Controller
{
private readonly ILogger<SampleDataController> logger;
public SampleDataController(ILogger<SampleDataController> _logger)
{
logger = _logger;
}
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet("[action]")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
public class WeatherForecast
{
public string DateFormatted { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF
{
get
{
return 32 + (int)(TemperatureC / 0.5556);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if (IndividualLocalAuth)
using Microsoft.AspNetCore.Authorization;
#endif
using Microsoft.AspNetCore.Mvc;
namespace Company.WebApplication1.Controllers
{
#if (IndividualLocalAuth)
[Authorize]
#endif
[Route("api/[controller]")]
public class SampleDataController : Controller
{
private readonly ILogger<SampleDataController> logger;
public SampleDataController(ILogger<SampleDataController> _logger)
{
logger = _logger;
}
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet("[action]")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
public class WeatherForecast
{
public string DateFormatted { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF
{
get
{
return 32 + (int)(TemperatureC / 0.5556);
}
}
}
}
}
|
apache-2.0
|
C#
|
0de1367903fab76cb2e1254c6701b73ba254f048
|
Revert "TODO"
|
GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity
|
Assets/Teak/Editor/TeakPostProcessScene.cs
|
Assets/Teak/Editor/TeakPostProcessScene.cs
|
#region License
/* Teak -- Copyright (C) 2016 GoCarrot 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.
*/
#endregion
#region References
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
#endregion
public class TeakPostProcessScene
{
[PostProcessScene]
public static void OnPostprocessScene()
{
if(!mRanThisBuild)
{
mRanThisBuild = true;
if(string.IsNullOrEmpty(TeakSettings.AppId))
{
Debug.LogError("Teak App Id needs to be assigned in the Edit/Teak menu.");
}
if(string.IsNullOrEmpty(TeakSettings.APIKey))
{
Debug.LogError("Teak API Key needs to be assigned in the Edit/Teak menu.");
}
Directory.CreateDirectory(Path.Combine(Application.dataPath, "Plugins/Android/res/values"));
XDocument doc = new XDocument(
new XElement("resources",
new XElement("string", TeakSettings.AppId, new XAttribute("name", "io_teak_app_id")),
new XElement("string", TeakSettings.APIKey, new XAttribute("name", "io_teak_api_key")),
String.IsNullOrEmpty(TeakSettings.GCMSenderId) ? null : new XElement("string", TeakSettings.GCMSenderId, new XAttribute("name", "io_teak_gcm_sender_id"))
)
);
doc.Save(Path.Combine(Application.dataPath, "Plugins/Android/res/values/teak.xml"));
}
}
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuildProject)
{
mRanThisBuild = false;
}
private static bool mRanThisBuild = false;
}
|
#region License
/* Teak -- Copyright (C) 2016 GoCarrot 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.
*/
#endregion
#region References
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
#endregion
public class TeakPostProcessScene
{
[PostProcessScene]
public static void OnPostprocessScene()
{
if(!mRanThisBuild)
{
mRanThisBuild = true;
if(string.IsNullOrEmpty(TeakSettings.AppId))
{
Debug.LogError("Teak App Id needs to be assigned in the Edit/Teak menu.");
}
if(string.IsNullOrEmpty(TeakSettings.APIKey))
{
Debug.LogError("Teak API Key needs to be assigned in the Edit/Teak menu.");
}
throw new System.Exception("TODO: Make this read existing so people can customize stuff.");
Directory.CreateDirectory(Path.Combine(Application.dataPath, "Plugins/Android/res/values"));
XDocument doc = new XDocument(
new XElement("resources",
new XElement("string", TeakSettings.AppId, new XAttribute("name", "io_teak_app_id")),
new XElement("string", TeakSettings.APIKey, new XAttribute("name", "io_teak_api_key")),
String.IsNullOrEmpty(TeakSettings.GCMSenderId) ? null : new XElement("string", TeakSettings.GCMSenderId, new XAttribute("name", "io_teak_gcm_sender_id"))
)
);
doc.Save(Path.Combine(Application.dataPath, "Plugins/Android/res/values/teak.xml"));
}
}
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuildProject)
{
mRanThisBuild = false;
}
private static bool mRanThisBuild = false;
}
|
apache-2.0
|
C#
|
5a7b4f282820e452d6601df7eb8aeaace1cc6741
|
Delete useless method calls.
|
WestHillApps/UniGif
|
Assets/UniGif/Example/Script/UniGifTest.cs
|
Assets/UniGif/Example/Script/UniGifTest.cs
|
/*
UniGif
Copyright (c) 2015 WestHillApps (Hironari Nishioka)
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class UniGifTest : MonoBehaviour
{
[SerializeField]
private InputField m_inputField;
[SerializeField]
private UniGifImage m_uniGifImage;
private bool m_mutex;
public void OnButtonClicked()
{
if (m_mutex || m_uniGifImage == null || string.IsNullOrEmpty(m_inputField.text))
{
return;
}
m_mutex = true;
StartCoroutine(ViewGifCoroutine());
}
private IEnumerator ViewGifCoroutine()
{
yield return StartCoroutine(m_uniGifImage.SetGifFromUrlCoroutine(m_inputField.text));
m_mutex = false;
}
}
|
/*
UniGif
Copyright (c) 2015 WestHillApps (Hironari Nishioka)
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class UniGifTest : MonoBehaviour
{
[SerializeField]
private InputField m_inputField;
[SerializeField]
private UniGifImage m_uniGifImage;
private bool m_mutex;
public void OnButtonClicked()
{
if (m_mutex || m_uniGifImage == null || string.IsNullOrEmpty(m_inputField.text))
{
return;
}
m_mutex = true;
m_uniGifImage.Stop();
StartCoroutine(ViewGifCoroutine());
}
private IEnumerator ViewGifCoroutine()
{
yield return StartCoroutine(m_uniGifImage.SetGifFromUrlCoroutine(m_inputField.text));
m_mutex = false;
}
}
|
mit
|
C#
|
a668685f7120a65941198c7594e0cd1b34e87171
|
Update security protocol support
|
Vivantio/apisamples,Vivantio/apisamples
|
DotNet/Vivantio.Samples/JsonApi/BaseApi.cs
|
DotNet/Vivantio.Samples/JsonApi/BaseApi.cs
|
using System.Configuration;
using System.Net;
using Vivantio.Samples.JsonApi.Shared;
namespace Vivantio.Samples.JsonApi
{
public abstract class BaseApi
{
static BaseApi()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
}
private readonly ApiUtility _utility;
protected ApiUtility ApiUtility
{
get { return _utility; }
}
protected BaseApi()
{
var url = ConfigurationManager.AppSettings["Vivantio.ApiUrl"];
var user = ConfigurationManager.AppSettings["Vivantio.ApiUser"];
var password = ConfigurationManager.AppSettings["Vivantio.ApiPassword"];
_utility = new ApiUtility(url, user, password);
}
}
}
|
using System.Configuration;
using Vivantio.Samples.JsonApi.Shared;
namespace Vivantio.Samples.JsonApi
{
public abstract class BaseApi
{
private readonly ApiUtility _utility;
protected ApiUtility ApiUtility
{
get { return _utility; }
}
protected BaseApi()
{
var url = ConfigurationManager.AppSettings["Vivantio.ApiUrl"];
var user = ConfigurationManager.AppSettings["Vivantio.ApiUser"];
var password = ConfigurationManager.AppSettings["Vivantio.ApiPassword"];
_utility = new ApiUtility(url, user, password);
}
}
}
|
mit
|
C#
|
73e231efb776bae85df69a2d1738963cadfaceac
|
Remove usings
|
orodriguez/FTF,orodriguez/FTF,orodriguez/FTF
|
FTF.IoC.SimpleInjector/ContainerFactory.cs
|
FTF.IoC.SimpleInjector/ContainerFactory.cs
|
using System.Linq;
using System.Reflection;
using FTF.Core.Attributes;
using FTF.Core.Delegates;
using FTF.Core.Entities;
using FTF.Core.Ports;
using FTF.IoC.SimpleInjector.PortsConfig;
using SimpleInjector;
namespace FTF.IoC.SimpleInjector
{
public class ContainerFactory
{
public static Container Make(IPorts ports, ScopedLifestyle scopedLifestyle)
{
var c = new Container();
c.Options.DefaultScopedLifestyle = scopedLifestyle;
c.Register(() => ports.GetCurrentTime);
c.Register<GetCurrentUser>(() => () => ports.Auth.CurrentUser);
c.Register<SetCurrentUser>(() => user => ports.Auth.CurrentUser = user);
c.Register(ports.Storage.MakeDbContext, Lifestyle.Scoped);
var allTypes = typeof (Note).Assembly.GetExportedTypes();
allTypes
.Where(t => t.GetCustomAttributes<RoleAttribute>().Any())
.Select(t => new
{
ServiceType = t.GetCustomAttribute<RoleAttribute>().RoleType,
ImplementationType = t
})
.ToList()
.ForEach(obj => c.Register(obj.ServiceType, obj.ImplementationType));
return c;
}
public static Container MakeWebApi(ScopedLifestyle scopedLifestyle) =>
Make(new WebApiPorts(), scopedLifestyle);
}
}
|
using System.Linq;
using System.Reflection;
using FTF.Core.Attributes;
using FTF.Core.Delegates;
using FTF.Core.Entities;
using FTF.Core.Ports;
using FTF.IoC.SimpleInjector.PortsConfig;
using SimpleInjector;
using SimpleInjector.Extensions.LifetimeScoping;
namespace FTF.IoC.SimpleInjector
{
public class ContainerFactory
{
public static Container Make(IPorts ports, ScopedLifestyle scopedLifestyle)
{
var c = new Container();
c.Options.DefaultScopedLifestyle = scopedLifestyle;
c.Register(() => ports.GetCurrentTime);
c.Register<GetCurrentUser>(() => () => ports.Auth.CurrentUser);
c.Register<SetCurrentUser>(() => user => ports.Auth.CurrentUser = user);
c.Register(ports.Storage.MakeDbContext, Lifestyle.Scoped);
var allTypes = typeof (Note).Assembly.GetExportedTypes();
allTypes
.Where(t => t.GetCustomAttributes<RoleAttribute>().Any())
.Select(t => new
{
ServiceType = t.GetCustomAttribute<RoleAttribute>().RoleType,
ImplementationType = t
})
.ToList()
.ForEach(obj => c.Register(obj.ServiceType, obj.ImplementationType));
return c;
}
public static Container MakeWebApi(ScopedLifestyle scopedLifestyle) =>
Make(new WebApiPorts(), scopedLifestyle);
}
}
|
mit
|
C#
|
05bb9c48935b13c8bae8dd8206994b34e92587d0
|
Add constructor for DeserializeAsAttribute
|
jzebedee/lcapi
|
LCAPI/LCAPI/JSON/DeserializeAsAttribute.cs
|
LCAPI/LCAPI/JSON/DeserializeAsAttribute.cs
|
#region License
// Copyright 2010 John Sheehan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
namespace LCAPI.JSON
{
/// <summary>
/// Allows control how class and property names and values are deserialized by XmlAttributeDeserializer
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)]
public sealed class DeserializeAsAttribute : Attribute
{
public DeserializeAsAttribute(string name, bool attribute = false)
{
Name = name;
Attribute = attribute;
}
/// <summary>
/// The name to use for the serialized element
/// </summary>
public string Name { get; set; }
/// <summary>
/// Sets if the property to Deserialize is an Attribute or Element (Default: false)
/// </summary>
public bool Attribute { get; set; }
}
}
|
#region License
// Copyright 2010 John Sheehan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
namespace LCAPI.JSON
{
/// <summary>
/// Allows control how class and property names and values are deserialized by XmlAttributeDeserializer
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)]
public sealed class DeserializeAsAttribute : Attribute
{
/// <summary>
/// The name to use for the serialized element
/// </summary>
public string Name { get; set; }
/// <summary>
/// Sets if the property to Deserialize is an Attribute or Element (Default: false)
/// </summary>
public bool Attribute { get; set; }
}
}
|
agpl-3.0
|
C#
|
bf40e69c95280ad374c094a51b62040d1a58220a
|
Add support for the new upcoming in3 payment method
|
Viincenttt/MollieApi,Viincenttt/MollieApi
|
Mollie.Api/Models/Payment/PaymentMethod.cs
|
Mollie.Api/Models/Payment/PaymentMethod.cs
|
namespace Mollie.Api.Models.Payment {
public static class PaymentMethod {
public const string Bancontact = "bancontact";
public const string BankTransfer = "banktransfer";
public const string Belfius = "belfius";
public const string CreditCard = "creditcard";
public const string DirectDebit = "directdebit";
public const string Eps = "eps";
public const string GiftCard = "giftcard";
public const string Giropay = "giropay";
public const string Ideal = "ideal";
public const string IngHomePay = "inghomepay";
public const string Kbc = "kbc";
public const string PayPal = "paypal";
public const string PaySafeCard = "paysafecard";
public const string Sofort = "sofort";
public const string Refund = "refund";
public const string KlarnaPayLater = "klarnapaylater";
public const string KlarnaSliceIt = "klarnasliceit";
public const string Przelewy24 = "przelewy24";
public const string ApplePay = "applepay";
public const string MealVoucher = "mealvoucher";
public const string In3 = "in3";
}
}
|
namespace Mollie.Api.Models.Payment {
public static class PaymentMethod {
public const string Bancontact = "bancontact";
public const string BankTransfer = "banktransfer";
public const string Belfius = "belfius";
public const string CreditCard = "creditcard";
public const string DirectDebit = "directdebit";
public const string Eps = "eps";
public const string GiftCard = "giftcard";
public const string Giropay = "giropay";
public const string Ideal = "ideal";
public const string IngHomePay = "inghomepay";
public const string Kbc = "kbc";
public const string PayPal = "paypal";
public const string PaySafeCard = "paysafecard";
public const string Sofort = "sofort";
public const string Refund = "refund";
public const string KlarnaPayLater = "klarnapaylater";
public const string KlarnaSliceIt = "klarnasliceit";
public const string Przelewy24 = "przelewy24";
public const string ApplePay = "applepay";
public const string MealVoucher = "mealvoucher";
}
}
|
mit
|
C#
|
3c3a2096bdae1d0ce1d9cbf1ae91a5d5703245a8
|
Update Index.cshtml - fixed "Edit" link.
|
NinjaVault/NinjaHive,NinjaVault/NinjaHive
|
NinjaHive.WebApp/Views/Skills/Index.cshtml
|
NinjaHive.WebApp/Views/Skills/Index.cshtml
|
@using NinjaHive.Contract.DTOs
@using NinjaHive.WebApp.Controllers
@using NinjaHive.WebApp.Services
@model Skill[]
<div class="row">
<div class="col-md-12">
<br />
<p>
@Html.ActionLink("Create Equipment Item", "Create", null, new { @class = "btn btn-default" })
</p>
<hr />
<h4>List of items in the database</h4>
</div>
@foreach (var item in Model)
{
var itemId = item.Id;
var itemDetailsUrl = UrlProvider<SkillsController>.GetUrl(c => c.Edit(itemId));
<div class="col-md-2">
<div class="thumbnail">
<a href="@itemDetailsUrl" class="thumbnail">
<img src="/Content/Images/default_image.png" alt="..." />
</a>
<div class="caption">
<p>@item.Name</p>
<p>
@*@Html.ActionLink("Delete", "Delete", item)<br />*@
@*<a href="@itemDetailsUrl"> Edit </a>*@
</p>
</div>
</div>
</div>
}
</div>
|
@using NinjaHive.Contract.DTOs
@using NinjaHive.WebApp.Controllers
@using NinjaHive.WebApp.Services
@model Skill[]
<div class="row">
<div class="col-md-12">
<br />
<p>
@Html.ActionLink("Create Equipment Item", "Create", null, new { @class = "btn btn-default" })
</p>
<hr />
<h4>List of items in the database</h4>
</div>
@foreach (var item in Model)
{
var itemId = item.Id;
//var itemDetailsUrl = UrlProvider<SkillsController>.GetUrl(c => c.Edit(itemId));
<div class="col-md-2">
<div class="thumbnail">
<a href="" class="thumbnail">
<img src="/Content/Images/default_image.png" alt="..." />
</a>
<div class="caption">
<p>@item.Name</p>
<p>
@*@Html.ActionLink("Delete", "Delete", item)<br />*@
@*<a href="@itemDetailsUrl"> Edit </a>*@
</p>
</div>
</div>
</div>
}
</div>
|
apache-2.0
|
C#
|
8594f53f01729e13730925d8d24ca3ad6e15eb96
|
fix nullable
|
acple/ParsecSharp
|
ParsecSharp/Core/Result/SuspendedResult.cs
|
ParsecSharp/Core/Result/SuspendedResult.cs
|
using System;
using System.Runtime.InteropServices;
namespace ParsecSharp
{
[StructLayout(LayoutKind.Auto)]
public readonly struct SuspendedResult<TToken, T> : ISuspendedState<TToken>
{
public Result<TToken, T> Result { get; }
public ISuspendedState<TToken> Rest { get; }
IDisposable? ISuspendedState<TToken>.InnerResource => this.Rest.InnerResource;
private SuspendedResult(Result<TToken, T> result, ISuspendedState<TToken> rest)
{
this.Result = result;
this.Rest = rest;
}
public void Deconstruct(out Result<TToken, T> result, out ISuspendedState<TToken> rest)
{
result = this.Result;
rest = this.Rest;
}
SuspendedResult<TToken, TResult> ISuspendedState<TToken>.Continue<TResult>(Parser<TToken, TResult> parser)
=> this.Rest.Continue(parser);
public void Dispose()
=> this.Rest.Dispose();
public static SuspendedResult<TToken, T> Create<TState>(Result<TToken, T> result, TState state)
where TState : IParsecState<TToken, TState>
=> new SuspendedResult<TToken, T>(result, new StateBox<TState>(state));
private sealed class StateBox<TState> : ISuspendedState<TToken>
where TState : IParsecState<TToken, TState>
{
private readonly TState _state;
public IDisposable? InnerResource => this._state.InnerResource;
public StateBox(TState state)
{
this._state = state;
}
public SuspendedResult<TToken, TResult> Continue<TResult>(Parser<TToken, TResult> parser)
=> parser.ParsePartially(this._state);
public void Dispose()
=> this._state.Dispose();
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace ParsecSharp
{
[StructLayout(LayoutKind.Auto)]
public readonly struct SuspendedResult<TToken, T> : ISuspendedState<TToken>
{
public Result<TToken, T> Result { get; }
public ISuspendedState<TToken> Rest { get; }
IDisposable? ISuspendedState<TToken>.InnerResource => this.Rest?.InnerResource;
private SuspendedResult(Result<TToken, T> result, ISuspendedState<TToken> rest)
{
this.Result = result;
this.Rest = rest;
}
public void Deconstruct(out Result<TToken, T> result, out ISuspendedState<TToken> rest)
{
result = this.Result;
rest = this.Rest;
}
SuspendedResult<TToken, TResult> ISuspendedState<TToken>.Continue<TResult>(Parser<TToken, TResult> parser)
=> this.Rest.Continue(parser);
public void Dispose()
=> this.Rest?.Dispose();
public static SuspendedResult<TToken, T> Create<TState>(Result<TToken, T> result, TState state)
where TState : IParsecState<TToken, TState>
=> new SuspendedResult<TToken, T>(result, new StateBox<TState>(state));
private sealed class StateBox<TState> : ISuspendedState<TToken>
where TState : IParsecState<TToken, TState>
{
private readonly TState _state;
public IDisposable? InnerResource => this._state.InnerResource;
public StateBox(TState state)
{
this._state = state;
}
public SuspendedResult<TToken, TResult> Continue<TResult>(Parser<TToken, TResult> parser)
=> parser.ParsePartially(this._state);
public void Dispose()
=> this._state.Dispose();
}
}
}
|
mit
|
C#
|
0eef398ca74ebf8d860ae81b86eab3ee0f0d9636
|
Remove redundant using directive
|
EVAST9919/osu,johnneijzen/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,peppy/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,2yangk23/osu,NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,ZLima12/osu,ppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new
|
osu.Game.Rulesets.Taiko/Objects/Drawables/DrawableSwellTick.cs
|
osu.Game.Rulesets.Taiko/Objects/Drawables/DrawableSwellTick.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.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Objects.Drawables
{
public class DrawableSwellTick : DrawableTaikoHitObject<SwellTick>
{
public override bool DisplayResult => false;
public DrawableSwellTick(SwellTick hitObject)
: base(hitObject)
{
}
public void TriggerResult(HitResult type) => ApplyResult(r => r.Type = type);
protected override void CheckForResult(bool userTriggered, double timeOffset)
{
}
public override bool OnPressed(TaikoAction action) => false;
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Objects.Drawables
{
public class DrawableSwellTick : DrawableTaikoHitObject<SwellTick>
{
public override bool DisplayResult => false;
public DrawableSwellTick(SwellTick hitObject)
: base(hitObject)
{
}
public void TriggerResult(HitResult type) => ApplyResult(r => r.Type = type);
protected override void CheckForResult(bool userTriggered, double timeOffset)
{
}
public override bool OnPressed(TaikoAction action) => false;
}
}
|
mit
|
C#
|
1b8c9742755b577154f3af146b6b9e78a98e1673
|
throw exception in case of compilation error
|
dinazil/blogsamples,dinazil/blogsamples,dinazil/blogsamples
|
run_time_code_generation/RpcClientGenerator/ClientGenerator.cs
|
run_time_code_generation/RpcClientGenerator/ClientGenerator.cs
|
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
namespace RpcClientGenerator
{
public static class ClientGenerator
{
public static T GenerateRpcClient<T> (IRpcClient client) where T : class
{
string code = GenerateInterfaceWrapperCode<T> ();
var provider = CodeDomProvider.CreateProvider("CSharp");
var parameters = new CompilerParameters ();
parameters.ReferencedAssemblies.Add (typeof(T).Assembly.Location);
var result = provider.CompileAssemblyFromSource (parameters, code);
if (result.Errors.HasErrors)
{
throw new Exception ("Could not compile auto-generated code");
}
var smartClientType = result.CompiledAssembly.GetType ("SmartClient");
return (T)Activator.CreateInstance (smartClientType, new object[] { client }, null);
}
private static string GeneratePrefixCode<T>()
{
string interfaceName = typeof(T).FullName;
var code = GetFormattingString("prefix");
return code.Replace ("{interfaceName}", interfaceName);
}
private static string GenerateMethodCode(MethodInfo method)
{
string returnType = method.ReturnType.FullName;
string methodName = method.Name;
string parameterType = method.GetParameters ().Single ().ParameterType.FullName;
var remoteNameAttribute = (RemoteProcedureNameAttribute)Attribute.GetCustomAttribute (method, typeof(RemoteProcedureNameAttribute));
string remoteMethodName = remoteNameAttribute == null ? method.Name : remoteNameAttribute.Name;
var code = GetFormattingString("method");
code = code.Replace ("{returnType}", returnType);
code = code.Replace ("{methodName}", methodName);
code = code.Replace ("{remoteMethodName}", remoteMethodName);
return code.Replace ("{parameterType}", parameterType);
}
private static string GenerateSuffixCode()
{
return GetFormattingString("suffix");
}
private static string GenerateInterfaceWrapperCode<T>()
{
string start = GeneratePrefixCode<T> ();
string end = GenerateSuffixCode ();
var methodInfos = typeof(T).GetMethods (BindingFlags.Public | BindingFlags.Instance);
string methods = string.Join(Environment.NewLine, methodInfos.Select(GenerateMethodCode));
return $"{start}{Environment.NewLine}{methods}{Environment.NewLine}{end}";
}
private static string GetFormattingString(string resource)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "RpcClientGenerator.Resources." + resource + ".txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
|
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
namespace RpcClientGenerator
{
public static class ClientGenerator
{
public static T GenerateRpcClient<T> (IRpcClient client) where T : class
{
string code = GenerateInterfaceWrapperCode<T> ();
var provider = CodeDomProvider.CreateProvider("CSharp");
var parameters = new CompilerParameters ();
parameters.ReferencedAssemblies.Add (typeof(T).Assembly.Location);
var result = provider.CompileAssemblyFromSource (parameters, code);
if (result.Errors.HasErrors)
{
Console.WriteLine (code);
Console.WriteLine ("Errors:");
foreach (var error in result.Errors)
{
Console.WriteLine (error);
}
}
var smartClientType = result.CompiledAssembly.GetType ("SmartClient");
return (T)Activator.CreateInstance (smartClientType, new object[] { client }, null);
}
private static string GeneratePrefixCode<T>()
{
string interfaceName = typeof(T).FullName;
var code = GetFormattingString("prefix");
return code.Replace ("{interfaceName}", interfaceName);
}
private static string GenerateMethodCode(MethodInfo method)
{
string returnType = method.ReturnType.FullName;
string methodName = method.Name;
string parameterType = method.GetParameters ().Single ().ParameterType.FullName;
var remoteNameAttribute = (RemoteProcedureNameAttribute)Attribute.GetCustomAttribute (method, typeof(RemoteProcedureNameAttribute));
string remoteMethodName = remoteNameAttribute == null ? method.Name : remoteNameAttribute.Name;
var code = GetFormattingString("method");
code = code.Replace ("{returnType}", returnType);
code = code.Replace ("{methodName}", methodName);
code = code.Replace ("{remoteMethodName}", remoteMethodName);
return code.Replace ("{parameterType}", parameterType);
}
private static string GenerateSuffixCode()
{
return GetFormattingString("suffix");
}
private static string GenerateInterfaceWrapperCode<T>()
{
string start = GeneratePrefixCode<T> ();
string end = GenerateSuffixCode ();
var methodInfos = typeof(T).GetMethods (BindingFlags.Public | BindingFlags.Instance);
string methods = string.Join(Environment.NewLine, methodInfos.Select(GenerateMethodCode));
return $"{start}{Environment.NewLine}{methods}{Environment.NewLine}{end}";
}
private static string GetFormattingString(string resource)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "RpcClientGenerator.Resources." + resource + ".txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
|
mit
|
C#
|
00fa7f0837ddfbae4bfd933b96b8f7da6fe68afd
|
Handle empty entity name in rescuer
|
jarzynam/continuous,jarzynam/rescuer
|
src/Rescuer/Rescuer.Management/Controller/RescuerController.cs
|
src/Rescuer/Rescuer.Management/Controller/RescuerController.cs
|
using System;
using System.Text;
using Rescuer.Management.Rescuers;
namespace Rescuer.Management.Controller
{
public class RescuerController : IRescuerController
{
private readonly IRescuerFactory _factory;
public RescuerController(IRescuerFactory factory)
{
_factory = factory;
}
public IRescuer[] IntializeRescuers(string[] monitoredEntities)
{
var rescuers = new IRescuer[monitoredEntities.Length];
for (int i = 0; i < rescuers.Length; i++)
{
if (String.IsNullOrWhiteSpace(monitoredEntities[i]))
{
var entitiesString = ToFlatString(monitoredEntities);
throw new ArgumentException($"monitored entity name can't be null or empty! FailedIndex: {i} Array: [{entitiesString}]");
}
rescuers[i] = _factory.Create();
rescuers[i].Connect(monitoredEntities[i]);
}
return rescuers;
}
public void DoWork(IRescuer[] rescuers)
{
for (int i = 0; i < rescuers.Length; i++)
{
rescuers[i].MonitorAndRescue();
}
}
private static string ToFlatString(string[] array)
{
var builder = new StringBuilder();
foreach (var entity in array)
{
builder.Append(entity);
builder.Append(",");
}
var str = builder.ToString();
return str.Remove(str.Length - 1, 1);
}
}
}
|
using Rescuer.Management.Rescuers;
namespace Rescuer.Management.Controller
{
public class RescuerController : IRescuerController
{
private readonly IRescuerFactory _factory;
public RescuerController(IRescuerFactory factory)
{
_factory = factory;
}
public IRescuer[] IntializeRescuers(string[] monitoredEntities)
{
var rescuers = new IRescuer[monitoredEntities.Length];
for (int i = 0; i < rescuers.Length; i++)
{
rescuers[i] = _factory.Create();
rescuers[i].Connect(monitoredEntities[i]);
}
return rescuers;
}
public void DoWork(IRescuer[] rescuers)
{
for (int i = 0; i < rescuers.Length; i++)
{
rescuers[i].MonitorAndRescue();
}
}
}
}
|
mit
|
C#
|
4c4d3a9d3dc8cde0e9ec2804c2a11f4a483355ac
|
Add string validation
|
protyposis/Aurio,protyposis/Aurio
|
AudioAlign/AudioAlign.WaveControls/TimeSpanConverter.cs
|
AudioAlign/AudioAlign.WaveControls/TimeSpanConverter.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
namespace AudioAlign.WaveControls {
/// <summary>
/// Converts a TimeSpan struct to its string representative by formatting it with the format specified by the parameter.
/// </summary>
public class TimeSpanConverter : IValueConverter {
#region IValueConverter Members
public static readonly string DEFAULT_FORMAT = "d\\.hh\\:mm\\:ss\\.fffffff";
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
string format = parameter as string ?? DEFAULT_FORMAT;
TimeSpan timeSpan = new TimeSpan();
if ((value as TimeSpan?) != null) {
timeSpan = (TimeSpan)value;
}
else if ((value as long?) != null) {
long ticks = (long)value;
timeSpan = new TimeSpan(ticks);
}
return format != null ? timeSpan.ToString(format) : timeSpan.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
string input = (string)value;
string format = parameter as string ?? DEFAULT_FORMAT;
try {
if (targetType == typeof(long)) {
return TimeSpan.ParseExact(input, format, null).Ticks;
}
else if (targetType == typeof(TimeSpan)) {
return TimeSpan.ParseExact(input, format, null);
}
}
catch (Exception e) {
return new ValidationResult(false, e.Message);
}
return null;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace AudioAlign.WaveControls {
/// <summary>
/// Converts a TimeSpan struct to its string representative by formatting it with the format specified by the parameter.
/// </summary>
public class TimeSpanConverter : IValueConverter {
#region IValueConverter Members
public static readonly string DEFAULT_FORMAT = "d\\.hh\\:mm\\:ss\\.fffffff";
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
string format = parameter as string ?? DEFAULT_FORMAT;
TimeSpan timeSpan = new TimeSpan();
if ((value as TimeSpan?) != null) {
timeSpan = (TimeSpan)value;
}
else if ((value as long?) != null) {
long ticks = (long)value;
timeSpan = new TimeSpan(ticks);
}
return format != null ? timeSpan.ToString(format) : timeSpan.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
string input = (string)value;
string format = parameter as string ?? DEFAULT_FORMAT;
if (targetType == typeof(long)) {
return TimeSpan.ParseExact(input, format, null).Ticks;
}
else if (targetType == typeof(TimeSpan)) {
return TimeSpan.ParseExact(input, format, null);
}
return null;
}
#endregion
}
}
|
agpl-3.0
|
C#
|
23e0e4583ca3d09851a8e40658a4392c369c9d28
|
Change in VS
|
miladinoviczeljko/GitTest1
|
SimpleWebApi/SimpleWebApi/Controllers/PingController.cs
|
SimpleWebApi/SimpleWebApi/Controllers/PingController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace SimpleWebApi.Controllers
{
public class PingController : Controller
{
[HttpGet]
[Route("ping")]
public IActionResult Ping()
{
// Change in Visual studio
return Ok("pongChanged");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace SimpleWebApi.Controllers
{
public class PingController : Controller
{
[HttpGet]
[Route("ping")]
public IActionResult Ping()
{
return Ok("pongChanged");
}
}
}
|
mit
|
C#
|
58fe66b729be7cb6debd1e2dabd5d258b2fb1713
|
Fix string test for ubuntu
|
stofte/ream-query
|
query/test/ReamQuery.Test/Helpers.cs
|
query/test/ReamQuery.Test/Helpers.cs
|
namespace ReamQuery.Test
{
using System;
using Xunit;
using ReamQuery.Helpers;
using Microsoft.CodeAnalysis.Text;
public class Helpers
{
[Fact]
public void String_InsertTextAt()
{
var inp = Environment.NewLine + " text" + Environment.NewLine;
var exp = Environment.NewLine + " new text" + Environment.NewLine;
var output = inp.InsertTextAt("new", 1, 1);
Assert.Equal(exp, output);
}
[Fact]
public void String_NormalizeNewlines_And_InsertTextAt()
{
var inp = "\r\n text\n";
var exp = Environment.NewLine + " new text" + Environment.NewLine;
var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1);
Assert.Equal(exp, output);
}
[Fact]
public void String_NormalizeNewlines()
{
var inp = "\r\n text\n";
var exp = Environment.NewLine + " text" + Environment.NewLine;
var output = inp.NormalizeNewlines();
Assert.Equal(exp, output);
}
[Fact]
public void String_ReplaceToken()
{
var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine;
var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine;
LinePosition pos;
var output = inp.ReplaceToken("token", string.Empty, out pos);
Assert.Equal(new LinePosition(2, 1), pos);
Assert.Equal(exp, output);
}
}
}
|
namespace ReamQuery.Test
{
using System;
using Xunit;
using ReamQuery.Helpers;
using Microsoft.CodeAnalysis.Text;
public class Helpers
{
[Fact]
public void String_InsertTextAt()
{
var inp = "\r\n text\r\n";
var exp = "\r\n new text\r\n";
var output = inp.InsertTextAt("new", 1, 1);
Assert.Equal(exp, output);
}
[Fact]
public void String_NormalizeNewlines_And_InsertTextAt()
{
var inp = "\r\n text\n";
var exp = "\r\n new text\r\n";
var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1);
Assert.Equal(exp, output);
}
[Fact]
public void String_NormalizeNewlines()
{
var inp = "\r\n text\n";
var exp = Environment.NewLine + " text" + Environment.NewLine;
var output = inp.NormalizeNewlines();
Assert.Equal(exp, output);
}
[Fact]
public void String_ReplaceToken()
{
var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine;
var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine;
LinePosition pos;
var output = inp.ReplaceToken("token", string.Empty, out pos);
Assert.Equal(new LinePosition(2, 1), pos);
Assert.Equal(exp, output);
}
}
}
|
mit
|
C#
|
9b196b0348dfdd296a3c4ca0797f165abb8b633e
|
fix #353 SideBarUserArea needs to handle the case of not logging in.
|
aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template
|
aspnet-core/src/AbpCompanyName.AbpProjectName.Web.Mvc/Views/Shared/Components/SideBarUserArea/Default.cshtml
|
aspnet-core/src/AbpCompanyName.AbpProjectName.Web.Mvc/Views/Shared/Components/SideBarUserArea/Default.cshtml
|
@using AbpCompanyName.AbpProjectName.Web.Views.Shared.Components.SideBarUserArea
@model SideBarUserAreaViewModel
@if (Model.LoginInformations != null && Model.LoginInformations.User != null)
{
<div class="user-info">
<div class="image">
<img src="~/images/user.png" width="48" height="48" alt="User" />
</div>
<div class="info-container">
<div class="name" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">@Html.Raw(Model.GetShownLoginName())</div>
<div class="email">@Model.LoginInformations.User.EmailAddress</div>
<div class="btn-group user-helper-dropdown">
<i class="material-icons" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">keyboard_arrow_down</i>
<ul class="dropdown-menu pull-right">
<li><a href="@Url.Action("Logout", "Account", new { area= string.Empty })"><i class="material-icons">input</i>@L("Logout")</a></li>
</ul>
</div>
</div>
</div>
}
|
@using AbpCompanyName.AbpProjectName.Web.Views.Shared.Components.SideBarUserArea
@model SideBarUserAreaViewModel
<div class="user-info">
<div class="image">
<img src="~/images/user.png" width="48" height="48" alt="User" />
</div>
<div class="info-container">
<div class="name" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">@Html.Raw(Model.GetShownLoginName())</div>
<div class="email">@Model.LoginInformations.User.EmailAddress</div>
<div class="btn-group user-helper-dropdown">
<i class="material-icons" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">keyboard_arrow_down</i>
<ul class="dropdown-menu pull-right">
<li><a href="@Url.Action("Logout", "Account", new { area= string.Empty })"><i class="material-icons">input</i>@L("Logout")</a></li>
</ul>
</div>
</div>
</div>
|
mit
|
C#
|
c8ea86d3421a5474763cb871f04a828083bfb354
|
Change CC/BCC capitalization.
|
brendanjbaker/Bakery
|
src/Bakery/Mail/RecipientType.cs
|
src/Bakery/Mail/RecipientType.cs
|
namespace Bakery.Mail
{
public enum RecipientType
{
Bcc,
Cc,
To
}
}
|
namespace Bakery.Mail
{
public enum RecipientType
{
BCC,
CC,
To
}
}
|
mit
|
C#
|
3fa011abe49793fd65e933298fe9a2f5b5c023d6
|
Update tests
|
pakdev/roslyn-analyzers,mavasani/roslyn-analyzers,mavasani/roslyn-analyzers,dotnet/roslyn-analyzers,pakdev/roslyn-analyzers,dotnet/roslyn-analyzers
|
src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/QualityGuidelines/DoNotDeclareEventFieldsAsVirtualTests.cs
|
src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/QualityGuidelines/DoNotDeclareEventFieldsAsVirtualTests.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.DoNotDeclareEventFieldsAsVirtual,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.UnitTests.QualityGuidelines
{
public class DoNotDeclareEventFieldsAsVirtualTests
{
[Fact]
public async Task EventFieldVirtual_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
public virtual event EventHandler ThresholdReached;
}",
VerifyCS.Diagnostic().WithLocation(5, 39).WithArguments("ThresholdReached"));
}
[Fact]
public async Task EventPropertyVirtual_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
public virtual event EventHandler ThresholdReached
{
add
{
}
remove
{
}
}
}");
}
[Theory]
// General analyzer option
[InlineData("public", "dotnet_code_quality.api_surface = public")]
[InlineData("public", "dotnet_code_quality.api_surface = private, internal, public")]
[InlineData("public", "dotnet_code_quality.api_surface = all")]
[InlineData("protected", "dotnet_code_quality.api_surface = public")]
[InlineData("protected", "dotnet_code_quality.api_surface = private, internal, public")]
[InlineData("protected", "dotnet_code_quality.api_surface = all")]
[InlineData("internal", "dotnet_code_quality.api_surface = internal")]
[InlineData("internal", "dotnet_code_quality.api_surface = private, internal")]
[InlineData("internal", "dotnet_code_quality.api_surface = all")]
// Specific analyzer option
[InlineData("internal", "dotnet_code_quality.CA1070.api_surface = all")]
[InlineData("internal", "dotnet_code_quality.Design.api_surface = all")]
// General + Specific analyzer option
[InlineData("internal", @"dotnet_code_quality.api_surface = private
dotnet_code_quality.CA1070.api_surface = all")]
// Case-insensitive analyzer option
[InlineData("internal", "DOTNET_code_quality.CA1070.API_SURFACE = ALL")]
// Invalid analyzer option ignored
[InlineData("internal", @"dotnet_code_quality.api_surface = all
dotnet_code_quality.CA1070.api_surface_2 = private")]
public async Task CSharp_ApiSurfaceOption(string accessibility, string editorConfigText)
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
$@"
using System;
public class OuterClass
{{
{accessibility} virtual event EventHandler [|ThresholdReached|];
}}"
},
AdditionalFiles = { (".editorconfig", editorConfigText), },
},
}.RunAsync();
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.DoNotDeclareEventFieldsAsVirtual,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.UnitTests.QualityGuidelines
{
public class DoNotDeclareEventFieldsAsVirtualTests
{
[Fact]
public async Task EventFieldVirtual_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
public virtual event EventHandler ThresholdReached;
}",
VerifyCS.Diagnostic().WithLocation(5, 39));
}
[Fact]
public async Task EventPropertyVirtual_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
public virtual event EventHandler ThresholdReached
{
add
{
}
remove
{
}
}
}");
}
[Fact]
public async Task EventFieldVirtualAllAccessibilities_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
public virtual event EventHandler [|Event1|];
protected virtual event EventHandler [|Event2|];
internal virtual event EventHandler [|Event3|];
protected internal virtual event EventHandler [|Event4|];
}");
}
}
}
|
mit
|
C#
|
ac7ce43739270fd19d447148c14a49ef152eeb9a
|
Implement LeadingSignCount and LeadingZeroCount ARM64 Base Intrinsics (#20306)
|
wtgodbe/corefx,mmitche/corefx,shimingsg/corefx,mmitche/corefx,Jiayili1/corefx,ptoonen/corefx,wtgodbe/corefx,ericstj/corefx,Jiayili1/corefx,ericstj/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,mmitche/corefx,mmitche/corefx,mmitche/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,BrennanConroy/corefx,mmitche/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,ericstj/corefx,Jiayili1/corefx,wtgodbe/corefx,Jiayili1/corefx,ptoonen/corefx,ptoonen/corefx,ptoonen/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,mmitche/corefx,ptoonen/corefx,Jiayili1/corefx,Jiayili1/corefx,wtgodbe/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx,BrennanConroy/corefx,ViktorHofer/corefx,ViktorHofer/corefx,BrennanConroy/corefx,shimingsg/corefx,ericstj/corefx,ptoonen/corefx,ericstj/corefx
|
src/Common/src/CoreLib/System/Runtime/Intrinsics/Arm/Arm64/Base.cs
|
src/Common/src/CoreLib/System/Runtime/Intrinsics/Arm/Arm64/Base.cs
|
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.Arm.Arm64
{
/// <summary>
/// This class provides access to the Arm64 Base intrinsics
///
/// These intrinsics are supported by all Arm64 CPUs
/// </summary>
[CLSCompliant(false)]
public static class Base
{
public static bool IsSupported { get { return IsSupported; }}
/// <summary>
/// Vector LeadingSignCount
/// Corresponds to integer forms of ARM64 CLS
/// </summary>
public static int LeadingSignCount(int value) => LeadingSignCount(value);
public static int LeadingSignCount(long value) => LeadingSignCount(value);
/// <summary>
/// Vector LeadingZeroCount
/// Corresponds to integer forms of ARM64 CLZ
/// </summary>
public static int LeadingZeroCount(int value) => LeadingZeroCount(value);
public static int LeadingZeroCount(uint value) => LeadingZeroCount(value);
public static int LeadingZeroCount(long value) => LeadingZeroCount(value);
public static int LeadingZeroCount(ulong value) => LeadingZeroCount(value);
}
}
|
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.Arm.Arm64
{
/// <summary>
/// This class provides access to the Arm64 Base intrinsics
///
/// These intrinsics are supported by all Arm64 CPUs
/// </summary>
[CLSCompliant(false)]
public static class Base
{
public static bool IsSupported { get { return false; }}
/// <summary>
/// Vector LeadingSignCount
/// Corresponds to integer forms of ARM64 CLS
/// </summary>
public static int LeadingSignCount(int value) => LeadingSignCount(value);
public static int LeadingSignCount(long value) => LeadingSignCount(value);
/// <summary>
/// Vector LeadingZeroCount
/// Corresponds to integer forms of ARM64 CLZ
/// </summary>
public static int LeadingZeroCount(int value) => LeadingZeroCount(value);
public static int LeadingZeroCount(uint value) => LeadingZeroCount(value);
public static int LeadingZeroCount(long value) => LeadingZeroCount(value);
public static int LeadingZeroCount(ulong value) => LeadingZeroCount(value);
}
}
|
mit
|
C#
|
d1770cc9c2214b0db6a3e68b6742223849e20db4
|
Use IClassificationTypeRegistryService instead of faking the behavior
|
mavasani/roslyn,mavasani/roslyn,VSadov/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,davkean/roslyn,gafter/roslyn,xasx/roslyn,stephentoub/roslyn,AmadeusW/roslyn,agocke/roslyn,VSadov/roslyn,tmeschter/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,panopticoncentral/roslyn,aelij/roslyn,reaction1989/roslyn,brettfo/roslyn,reaction1989/roslyn,tmeschter/roslyn,bkoelman/roslyn,physhi/roslyn,MichalStrehovsky/roslyn,dotnet/roslyn,abock/roslyn,cston/roslyn,dotnet/roslyn,heejaechang/roslyn,diryboy/roslyn,tannergooding/roslyn,aelij/roslyn,dpoeschl/roslyn,cston/roslyn,ErikSchierboom/roslyn,bkoelman/roslyn,genlu/roslyn,eriawan/roslyn,tmeschter/roslyn,xasx/roslyn,OmarTawfik/roslyn,tmat/roslyn,dotnet/roslyn,OmarTawfik/roslyn,KevinRansom/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,gafter/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,agocke/roslyn,tmat/roslyn,bkoelman/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,panopticoncentral/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,MichalStrehovsky/roslyn,jamesqo/roslyn,CyrusNajmabadi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,brettfo/roslyn,agocke/roslyn,KirillOsenkov/roslyn,physhi/roslyn,wvdd007/roslyn,mavasani/roslyn,paulvanbrenk/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bartdesmet/roslyn,xasx/roslyn,nguerrera/roslyn,diryboy/roslyn,weltkante/roslyn,heejaechang/roslyn,swaroop-sridhar/roslyn,abock/roslyn,cston/roslyn,weltkante/roslyn,wvdd007/roslyn,stephentoub/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,OmarTawfik/roslyn,jcouv/roslyn,abock/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,sharwell/roslyn,davkean/roslyn,genlu/roslyn,diryboy/roslyn,bartdesmet/roslyn,eriawan/roslyn,AmadeusW/roslyn,physhi/roslyn,paulvanbrenk/roslyn,davkean/roslyn,brettfo/roslyn,jmarolf/roslyn,nguerrera/roslyn,KevinRansom/roslyn,genlu/roslyn,jcouv/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,jcouv/roslyn,DustinCampbell/roslyn,dpoeschl/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mgoertz-msft/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,nguerrera/roslyn,VSadov/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,AlekseyTs/roslyn,dpoeschl/roslyn,jamesqo/roslyn,jamesqo/roslyn
|
src/EditorFeatures/Test/Workspaces/ClassificationTypeNamesTests.cs
|
src/EditorFeatures/Test/Workspaces/ClassificationTypeNamesTests.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Reflection;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public class ClassificationTypeNamesTests
{
public static IEnumerable<object[]> AllClassificationTypeNames
{
get
{
foreach (var field in typeof(ClassificationTypeNames).GetFields(BindingFlags.Static | BindingFlags.Public))
{
yield return new object[] { field.Name, field.GetRawConstantValue() };
}
}
}
[Theory]
[MemberData(nameof(AllClassificationTypeNames))]
[WorkItem(25716, "https://github.com/dotnet/roslyn/issues/25716")]
public void ClassificationTypeExported(string fieldName, object constantValue)
{
var classificationTypeName = Assert.IsType<string>(constantValue);
var exportProvider = TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
var classificationTypeRegistryService = exportProvider.GetExport<IClassificationTypeRegistryService>().Value;
var classificationType = classificationTypeRegistryService.GetClassificationType(classificationTypeName);
Assert.True(classificationType != null, $"{nameof(ClassificationTypeNames)}.{fieldName} has value \"{classificationTypeName}\", but no matching {nameof(ClassificationTypeDefinition)} was exported.");
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public class ClassificationTypeNamesTests
{
public static IEnumerable<object[]> AllClassificationTypeNames
{
get
{
foreach (var field in typeof(ClassificationTypeNames).GetFields(BindingFlags.Static | BindingFlags.Public))
{
yield return new object[] { field.Name, field.GetRawConstantValue() };
}
}
}
[Theory]
[MemberData(nameof(AllClassificationTypeNames))]
[WorkItem(25716, "https://github.com/dotnet/roslyn/issues/25716")]
public void ClassificationTypeExported(string fieldName, object constantValue)
{
Assert.IsType<string>(constantValue);
string classificationTypeName = (string)constantValue;
var exportProvider = TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
var exports = exportProvider.GetExports<ClassificationTypeDefinition, IClassificationTypeDefinitionMetadata>();
var export = exports.FirstOrDefault(x => x.Metadata.Name == classificationTypeName);
Assert.True(export != null, $"{nameof(ClassificationTypeNames)}.{fieldName} has value \"{classificationTypeName}\", but no matching {nameof(ClassificationTypeDefinition)} was exported.");
}
public interface IClassificationTypeDefinitionMetadata
{
string Name
{
get;
}
[DefaultValue(null)]
IEnumerable<string> BaseDefinition
{
get;
}
}
}
}
|
mit
|
C#
|
d8c009b734758936cbba86e5e9b69f51289e7af1
|
Fix duplicate 'CollectionBehavior' attribute
|
akrisiun/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jazzay/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,MrDaedra/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,MrDaedra/Avalonia
|
tests/Avalonia.Markup.Xaml.UnitTests/Properties/AssemblyInfo.cs
|
tests/Avalonia.Markup.Xaml.UnitTests/Properties/AssemblyInfo.cs
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Reflection;
using Xunit;
[assembly: AssemblyTitle("Avalonia.Markup.Xaml.UnitTests")]
// Don't run tests in parallel.
[assembly: CollectionBehavior(MaxParallelThreads = 1)]
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Reflection;
using Xunit;
[assembly: AssemblyTitle("Avalonia.Markup.Xaml.UnitTests")]
// Don't run tests in parallel.
[assembly: CollectionBehavior(DisableTestParallelization = true)]
[assembly: CollectionBehavior(MaxParallelThreads = 1)]
|
mit
|
C#
|
81ae20bd85c6c471e9292a8c02ddb903586b7ab1
|
Add Copyrights
|
mono/ServiceStack.Text,NServiceKit/NServiceKit.Text,gerryhigh/ServiceStack.Text,NServiceKit/NServiceKit.Text,gerryhigh/ServiceStack.Text,mono/ServiceStack.Text
|
src/ServiceStack.Text/HashSet.cs
|
src/ServiceStack.Text/HashSet.cs
|
//
// http://code.google.com/p/servicestack/wiki/TypeSerializer
// ServiceStack.Text: .NET C# POCO Type Text Serializer.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
// Mijail Cisneros (cisneros@mijail.ru)
//
// Copyright 2012 Liquidbit Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ServiceStack.Text.WP
{
///<summary>
/// A hashset implementation that uses an IDictionary
///</summary>
public class HashSet<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
private readonly Dictionary<T, short> _dict;
public HashSet()
{
_dict = new Dictionary<T, short>();
}
public HashSet(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
_dict = new Dictionary<T, short>(collection.Count());
foreach (T item in collection)
Add(item);
}
public void Add(T item)
{
_dict.Add(item, 0);
}
public void Clear()
{
_dict.Clear();
}
public bool Contains(T item)
{
return _dict.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_dict.Keys.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return _dict.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return _dict.Keys.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _dict.Keys.GetEnumerator();
}
public int Count
{
get { return _dict.Keys.Count(); }
}
public bool IsReadOnly
{
get { return false; }
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ServiceStack.Text.WP
{
///<summary>
/// A hashset implementation that uses an IDictionary
///</summary>
public class HashSet<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
private readonly Dictionary<T, short> _dict;
public HashSet()
{
_dict = new Dictionary<T, short>();
}
public HashSet(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
_dict = new Dictionary<T, short>(collection.Count());
foreach (T item in collection)
Add(item);
}
public void Add(T item)
{
_dict.Add(item, 0);
}
public void Clear()
{
_dict.Clear();
}
public bool Contains(T item)
{
return _dict.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_dict.Keys.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return _dict.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return _dict.Keys.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _dict.Keys.GetEnumerator();
}
public int Count
{
get { return _dict.Keys.Count(); }
}
public bool IsReadOnly
{
get { return false; }
}
}
}
|
bsd-3-clause
|
C#
|
32991ca8df722aa6c05e982cfbdd5070b11697e9
|
Upgrade to latest Xamarin version
|
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
|
XamarinComponent/raygun4net/component/samples/Raygun.Android.Sample/Raygun.Android.Sample/Resources/Resource.Designer.cs
|
XamarinComponent/raygun4net/component/samples/Raygun.Android.Sample/Raygun.Android.Sample/Resources/Resource.Designer.cs
|
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("Raygun.Android.Sample.Resource", IsApplication=true)]
namespace Raygun.Android.Sample
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues()
{
global::Mindscape.Raygun4Net.Xamarin.Android.Resource.String.library_name = global::Raygun.Android.Sample.Resource.String.library_name;
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int Icon = 2130837504;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f050000
public const int MyButton = 2131034112;
static Id()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int Main = 2130903040;
static Layout()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f040002
public const int ApplicationName = 2130968578;
// aapt resource value: 0x7f040001
public const int Crash = 2130968577;
// aapt resource value: 0x7f040000
public const int library_name = 2130968576;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
|
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("Raygun.Android.Sample.Resource", IsApplication=true)]
namespace Raygun.Android.Sample
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues()
{
global::Mindscape.Raygun4Net.Xamarin.Android.Resource.String.library_name = global::Raygun.Android.Sample.Resource.String.library_name;
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int Icon = 2130837504;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f050000
public const int MyButton = 2131034112;
static Id()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int Main = 2130903040;
static Layout()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f040002
public const int ApplicationName = 2130968578;
// aapt resource value: 0x7f040001
public const int Crash = 2130968577;
// aapt resource value: 0x7f040000
public const int library_name = 2130968576;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
|
mit
|
C#
|
974bd2061afa2158df9f6bf8923ab3f467cbe9e8
|
Update 50.EnumConverter.cs
|
p07r0457/FileHelpers,MarcosMeli/FileHelpers,aim00ver/FileHelpers,guillaumejay/FileHelpers
|
FileHelpers.Examples/Examples/18.Converters/50.EnumConverter.cs
|
FileHelpers.Examples/Examples/18.Converters/50.EnumConverter.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using FileHelpers;
namespace ExamplesFx
{
public class EnumConverterExample : ExampleBase
{
//-> Name:Enum Converter
//-> Description:When you have a string field in your files that can be better handled if you map it to an enum.
//-> FileIn:Input.txt
/*ALFKI|Alfreds Futterkiste|Maria Anders|SalesRepresentative
ANATR|Ana Trujillo Emparedados y helados|Ana Trujillo|Owner
FRANR|France restauration|Carine Schmitt|MarketingManager
ANTON|Antonio Moreno Taquería|Antonio Moreno|Owner*/
//-> /File
//-> File:CustomerTitle.cs
public enum CustomerTitle
{
Owner,
SalesRepresentative,
MarketingManager
}
//-> /File
//-> File:Customers with Enum.cs
[DelimitedRecord("|")]
public class Customer
{
public string CustomerID;
public string CompanyName;
public string ContactName;
// Notice last field is our enumerator
public CustomerTitle ContactTitle;
}
//-> /File
//-> File:RunEngine.cs
public override void Run()
{
var engine = new DelimitedFileEngine<Customer>();
// Read input records, enumeration automatically converted
Customer[] customers = engine.ReadFile("Input.txt");
foreach (var cust in customers)
Console.WriteLine("Customer name {0} is a {1}", cust.ContactName, cust.ContactTitle);
}
//-> /File
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using FileHelpers;
namespace ExamplesFx
{
public class EnumConverterExample : ExampleBase
{
//-> Name:Enum Converter
//-> Description:When you have a string field in your files that can be better handled if you map it to an enum.
//-> FileIn:Input.txt
/*ALFKI|Alfreds Futterkiste|Maria Anders|SalesRepresentative
ANATR|Ana Trujillo Emparedados y helados|Ana Trujillo|Owner
FRANR|France restauration|Carine Schmitt|MarketingManager
ANTON|Antonio Moreno Taquería|Antonio Moreno|Owner*/
//-> /File
//-> File:CustomerTitle.cs
public enum CustomerTitle
{
Owner,
SalesRepresentative,
MarketingManager
}
//-> /File
//-> File:Customers with Enum.cs
[DelimitedRecord("|")]
public class Customer
{
public string CustomerID;
public string CompanyName;
public string ContactName;
// Notice last feild is our enumerator
public CustomerTitle ContactTitle;
}
//-> /File
//-> File:RunEngine.cs
public override void Run()
{
var engine = new DelimitedFileEngine<Customer>();
// Read input records, enumeration automatically converted
Customer[] customers = engine.ReadFile("Input.txt");
foreach (var cust in customers)
Console.WriteLine("Customer name {0} is a {1}", cust.ContactName, cust.ContactTitle);
}
//-> /File
}
}
|
mit
|
C#
|
be234f3adbb336510d01d18887d2b5a28df75abc
|
Change how the GrafeasClient is constructed
|
googleapis/google-cloud-dotnet,jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet
|
apis/Google.Cloud.DevTools.ContainerAnalysis.V1/Google.Cloud.DevTools.ContainerAnalysis.V1/ContainerAnalysisClientPartial.cs
|
apis/Google.Cloud.DevTools.ContainerAnalysis.V1/Google.Cloud.DevTools.ContainerAnalysis.V1/ContainerAnalysisClientPartial.cs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax.Grpc;
using Grafeas.V1;
using System;
namespace Google.Cloud.DevTools.ContainerAnalysis.V1
{
// Partial classes to provide easy access to the Grafeas API.
public partial class ContainerAnalysisSettings
{
/// <summary>
/// Settings for the Grafeas client returned by <see cref="ContainerAnalysisClient.GrafeasClient"/>.
/// </summary>
public GrafeasSettings GrafeasSettings { get; set; } = new GrafeasSettings();
partial void OnCopy(ContainerAnalysisSettings existing)
{
GrafeasSettings = existing.GrafeasSettings?.Clone();
}
}
public partial class ContainerAnalysisClient
{
/// <summary>
/// Returns a <see cref="GrafeasClient"/> using the same endpoint and credentials
/// as this client.
/// </summary>
public virtual GrafeasClient GrafeasClient => throw new NotImplementedException();
}
public partial class ContainerAnalysisClientImpl
{
private GrafeasClient _grafeasClient;
/// <inheritdoc />
public override GrafeasClient GrafeasClient => _grafeasClient;
partial void OnConstruction(ContainerAnalysis.ContainerAnalysisClient grpcClient, ContainerAnalysisSettings effectiveSettings, ClientHelper clientHelper) =>
_grafeasClient = new GrafeasClientImpl(grpcClient.CreateGrafeasClient(), effectiveSettings.GrafeasSettings);
}
public static partial class ContainerAnalysis
{
public partial class ContainerAnalysisClient
{
internal global::Grafeas.V1.Grafeas.GrafeasClient CreateGrafeasClient() => new global::Grafeas.V1.Grafeas.GrafeasClient(CallInvoker);
}
}
}
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax.Grpc;
using Grafeas.V1;
using System;
namespace Google.Cloud.DevTools.ContainerAnalysis.V1
{
// Partial classes to provide easy access to the Grafeas API.
public partial class ContainerAnalysisSettings
{
/// <summary>
/// Settings for the Grafeas client returned by <see cref="ContainerAnalysisClient.GrafeasClient"/>.
/// </summary>
public GrafeasSettings GrafeasSettings { get; set; } = new GrafeasSettings();
partial void OnCopy(ContainerAnalysisSettings existing)
{
GrafeasSettings = existing.GrafeasSettings?.Clone();
}
}
public partial class ContainerAnalysisClient
{
/// <summary>
/// Returns a <see cref="GrafeasClient"/> using the same endpoint and credentials
/// as this client.
/// </summary>
public virtual GrafeasClient GrafeasClient => throw new NotImplementedException();
}
public partial class ContainerAnalysisClientImpl
{
private GrafeasClient _grafeasClient;
/// <inheritdoc />
public override GrafeasClient GrafeasClient => _grafeasClient;
partial void OnConstruction(ContainerAnalysis.ContainerAnalysisClient grpcClient, ContainerAnalysisSettings effectiveSettings, ClientHelper clientHelper) =>
_grafeasClient = grpcClient.CreateGrafeasClient(effectiveSettings.GrafeasSettings);
}
public static partial class ContainerAnalysis
{
public partial class ContainerAnalysisClient
{
internal GrafeasClient CreateGrafeasClient(GrafeasSettings settings) => GrafeasClient.Create(CallInvoker, settings);
}
}
}
|
apache-2.0
|
C#
|
00cbe1b4d3751cbdec9016af5e2ef95343363a25
|
Rename var changeSet to commit
|
CamTechConsultants/CvsntGitImporter
|
Program.cs
|
Program.cs
|
/*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace CvsGitConverter
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
throw new ArgumentException("Need a cvs.log file");
var parser = new CvsLogParser(args[0]);
var revisions = from r in parser.Parse()
where !(r.Revision == "1.1" && Regex.IsMatch(r.Message, @"file .* was initially added on branch "))
select r;
var commits = new Dictionary<string, Commit>();
foreach (var revision in revisions)
{
Commit commit;
if (commits.TryGetValue(revision.CommitId, out commit))
{
commit.Add(revision);
}
else
{
commit = new Commit(revision.CommitId) { revision };
commits.Add(commit.CommitId, commit);
}
}
foreach (var commit in commits.Values.OrderBy(c => c.Time))
{
if (!commit.Verify())
{
Console.Error.WriteLine("Verification failed: {0} {1}", commit.CommitId, commit.Time);
foreach (var revision in commit)
Console.Error.WriteLine(" {0} r{1}", revision.File, revision.Revision);
foreach (var error in commit.Errors)
{
Console.Error.WriteLine(error);
Console.Error.WriteLine("========================================");
}
}
}
foreach (var f in parser.Files)
{
Console.Out.WriteLine("File {0}", f.Name);
foreach (var t in f.Branches)
Console.Out.WriteLine(" {0} = {1}", t.Key, t.Value);
}
}
}
}
|
/*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace CvsGitConverter
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
throw new ArgumentException("Need a cvs.log file");
var parser = new CvsLogParser(args[0]);
var revisions = from r in parser.Parse()
where !(r.Revision == "1.1" && Regex.IsMatch(r.Message, @"file .* was initially added on branch "))
select r;
var commits = new Dictionary<string, Commit>();
foreach (var revision in revisions)
{
Commit changeSet;
if (commits.TryGetValue(revision.CommitId, out changeSet))
{
changeSet.Add(revision);
}
else
{
changeSet = new Commit(revision.CommitId) { revision };
commits.Add(changeSet.CommitId, changeSet);
}
}
foreach (var commit in commits.Values.OrderBy(c => c.Time))
{
if (!commit.Verify())
{
Console.Error.WriteLine("Verification failed: {0} {1}", commit.CommitId, commit.Time);
foreach (var revision in commit)
Console.Error.WriteLine(" {0} r{1}", revision.File, revision.Revision);
foreach (var error in commit.Errors)
{
Console.Error.WriteLine(error);
Console.Error.WriteLine("========================================");
}
}
}
foreach (var f in parser.Files)
{
Console.Out.WriteLine("File {0}", f.Name);
foreach (var t in f.Branches)
Console.Out.WriteLine(" {0} = {1}", t.Key, t.Value);
}
}
}
}
|
mit
|
C#
|
f828e1de51c1533b1568976ce8545f33fe3f9554
|
define vars
|
ddahoo/trebuchet-calculator
|
Program.cs
|
Program.cs
|
using System;
class Program
{
float tHeight,
pMass,
wMass,
armLength,
backLength,
sLength;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
|
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
|
mit
|
C#
|
956ebf20123d3fb1a61aa2d208058ceb6ab4b2e2
|
update unit test for new behaviour
|
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
|
src/SFA.DAS.ProviderApprenticeshipsService.Application.UnitTests/Extensions/ITrainingProgrammeExtensionsTest/WhenDeterminingWhetherACourseIsActive.cs
|
src/SFA.DAS.ProviderApprenticeshipsService.Application.UnitTests/Extensions/ITrainingProgrammeExtensionsTest/WhenDeterminingWhetherACourseIsActive.cs
|
using System;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderApprenticeshipsService.Application.Extensions;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Models.ApprenticeshipCourse;
namespace SFA.DAS.ProviderApprenticeshipsService.Application.UnitTests.Extensions.ITrainingProgrammeExtensionsTest
{
[TestFixture]
public class WhenDeterminingWhetherACourseIsActive
{
[TestCase("2016-01-01", "2016-12-01", "2016-06-01", true, Description = "Within date range")]
[TestCase("2016-01-15", "2016-12-15", "2016-01-01", true, Description = "Within date range - ignoring start day")]
[TestCase("2016-01-15", "2016-12-15", "2016-12-30", false, Description = "After date range (but in same month as courseEnd")]
[TestCase(null, "2016-12-01", "2016-06-01", true, Description = "Within date range with no defined course start date")]
[TestCase("2016-01-01", null, "2016-06-01", true, Description = "Within date range, with no defined course end date")]
[TestCase(null, null, "2016-06-01", true, Description = "Within date range, with no defined course effective dates")]
[TestCase("2016-01-01", "2016-12-01", "2015-06-01", false, Description = "Outside (before) date range")]
[TestCase("2016-01-01", "2016-12-01", "2017-06-01", false, Description = "Outside (after) date range")]
public void ThenIfWithinCourseEffectiveRangeThenIsActive(DateTime? courseStart, DateTime? courseEnd, DateTime effectiveDate, bool expectIsActive)
{
//Arrange
var course = new Mock<ITrainingProgramme>();
course.SetupGet(x => x.EffectiveFrom).Returns(courseStart);
course.SetupGet(x => x.EffectiveTo).Returns(courseEnd);
//Act
var result = course.Object.IsActiveOn(effectiveDate);
//Assert
Assert.AreEqual(expectIsActive, result);
}
}
}
|
using System;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderApprenticeshipsService.Application.Extensions;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Models.ApprenticeshipCourse;
namespace SFA.DAS.ProviderApprenticeshipsService.Application.UnitTests.Extensions.ITrainingProgrammeExtensionsTest
{
[TestFixture]
public class WhenDeterminingWhetherACourseIsActive
{
[TestCase("2016-01-01", "2016-12-01", "2016-06-01", true, Description = "Within date range")]
[TestCase("2016-01-15", "2016-12-15", "2016-01-01", true, Description = "Within date range - ignoring start day")]
[TestCase("2016-01-15", "2016-12-15", "2016-12-30", true, Description = "Within date range - ignoring end day")]
[TestCase(null, "2016-12-01", "2016-06-01", true, Description = "Within date range with no defined course start date")]
[TestCase("2016-01-01", null, "2016-06-01", true, Description = "Within date range, with no defined course end date")]
[TestCase(null, null, "2016-06-01", true, Description = "Within date range, with no defined course effective dates")]
[TestCase("2016-01-01", "2016-12-01", "2015-06-01", false, Description = "Outside (before) date range")]
[TestCase("2016-01-01", "2016-12-01", "2017-06-01", false, Description = "Outside (after) date range")]
public void ThenIfWithinCourseEffectiveRangeThenIsActive(DateTime? courseStart, DateTime? courseEnd, DateTime effectiveDate, bool expectIsActive)
{
//Arrange
var course = new Mock<ITrainingProgramme>();
course.SetupGet(x => x.EffectiveFrom).Returns(courseStart);
course.SetupGet(x => x.EffectiveTo).Returns(courseEnd);
//Act
var result = course.Object.IsActiveOn(effectiveDate);
//Assert
Assert.AreEqual(expectIsActive, result);
}
}
}
|
mit
|
C#
|
cf4791ec99a84fbceb571600ff5d349bd6e2c593
|
disable documentation warning for KnownFolderFlags.cs
|
Willster419/RelicModManager,Willster419/RelhaxModpack,Willster419/RelhaxModpack
|
RelhaxModpack/RelhaxModpack/Utilities/Enums/KnownFolderFlags.cs
|
RelhaxModpack/RelhaxModpack/Utilities/Enums/KnownFolderFlags.cs
|
using System;
namespace RelhaxModpack.Utilities.Enums
{
#pragma warning disable CS1591
///<Summary>
/// Enums for Known Folder Flags
///</Summary>
[Flags]
public enum KnownFolderFlags : uint
{
SimpleIDList = 0x00000100,
NotParentRelative = 0x00000200,
DefaultPath = 0x00000400,
Init = 0x00000800,
NoAlias = 0x00001000,
DontUnexpand = 0x00002000,
DontVerify = 0x00004000,
Create = 0x00008000,
NoAppcontainerRedirection = 0x00010000,
AliasOnly = 0x80000000
}
#pragma warning restore CS1591
}
|
using System;
namespace RelhaxModpack.Utilities.Enums
{
///<Summary>
/// Enums for Known Folder Flags
///</Summary>
[Flags]
public enum KnownFolderFlags : uint
{
SimpleIDList = 0x00000100,
NotParentRelative = 0x00000200,
DefaultPath = 0x00000400,
Init = 0x00000800,
NoAlias = 0x00001000,
DontUnexpand = 0x00002000,
DontVerify = 0x00004000,
Create = 0x00008000,
NoAppcontainerRedirection = 0x00010000,
AliasOnly = 0x80000000
}
}
|
apache-2.0
|
C#
|
9c5fca99d19e60aeba170f751bfbcfcc330e37f4
|
Update SortCriterion.cs
|
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
|
main/Smartsheet/Api/Models/SortCriterion.cs
|
main/Smartsheet/Api/Models/SortCriterion.cs
|
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// 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.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Smartsheet.Api.Models
{
public class SortCriterion
{
/// <summary>
/// The column Id to sort on
/// </summary>
private long columnId;
/// <summary>
/// The direction of the sort
/// </summary>
private SortDirection direction;
/// <summary>
/// Get the column Id of the column to sort on
/// </summary>
/// <returns> the column Id </returns>
public long ColumnId
{
get { return columnId; }
set { columnId = value; }
}
/// <summary>
/// Get the sort direction
/// </summary>
/// <returns> the sort direction </returns>
public SortDirection Direction
{
get { return direction; }
set { direction = value; }
}
}
}
|
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// 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.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Smartsheet.Api.Models
{
public class SortCriterion
{
/// <summary>
/// The column ID to sort on
/// </summary>
private long columnId;
/// <summary>
/// The direction of the sort
/// </summary>
private SortDirection direction;
/// <summary>
/// Get the column ID of the column to sort on
/// </summary>
/// <returns> the column ID </returns>
public long ColumnId
{
get { return columnId; }
set { columnId = value; }
}
/// <summary>
/// Get the sort direction
/// </summary>
/// <returns> the sort direction </returns>
public SortDirection Direction
{
get { return direction; }
set { direction = value; }
}
}
}
|
apache-2.0
|
C#
|
0d4a5aa4a9f5dcbd65a7c5483b46256b35bf4e74
|
Edit credit-reverse
|
balanced/balanced-csharp
|
scenarios/snippets/credit-reverse.cs
|
scenarios/snippets/credit-reverse.cs
|
Credit credit = Credit.Fetch(credit_href);
Reversal reversal = credit.Reverse();
|
Credit credit = Order.credits.First();
Reversal reversal = credit.Reverse();
|
mit
|
C#
|
8ef2c2917d31892f9fbc126aaef87146af007831
|
Update source/XeroApi/Model/Organisation.cs
|
MatthewSteeples/XeroAPI.Net,jcvandan/XeroAPI.Net,XeroAPI/XeroAPI.Net,TDaphneB/XeroAPI.Net
|
source/XeroApi/Model/Organisation.cs
|
source/XeroApi/Model/Organisation.cs
|
using System;
namespace XeroApi.Model
{
public class Organisation : EndpointModelBase
{
public string Name;
public string LegalName;
public DateTime CreatedDateUTC;
public string APIKey;
public bool PaysTax;
public string Version;
public string OrganisationType;
public string BaseCurrency;
public string CountryCode;
public bool IsDemoCompany;
public DateTime? PeriodLockDate;
public DateTime? EndOfYearLockDate;
public string TaxNumber;
public int FinancialYearEndDay;
public int FinancialYearEndMonth;
public string Timezone;
public override string ToString()
{
return string.Format("Organisation:{0}", Name);
}
}
public class Organisations : ModelList<Organisation>
{
}
}
|
using System;
namespace XeroApi.Model
{
public class Organisation : EndpointModelBase
{
public string Name;
public string LegalName;
public DateTime CreatedDateUTC;
public string APIKey;
public bool PaysTax;
public string Version;
public string OrganisationType;
public string BaseCurrency;
public string CountryCode;
public bool IsDemoCompany;
public DateTime? PeriodLockDate;
public DateTime? EndOfYearLockDate;
public string TaxNumber;
public int FinancialYearEndDay;
public int FinancialYearEndMonth;
public override string ToString()
{
return string.Format("Organisation:{0}", Name);
}
}
public class Organisations : ModelList<Organisation>
{
}
}
|
mit
|
C#
|
2499c760f99986709c3063e81c278ceabe02d839
|
Add book reference
|
scott-fleischman/algorithms-csharp
|
src/Algorithms.Sort/InsertionSort.cs
|
src/Algorithms.Sort/InsertionSort.cs
|
using System.Collections.Generic;
namespace Algorithms.Sort
{
public static class InsertionSort
{
public static void SortInPlace<T>(IList<T> list)
{
SortInPlace(list, Comparer<T>.Default);
}
// Ch 2.1, p.18
public static void SortInPlace<T>(IList<T> list, IComparer<T> comparer)
{
if (list.Count < 2)
return;
for (int currentIndex = 1; currentIndex < list.Count; currentIndex++)
{
T currentItem = list[currentIndex];
int insertIndex = currentIndex - 1;
while (insertIndex >= 0 && comparer.Compare(list[insertIndex], currentItem) > 0)
{
list[insertIndex + 1] = list[insertIndex];
insertIndex--;
}
list[insertIndex + 1] = currentItem;
}
}
}
}
|
using System.Collections.Generic;
namespace Algorithms.Sort
{
public static class InsertionSort
{
public static void SortInPlace<T>(IList<T> list)
{
SortInPlace(list, Comparer<T>.Default);
}
public static void SortInPlace<T>(IList<T> list, IComparer<T> comparer)
{
if (list.Count < 2)
return;
for (int currentIndex = 1; currentIndex < list.Count; currentIndex++)
{
T currentItem = list[currentIndex];
int insertIndex = currentIndex - 1;
while (insertIndex >= 0 && comparer.Compare(list[insertIndex], currentItem) > 0)
{
list[insertIndex + 1] = list[insertIndex];
insertIndex--;
}
list[insertIndex + 1] = currentItem;
}
}
}
}
|
mit
|
C#
|
1b2bfd45da8f2ebc5e4110482ada8c311e10728a
|
Disable delayed messages to see what effect it has on tests.
|
FoundatioFx/Foundatio,Bartmax/Foundatio,vebin/Foundatio,exceptionless/Foundatio,wgraham17/Foundatio
|
src/Core/Messaging/MessageBusBase.cs
|
src/Core/Messaging/MessageBusBase.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Extensions;
using Foundatio.Utility;
namespace Foundatio.Messaging {
public abstract class MessageBusBase : IMessagePublisher, IDisposable {
private readonly CancellationTokenSource _queueDisposedCancellationTokenSource;
private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>();
public MessageBusBase() {
_queueDisposedCancellationTokenSource = new CancellationTokenSource();
//TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100));
}
private Task DoMaintenance() {
Trace.WriteLine("Doing maintenance...");
foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) {
_delayedMessages.Remove(message);
Publish(message.MessageType, message.Message);
}
return TaskHelper.Completed();
}
public abstract void Publish(Type messageType, object message, TimeSpan? delay = null);
protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) {
if (message == null)
throw new ArgumentNullException("message");
_delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) });
}
protected class DelayedMessage {
public DateTime SendTime { get; set; }
public Type MessageType { get; set; }
public object Message { get; set; }
}
public virtual void Dispose() {
_queueDisposedCancellationTokenSource.Cancel();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Extensions;
using Foundatio.Utility;
namespace Foundatio.Messaging {
public abstract class MessageBusBase : IMessagePublisher, IDisposable {
private readonly CancellationTokenSource _queueDisposedCancellationTokenSource;
private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>();
public MessageBusBase() {
_queueDisposedCancellationTokenSource = new CancellationTokenSource();
TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100));
}
private Task DoMaintenance() {
Trace.WriteLine("Doing maintenance...");
foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) {
_delayedMessages.Remove(message);
Publish(message.MessageType, message.Message);
}
return TaskHelper.Completed();
}
public abstract void Publish(Type messageType, object message, TimeSpan? delay = null);
protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) {
if (message == null)
throw new ArgumentNullException("message");
_delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) });
}
protected class DelayedMessage {
public DateTime SendTime { get; set; }
public Type MessageType { get; set; }
public object Message { get; set; }
}
public virtual void Dispose() {
_queueDisposedCancellationTokenSource.Cancel();
}
}
}
|
apache-2.0
|
C#
|
738ec6c0e46c2186a327fd170ddc61dfb9237612
|
Update MFractor location, contact email and bio. (#631)
|
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
|
src/Firehose.Web/Authors/MFractor.cs
|
src/Firehose.Web/Authors/MFractor.cs
|
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class MFractor : IAmACommunityMember
{
public string FirstName => "MFractor";
public string LastName => "";
public string StateOrRegion => "Brisbane, Australia";
public string EmailAddress => "matthew@mfractor.com";
public string ShortBioOrTagLine => "is a powerful productivity tool for Xamarin Developers.";
public Uri WebSite => new Uri("https://www.mfractor.com/");
public string TwitterHandle => "mfractor";
public string GitHubHandle => "mfractor";
public string GravatarHash => "35bac056166a67222ddcd48b57113a32";
public IEnumerable<Uri> FeedUris
{
get
{
return new List<Uri>()
{
new Uri("https://www.mfractor.com/blogs/news.atom")
};
}
}
public GeoPosition Position => new GeoPosition(-27.470125, 153.021072);
public string FeedLanguageCode => "en";
}
}
|
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class MFractor : IAmACommunityMember
{
public string FirstName => "MFractor";
public string LastName => "";
public string StateOrRegion => "Sydney, Australia";
public string EmailAddress => "hello@mfractor.com";
public string ShortBioOrTagLine => "is a mobile first productivity tool for Visual Studio for Mac.";
public Uri WebSite => new Uri("https://www.mfractor.com/");
public string TwitterHandle => "mfractor";
public string GitHubHandle => "mfractor";
public string GravatarHash => "35bac056166a67222ddcd48b57113a32";
public IEnumerable<Uri> FeedUris
{
get
{
return new List<Uri>()
{
new Uri("https://www.mfractor.com/blogs/news.atom")
};
}
}
public GeoPosition Position => new GeoPosition(-33.8678500, 151.2073200);
public string FeedLanguageCode => "en";
}
}
|
mit
|
C#
|
a234127bdb46619d2e7e692f77358f8f853d8390
|
Refactor Atata.KendoUI.TestApp.Startup
|
atata-framework/atata-kendoui,atata-framework/atata-kendoui
|
src/Atata.KendoUI.TestApp/Startup.cs
|
src/Atata.KendoUI.TestApp/Startup.cs
|
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Atata.KendoUI.TestApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Atata.KendoUI.TestApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
|
apache-2.0
|
C#
|
58a67b69a949f5e0e5349573a66a9d663f98268c
|
Revert "(GH-36) Fix broken test"
|
enkafan/Cake.Figlet
|
src/Cake.Figlet.Tests/FigletTests.cs
|
src/Cake.Figlet.Tests/FigletTests.cs
|
using System;
using Shouldly;
using Xunit;
namespace Cake.Figlet.Tests
{
public class FigletTests
{
[Fact]
public void Figlet_can_render()
{
const string expected = @"
_ _ _ _ __ __ _ _
| | | | ___ | || | ___ \ \ / / ___ _ __ | | __| |
| |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` |
| _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| |
|_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_|
|/
";
FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected);
}
}
public static class ShouldlyAsciiExtensions
{
/// <summary>
/// Helper to allow the expected ASCII art to be on it's own line when declaring
/// the expected value in the source code
/// </summary>
/// <param name="input">The input.</param>
/// <param name="expected">The expected.</param>
public static void ShouldBeWithLeadingLineBreak(this string input, string expected)
{
(Environment.NewLine + input).ShouldBe(expected);
}
}
}
|
using System;
using Shouldly;
using Xunit;
namespace Cake.Figlet.Tests
{
public class FigletTests
{
[Fact]
public void Figlet_can_render()
{
const string expected = @"
_ _ _ _ __ __ _ _
| | | | ___ | || | ___ \ \ / / ___ _ __ | | __| |
| |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` |
| _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| |
|_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_|
|/
";
FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected);
}
}
public static class ShouldlyAsciiExtensions
{
/// <summary>
/// Helper to allow the expected ASCII art to be on it's own line when declaring
/// the expected value in the source code
/// </summary>
/// <param name="input">The input.</param>
/// <param name="expected">The expected.</param>
public static void ShouldBeWithLeadingLineBreak(this string input, string expected)
{
(Environment.NewLine + input).ShouldBe(expected, StringCompareShould.IgnoreLineEndings);
}
}
}
|
mit
|
C#
|
55441d59a13324bac28044fd590c9debe49b69e1
|
Convert fields to properties, place after constructor
|
mmoening/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl
|
MatterControlLib/ConfigurationPage/PrintLeveling/PrintLevelingData.cs
|
MatterControlLib/ConfigurationPage/PrintLeveling/PrintLevelingData.cs
|
/*
Copyright (c) 2018, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class PrintLevelingData
{
public PrintLevelingData()
{
}
public List<Vector3> SampledPositions = new List<Vector3>();
public LevelingSystem LevelingSystem { get; set; }
public DateTime CreationDate { get; set; }
public double BedTemperature { get; set; }
public bool IssuedLevelingTempWarning { get; set; }
public bool SamplesAreSame(List<Vector3> sampledPositions)
{
if (sampledPositions.Count == SampledPositions.Count)
{
for (int i = 0; i < sampledPositions.Count; i++)
{
if (sampledPositions[i] != SampledPositions[i])
{
return false;
}
}
return true;
}
return false;
}
}
}
|
/*
Copyright (c) 2018, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class PrintLevelingData
{
#region JSON data
public List<Vector3> SampledPositions = new List<Vector3>();
public LevelingSystem LevelingSystem;
public DateTime CreationDate;
public double BedTemperature;
public bool IssuedLevelingTempWarning;
#endregion
public PrintLevelingData()
{
}
public bool SamplesAreSame(List<Vector3> sampledPositions)
{
if (sampledPositions.Count == SampledPositions.Count)
{
for (int i = 0; i < sampledPositions.Count; i++)
{
if (sampledPositions[i] != SampledPositions[i])
{
return false;
}
}
return true;
}
return false;
}
}
}
|
bsd-2-clause
|
C#
|
1d637d94f69702122f04fd3d33a1d3798055671a
|
Fix xml comment cref compiler warning
|
tyrotoxin/AsyncEnumerable
|
src/ForEachAsyncCanceledException.cs
|
src/ForEachAsyncCanceledException.cs
|
namespace System.Collections.Async
{
/// <summary>
/// This exception is thrown when you call <see cref="ForEachAsyncExtensions.Break"/>.
/// </summary>
public sealed class ForEachAsyncCanceledException : OperationCanceledException { }
}
|
namespace System.Collections.Async
{
/// <summary>
/// This exception is thrown when you call <see cref="AsyncEnumerable{T}.Break"/>.
/// </summary>
public sealed class ForEachAsyncCanceledException : OperationCanceledException { }
}
|
mit
|
C#
|
b35167c30eb6b21a2978fa26faa1398ef11598ac
|
Add experimental flag
|
stephentoub/roslyn,AlekseyTs/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,wvdd007/roslyn,sharwell/roslyn,panopticoncentral/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,AmadeusW/roslyn,diryboy/roslyn,KevinRansom/roslyn,tannergooding/roslyn,dotnet/roslyn,gafter/roslyn,bartdesmet/roslyn,dotnet/roslyn,tannergooding/roslyn,mavasani/roslyn,wvdd007/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,physhi/roslyn,physhi/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,KirillOsenkov/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,heejaechang/roslyn,eriawan/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,wvdd007/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,diryboy/roslyn,diryboy/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,physhi/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,tmat/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,eriawan/roslyn,eriawan/roslyn,weltkante/roslyn,sharwell/roslyn
|
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
|
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists";
public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache";
/// <remarks>
/// From https://devdiv.visualstudio.com/DevDiv/_git/VSLanguageServerClient?path=%2Fsrc%2Fproduct%2FRemoteLanguage%2FImpl%2FFeatures%2FDiagnostics%2FRemoteDiagnosticsBrokerHelper.cs&version=GBdevelop&line=28&lineEnd=29&lineStartColumn=1&lineEndColumn=1&lineStyle=plain
/// </remarks>
public const string LspPullDiagnostics = "VS.LSPPullModelDiagnosticVSLS";
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists";
public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache";
}
}
|
mit
|
C#
|
384038b3298aa2301f06e6e68449c7c96f988218
|
Update ShapeStateTypeConverter.cs
|
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
|
src/Core2D/Serializer/Xaml/Converters/ShapeStateTypeConverter.cs
|
src/Core2D/Serializer/Xaml/Converters/ShapeStateTypeConverter.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 System.ComponentModel;
using System.Globalization;
using Core2D.Renderer;
namespace Core2D.Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ShapeState"/> type converter.
/// </summary>
internal class ShapeStateTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ShapeState.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return value is ShapeState state ? state.ToString() : throw new NotSupportedException();
}
}
}
|
// 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.Globalization;
using System.ComponentModel;
using Core2D.Renderer;
namespace Core2D.Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ShapeState"/> type converter.
/// </summary>
internal class ShapeStateTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ShapeState.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return value is ShapeState state ? state.ToString() : throw new NotSupportedException();
}
}
}
|
mit
|
C#
|
fdc73259a67a0c005a530b61cbca39f41226b13f
|
Handle cases when the short folder name cannot be executed
|
joelverhagen/NuGetTools,joelverhagen/NuGetTools,joelverhagen/NuGetTools,joelverhagen/NuGetTools
|
src/Knapcode.NuGetTools.Website/Views/Home/ParseFramework.cshtml
|
src/Knapcode.NuGetTools.Website/Views/Home/ParseFramework.cshtml
|
@model SelectedVersionOutput<ParseFrameworkOutput>
@{
ViewData["Title"] = "Parse Framework";
var output = Model.Output;
}
<h1>Parse a framework</h1>
<p>
Enter a NuGet framework to see how it parses. Both short form (e.g. <code>net45</code>) and long form (e.g. <code>.NETFramework,Version=v4.5</code>) are supported.
</p>
<form method="GET" action="">
<div class="form-group">
<label for="framework">Framework</label>
<input type="text" class="form-control framework-short-folder-name-typeahead monospace" name="framework" id="framework"
autocomplete="off" placeholder="net45" value="@output.Input.Framework">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<div class="results">
@if (@output.InputStatus == InputStatus.Valid)
{
<div class="alert alert-success" role="alert">
<p>
The input value is <b>@output.Input.Framework</b>.
</p>
@try
{
string shortFolderName = output.Framework.ShortFolderName;
<p>The short folder name is <code>@shortFolderName</code>.</p>
}
catch
{
<p>
<span class="glyphicon glyphicon-alert" aria-hidden="true"></span>
While determining the short folder name, an exception was thrown.
</p>
}
<p>
The .NET framework name is <code>@output.Framework.DotNetFrameworkName</code>.
</p>
</div>
}
else if (@output.InputStatus == InputStatus.Invalid)
{
<div class="alert alert-danger" role="alert">
The framework <b>@output.Input.Framework</b> could not be parsed.
</div>
}
</div>
|
@model SelectedVersionOutput<ParseFrameworkOutput>
@{
ViewData["Title"] = "Parse Framework";
var output = Model.Output;
}
<h1>Parse a framework</h1>
<p>
Enter a NuGet framework to see how it parses. Both short form (e.g. <code>net45</code>) and long form (e.g. <code>.NETFramework,Version=v4.5</code>) are supported.
</p>
<form method="GET" action="">
<div class="form-group">
<label for="framework">Framework</label>
<input type="text" class="form-control framework-short-folder-name-typeahead monospace" name="framework" id="framework"
autocomplete="off" placeholder="net45" value="@output.Input.Framework">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<div class="results">
@if (@output.InputStatus == InputStatus.Valid)
{
<div class="alert alert-success" role="alert">
<p>
The input value is <b>@output.Input.Framework</b>.
</p>
<p>
The short folder name is <code>@output.Framework.ShortFolderName</code>.
</p>
<p>
The .NET framework name is <code>@output.Framework.DotNetFrameworkName</code>.
</p>
</div>
}
else if (@output.InputStatus == InputStatus.Invalid)
{
<div class="alert alert-danger" role="alert">
The framework <b>@output.Input.Framework</b> could not be parsed.
</div>
}
</div>
|
mit
|
C#
|
75e6e28ac3d99da6d7238616ac2df79cedc01cb7
|
remove unused code
|
EhrgoHealth/CS6440,EhrgoHealth/CS6440
|
src/EhrgoHealth.Web/Areas/Patient/Controllers/HomeController.cs
|
src/EhrgoHealth.Web/Areas/Patient/Controllers/HomeController.cs
|
using Fitbit.Api.Portable;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace EhrgoHealth.Web.Areas.Patient.Controllers
{
public class HomeController : PatientBaseController
{
private readonly ApplicationUserManager userManager;
public HomeController(ApplicationUserManager userManager)
{
this.userManager = userManager;
}
public ActionResult Index()
{
var user = this.User.Identity;
return View();
}
}
}
|
using Fitbit.Api.Portable;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace EhrgoHealth.Web.Areas.Patient.Controllers
{
public class HomeController : PatientBaseController
{
private readonly FitbitClient fitbitClient;
private readonly ApplicationUserManager userManager;
public HomeController(ApplicationUserManager userManager)
{
this.userManager = userManager;
this.fitbitClient = fitbitClient;
}
public ActionResult Index()
{
var user = this.User.Identity;
return View();
}
}
}
|
mit
|
C#
|
4a38e2aa18bc02a7bd3e1c86a645003284a9f59e
|
Remove redundant string interpolation
|
ppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,default0/osu-framework,peppy/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,default0/osu-framework
|
osu.Framework.Tests/Visual/TestCaseCircularContainer.cs
|
osu.Framework.Tests/Visual/TestCaseCircularContainer.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Graphics;
using OpenTK;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual
{
[System.ComponentModel.Description(@"Checking for bugged corner radius")]
internal class TestCaseCircularContainer : TestCase
{
private SingleUpdateCircularContainer container;
public TestCaseCircularContainer()
{
AddStep("128x128 box", () => addContainer(new Vector2(128)));
AddAssert("Expect CornerRadius = 64", () => container.CornerRadius == 64);
AddStep("128x64 box", () => addContainer(new Vector2(128, 64)));
AddAssert("Expect CornerRadius = 32", () => container.CornerRadius == 32);
AddStep("64x128 box", () => addContainer(new Vector2(64, 128)));
AddAssert("Expect CornerRadius = 32", () => container.CornerRadius == 32);
}
private void addContainer(Vector2 size)
{
Clear();
Add(container = new SingleUpdateCircularContainer
{
Masking = true,
AutoSizeAxes = Axes.Both,
Child = new Box { Size = size }
});
}
private class SingleUpdateCircularContainer : CircularContainer
{
private bool firstUpdate = true;
public override bool UpdateSubTree()
{
if (!firstUpdate)
return true;
firstUpdate = false;
return base.UpdateSubTree();
}
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Graphics;
using OpenTK;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual
{
[System.ComponentModel.Description(@"Checking for bugged corner radius")]
internal class TestCaseCircularContainer : TestCase
{
private SingleUpdateCircularContainer container;
public TestCaseCircularContainer()
{
AddStep("128x128 box", () => addContainer(new Vector2(128)));
AddAssert($"Expect CornerRadius = 64", () => container.CornerRadius == 64);
AddStep("128x64 box", () => addContainer(new Vector2(128, 64)));
AddAssert($"Expect CornerRadius = 32", () => container.CornerRadius == 32);
AddStep("64x128 box", () => addContainer(new Vector2(64, 128)));
AddAssert($"Expect CornerRadius = 32", () => container.CornerRadius == 32);
}
private void addContainer(Vector2 size)
{
Clear();
Add(container = new SingleUpdateCircularContainer
{
Masking = true,
AutoSizeAxes = Axes.Both,
Child = new Box { Size = size }
});
}
private class SingleUpdateCircularContainer : CircularContainer
{
private bool firstUpdate = true;
public override bool UpdateSubTree()
{
if (!firstUpdate)
return true;
firstUpdate = false;
return base.UpdateSubTree();
}
}
}
}
|
mit
|
C#
|
6db22366e2bcd50bb60aaa5b327d42e6fa639ad0
|
Add new tests and tidy up existing tests
|
ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,smoogipooo/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu
|
osu.Game.Tests/Visual/Gameplay/TestSceneFailingLayer.cs
|
osu.Game.Tests/Visual/Gameplay/TestSceneFailingLayer.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailingLayer : OsuTestScene
{
private FailingLayer layer;
[Resolved]
private OsuConfigManager config { get; set; }
[SetUpSteps]
public void SetUpSteps()
{
AddStep("create layer", () => Child = layer = new FailingLayer());
AddStep("enable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, true));
AddUntilStep("layer is visible", () => layer.IsPresent);
}
[Test]
public void TestLayerDisabledViaConfig()
{
AddStep("disable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, false));
AddUntilStep("layer is not visible", () => !layer.IsPresent);
}
[Test]
public void TestLayerVisibilityWithAccumulatingProcessor()
{
AddStep("bind accumulating processor", () => layer.BindHealthProcessor(new AccumulatingHealthProcessor(1)));
AddUntilStep("layer is not visible", () => !layer.IsPresent);
}
[Test]
public void TestLayerVisibilityWithDrainingProcessor()
{
AddStep("bind accumulating processor", () => layer.BindHealthProcessor(new DrainingHealthProcessor(1)));
AddWaitStep("wait for potential fade", 10);
AddAssert("layer is still visible", () => layer.IsPresent);
}
[Test]
public void TestLayerFading()
{
AddSliderStep("current health", 0.0, 1.0, 1.0, val =>
{
if (layer != null)
layer.Current.Value = val;
});
AddStep("set health to 0.10", () => layer.Current.Value = 0.1);
AddUntilStep("layer fade is visible", () => layer.Child.Alpha > 0.1f);
AddStep("set health to 1", () => layer.Current.Value = 1f);
AddUntilStep("layer fade is invisible", () => !layer.Child.IsPresent);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Configuration;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailingLayer : OsuTestScene
{
private readonly FailingLayer layer;
[Resolved]
private OsuConfigManager config { get; set; }
public TestSceneFailingLayer()
{
Child = layer = new FailingLayer();
}
[Test]
public void TestLayerConfig()
{
AddStep("enable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, true));
AddWaitStep("wait for transition to finish", 5);
AddAssert("layer is enabled", () => layer.IsPresent);
AddStep("disable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, false));
AddWaitStep("wait for transition to finish", 5);
AddAssert("layer is disabled", () => !layer.IsPresent);
AddStep("restore layer enabling", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, true));
}
[Test]
public void TestLayerFading()
{
AddSliderStep("current health", 0.0, 1.0, 1.0, val => layer.Current.Value = val);
var box = layer.Child;
AddStep("set health to 0.10", () => layer.Current.Value = 0.10);
AddWaitStep("wait for fade to finish", 5);
AddAssert("layer fade is visible", () => box.IsPresent);
AddStep("set health to 1", () => layer.Current.Value = 1f);
AddWaitStep("wait for fade to finish", 10);
AddAssert("layer fade is invisible", () => !box.IsPresent);
}
}
}
|
mit
|
C#
|
c6c9bfa12843124a7ba690969c714fa3662eb496
|
Fix iOS builds
|
peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework
|
osu.Framework.iOS/IOSClipboard.cs
|
osu.Framework.iOS/IOSClipboard.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Platform;
using SixLabors.ImageSharp;
using UIKit;
namespace osu.Framework.iOS
{
public class IOSClipboard : Clipboard
{
private readonly IOSGameView gameView;
internal IOSClipboard(IOSGameView gameView)
{
this.gameView = gameView;
}
public override string GetText()
{
string text = "";
gameView.InvokeOnMainThread(() => text = UIPasteboard.General.String);
return text;
}
public override void SetText(string selectedText) => gameView.InvokeOnMainThread(() => UIPasteboard.General.String = selectedText);
public override Image<TPixel> GetImage<TPixel>()
{
return null;
}
public override bool SetImage(Image image)
{
return false;
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Platform;
using UIKit;
namespace osu.Framework.iOS
{
public class IOSClipboard : Clipboard
{
private readonly IOSGameView gameView;
internal IOSClipboard(IOSGameView gameView)
{
this.gameView = gameView;
}
public override string GetText()
{
string text = "";
gameView.InvokeOnMainThread(() => text = UIPasteboard.General.String);
return text;
}
public override void SetText(string selectedText) => gameView.InvokeOnMainThread(() => UIPasteboard.General.String = selectedText);
public override Image<TPixel> GetImage<TPixel>()
{
return null;
}
public override bool SetImage(Image image)
{
return false;
}
}
}
|
mit
|
C#
|
22468f1cf2a03080167c16336906432068b5714a
|
Add `being_called` value
|
antonpup/Aurora,antonpup/Aurora,antonpup/Aurora,antonpup/Aurora,antonpup/Aurora
|
Project-Aurora/Project-Aurora/Profiles/Discord/GSI/Nodes/UserNode.cs
|
Project-Aurora/Project-Aurora/Profiles/Discord/GSI/Nodes/UserNode.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aurora.Profiles.Discord.GSI.Nodes {
public enum DiscordStatus
{
Undefined,
Online,
Idle,
DoNotDisturb,
Invisible
}
public class UserNode : AutoJsonNode<UserNode> {
public long Id = 0;
[AutoJsonIgnore] public DiscordStatus Status;
[AutoJsonPropertyName("self_mute")] public bool SelfMute;
[AutoJsonPropertyName("self_deafen")] public bool SelfDeafen;
public bool Mentions;
[AutoJsonPropertyName("unread_messages")] public bool UnreadMessages;
[AutoJsonPropertyName("being_called")] public bool BeingCalled;
internal UserNode(string json) : base(json) {
Status = GetStatus(GetString("status"));
}
private static DiscordStatus GetStatus(string status)
{
switch (status)
{
case "online":
return DiscordStatus.Online;
case "dnd":
return DiscordStatus.DoNotDisturb;
case "invisible":
return DiscordStatus.Invisible;
case "idle":
return DiscordStatus.Idle;
default:
return DiscordStatus.Undefined;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aurora.Profiles.Discord.GSI.Nodes {
public enum DiscordStatus
{
Undefined,
Online,
Idle,
DoNotDisturb,
Invisible
}
public class UserNode : AutoJsonNode<UserNode> {
public long Id = 0;
[AutoJsonIgnore] public DiscordStatus Status;
[AutoJsonPropertyName("self_mute")] public bool SelfMute;
[AutoJsonPropertyName("self_deafen")] public bool SelfDeafen;
public bool Mentions;
[AutoJsonPropertyName("unread_messages")] public bool UnreadMessages;
internal UserNode(string json) : base(json) {
Status = GetStatus(GetString("status"));
}
private static DiscordStatus GetStatus(string status)
{
switch (status)
{
case "online":
return DiscordStatus.Online;
case "dnd":
return DiscordStatus.DoNotDisturb;
case "invisible":
return DiscordStatus.Invisible;
case "idle":
return DiscordStatus.Idle;
default:
return DiscordStatus.Undefined;
}
}
}
}
|
mit
|
C#
|
8a6289c6756c488870ff6d06345af5afeadb47a6
|
Format changes
|
mono-soc-2012/Tasque,mono-soc-2012/Tasque,mono-soc-2012/Tasque
|
src/Addins/DummyBackend/DummyTask.cs
|
src/Addins/DummyBackend/DummyTask.cs
|
// DummyTask.cs created with MonoDevelop
// User: boyd at 8:50 PM 2/10/2008
//
// DummyTask.cs
//
// Author:
// Antonius Riha <antoniusriha@gmail.com>
//
// Copyright (c) 2012 Antonius Riha
//
// 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 Tasque;
using System.Diagnostics;
namespace Tasque.Backends.Dummy
{
public class DummyTask : Task
{
public DummyTask (string name) : base (name, TaskNoteSupport.Multiple) {}
public override void Activate ()
{
Debug.WriteLine ("DummyTask.Activate ()");
CompletionDate = DateTime.MinValue;
State = TaskState.Active;
}
public override void Inactivate ()
{
Debug.WriteLine ("DummyTask.Inactivate ()");
CompletionDate = DateTime.Now;
State = TaskState.Inactive;
}
public override void Complete ()
{
Debug.WriteLine ("DummyTask.Complete ()");
CompletionDate = DateTime.Now;
State = TaskState.Completed;
}
public override void Delete ()
{
Debug.WriteLine ("DummyTask.Delete ()");
State = TaskState.Deleted;
}
public override TaskNote CreateNote (string text)
{
return new DummyNote (text);
}
}
}
|
// DummyTask.cs created with MonoDevelop
// User: boyd at 8:50 PM 2/10/2008
//
// DummyTask.cs
//
// Author:
// Antonius Riha <antoniusriha@gmail.com>
//
// Copyright (c) 2012 Antonius Riha
//
// 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 Tasque;
using System.Diagnostics;
namespace Tasque.Backends.Dummy
{
public class DummyTask : Task
{
public DummyTask(string name) : base (name, TaskNoteSupport.Multiple) {}
public override void Activate ()
{
Debug.WriteLine ("DummyTask.Activate ()");
CompletionDate = DateTime.MinValue;
State = TaskState.Active;
}
public override void Inactivate ()
{
Debug.WriteLine ("DummyTask.Inactivate ()");
CompletionDate = DateTime.Now;
State = TaskState.Inactive;
}
public override void Complete ()
{
Debug.WriteLine ("DummyTask.Complete ()");
CompletionDate = DateTime.Now;
State = TaskState.Completed;
}
public override void Delete ()
{
Debug.WriteLine ("DummyTask.Delete ()");
State = TaskState.Deleted;
}
public override TaskNote CreateNote (string text)
{
return new DummyNote (text);
}
}
}
|
mit
|
C#
|
06d7e844d98d0e0be4b1d8a6f701eea7c7845233
|
Fix for #11
|
tylerlrhodes/bagombo,tylerlrhodes/bagombo,tylerlrhodes/bagombo
|
src/Bagombo/Views/Home/Search.cshtml
|
src/Bagombo/Views/Home/Search.cshtml
|
@using Bagombo.Models.ViewModels.Home
@model SearchResultsViewModel
@{
ViewData["Title"] = $"Posts for Search: {Model.SearchTerm}";
Layout = "_Layout";
}
<div class="container-fluid">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h3>Posts for Search: <span class="label label-info">@Model.SearchTerm</span></h3>
<hr />
</div>
</div>
@foreach (var post in Model.BlogPosts)
{
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-body">
<h3>
<a asp-action="BlogPost" asp-route-id="@post.BlogPost.Id">@post.BlogPost.Title</a>
</h3>
<h5>
Author: @post.BlogPost.Author.FirstName @post.BlogPost.Author.LastName
</h5>
<hr />
<h5>
@post.BlogPost.Description
</h5>
<h5>
@foreach (var c in post.Categories)
{
<span class="label label-info"> @c.Name </span>
}
</h5>
</div>
</div>
</div>
</div>
}
</div>
|
@using Bagombo.Models.ViewModels.Home
@model SearchResultsViewModel
@{
ViewData["Title"] = $"Posts for Search: {Model.SearchTerm}";
Layout = "_Layout";
}
<div class="container-fluid">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h3>Posts for Search: <span class="label label-info">@Model.SearchTerm</span></h3>
<hr />
</div>
</div>
@foreach (var post in Model.BlogPosts)
{
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-body">
<h3>
<a asp-action="BlogPost" asp-route-id="@post.BlogPost.Id">@post.BlogPost.Title</a>
</h3>
<h5>
Author: @post.BlogPost.Author.FirstName @post.BlogPost.Author.LastName
</h5>
<hr />
<h5>
@post.BlogPost.Description
</h5>
</div>
</div>
</div>
</div>
}
</div>
|
mit
|
C#
|
ec226cc8b17e04500e4c8559a097dc71695b306b
|
Remove session-commit statement that is not needed and already handled by middleware
|
billboga/motleyflash,billboga/motleyflash
|
src/MotleyFlash.AspNetCore.MessageProviders/SessionMessageProvider.cs
|
src/MotleyFlash.AspNetCore.MessageProviders/SessionMessageProvider.cs
|
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Text;
namespace MotleyFlash.AspNetCore.MessageProviders
{
public class SessionMessageProvider : IMessageProvider
{
public SessionMessageProvider(ISession session)
{
this.session = session;
}
private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
};
private readonly ISession session;
private const string sessionKey = "motleyflash-session-message-provider";
public object Get()
{
byte[] value;
object messages = null;
if (session.TryGetValue(sessionKey, out value))
{
if (value != null)
{
messages =
JsonConvert.DeserializeObject(
Encoding.UTF8.GetString(value, 0, value.Length),
jsonSerializerSettings);
}
}
return messages;
}
public void Set(object messages)
{
session.Set(
sessionKey,
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(
messages,
jsonSerializerSettings)));
}
}
}
|
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Text;
namespace MotleyFlash.AspNetCore.MessageProviders
{
public class SessionMessageProvider : IMessageProvider
{
public SessionMessageProvider(ISession session)
{
this.session = session;
}
private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
};
private readonly ISession session;
private const string sessionKey = "motleyflash-session-message-provider";
public object Get()
{
byte[] value;
object messages = null;
if (session.TryGetValue(sessionKey, out value))
{
if (value != null)
{
messages =
JsonConvert.DeserializeObject(
Encoding.UTF8.GetString(value, 0, value.Length),
jsonSerializerSettings);
}
}
return messages;
}
public void Set(object messages)
{
session.Set(
sessionKey,
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(
messages,
jsonSerializerSettings)));
session.CommitAsync();
}
}
}
|
mit
|
C#
|
37992beb1fc29679b7163559348dbcdc925cca89
|
Enable loading of TraceEvent from byte array. In that case we use as assembly location the executable location as fallback since there is no file name attached to the byte array.
|
vancem/perfview,vancem/perfview,vancem/perfview,vancem/perfview,vancem/perfview
|
src/TraceEvent/NativeDlls.cs
|
src/TraceEvent/NativeDlls.cs
|
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
/// <summary>
/// Finds native DLLS next to the managed DLL that uses them.
/// </summary>
class NativeDlls
{
/// <summary>
/// ManifestModule.FullyQualifiedName returns this as file path if the assembly is loaded as byte array
/// </summary>
const string UnknownLocation = "<Unknown>";
/// <summary>
/// Loads a native DLL with a filename-extension of 'simpleName' by adding the path of the currently executing assembly
///
/// </summary>
/// <param name="simpleName"></param>
public static void LoadNative(string simpleName)
{
// When TraceEvent is loaded as embedded assembly the manifest path is <Unkown>
// We use as fallback in that case the process executable location to enable scenarios where TraceEvent and related dlls
// are loaded from byte arrays into the AppDomain to create self contained executables with no other dependent libraries.
string assemblyLocation = Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName;
if( assemblyLocation == UnknownLocation)
{
assemblyLocation = Process.GetCurrentProcess().MainModule.FileName;
}
var thisDllDir = Path.GetDirectoryName(assemblyLocation);
var dllName = Path.Combine(Path.Combine(thisDllDir, ProcessArchitectureDirectory), simpleName);
var ret = LoadLibrary(dllName);
if (ret == IntPtr.Zero)
{
var errorCode = Marshal.GetLastWin32Error();
throw new ApplicationException("Could not load native DLL " + dllName + " HRESULT=0x" + errorCode.ToString("x"));
}
}
public static ProcessorArchitecture ProcessArch
{
get
{
return IntPtr.Size == 8 ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.X86;
}
}
/// <summary>
/// Gets the name of the directory containing compiled binaries (DLLs) which have the same architecture as the
/// currently executing process.
/// </summary>
public static string ProcessArchitectureDirectory
{
get
{
if (s_ProcessArchDirectory == null)
{
s_ProcessArchDirectory = ProcessArch.ToString().ToLowerInvariant();
}
return s_ProcessArchDirectory;
}
}
/// <summary>
/// This is the backing field for the lazily-computed <see cref="ProcessArchitectureDirectory"/> property.
/// </summary>
private static string s_ProcessArchDirectory;
[System.Runtime.InteropServices.DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr LoadLibrary(string lpFileName);
}
|
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
/// <summary>
/// Finds native DLLS next to the managed DLL that uses them.
/// </summary>
class NativeDlls
{
/// <summary>
/// Loads a native DLL with a filename-extention of 'simpleName' by adding the path of the currently executing assembly
///
/// </summary>
/// <param name="simpleName"></param>
public static void LoadNative(string simpleName)
{
// When TraceEvent is loaded as embedded assembly the executing assembly is mscorlib which points to the wrong path.
// We use therefore the executable as entry point
var thisDllDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().ManifestModule.FullyQualifiedName);
var dllName = Path.Combine(Path.Combine(thisDllDir, ProcessArchitectureDirectory), simpleName);
var ret = LoadLibrary(dllName);
if (ret == IntPtr.Zero)
{
var errorCode = Marshal.GetLastWin32Error();
throw new ApplicationException("Could not load native DLL " + dllName + " HRESULT=0x" + errorCode.ToString("x"));
}
}
public static ProcessorArchitecture ProcessArch
{
get
{
return IntPtr.Size == 8 ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.X86;
}
}
/// <summary>
/// Gets the name of the directory containing compiled binaries (DLLs) which have the same architecture as the
/// currently executing process.
/// </summary>
public static string ProcessArchitectureDirectory
{
get
{
if (s_ProcessArchDirectory == null)
{
s_ProcessArchDirectory = ProcessArch.ToString().ToLowerInvariant();
}
return s_ProcessArchDirectory;
}
}
/// <summary>
/// This is the backing field for the lazily-computed <see cref="ProcessArchitectureDirectory"/> property.
/// </summary>
private static string s_ProcessArchDirectory;
[System.Runtime.InteropServices.DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr LoadLibrary(string lpFileName);
}
|
mit
|
C#
|
7d51a5915ea02ed050e2febb39426ead9cbb476e
|
Remove SetExclusive logic
|
peppy/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,paparony03/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,default0/osu-framework,ppy/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,default0/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,naoey/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,paparony03/osu-framework
|
osu.Framework/Audio/Track/TrackManager.cs
|
osu.Framework/Audio/Track/TrackManager.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Linq;
using osu.Framework.IO.Stores;
using System;
namespace osu.Framework.Audio.Track
{
public class TrackManager : AudioCollectionManager<Track>
{
private readonly IResourceStore<byte[]> store;
public TrackManager(IResourceStore<byte[]> store)
{
this.store = store;
}
public Track Get(string name)
{
TrackBass track = new TrackBass(store.GetStream(name));
AddItem(track);
return track;
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Linq;
using osu.Framework.IO.Stores;
using System;
namespace osu.Framework.Audio.Track
{
public class TrackManager : AudioCollectionManager<Track>
{
private readonly IResourceStore<byte[]> store;
private Track exclusiveTrack;
private readonly object exclusiveMutex = new object();
public TrackManager(IResourceStore<byte[]> store)
{
this.store = store;
}
public Track Get(string name)
{
TrackBass track = new TrackBass(store.GetStream(name));
AddItem(track);
return track;
}
/// <summary>
/// Specify an AudioTrack which should get exclusive playback over everything else.
/// Will pause all other tracks and throw away any existing exclusive track.
/// </summary>
public void SetExclusive(Track track)
{
if (track == null)
throw new ArgumentNullException(nameof(track));
Track last;
lock (exclusiveMutex)
{
if (exclusiveTrack == track) return;
last = exclusiveTrack;
exclusiveTrack = track;
}
PendingActions.Enqueue(() =>
{
foreach (var item in Items)
if (!item.HasCompleted)
item.Stop();
last?.Dispose();
AddItem(track);
});
}
public override void Update()
{
if (exclusiveTrack?.HasCompleted != false)
lock (exclusiveMutex)
// We repeat the if-check inside the lock to make sure exclusiveTrack
// has not been overwritten prior to us taking the lock.
if (exclusiveTrack?.HasCompleted != false)
{
if (exclusiveTrack != null)
UnregisterItem(exclusiveTrack);
exclusiveTrack = Items.FirstOrDefault();
}
base.Update();
}
}
}
|
mit
|
C#
|
5e190c1cdcd1df54fd7394b3c6a9c3d153101fe6
|
make sure we don't crash due to missing items
|
liam-middlebrook/Navier-Boats
|
Navier-Boats/Navier-Boats/Navier-Boats/Engine/Inventory/ItemManager.cs
|
Navier-Boats/Navier-Boats/Navier-Boats/Engine/Inventory/ItemManager.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using Microsoft.Xna.Framework.Graphics;
using Navier_Boats.Engine.Entities;
namespace Navier_Boats.Engine.Inventory
{
public class ItemManager
{
private static ItemManager instance = new ItemManager();
private List<IGameItem> items = new List<IGameItem>();
public static ItemManager GetInstance()
{
return instance;
}
private ItemManager()
{
}
public void LoadItems()
{
//path searched for .itm files, for now
string path = "./Content/Items";
if (!Directory.Exists(path))
{
return;
}
string [] files = Directory.GetFiles(path, "*.itm");
foreach (string file in files)
{
string output;
StreamReader reader = new StreamReader(file);
output = reader.ReadToEnd();
// SEAN: no longer using item factories. just store the item itself.
CustomGameItem item = JsonConvert.DeserializeObject<CustomGameItem>(output);
items.Add(item);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using Microsoft.Xna.Framework.Graphics;
using Navier_Boats.Engine.Entities;
namespace Navier_Boats.Engine.Inventory
{
public class ItemManager
{
private static ItemManager instance = new ItemManager();
private List<IGameItem> items = new List<IGameItem>();
public static ItemManager GetInstance()
{
return instance;
}
private ItemManager()
{
}
public void LoadItems()
{
//path searched for .itm files, for now
string path = "./Content/Items";
string [] files = Directory.GetFiles(path, "*.itm");
foreach (string file in files)
{
string output;
StreamReader reader = new StreamReader(file);
output = reader.ReadToEnd();
// SEAN: no longer using item factories. just store the item itself.
CustomGameItem item = JsonConvert.DeserializeObject<CustomGameItem>(output);
items.Add(item);
}
}
}
}
|
apache-2.0
|
C#
|
780af0fd5f8970bc18025d6fa581e21e2b95d85b
|
fix dynamo datetime handling
|
carbon/Amazon
|
src/Amazon.DynamoDb/Extensions/JsonElementExtensions.cs
|
src/Amazon.DynamoDb/Extensions/JsonElementExtensions.cs
|
using Amazon.DynamoDb.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Text.Json;
namespace Amazon.DynamoDb.Extensions
{
public static class JsonElementExtensions
{
public static string[] GetStringArray(this JsonElement element)
{
string[] items = new string[element.GetArrayLength()];
int i = 0;
foreach (var el in element.EnumerateArray())
{
items[i] = el.GetString();
i++;
}
return items;
}
public static T GetEnum<T>(this JsonElement element) where T : struct, Enum
{
if (Enum.TryParse<T>(element.GetString(), out T enumValue))
{
return enumValue;
}
throw new InvalidEnumArgumentException($"{element.GetString()} could not be parsed as enum {typeof(T)}");
}
public static DateTimeOffset GetDynamoDateTimeOffset(this JsonElement element)
{
double timestampSeconds = element.GetDouble();
return DateTimeOffset.FromUnixTimeMilliseconds((long)(timestampSeconds * 1000d));
}
public static T GetObject<T>(this JsonElement el) where T : IConvertibleFromJson, new()
{
T obj = new T();
foreach (var prop in el.EnumerateObject())
{
obj.FillField(prop);
}
return obj;
}
public static T[] GetObjectArray<T>(this JsonElement el) where T : IConvertibleFromJson, new()
{
T[] objArray = new T[el.GetArrayLength()];
int i = 0;
foreach (var childElement in el.EnumerateArray())
{
objArray[i++] = GetObject<T>(childElement);
}
return objArray;
}
}
}
|
using Amazon.DynamoDb.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Text.Json;
namespace Amazon.DynamoDb.Extensions
{
public static class JsonElementExtensions
{
public static string[] GetStringArray(this JsonElement element)
{
string[] items = new string[element.GetArrayLength()];
int i = 0;
foreach (var el in element.EnumerateArray())
{
items[i] = el.GetString();
i++;
}
return items;
}
public static T GetEnum<T>(this JsonElement element) where T : struct, Enum
{
if (Enum.TryParse<T>(element.GetString(), out T enumValue))
{
return enumValue;
}
throw new InvalidEnumArgumentException($"{element.GetString()} could not be parsed as enum {typeof(T)}");
}
public static DateTimeOffset GetDynamoDateTimeOffset(this JsonElement element)
{
long timestampSeconds = element.GetInt64();
return DateTimeOffset.FromUnixTimeSeconds(timestampSeconds);
}
public static T GetObject<T>(this JsonElement el) where T : IConvertibleFromJson, new()
{
T obj = new T();
foreach (var prop in el.EnumerateObject())
{
obj.FillField(prop);
}
return obj;
}
public static T[] GetObjectArray<T>(this JsonElement el) where T : IConvertibleFromJson, new()
{
T[] objArray = new T[el.GetArrayLength()];
int i = 0;
foreach (var childElement in el.EnumerateArray())
{
objArray[i++] = GetObject<T>(childElement);
}
return objArray;
}
}
}
|
mit
|
C#
|
94e319b9b23f73938bb95f1453a4d07c73f5983e
|
fix ctxt prop type
|
icraftsoftware/BizTalk.Factory,icraftsoftware/BizTalk.Factory,icraftsoftware/BizTalk.Factory
|
src/BizTalk.Schemas/ContextProperties/SftpProperties.cs
|
src/BizTalk.Schemas/ContextProperties/SftpProperties.cs
|
#region Copyright & License
// Copyright © 2012 - 2017 François Chabot, Yves Dierick
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using SFTP;
namespace Be.Stateless.BizTalk.ContextProperties
{
public class SftpProperties
{
public static readonly MessageContextProperty<TargetFileName, string> TargetFileName
= new MessageContextProperty<TargetFileName, string>();
}
}
|
#region Copyright & License
// Copyright © 2012 - 2017 François Chabot, Yves Dierick
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using SFTP;
namespace Be.Stateless.BizTalk.ContextProperties
{
public class SftpProperties
{
public static readonly MessageContextProperty<TargetFileName, bool> TargetFileName
= new MessageContextProperty<TargetFileName, bool>();
}
}
|
apache-2.0
|
C#
|
ed5810aa6f0cfb7121626ac3ce4c2b9bf883adc4
|
Update to use property, not field. bugid: 146
|
jonnybee/csla,MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,JasonBock/csla,BrettJaner/csla,ronnymgm/csla-light,BrettJaner/csla,JasonBock/csla,jonnybee/csla,BrettJaner/csla,rockfordlhotka/csla,MarimerLLC/csla,ronnymgm/csla-light,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light
|
cslatest/Csla.Test/Silverlight/Server/DataPortal/TestableDataPortal.cs
|
cslatest/Csla.Test/Silverlight/Server/DataPortal/TestableDataPortal.cs
|
using System;
using Csla.Server;
namespace Csla.Testing.Business.DataPortal
{
/// <summary>
/// Basically this test class exposes protected DataPortal constructor overloads to the
/// Unit Testing System, allowing for a more fine-grained Unit Tests
/// </summary>
public class TestableDataPortal : Csla.Server.DataPortal
{
public TestableDataPortal() : base(){}
public TestableDataPortal(string cslaAuthorizationProviderAppSettingName):
base(cslaAuthorizationProviderAppSettingName)
{
}
public TestableDataPortal(Type authProviderType):base(authProviderType) { }
public static void Setup()
{
Authorizer = null;
}
public Type AuthProviderType
{
get { return Authorizer.GetType(); }
}
public IAuthorizeDataPortal AuthProvider
{
get { return Authorizer; }
}
public bool NullAuthorizerUsed
{
get
{
return AuthProviderType == typeof (NullAuthorizer);
}
}
}
}
|
using System;
using Csla.Server;
namespace Csla.Testing.Business.DataPortal
{
/// <summary>
/// Basically this test class exposes protected DataPortal constructor overloads to the
/// Unit Testing System, allowing for a more fine-grained Unit Tests
/// </summary>
public class TestableDataPortal : Csla.Server.DataPortal
{
public TestableDataPortal() : base(){}
public TestableDataPortal(string cslaAuthorizationProviderAppSettingName):
base(cslaAuthorizationProviderAppSettingName)
{
}
public TestableDataPortal(Type authProviderType):base(authProviderType) { }
public static void Setup()
{
_authorizer = null;
}
public Type AuthProviderType
{
get { return _authorizer.GetType(); }
}
public IAuthorizeDataPortal AuthProvider
{
get { return _authorizer; }
}
public bool NullAuthorizerUsed
{
get
{
return AuthProviderType == typeof (NullAuthorizer);
}
}
}
}
|
mit
|
C#
|
6d050189e7e62d4fe909b81146084056651fc29b
|
Add plugs
|
CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos
|
source/Cosmos.Core_Plugs/Interop/SysImpl.cs
|
source/Cosmos.Core_Plugs/Interop/SysImpl.cs
|
using IL2CPU.API.Attribs;
using System;
namespace Cosmos.Core_Plugs.Interop
{
[Plug("Interop+Sys, System.Private.CoreLib", IsOptional = true)]
class SysImpl
{
[PlugMethod(Signature = "System_IntPtr__Interop_Sys_GetUnixNamePrivate__")]
public static IntPtr GetUnixNamePrivate()
{
throw new NotImplementedException();
}
[PlugMethod(Signature = "System_Int32__Interop_Sys_Stat__System_Byte___Interop_Sys_FileStatus_")]
public static int Stat(string path, out object output)
{
throw new NotImplementedException();
}
[PlugMethod(Signature = "System_Int32__Interop_Sys_LStat__System_Byte___Interop_Sys_FileStatus_")]
public static int LStat(string path, out object output)
{
throw new NotImplementedException();
}
[PlugMethod(Signature = "SystemPrivateCoreLibInterop_Error__Interop_Sys_ConvertErrorPlatformToPal_System_Int32_")]
public static object ConvertErrorPlatformToPal(int platformErrno)
{
throw new NotImplementedException();
}
[PlugMethod(Signature = "System_Int32__Interop_Sys_ConvertErrorPalToPlatform_SystemPrivateCoreLibInterop_Error_")]
public static int ConvertErrorPalToPlatform(object error)
{
throw new NotImplementedException();
}
[PlugMethod(Signature = "System_Byte#__Interop_Sys_StrErrorR_System_Int32__System_Byte#__System_Int32_")]
public static unsafe byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize)
{
throw new NotImplementedException();
}
}
}
|
using IL2CPU.API.Attribs;
using System;
namespace Cosmos.Core_Plugs.Interop
{
[Plug("Interop+Sys, System.Private.CoreLib", IsOptional = true)]
class SysImpl
{
[PlugMethod(Signature = "System_IntPtr__Interop_Sys_GetUnixNamePrivate__")]
public static IntPtr GetUnixNamePrivate()
{
throw new NotImplementedException();
}
[PlugMethod(Signature = "System_Int32__Interop_Sys_LStat__System_Byte___Interop_Sys_FileStatus_")]
public static int LStat(string path, out object output)
{
throw new NotImplementedException();
}
}
}
|
bsd-3-clause
|
C#
|
2c6f4b743a1114ab2559fd083e9def8a6bff3596
|
add try catch to accounts controller in dbapi
|
MassDebaters/DebateApp,MassDebaters/DebateApp,MassDebaters/DebateApp
|
DebateAppDB/DebateAppDB.dbRest/Controllers/AccountsController.cs
|
DebateAppDB/DebateAppDB.dbRest/Controllers/AccountsController.cs
|
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using DebateApp.db;
using DebateAppDB.dbRest.Models;
using System.IO;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
namespace DebateAppDB.dbRest.Controllers
{
[Produces("application/json", "text/plain")]
[Route("api/Accounts")]
public class AccountsController : Controller
{
private AccountModel account;
private readonly IConfiguration _Configuration;
public AccountsController(IConfiguration configuration)
{
_Configuration = configuration;
account = new AccountModel(_Configuration);
}
[HttpGet]
public IEnumerable<AccountModel> GetAllAccounts()
{
return account.GetAllAccounts();
}
// GET: api/Accounts/5
[HttpGet("{id}")]
public AccountModel GetAccount(int id)
{
try
{
return account.GetAccount(id);
}
catch(Exception)
{
return new AccountModel(this._Configuration)
{
};
}
}
//GET: api/Accounts/username/somestring
[HttpGet("username/{username}")]
public bool UniqueUsername(string username)
{
return account.UniqueUsername(username);
}
public string error()
{
return "did not work boy";
}
/*[HttpPost("debate")]
public void Debate([FromBody]object dString)
{
//file.WriteLine(dString);
}*/
// POST: api/Accounts
[HttpPost]
public void Post([FromBody]Accounts user)
{
account.AddAccount(user);
}
// PUT: api/Accounts/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
account.DeleteAccount(id);
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using DebateApp.db;
using DebateAppDB.dbRest.Models;
using System.IO;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
namespace DebateAppDB.dbRest.Controllers
{
[Produces("application/json", "text/plain")]
[Route("api/Accounts")]
public class AccountsController : Controller
{
private AccountModel account;
private readonly IConfiguration _Configuration;
public AccountsController(IConfiguration configuration)
{
_Configuration = configuration;
account = new AccountModel(_Configuration);
}
[HttpGet]
public IEnumerable<AccountModel> GetAllAccounts()
{
return account.GetAllAccounts();
}
// GET: api/Accounts/5
[HttpGet("{id}")]
public AccountModel GetAccount(int id)
{
return account.GetAccount(id);
}
//GET: api/Accounts/username/somestring
[HttpGet("username/{username}")]
public bool UniqueUsername(string username)
{
return account.UniqueUsername(username);
}
/*[HttpPost("debate")]
public void Debate([FromBody]object dString)
{
//file.WriteLine(dString);
}*/
// POST: api/Accounts
[HttpPost]
public void Post([FromBody]Accounts user)
{
account.AddAccount(user);
}
// PUT: api/Accounts/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
account.DeleteAccount(id);
}
}
}
|
mit
|
C#
|
3e954ed2831b3e1c064f81763b32144c47add172
|
Update JamesMontemagno.cs (#331)
|
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
|
src/Firehose.Web/Authors/JamesMontemagno.cs
|
src/Firehose.Web/Authors/JamesMontemagno.cs
|
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
using System.ServiceModel.Syndication;
using System.Linq;
namespace Firehose.Web.Authors
{
public class JamesMontemagno : IWorkAtXamarinOrMicrosoft, IFilterMyBlogPosts
{
public string FirstName => "James";
public string LastName => "Montemagno";
public string StateOrRegion => "Seattle, WA";
public string EmailAddress => "";
public string ShortBioOrTagLine => "is a Principal Program Manager for Mobile Developer Tools";
public Uri WebSite => new Uri("https://montemagno.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://montemagno.com/rss"); }
}
public string TwitterHandle => "JamesMontemagno";
public string GravatarHash => "5df4d86308e585c879c19e5f909d8bfe";
public string GitHubHandle => "jamesmontemagno";
public GeoPosition Position => new GeoPosition(47.6541770, -122.3500000);
public bool Filter(SyndicationItem item) =>
item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin"));
}
}
|
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
using System.ServiceModel.Syndication;
using System.Linq;
namespace Firehose.Web.Authors
{
public class JamesMontemagno : IWorkAtXamarinOrMicrosoft, IFilterMyBlogPosts
{
public string FirstName => "James";
public string LastName => "Montemagno";
public string StateOrRegion => "Seattle, WA";
public string EmailAddress => "";
public string ShortBioOrTagLine => "is a Principal Program Manager for Mobile Developer Tools";
public Uri WebSite => new Uri("http://motzcod.es");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://motzcod.es/rss"); }
}
public string TwitterHandle => "JamesMontemagno";
public string GravatarHash => "5df4d86308e585c879c19e5f909d8bfe";
public string GitHubHandle => "jamesmontemagno";
public GeoPosition Position => new GeoPosition(47.6541770, -122.3500000);
public bool Filter(SyndicationItem item) =>
item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin"));
}
}
|
mit
|
C#
|
9fddf5a0fb2e99d9d2d207d5e29576cc6dd47394
|
Rename copied class TfsHelperVS2012Base to TfsHelpverVs2017Base
|
PKRoma/git-tfs,git-tfs/git-tfs
|
src/GitTfs.VsCommon/TfsHelper.Vs2017Base.cs
|
src/GitTfs.VsCommon/TfsHelper.Vs2017Base.cs
|
using System;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using StructureMap;
using GitTfs.Core.TfsInterop;
using Microsoft.TeamFoundation.Build.Client;
namespace GitTfs.VsCommon
{
public abstract class TfsHelperVS2017Base : TfsHelperBase
{
protected abstract string TfsVersionString { get; }
public TfsHelperVS2017Base(TfsApiBridge bridge, IContainer container)
: base(bridge, container)
{ }
protected override bool HasWorkItems(Changeset changeset)
{
return Retry.Do(() => changeset.AssociatedWorkItems.Length > 0);
}
private string vsInstallDir;
protected override string GetVsInstallDir()
{
if (vsInstallDir == null)
{
vsInstallDir = TryGetRegString(@"Software\WOW6432Node\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetRegString(@"Software\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetUserRegString(@"Software\WOW6432Node\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir")
?? TryGetUserRegString(@"Software\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir");
}
return vsInstallDir;
}
protected override IBuildDetail GetSpecificBuildFromQueuedBuild(IQueuedBuild queuedBuild, string shelvesetName)
{
var build = queuedBuild.Builds.FirstOrDefault(b => b.ShelvesetName == shelvesetName);
return build != null ? build : queuedBuild.Build;
}
#pragma warning disable 618
private IGroupSecurityService GroupSecurityService
{
get { return GetService<IGroupSecurityService>(); }
}
public override IIdentity GetIdentity(string username)
{
return _bridge.Wrap<WrapperForIdentity, Identity>(Retry.Do(() => GroupSecurityService.ReadIdentity(SearchFactor.AccountName, username, QueryMembership.None)));
}
protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
{
return HasCredentials ?
new TfsTeamProjectCollection(uri, GetCredential(), new UICredentialsProvider()) :
new TfsTeamProjectCollection(uri, new UICredentialsProvider());
#pragma warning restore 618
}
}
}
|
using System;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using StructureMap;
using GitTfs.Core.TfsInterop;
using Microsoft.TeamFoundation.Build.Client;
namespace GitTfs.VsCommon
{
public abstract class TfsHelperVs2012Base : TfsHelperBase
{
protected abstract string TfsVersionString { get; }
protected TfsHelperVs2012Base(TfsApiBridge bridge, IContainer container)
: base(bridge, container)
{ }
protected override bool HasWorkItems(Changeset changeset)
{
return Retry.Do(() => changeset.AssociatedWorkItems.Length > 0);
}
private string vsInstallDir;
protected override string GetVsInstallDir()
{
if (vsInstallDir == null)
{
vsInstallDir = TryGetRegString(@"Software\WOW6432Node\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetRegString(@"Software\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetUserRegString(@"Software\WOW6432Node\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir")
?? TryGetUserRegString(@"Software\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir");
}
return vsInstallDir;
}
protected override IBuildDetail GetSpecificBuildFromQueuedBuild(IQueuedBuild queuedBuild, string shelvesetName)
{
var build = queuedBuild.Builds.FirstOrDefault(b => b.ShelvesetName == shelvesetName);
return build != null ? build : queuedBuild.Build;
}
#pragma warning disable 618
private IGroupSecurityService GroupSecurityService
{
get { return GetService<IGroupSecurityService>(); }
}
public override IIdentity GetIdentity(string username)
{
return _bridge.Wrap<WrapperForIdentity, Identity>(Retry.Do(() => GroupSecurityService.ReadIdentity(SearchFactor.AccountName, username, QueryMembership.None)));
}
protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
{
return HasCredentials ?
new TfsTeamProjectCollection(uri, GetCredential(), new UICredentialsProvider()) :
new TfsTeamProjectCollection(uri, new UICredentialsProvider());
#pragma warning restore 618
}
}
}
|
apache-2.0
|
C#
|
b114f1afc31b206dc3e099a900843ecec6a45504
|
Package hotfix
|
lfreneda/GzipS3Client
|
src/GzipS3Client/Properties/AssemblyInfo.cs
|
src/GzipS3Client/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("GzipS3Client")]
[assembly: AssemblyDescription("Lightweight AWS S3 Client. Simplify usage of AWS S3 to get and put objects.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("lfreneda~")]
[assembly: AssemblyProduct("GzipS3Client")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1535e9db-9f7f-4dfb-9bd2-2b241828d0dd")]
// 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.1.1")]
[assembly: AssemblyFileVersion("1.0.1.1")]
|
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("GzipS3Client")]
[assembly: AssemblyDescription("Lightweight AWS S3 Client. Simplify usage of AWS S3 to get and put objects.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("lfreneda~")]
[assembly: AssemblyProduct("GzipS3Client")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1535e9db-9f7f-4dfb-9bd2-2b241828d0dd")]
// 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#
|
d191e222e473cf3045382e9342059b8fb8388861
|
Fix a bad comment
|
vbfox/pinvoke,AArnott/pinvoke,jmelosegui/pinvoke
|
src/Kernel32.Desktop/Kernel32+GRPICONDIR.cs
|
src/Kernel32.Desktop/Kernel32+GRPICONDIR.cs
|
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System.Runtime.InteropServices;
/// <content>
/// Contains the <see cref="GRPICONDIR"/> nested type.
/// </content>
public partial class Kernel32
{
/// <summary>
/// Represents a group of icons as stored in a resource
/// </summary>
/// <remarks>
/// The structure is followed by <see cref="idCount"/> <see cref="GRPICONDIRENTRY"/> entries.
/// </remarks>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct GRPICONDIR
{
/// <summary>
/// Reserved (must be 0)
/// </summary>
public ushort idReserved;
/// <summary>
/// Resource type (1 for icons)
/// </summary>
public ushort idType;
/// <summary>
/// How many images?
/// </summary>
public ushort idCount;
}
}
}
|
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System.Runtime.InteropServices;
/// <content>
/// Contains the <see cref="GRPICONDIR"/> nested type.
/// </content>
public partial class Kernel32
{
/// <summary>
/// Represents a group of icons as stored in a resource
/// </summary>
/// <remarks>
/// The structure is followed by <see cref="idCount"/> <see cref="ICONDIRENTRY"/> entries.
/// </remarks>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct GRPICONDIR
{
/// <summary>
/// Reserved (must be 0)
/// </summary>
public ushort idReserved;
/// <summary>
/// Resource type (1 for icons)
/// </summary>
public ushort idType;
/// <summary>
/// How many images?
/// </summary>
public ushort idCount;
}
}
}
|
mit
|
C#
|
7a2816720691c4d41e81135136d58192af5a4954
|
Update NestedAwaitsDoNotDeadlockScenario.cs
|
JoeMighty/shouldly
|
src/Shouldly.Tests/ShouldNotThrow/NestedAwaitsDoNotDeadlockScenario.cs
|
src/Shouldly.Tests/ShouldNotThrow/NestedAwaitsDoNotDeadlockScenario.cs
|
using System;
using System.Threading.Tasks;
using System.Threading;
using Xunit;
namespace Shouldly.Tests.ShouldNotThrow
{
public class NestedAwaitsDoNotDeadlockScenario
{
[Fact]
public void DelegateShouldDropSynchronisationContext()
{
// The await keyword will automatically capture synchronization context
// Because shouldly uses .Wait() we cannot let continuations run on the sync context without a deadlock
var synchronizationContext = new SynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synchronizationContext);
SynchronizationContext.Current.ShouldNotBe(null);
var syncFunc1 = new Func<Task<object>>(() =>
{
SynchronizationContext.Current.ShouldBe(null);
var taskCompletionSource = new TaskCompletionSource<object>();
taskCompletionSource.SetResult(null);
return taskCompletionSource.Task;
});
syncFunc1.ShouldNotThrow();
var syncFunc2 = new Func<Task>(() =>
{
SynchronizationContext.Current.ShouldBe(null);
var taskCompletionSource = new TaskCompletionSource<object>();
taskCompletionSource.SetResult(null);
return taskCompletionSource.Task;
});
syncFunc2.ShouldNotThrow();
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Threading;
using Xunit;
namespace Shouldly.Tests.ShouldNotThrow
{
public class NestedAwaitsDoNotDeadlockScenario
{
[Fact]
public void DelegateShouldDropSynchronisationContext()
{
// The await keyword will automatically capture synchronization context
// Because shouldly uses .Wait() we cannot let continuations run on the sync context without a deadlock
var synchronizationContext = new SynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synchronizationContext);
SynchronizationContext.Current.ShouldNotBe(null);
var syncFunc1 = new Func<Task<object>>(() =>
{
SynchronizationContext.Current.ShouldBe(null);
var taskCompletionSource = new TaskCompletionSource<object>();
taskCompletionSource.SetResult(null);
return taskCompletionSource.Task;
});
syncFunc1.ShouldNotThrow();
var syncFunc2 = new Func<Task>(() =>
{
SynchronizationContext.Current.ShouldBe(null);
var taskCompletionSource = new TaskCompletionSource<object>();
taskCompletionSource.SetResult(null);
return taskCompletionSource.Task;
});
syncFunc2.ShouldNotThrow();
}
}
}
|
bsd-3-clause
|
C#
|
d4d52c0512d90da430d6b9dca0e91fa867d95cd6
|
Resolve Name Conflict
|
unity-chicken/VFW,laicasaane/VFW,vexe/VFW,wizcas/VFW
|
Assets/Plugins/Vexe/Runtime/Library/Extensions/UnityObjectExtensions.cs
|
Assets/Plugins/Vexe/Runtime/Library/Extensions/UnityObjectExtensions.cs
|
using UnityEngine;
using UnityObject = UnityEngine.Object;
namespace Vexe.Runtime.Extensions
{
public static class UnityObjectExtensions
{
public static T Copy<T>(this T source, Vector3 pos, Quaternion rot) where T : UnityObject
{
return UnityObject.Instantiate(source, pos, rot) as T;
}
public static T Copy<T>(this T source, Vector3 pos) where T : UnityObject
{
return UnityObject.Instantiate(source, pos, Quaternion.identity) as T;
}
public static T Copy<T>(this T source) where T : UnityObject
{
return UnityObject.Instantiate(source, Vector3.zero, Quaternion.identity) as T;
}
/// <summary>
/// Calls Destroy on this object if we're in playmode, otherwise (edit-time) DestroyImmediate
/// </summary>
public static void Destroy(this UnityObject obj, bool allowDestroyingAssets)
{
if (obj == null) return;
if (Application.isPlaying)
{
if (obj is GameObject)
{
GameObject gameObject = obj as GameObject;
gameObject.transform.SetParent(null, false);
}
UnityObject.Destroy(obj);
}
else
{
UnityObject.DestroyImmediate(obj, allowDestroyingAssets);
}
}
public static void Destroy(this UnityObject obj)
{
Destroy(obj, false);
}
}
}
|
using UnityEngine;
using UnityObject = UnityEngine.Object;
namespace Vexe.Runtime.Extensions
{
public static class UnityObjectExtensions
{
public static T Instantiate<T>(this T source, Vector3 pos, Quaternion rot) where T : UnityObject
{
return UnityObject.Instantiate(source, pos, rot) as T;
}
public static T Instantiate<T>(this T source, Vector3 pos) where T : UnityObject
{
return UnityObject.Instantiate(source, pos, Quaternion.identity) as T;
}
public static T Instantiate<T>(this T source) where T : UnityObject
{
return UnityObject.Instantiate(source, Vector3.zero, Quaternion.identity) as T;
}
/// <summary>
/// Calls Destroy on this object if we're in playmode, otherwise (edit-time) DestroyImmediate
/// </summary>
public static void Destroy(this UnityObject obj, bool allowDestroyingAssets)
{
if (obj == null) return;
if (Application.isPlaying)
{
if (obj is GameObject)
{
GameObject gameObject = obj as GameObject;
gameObject.transform.SetParent(null, false);
}
UnityObject.Destroy(obj);
}
else
{
UnityObject.DestroyImmediate(obj, allowDestroyingAssets);
}
}
public static void Destroy(this UnityObject obj)
{
Destroy(obj, false);
}
}
}
|
mit
|
C#
|
151173d7d9e6f0de39c831ee3ee96cf3c0febbda
|
Make the UWP page presenter us a common content control
|
KallynGowdy/ReactiveUI.Routing
|
src/ReactiveUI.Routing.UWP/PagePresenter.cs
|
src/ReactiveUI.Routing.UWP/PagePresenter.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using ReactiveUI.Routing.Presentation;
using Splat;
namespace ReactiveUI.Routing.UWP
{
public class PagePresenter : Presenter<PagePresenterRequest>
{
private readonly ContentControl host;
private readonly IViewLocator locator;
public PagePresenter(ContentControl host, IViewLocator locator = null)
{
this.host = host ?? throw new ArgumentNullException(nameof(host));
this.locator = locator ?? Locator.Current.GetService<IViewLocator>();
}
protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request)
{
return Observable.Create<PresenterResponse>(o =>
{
try
{
var view = locator.ResolveView(request.ViewModel);
var disposable = view.WhenActivated(d =>
{
o.OnNext(new PresenterResponse(view));
o.OnCompleted();
});
view.ViewModel = request.ViewModel;
host.Content = view;
return disposable;
}
catch (Exception ex)
{
o.OnError(ex);
throw;
}
});
}
public static IDisposable RegisterHost(ContentControl control)
{
var resolver = Locator.Current.GetService<IMutablePresenterResolver>();
return resolver.Register(new PagePresenter(control));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using ReactiveUI.Routing.Presentation;
using Splat;
namespace ReactiveUI.Routing.UWP
{
public class PagePresenter : Presenter<PagePresenterRequest>
{
private readonly Frame host;
private readonly IViewLocator locator;
public PagePresenter(Frame host, IViewLocator locator = null)
{
this.host = host ?? throw new ArgumentNullException(nameof(host));
this.locator = locator ?? Locator.Current.GetService<IViewLocator>();
}
protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request)
{
return Observable.Create<PresenterResponse>(o =>
{
try
{
var view = locator.ResolveView(request.ViewModel);
view.ViewModel = request.ViewModel;
host.Navigate(view.GetType());
o.OnNext(new PresenterResponse(view));
o.OnCompleted();
}
catch (Exception ex)
{
o.OnError(ex);
}
return new CompositeDisposable();
});
}
public static IDisposable RegisterHost(Frame control)
{
var resolver = Locator.Current.GetService<IMutablePresenterResolver>();
return resolver.Register(new PagePresenter(control));
}
}
}
|
mit
|
C#
|
c2109060934529ed72a3a869d11db1c6589da0bd
|
Allow ChoiceInstances to have a public constructor
|
ivaylo5ev/ink,inkle/ink,ivaylo5ev/ink,inkle/ink,ghostpattern/ink,ghostpattern/ink
|
ink-engine-runtime/ChoiceInstance.cs
|
ink-engine-runtime/ChoiceInstance.cs
|
namespace Ink.Runtime
{
public class ChoiceInstance : Runtime.Object
{
public string choiceText { get; internal set; }
internal bool hasBeenChosen { get; set; }
internal Choice choice { get; private set; }
internal CallStack.Thread threadAtGeneration { get; set; }
public ChoiceInstance()
{
}
internal ChoiceInstance (Choice choice)
{
this.choice = choice;
}
}
}
|
namespace Ink.Runtime
{
public class ChoiceInstance : Runtime.Object
{
public string choiceText { get; internal set; }
internal bool hasBeenChosen { get; set; }
internal Choice choice { get; private set; }
internal CallStack.Thread threadAtGeneration { get; set; }
internal ChoiceInstance (Choice choice)
{
this.choice = choice;
}
}
}
|
mit
|
C#
|
4c02927e0b1e6be7cb2b8587ff0ca605c0175c04
|
Update PushalotMessageBuilder.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Analytics/Telemetry/Pushalot/PushalotMessageBuilder.cs
|
TIKSN.Core/Analytics/Telemetry/Pushalot/PushalotMessageBuilder.cs
|
using System;
namespace TIKSN.Analytics.Telemetry.Pushalot
{
public class PushalotMessageBuilder
{
public string MessageBody { get; set; }
public string MessageImage { get; set; }
public bool MessageIsImportant { get; set; }
public bool MessageIsSilent { get; set; }
public string MessageLink { get; set; }
public string MessageLinkTitle { get; set; }
public string MessageSource { get; set; }
public int? MessageTimeToLive { get; set; }
public string MessageTitle { get; set; }
public PushalotMessage Build()
{
PushalotMessageLink link = null;
if (!string.IsNullOrEmpty(this.MessageLink))
{
link = new PushalotMessageLink(this.MessageLinkTitle, new Uri(this.MessageLink));
}
PushalotMessageImage image = null;
if (!string.IsNullOrEmpty(this.MessageImage))
{
image = new PushalotMessageImage(new Uri(this.MessageImage));
}
var message = new PushalotMessage(this.MessageTitle, this.MessageBody, link, this.MessageIsImportant,
this.MessageIsSilent, image, this.MessageSource, this.MessageTimeToLive);
return message;
}
}
}
|
namespace TIKSN.Analytics.Telemetry.Pushalot
{
public class PushalotMessageBuilder
{
public PushalotMessageBuilder()
{
}
public string MessageBody { get; set; }
public string MessageImage { get; set; }
public bool MessageIsImportant { get; set; }
public bool MessageIsSilent { get; set; }
public string MessageLink { get; set; }
public string MessageLinkTitle { get; set; }
public string MessageSource { get; set; }
public int? MessageTimeToLive { get; set; }
public string MessageTitle { get; set; }
public PushalotMessage Build()
{
PushalotMessageLink link = null;
if (!string.IsNullOrEmpty(this.MessageLink))
{
link = new PushalotMessageLink(this.MessageLinkTitle, new System.Uri(this.MessageLink));
}
PushalotMessageImage image = null;
if (!string.IsNullOrEmpty(this.MessageImage))
{
image = new PushalotMessageImage(new System.Uri(this.MessageImage));
}
var message = new PushalotMessage(this.MessageTitle, this.MessageBody, link, this.MessageIsImportant, this.MessageIsSilent, image, this.MessageSource, this.MessageTimeToLive);
return message;
}
}
}
|
mit
|
C#
|
7db39ef7330697de2507693518b8d9f6db1bacca
|
Update FileSystemComponent.cs
|
grzesiek-galezowski/component-based-test-tool
|
ComponentBasedTestTool/Components/FileSystemComponent.cs
|
ComponentBasedTestTool/Components/FileSystemComponent.cs
|
using System.Windows;
using ExtensionPoints.ImplementedByComponents;
using ExtensionPoints.ImplementedByContext;
using ExtensionPoints.ImplementedByContext.StateMachine;
namespace Components;
public class FileSystemComponent :
CoreTestComponent,
Capabilities.CustomGui,
Capabilities.CleanupOnEnvironmentClosing
{
private OperationControl _ls;
private OperationControl _cs;
private OperationControl _cat;
private OperationControl _wait;
private OperationControl _configure;
private readonly string _configureName = "configure";
private CustomGui _customGui;
private const string SleepName = "sleep";
private const string CatName = "cat";
private const string CdName = "cd";
private const string LsName = "ls";
public void PopulateOperations(TestComponentOperationDestination ctx)
{
ctx.AddOperation(_configureName, _configure);
ctx.AddOperation(LsName, _ls, _configureName);
ctx.AddOperation(CdName, _cs, _configureName);
ctx.AddOperation(CatName, _cat, _configureName);
ctx.AddOperation(SleepName, _wait, _configureName);
}
public void CreateOperations(TestComponentContext ctx)
{
_ls = ctx.CreateOperation(new LsOperation(ctx.CreateOutFor(LsName)));
_cs = ctx.CreateOperation(new CdOperation(ctx.CreateOutFor(CdName)));
_cat = ctx.CreateOperation(new CatOperation(ctx.CreateOutFor(CatName)));
_wait = ctx.CreateOperation(new WaitOperation(ctx.CreateOutFor(SleepName)));
_configure = ctx.CreateOperation(new ConfigureOperation(ctx.CreateOutFor(_configureName)));
}
public void ShowCustomUi()
{
if (_customGui is not { IsLoaded: true })
{
_customGui = new CustomGui(_wait, _configure)
{
Owner = Application.Current.MainWindow
};
_customGui.Show();
}
else
{
_customGui.Focus();
}
}
public void CleanupOnClosing()
{
MessageBox.Show("Cleaning up!");
}
}
|
using System.Windows;
using ExtensionPoints.ImplementedByComponents;
using ExtensionPoints.ImplementedByContext;
using ExtensionPoints.ImplementedByContext.StateMachine;
namespace Components;
public class FileSystemComponent :
CoreTestComponent,
Capabilities.CustomGui,
Capabilities.CleanupOnEnvironmentClosing
{
private OperationControl _ls;
private OperationControl _cs;
private OperationControl _cat;
private OperationControl _wait;
private OperationControl _configure;
private readonly string _configureName = "configure";
private CustomGui _customGui;
private const string SleepName = "sleep";
private const string CatName = "cat";
private const string CdName = "cd";
private const string LsName = "ls";
public void PopulateOperations(TestComponentOperationDestination ctx)
{
ctx.AddOperation(_configureName, _configure);
ctx.AddOperation(LsName, _ls, _configureName);
ctx.AddOperation(CdName, _cs, _configureName);
ctx.AddOperation(CatName, _cat, _configureName);
ctx.AddOperation(SleepName, _wait, _configureName);
}
public void CreateOperations(TestComponentContext ctx)
{
_ls = ctx.CreateOperation(new LsOperation(ctx.CreateOutFor(LsName)));
_cs = ctx.CreateOperation(new CdOperation(ctx.CreateOutFor(CdName)));
_cat = ctx.CreateOperation(new CatOperation(ctx.CreateOutFor(CatName)));
_wait = ctx.CreateOperation(new WaitOperation(ctx.CreateOutFor(SleepName)));
_configure = ctx.CreateOperation(new ConfigureOperation(ctx.CreateOutFor(_configureName)));
}
public void ShowCustomUi()
{
if (_customGui == null || !_customGui.IsLoaded)
{
_customGui = new CustomGui(_wait, _configure)
{
Owner = Application.Current.MainWindow
};
_customGui.Show();
}
else
{
_customGui.Focus();
}
}
public void CleanupOnClosing()
{
MessageBox.Show("Cleaning up!");
}
}
|
mit
|
C#
|
12253be382bfdaf4eccca281b47f49070bf5e082
|
Fix compile error around exporting SecureString
|
Zoxive/libgit2sharp,Zoxive/libgit2sharp,PKRoma/libgit2sharp,libgit2/libgit2sharp
|
LibGit2Sharp.Shared/SecureUsernamePasswordCredentials.cs
|
LibGit2Sharp.Shared/SecureUsernamePasswordCredentials.cs
|
using System;
using System.Runtime.InteropServices;
using System.Security;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access.
/// </summary>
public sealed class SecureUsernamePasswordCredentials : Credentials
{
/// <summary>
/// Callback to acquire a credential object.
/// </summary>
/// <param name="cred">The newly created credential object.</param>
/// <returns>0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired.</returns>
protected internal override int GitCredentialHandler(out IntPtr cred)
{
if (Username == null || Password == null)
{
throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password.");
}
IntPtr passwordPtr = IntPtr.Zero;
try
{
#if NET40
passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password);
#else
passwordPtr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(Password);
#endif
return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr));
}
finally
{
#if NET40
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
#else
SecureStringMarshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
#endif
}
}
/// <summary>
/// Username for username/password authentication (as in HTTP basic auth).
/// </summary>
public string Username { get; set; }
/// <summary>
/// Password for username/password authentication (as in HTTP basic auth).
/// </summary>
public SecureString Password { get; set; }
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Security;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access.
/// </summary>
public sealed class SecureUsernamePasswordCredentials : Credentials
{
/// <summary>
/// Callback to acquire a credential object.
/// </summary>
/// <param name="cred">The newly created credential object.</param>
/// <returns>0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired.</returns>
protected internal override int GitCredentialHandler(out IntPtr cred)
{
if (Username == null || Password == null)
{
throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password.");
}
IntPtr passwordPtr = IntPtr.Zero;
try
{
passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password);
return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr));
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
}
}
/// <summary>
/// Username for username/password authentication (as in HTTP basic auth).
/// </summary>
public string Username { get; set; }
/// <summary>
/// Password for username/password authentication (as in HTTP basic auth).
/// </summary>
public SecureString Password { get; set; }
}
}
|
mit
|
C#
|
7c1c9ca3764f5cc1b9e775c51133eadd63413e18
|
Fix location of pragmas to get XML documentation to build.
|
BenJenkinson/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,nodatime/nodatime,jskeet/nodatime,zaccharles/nodatime,zaccharles/nodatime,nodatime/nodatime,zaccharles/nodatime,zaccharles/nodatime,jskeet/nodatime,malcolmr/nodatime,malcolmr/nodatime,malcolmr/nodatime,zaccharles/nodatime
|
src/NodaTime/IClock.cs
|
src/NodaTime/IClock.cs
|
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime
{
#pragma warning disable 1584,1711,1572,1581,1580
/// <summary>
/// Represents a clock which can return the current time as an <see cref="Instant" />.
/// </summary>
/// <remarks>
/// <see cref="IClock"/> is intended for use anywhere you need to have access to the current time.
/// Although it's not strictly incorrect to call <c>SystemClock.Instance.Now</c> directly,
/// in the same way as you might call <see cref="DateTime.UtcNow"/>, it's strongly discouraged
/// as a matter of style for production code. We recommend providing an instance of <see cref="IClock"/>
/// to anything that needs it, which allows you to write tests using the fake clock in the NodaTime.Testing
/// assembly (or your own implementation).
/// </remarks>
/// <seealso cref="SystemClock"/>
/// <seealso cref="T:NodaTime.Testing.FakeClock"/>
/// <threadsafety>All implementations in Noda Time are thread-safe; custom implementations
/// should be thread-safe too. See the thread safety section of the user guide for more information.
/// </threadsafety>
public interface IClock
#pragma warning restore 1584,1711,1572,1581,1580
{
/// <summary>
/// Gets the current <see cref="Instant"/> on the time line according to this clock.
/// </summary>
Instant Now { get; }
}
}
|
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime
{
/// <summary>
/// Represents a clock which can return the current time as an <see cref="Instant" />.
/// </summary>
/// <remarks>
/// <see cref="IClock"/> is intended for use anywhere you need to have access to the current time.
/// Although it's not strictly incorrect to call <c>SystemClock.Instance.Now</c> directly,
/// in the same way as you might call <see cref="DateTime.UtcNow"/>, it's strongly discouraged
/// as a matter of style for production code. We recommend providing an instance of <see cref="IClock"/>
/// to anything that needs it, which allows you to write tests using the fake clock in the NodaTime.Testing
/// assembly (or your own implementation).
/// </remarks>
/// <seealso cref="SystemClock"/>
#pragma warning disable 1584,1711,1572,1581,1580
/// <seealso cref="T:NodaTime.Testing.FakeClock"/>
#pragma warning restore 1584,1711,1572,1581,1580
/// <threadsafety>All implementations in Noda Time are thread-safe; custom implementations
/// should be thread-safe too. See the thread safety section of the user guide for more information.
/// </threadsafety>
public interface IClock
{
/// <summary>
/// Gets the current <see cref="Instant"/> on the time line according to this clock.
/// </summary>
Instant Now { get; }
}
}
|
apache-2.0
|
C#
|
18c8a9b9b805ef1f103dbcdf336591b9a8f4a642
|
Add safety to ice cream hours.
|
samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays
|
TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/IceCreamConfirm.cs
|
TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/IceCreamConfirm.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Newtonsoft.Json;
public class IceCreamConfirm : ComponentSolver
{
public IceCreamConfirm(BombCommander bombCommander, BombComponent bombComponent) :
base(bombCommander, bombComponent)
{
_component = bombComponent.GetComponent(_componentType);
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType());
KMModSettings modSettings = bombComponent.GetComponent<KMModSettings>();
try
{
settings = JsonConvert.DeserializeObject<Settings>(modSettings.Settings);
}
catch (Exception ex)
{
DebugHelper.LogException(ex, "Could not deserialize ice cream settings:");
TwitchPlaySettings.data.ShowHours = false;
TwitchPlaySettings.WriteDataToFile();
}
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
if (inputCommand.ToLowerInvariant().Equals("hours"))
{
string hours;
yield return null;
if (!TwitchPlaySettings.data.ShowHours)
{
yield return $"sendtochat Sorry, hours are currently unavailable. Enjoy your ice cream!";
yield break;
}
if (settings.openingTimeEnabled)
{
hours = "We are open every other hour today.";
}
else
{
hours = "We're open all day today!";
}
yield return $"sendtochat {hours}";
}
else
{
IEnumerator command = (IEnumerator)_ProcessCommandMethod.Invoke(_component, new object[] { inputCommand });
if (command == null) yield break;
while (command.MoveNext())
{
yield return command.Current;
}
}
}
static IceCreamConfirm()
{
_componentType = ReflectionHelper.FindType("IceCreamModule");
_ProcessCommandMethod = _componentType.GetMethod("ProcessTwitchCommand", BindingFlags.Public | BindingFlags.Instance);
}
class Settings
{
public bool openingTimeEnabled;
}
private static Type _componentType = null;
private static MethodInfo _ProcessCommandMethod = null;
private object _component = null;
private Settings settings;
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Newtonsoft.Json;
public class IceCreamConfirm : ComponentSolver
{
public IceCreamConfirm(BombCommander bombCommander, BombComponent bombComponent) :
base(bombCommander, bombComponent)
{
_component = bombComponent.GetComponent(_componentType);
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType());
KMModSettings modSettings = bombComponent.GetComponent<KMModSettings>();
settings = JsonConvert.DeserializeObject<Settings>(modSettings.Settings);
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
if (inputCommand.ToLowerInvariant().Equals("hours"))
{
string hours;
yield return null;
if (!TwitchPlaySettings.data.ShowHours)
{
yield return $"sendtochat Sorry, hours are currently unavailable. Enjoy your ice cream!";
yield break;
}
if (settings.openingTimeEnabled)
{
hours = "We are open every other hour today.";
}
else
{
hours = "We're open all day today!";
}
yield return $"sendtochat {hours}";
}
else
{
IEnumerator command = (IEnumerator)_ProcessCommandMethod.Invoke(_component, new object[] { inputCommand });
if (command == null) yield break;
while (command.MoveNext())
{
yield return command.Current;
}
}
}
static IceCreamConfirm()
{
_componentType = ReflectionHelper.FindType("IceCreamModule");
_ProcessCommandMethod = _componentType.GetMethod("ProcessTwitchCommand", BindingFlags.Public | BindingFlags.Instance);
}
class Settings
{
public bool openingTimeEnabled;
}
private static Type _componentType = null;
private static MethodInfo _ProcessCommandMethod = null;
private object _component = null;
private Settings settings;
}
|
mit
|
C#
|
d81639e0dbefaad73dd36aed4ab153ed45ac656d
|
Remove the build attributes because they'll be generated with a full namespace
|
thenucleus/nuclei.build
|
src/nuclei.build/Properties/AssemblyInfo.cs
|
src/nuclei.build/Properties/AssemblyInfo.cs
|
//-----------------------------------------------------------------------
// <copyright company="TheNucleus">
// Copyright (c) TheNucleus. All rights reserved.
// Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using Nuclei.Build;
[assembly: AssemblyCulture("")]
// Resources
[assembly: NeutralResourcesLanguage("en-US")]
// 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: AssemblyTrademark("")]
// 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)]
// Indicate that the assembly is CLS compliant.
[assembly: CLSCompliant(true)]
|
//-----------------------------------------------------------------------
// <copyright company="TheNucleus">
// Copyright (c) TheNucleus. All rights reserved.
// Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using Nuclei.Build;
[assembly: AssemblyCulture("")]
// Resources
[assembly: NeutralResourcesLanguage("en-US")]
// 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: AssemblyTrademark("")]
// 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)]
// Indicate that the assembly is CLS compliant.
[assembly: CLSCompliant(true)]
// The time the assembly was build
[assembly: AssemblyBuildTime(buildTime: "1900-01-01T00:00:00.0000000+00:00")]
// The version from which the assembly was build
[module: SuppressMessage(
"Microsoft.Usage",
"CA2243:AttributeStringLiteralsShouldParseCorrectly",
Justification = "It's a VCS revision, not a version")]
[assembly: AssemblyBuildInformation(buildNumber: 0, versionControlInformation: "1234567890123456789012345678901234567890")]
|
apache-2.0
|
C#
|
52917efd1a42a1a8ef203ca632fa5fe5e4a22908
|
fix UnitType.id comment
|
ad510/plausible-deniability
|
Assets/Scripts/UnitType.cs
|
Assets/Scripts/UnitType.cs
|
// Copyright (c) 2013 Andrew Downing
// 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.Collections.Generic;
using System.Linq;
using System.Text;
public class UnitType {
public int id; // index in unit type array
public string name;
public string imgPath;
public FP.Vector imgOffset; // how much to offset center of image when drawing it
public long imgHalfHeight; // how tall half of image height should be drawn
public FP.Vector selMinPos; // minimum relative position where clicking would select the unit
public FP.Vector selMaxPos; // maximum relative position where clicking would select the unit
/*public string sndSelect;
public string sndMove;
public string sndAttack;
public string sndNoHealth;*/
public int maxHealth;
public long speed; // in position units per millisecond
public long reload; // time needed to reload
public long range; // range of attack
public long tightFormationSpacing;
public long makeUnitMinDist; // minimum distance that new units of this unit type move away
public long makeUnitMaxDist; // maximum distance that new units of this unit type move away
public long makePathMinDist; // minimum distance that new paths of this unit type move away
public long makePathMaxDist; // maximum distance that new paths of this unit type move away
public UnitType makeOnUnitT; // unit type that this unit type should be made on top of
public int[] damage; // damage done per attack to each unit type
public bool[] canMake; // whether can make each unit type
public long[] rscCost; // cost to make unit (may not be negative)
public long[] rscCollectRate; // resources collected per each millisecond that unit exists (may not be negative)
}
|
// Copyright (c) 2013 Andrew Downing
// 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.Collections.Generic;
using System.Linq;
using System.Text;
public class UnitType {
public int id; // index in player array
public string name;
public string imgPath;
public FP.Vector imgOffset; // how much to offset center of image when drawing it
public long imgHalfHeight; // how tall half of image height should be drawn
public FP.Vector selMinPos; // minimum relative position where clicking would select the unit
public FP.Vector selMaxPos; // maximum relative position where clicking would select the unit
/*public string sndSelect;
public string sndMove;
public string sndAttack;
public string sndNoHealth;*/
public int maxHealth;
public long speed; // in position units per millisecond
public long reload; // time needed to reload
public long range; // range of attack
public long tightFormationSpacing;
public long makeUnitMinDist; // minimum distance that new units of this unit type move away
public long makeUnitMaxDist; // maximum distance that new units of this unit type move away
public long makePathMinDist; // minimum distance that new paths of this unit type move away
public long makePathMaxDist; // maximum distance that new paths of this unit type move away
public UnitType makeOnUnitT; // unit type that this unit type should be made on top of
public int[] damage; // damage done per attack to each unit type
public bool[] canMake; // whether can make each unit type
public long[] rscCost; // cost to make unit (may not be negative)
public long[] rscCollectRate; // resources collected per each millisecond that unit exists (may not be negative)
}
|
mit
|
C#
|
d836234cf8f5cb6873cd53698d4861262e2415f4
|
Change attributes order
|
Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates
|
src/CurrencyRates/Entity/Currency.cs
|
src/CurrencyRates/Entity/Currency.cs
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace CurrencyRates.Entity
{
public class Currency
{
[Key, MaxLength(3), MinLength(3)]
public string Code { get; set; }
[MaxLength(128), Required]
public string Name { get; set; }
public ICollection<Rate> Rates { get; set; }
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace CurrencyRates.Entity
{
public class Currency
{
[Key, MaxLength(3), MinLength(3)]
public string Code { get; set; }
[Required, MaxLength(128)]
public string Name { get; set; }
public ICollection<Rate> Rates { get; set; }
}
}
|
mit
|
C#
|
df57c8174c75a81a10b8e7a93f79d2b68a5685df
|
remove comments from settings
|
Dethrail/pinball
|
Assets/scripts/common/Settings.cs
|
Assets/scripts/common/Settings.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using UnityEngine;
[XmlType("settings")]
public sealed class Settings
{
public static Settings Instance;
[XmlAttribute("lives-count")]
public int LivesCount;
[XmlArray("obstacles")]
public List<XMLObstacleType> ObstacleScore;
public static void Create()
{
var resourceDirectory = GetTextFilesFromDirectory(GetLocalFilesDirectory());
foreach(var settings in resourceDirectory) {
Settings s = XmlResource.LoadFromFile<Settings>(settings);
if(s != null) {
Instance = s;
}
}
if(Instance == null) {
Instance = new Settings();
Instance.ObstacleScore = new List<XMLObstacleType>((byte)ObstacleType.Count);
Instance.LivesCount = 3;
foreach(ObstacleType suit in Enum.GetValues(typeof(ObstacleType))) {
XMLObstacleType elem = new XMLObstacleType();
elem.Name = suit.ToString();
elem.Score = 25;
Instance.ObstacleScore.Add(elem);
}
}
}
public static bool LocalFolderExists()
{
return GetTextFilesFromDirectory(GetLocalFilesDirectory()).Length > 0;
}
public static string[] GetTextFilesFromDirectory(string directory)
{
return Directory.GetFiles(directory, "*.xml");
}
public static string GetSourceDirectory()
{
return Application.streamingAssetsPath + "/";
}
public static string GetLocalFilesDirectory()
{
#if UNITY_EDITOR
return Application.streamingAssetsPath + "/";
#else
return Application.persistentDataPath;
#endif
}
public void Save()
{
XmlResource.SaveToFile(Path.Combine(GetLocalFilesDirectory(), "settings.xml"), Instance);
}
}
[XmlType("obstacle")]
public sealed class XMLObstacleType
{
[XmlAttribute("name")]
public string Name;
[XmlAttribute("score")]
public int Score;
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using UnityEngine;
[XmlType("settings")]
public sealed class Settings
{
public static Settings Instance;
[XmlAttribute("lives-count")]
public int LivesCount;
[XmlArray("obstacles")]
public List<XMLObstacleType> ObstacleScore;
public static void Create()
{
//if(!LocalFolderExists()) {
// WriteToLocalStorage();
//}
var resourceDirectory = GetTextFilesFromDirectory(GetLocalFilesDirectory());
foreach(var settings in resourceDirectory) {
Settings s = XmlResource.LoadFromFile<Settings>(settings);
if(s != null) {
Instance = s;
}
}
if(Instance == null) {
Instance = new Settings();
Instance.ObstacleScore = new List<XMLObstacleType>((byte)ObstacleType.Count);
Instance.LivesCount = 3;
foreach(ObstacleType suit in Enum.GetValues(typeof(ObstacleType))) {
XMLObstacleType elem = new XMLObstacleType();
elem.Name = suit.ToString();
elem.Score = 25;
Instance.ObstacleScore.Add(elem);
}
}
}
public static bool LocalFolderExists()
{
return GetTextFilesFromDirectory(GetLocalFilesDirectory()).Length > 0;
}
public static string[] GetTextFilesFromDirectory(string directory)
{
return Directory.GetFiles(directory, "*.xml");
}
public static string GetSourceDirectory()
{
return Application.streamingAssetsPath + "/";
}
public static string GetLocalFilesDirectory()
{
#if UNITY_EDITOR
return Application.streamingAssetsPath + "/";
#else
return Application.persistentDataPath;
#endif
}
//public static void WriteToLocalStorage()
//{
// string srcDir = GetSourceDirectory();
// string dstDir = GetLocalFilesDirectory();
// var villageInputFiles = GetTextFilesFromDirectory(GetSourceDirectory()).Select(x => x.Substring(srcDir.Length + 1));
// Debug.LogError(villageInputFiles.First());
// foreach(var villageFile in villageInputFiles) {
// File.Copy(Path.Combine(srcDir, villageFile), Path.Combine(dstDir, villageFile), true);
// }
//}
public void Save()
{
XmlResource.SaveToFile(Path.Combine(GetLocalFilesDirectory(), "settings.xml"), Instance);
}
}
[XmlType("obstacle")]
public sealed class XMLObstacleType
{
[XmlAttribute("name")]
public string Name;
[XmlAttribute("score")]
public int Score;
}
|
mit
|
C#
|
a1cef528e162b3529cd8a5c53807f728ff5ddce9
|
make Loggger Builder
|
CloudBreadProject/CloudBread-Admin-Web,CloudBreadProject/CloudBread-Admin-Web,yshong93/CloudBread-Admin-Web,yshong93/CloudBread-Admin-Web,yshong93/CloudBread-Admin-Web,CloudBreadProject/CloudBread-Admin-Web
|
CBLoggerBuilder.cs
|
CBLoggerBuilder.cs
|
using CloudBreadAdminWebAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Http.OData;
namespace CloudBread_Admin_Web
{
public class CBLoggerBuilder
{
public enum LoggerType { GET, GETbyIID, PUT, POST, PATCH, DELETE };
public enum LevelType { INFO };
public static Logging.CBLoggers Build(string sid, LevelType level, string logger, string message)
{
Logging.CBLoggers logMessage = new Logging.CBLoggers();
logMessage.memberID = sid;
logMessage.Level = level.ToString();
logMessage.Logger = logger;
logMessage.Message = message;
return logMessage;
}
private string controllerTag;
public CBLoggerBuilder(string controllerTag)
{
this.controllerTag = controllerTag;
}
public Logging.CBLoggers build(ODataController controller, LevelType level, LoggerType type, string message = null)
{
string sid = CBAuth.getMemberID(controller.User as ClaimsPrincipal);
string logger = controllerTag + "-" + type.ToString();
if (message == null)
{
switch (type)
{
case LoggerType.GET:
case LoggerType.GETbyIID:
message = controller.Request.RequestUri.PathAndQuery.ToString();
break;
default:
message = "No Message";
break;
}
}
return CBLoggerBuilder.Build(sid, level, logger, message);
}
}
}
|
using CloudBreadAdminWebAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
namespace CloudBread_Admin_Web
{
public class CBLoggerBuilder
{
public enum LoggerType { GET, GETbyIID, PUT, POST, PATCH, DELETE };
public enum LevelType { INFO };
public static void Build(ref Logging.CBLoggers logMsg, ClaimsPrincipal claims,
string controllerName, LevelType levelType, LoggerType loggerType, string message)
{
logMsg.memberID = CBAuth.getMemberID(claims);
logMsg.Level = levelType.ToString();
logMsg.Logger = controllerName + "-" + loggerType.ToString();
logMsg.Message = message;
}
}
}
|
mit
|
C#
|
cfab2643e3202955c53a1120dca752b5ed9f6075
|
make virtual
|
coderUT/Dragablz,ButchersBoy/Dragablz
|
Dragablz/DefaultInterTabClient.cs
|
Dragablz/DefaultInterTabClient.cs
|
using System;
using System.Linq;
using System.Windows;
using Dragablz.Core;
namespace Dragablz
{
public class DefaultInterTabClient : IInterTabClient
{
public virtual INewTabHost<Window> GetNewHost(IInterTabClient interTabClient, object partition, TabablzControl source)
{
if (source == null) throw new ArgumentNullException("source");
var sourceWindow = Window.GetWindow(source);
if (sourceWindow == null) throw new ApplicationException("Unable to ascrtain source window.");
var newWindow = (Window)Activator.CreateInstance(sourceWindow.GetType());
var newTabablzControl = newWindow.LogicalTreeDepthFirstTraversal().OfType<TabablzControl>().FirstOrDefault();
if (newTabablzControl == null) throw new ApplicationException("Unable to ascrtain tab control.");
newTabablzControl.Items.Clear();
return new NewTabHost<Window>(newWindow, newTabablzControl);
}
public virtual TabEmptiedResponse TabEmptiedHandler(TabablzControl tabControl, Window window)
{
return TabEmptiedResponse.CloseWindowOrLayoutBranch;
}
}
}
|
using System;
using System.Linq;
using System.Windows;
using Dragablz.Core;
namespace Dragablz
{
public class DefaultInterTabClient : IInterTabClient
{
public INewTabHost<Window> GetNewHost(IInterTabClient interTabClient, object partition, TabablzControl source)
{
if (source == null) throw new ArgumentNullException("source");
var sourceWindow = Window.GetWindow(source);
if (sourceWindow == null) throw new ApplicationException("Unable to ascrtain source window.");
var newWindow = (Window)Activator.CreateInstance(sourceWindow.GetType());
var newTabablzControl = newWindow.LogicalTreeDepthFirstTraversal().OfType<TabablzControl>().FirstOrDefault();
if (newTabablzControl == null) throw new ApplicationException("Unable to ascrtain tab control.");
newTabablzControl.Items.Clear();
return new NewTabHost<Window>(newWindow, newTabablzControl);
}
public TabEmptiedResponse TabEmptiedHandler(TabablzControl tabControl, Window window)
{
return TabEmptiedResponse.CloseWindowOrLayoutBranch;
}
}
}
|
mit
|
C#
|
d6568ffa469525d6e92cf688e22c5d5b7450744c
|
modify typo
|
mmd-for-unity-proj/mmd-for-unity
|
Editor/Inspector/InspectorBase.cs
|
Editor/Inspector/InspectorBase.cs
|
// Inspectorからインポートなどができるようになります
// 他スクリプトと競合してしまう時はコメントアウトしてください
#define USE_INSPECTOR
//----------
#if USE_INSPECTOR
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
namespace MMD
{
public class InspectorBase : Editor
{
[DidReloadScripts]
static void OnDidReloadScripts()
{
EditorApplication.update += () =>
{
if (Selection.objects.Length != 0)
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
string extension = Path.GetExtension(path).ToLower();
if (extension == ".pmd" || extension == ".pmx")
{
SetupScriptableObject<PMDScriptableObject>(path);
}
else if (extension == ".vmd")
{
SetupScriptableObject<VMDScriptableObject>(path);
}
}
};
}
static void SetupScriptableObject<T>(string path) where T : ScriptableObjectBase
{
int count = Selection.objects.OfType<T>().Count();
if (count != 0) return;
T scriptableObject = ScriptableObject.CreateInstance<T>();
scriptableObject.assetPath = path;
Selection.activeObject = scriptableObject;
EditorUtility.UnloadUnusedAssets();
}
}
}
#endif
|
// Inspectorからインポートなどができるようになります
// 他スクリプトと競合してしまう時はコメントアウトしてください
#define USE_INSPECTOR
//----------
#if USE_INSPECTOR
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
namespace MMD
{
public class InspectorBase : Editor
{
[DidReloadScripts]
static void OnDidReloadScripts()
{
EditorApplication.update += () =>
{
if (Selection.objects.Length != 0)
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
string extension = Path.GetExtension(path).ToLower();
if (extension == ".pmd" || extension == ".pmx")
{
SetupScriptableObject<PMDScriptableObject>(path);
}
else if (extension == ".vmd")
{
SetupScriptableObject<PMDScriptableObject>(path);
}
}
};
}
static void SetupScriptableObject<T>(string path) where T : ScriptableObjectBase
{
int count = Selection.objects.OfType<T>().Count();
if (count != 0) return;
T scriptableObject = ScriptableObject.CreateInstance<T>();
scriptableObject.assetPath = path;
Selection.activeObject = scriptableObject;
EditorUtility.UnloadUnusedAssets();
}
}
}
#endif
|
bsd-3-clause
|
C#
|
9836d20522e720fa9d255c3636d2fc9ee2db57ea
|
adjust landing page to Stand-Up Timer content
|
PapaMufflon/StandUpTimer,PapaMufflon/StandUpTimer,PapaMufflon/StandUpTimer
|
StandUpTimer.Web/Views/Home/Index.cshtml
|
StandUpTimer.Web/Views/Home/Index.cshtml
|
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>Stand-Up Timer Statistics</h1>
<p class="lead">This is just a project to teach myself a bit of ASP.NET MVC. But feel free to use it anyway.</p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Download app</h2>
<p>
Try the Stand-Up Timer Windows App to live by a healthy stand-sit-dynamic while working at a desk.
</p>
<p><a class="btn btn-default" href="http://papamufflon.github.io/StandUpTimer/">Download »</a></p>
</div>
<div class="col-md-4">
<h2>Register a user</h2>
<p>Create yourself a user and log youself in via the Windows App to see beautiful charts about your stand-sit-dynamics on this website.</p>
<p><a class="btn btn-default" href="/Account/Register">Register »</a></p>
</div>
<div class="col-md-4">
<h2>Help</h2>
<p>When you have any ideas extending the Stand-Up Timer or this website, just drop me a line and I'll see what I can do. Or - even better - submit a pull request!</p>
<p><a class="btn btn-default" href="https://github.com/PapaMufflon/StandUpTimer">Contribute »</a></p>
</div>
</div>
|
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div>
|
mit
|
C#
|
43c9d19b125bdeaf9d631a3aa55290c6658c9d95
|
Use the same folder as the JAVA implementation
|
Floobits/floobits-vsp
|
plugin-common-cs/Constants.cs
|
plugin-common-cs/Constants.cs
|
using System;
using System.Text.RegularExpressions;
namespace Floobits.Common
{
public class Constants {
static public string baseDir = baseDirInit();
static public string shareDir = FilenameUtils.concat(baseDir, "share");
static public string version = "0.11";
static public string pluginVersion = "0.01";
static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com";
static public int OUTBOUND_FILTER_PROXY_PORT = 443;
static public string floobitsDomain = "floobits.com";
static public string defaultHost = "floobits.com";
static public int defaultPort = 3448;
static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled);
static public int TOO_MANY_BIG_DIRS = 50;
static public string baseDirInit()
{
return FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "floobits");
}
}
}
|
using System;
using System.Text.RegularExpressions;
namespace Floobits.Common
{
public class Constants {
static public string baseDir = FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "floobits");
static public string shareDir = FilenameUtils.concat(baseDir, "share");
static public string version = "0.11";
static public string pluginVersion = "0.01";
static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com";
static public int OUTBOUND_FILTER_PROXY_PORT = 443;
static public string floobitsDomain = "floobits.com";
static public string defaultHost = "floobits.com";
static public int defaultPort = 3448;
static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled);
static public int TOO_MANY_BIG_DIRS = 50;
}
}
|
apache-2.0
|
C#
|
46a9833e1ff7bed7d9c17c147ec5c5a32e94e6ce
|
Change default JSON serialization to CamelCase
|
mstrother/BmpListener
|
BmpListener.ConsoleExample/Program.cs
|
BmpListener.ConsoleExample/Program.cs
|
using System;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace BmpListener.ConsoleExample
{
internal class Program
{
private static void Main()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new IPAddressConverter());
settings.Converters.Add(new StringEnumConverter());
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
return settings;
};
var bmpListener = new BmpListener();
bmpListener.Start(WriteJson).Wait();
}
private static void WriteJson(BmpMessage msg)
{
var json = JsonConvert.SerializeObject(msg);
Console.WriteLine(json);
}
}
}
|
using System;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BmpListener.ConsoleExample
{
internal class Program
{
private static void Main()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new IPAddressConverter());
settings.Converters.Add(new StringEnumConverter());
return settings;
};
var bmpListener = new BmpListener();
bmpListener.Start(WriteJson).Wait();
}
private static void WriteJson(BmpMessage msg)
{
var json = JsonConvert.SerializeObject(msg);
Console.WriteLine(json);
}
}
}
|
mit
|
C#
|
e4d6e0def59bbbacff520c4744b1db9a6999b26d
|
Add an Emit method to emit text with style
|
directhex/xwt,iainx/xwt,lytico/xwt,mminns/xwt,akrisiun/xwt,residuum/xwt,mono/xwt,hwthomas/xwt,mminns/xwt,antmicro/xwt,sevoku/xwt,cra0zy/xwt,hamekoz/xwt,TheBrainTech/xwt,steffenWi/xwt
|
Xwt/Xwt.Backends/IMarkdownViewBackend.cs
|
Xwt/Xwt.Backends/IMarkdownViewBackend.cs
|
//
// IMarkdownViewBackend.cs
//
// Author:
// Jérémie Laval <jeremie.laval@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
using System;
namespace Xwt.Backends
{
[Flags]
enum MarkdownInlineStyle
{
Italic,
Bold,
Monospace
}
public interface IMarkdownViewBackend : IWidgetBackend
{
object CreateBuffer ();
// Emit unstyled text
void EmitText (object buffer, string text);
// Emit text using combination of the MarkdownInlineStyle
void EmitStyledText (object buffer, string text, MarkdownInlineStyle style);
// Emit a header (h1, h2, ...)
void EmitHeader (object buffer, string title, int level);
// What's outputed afterwards will be a in new paragrapgh
void EmitStartParagraph (object buffer);
void EmitEndParagraph (object buffer);
// Emit a list
// Chain is:
// open-list, open-bullet, <above methods>, close-bullet, close-list
void EmitOpenList (object buffer);
void EmitOpenBullet (object buffer);
void EmitCloseBullet (object buffet);
void EmitCloseList (object buffer);
// Emit a link displaying text and opening the href URL
void EmitLink (object buffer, string href, string text);
// Emit code in a preformated blockquote
void EmitCodeBlock (object buffer, string code);
// Emit an horizontal ruler
void EmitHorizontalRuler (object buffer);
// Display the passed buffer
void SetBuffer (object buffer);
}
}
|
//
// IMarkdownViewBackend.cs
//
// Author:
// Jérémie Laval <jeremie.laval@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
using System;
namespace Xwt.Backends
{
[Flags]
enum MarkdownInlineStyle
{
Italic,
Bold,
Monospace
}
public interface IMarkdownViewBackend : IWidgetBackend
{
object CreateBuffer ();
// Emit unstyled text
void EmitText (object buffer, string text);
// Emit a header (h1, h2, ...)
void EmitHeader (object buffer, string title, int level);
// What's outputed afterwards will be a in new paragrapgh
void EmitStartParagraph (object buffer);
void EmitEndParagraph (object buffer);
// Emit a list
// Chain is:
// open-list, open-bullet, <above methods>, close-bullet, close-list
void EmitOpenList (object buffer);
void EmitOpenBullet (object buffer);
void EmitCloseBullet (object buffet);
void EmitCloseList (object buffer);
// Emit a link displaying text and opening the href URL
void EmitLink (object buffer, string href, string text);
// Emit code in a preformated blockquote
void EmitCodeBlock (object buffer, string code);
// Emit an horizontal ruler
void EmitHorizontalRuler (object buffer);
// Display the passed buffer
void SetBuffer (object buffer);
}
}
|
mit
|
C#
|
9559d549b4614486934b3c157aba40e4c50e2e07
|
Use Var
|
ms-iot/UniversalMediaEngine
|
samples/speechSynthesisSample/speechSynthesisSample/MainPage.xaml.cs
|
samples/speechSynthesisSample/speechSynthesisSample/MainPage.xaml.cs
|
using Microsoft.Maker.Media.UniversalMediaEngine;
using System;
using System.Diagnostics;
using Windows.Media.SpeechSynthesis;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace speechSynthesisSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private MediaEngine mediaEngine= new MediaEngine();
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
var stream = await synth.SynthesizeTextToStreamAsync("Hello World");
mediaEngine.PlayStream(stream);
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var result = await mediaEngine.InitializeAsync();
if (MediaEngineInitializationResult.Success != result)
{
Debug.WriteLine("Failed to start MediaEngine");
}
}
}
}
|
using Microsoft.Maker.Media.UniversalMediaEngine;
using System;
using System.Diagnostics;
using Windows.Media.SpeechSynthesis;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace speechSynthesisSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private MediaEngine mediaEngine= new MediaEngine();
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");
mediaEngine.PlayStream(stream);
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var result = await mediaEngine.InitializeAsync();
if (MediaEngineInitializationResult.Success != result)
{
Debug.WriteLine("Failed to start MediaEngine");
}
}
}
}
|
mit
|
C#
|
596efee46e38f4119c48a1f38efef5015d2dc22e
|
increment version number
|
NickStrupat/DiscogsNet
|
DiscogsNet/Properties/AssemblyInfo.cs
|
DiscogsNet/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("DiscogsNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DiscogsNet")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("165c3b90-583e-41c7-9588-e3227b61a0a0")]
// 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.6.1.1")]
[assembly: AssemblyFileVersion("1.6.1.1")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DiscogsNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DiscogsNet")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("165c3b90-583e-41c7-9588-e3227b61a0a0")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
|
lgpl-2.1
|
C#
|
a4fc7e91b171516806ce740a905ca1999be96c62
|
Use Timer based Observable to generate data
|
WillemRB/DataGenerator
|
Program.cs
|
Program.cs
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataGenerator
{
class Program
{
static void Main(string[] args)
{
var data = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]);
var tick = TimeSpan.Parse(ConfigurationSettings.AppSettings["timespan"]);
Observable
.Timer(TimeSpan.Zero, tick)
.Subscribe(
t => { Console.WriteLine(data.Generate()); }
);
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataGenerator
{
class Program
{
static void Main(string[] args)
{
var gen = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]);
for (int i = 0; i < 25; i++)
{
Console.WriteLine(gen.Generate());
}
Console.ReadLine();
}
}
}
|
mit
|
C#
|
fb0e490af34f0e8e19c5853417b69ce0632963a0
|
Add missing license plate
|
or-tools/or-tools,google/or-tools,or-tools/or-tools,or-tools/or-tools,google/or-tools,or-tools/or-tools,or-tools/or-tools,or-tools/or-tools,google/or-tools,google/or-tools,google/or-tools,google/or-tools
|
ortools/dotnet/CreateSigningKey/Program.cs
|
ortools/dotnet/CreateSigningKey/Program.cs
|
// Copyright 2010-2020 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Security.Cryptography;
namespace CreateSigningKey
{
class Program
{
static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
Console.WriteLine("Key filename not specified.");
return;
}
string path = Directory.GetCurrentDirectory() + args[0];
Console.WriteLine("Key filename:" + path);
if (Console.Out != null)
Console.Out.Flush();
File.WriteAllBytes(path, GenerateStrongNameKeyPair());
}
public static byte[] GenerateStrongNameKeyPair()
{
using (var provider = new RSACryptoServiceProvider(4096))
{
return provider.ExportCspBlob(!provider.PublicOnly);
}
}
}
}
|
using System;
using System.IO;
using System.Security.Cryptography;
namespace CreateSigningKey
{
class Program
{
static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
Console.WriteLine("Key filename not specified.");
return;
}
string path = Directory.GetCurrentDirectory() + args[0];
Console.WriteLine("Key filename:" + path);
if (Console.Out != null)
Console.Out.Flush();
File.WriteAllBytes(path, GenerateStrongNameKeyPair());
}
public static byte[] GenerateStrongNameKeyPair()
{
using (var provider = new RSACryptoServiceProvider(4096))
{
return provider.ExportCspBlob(!provider.PublicOnly);
}
}
}
}
|
apache-2.0
|
C#
|
5d8326b7ca64125cde201d32a7872b1cc45f20d2
|
Update AssemblyInfo.cs
|
shanewalters/qif,hazzik/qif
|
QifApi/Properties/AssemblyInfo.cs
|
QifApi/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(true)]
// 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("QifApi")]
[assembly: AssemblyDescription("Quicken Interchange Format API (.NET Managed Wrapper)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("https://github.com/shanewalters/qif")]
[assembly: AssemblyProduct("QifApi")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef9b7bba-d661-4d77-9d53-80c10a71ec84")]
// 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.*")]
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(true)]
// 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("QifApi")]
[assembly: AssemblyDescription("Quicken Interchange Format API (.NET Managed Wrapper)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("http://qif.codeplex.com/")]
[assembly: AssemblyProduct("QifApi")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef9b7bba-d661-4d77-9d53-80c10a71ec84")]
// 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.*")]
|
mit
|
C#
|
8e6ece27e8478e74d0a639ed6f903a4f0552698f
|
Add movement duplication
|
dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo
|
DynamixelServo.TestConsole/Program.cs
|
DynamixelServo.TestConsole/Program.cs
|
using System;
using System.Threading;
using DynamixelServo.Driver;
namespace DynamixelServo.TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting");
using (DynamixelDriver driver = new DynamixelDriver("COM17"))
{
driver.SetTorque(1, false);
driver.SetTorque(2, false);
while (true)
{
driver.WriteGoalPosition(4,(ushort) (1024 - driver.ReadPresentPosition(1)));
driver.WriteGoalPosition(3,(ushort) (1024 - driver.ReadPresentPosition(2)));
Thread.Sleep(50);
}
}
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
|
using System;
using DynamixelServo.Driver;
namespace DynamixelServo.TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting");
using (DynamixelDriver driver = new DynamixelDriver("COM17"))
{
byte[] servos = driver.Search(1, 10);
Console.WriteLine("Leds on");
Console.WriteLine("Press enter to turn leds on");
Console.ReadLine();
foreach (byte servo in servos)
{
driver.SetLed(servo, true);
}
Console.WriteLine("Press enter to turn leds off");
Console.ReadLine();
foreach (byte servo in servos)
{
driver.SetLed(servo, false);
}
Console.WriteLine("Leds off");
}
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
|
apache-2.0
|
C#
|
10058bed7e1b9277fd7cc89a943cde24d201c320
|
Update server side API for single multiple answer question
|
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
|
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
|
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
|
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
|
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.