content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
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("Server Density Monitoring Agent Service")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Boxed Ice")]
[assembly: AssemblyProduct("Server Density Monitoring Agent Service")]
[assembly: AssemblyCopyright("Copyright © Boxed Ice 2012")]
[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("525a1f20-291e-473e-ab42-574385f4acb6")]
// 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.0.6")]
[assembly: AssemblyFileVersion("1.6.0.6")]
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
| 41.131579 | 85 | 0.734485 | [
"BSD-3-Clause"
] | serverdensity/sd-agent-windows | BoxedIce.ServerDensity.Agent.WindowsService/AssemblyInfo.cs | 1,566 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace LadderDemo.GumRuntimes.DefaultForms
{
public partial class ScrollBarRuntime
{
partial void CustomInitialize ()
{
}
}
}
| 16.714286 | 45 | 0.675214 | [
"MIT"
] | coldacid/FlatRedBall | Samples/Platformer/LadderDemo/LadderDemo/GumRuntimes/DefaultForms/ScrollBarRuntime.cs | 234 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using VkNet.Abstractions;
using VkNet.Enums;
using VkNet.Enums.Filters;
using VkNet.Model;
using VkNet.Model.Attachments;
using VkNet.Model.RequestParams;
using VkNet.Utils;
namespace VkNet.Categories
{
/// <inheritdoc />
public partial class AudioCategory : IAudioCategory
{
private readonly IVkApiInvoke _vk;
/// <summary>
/// api vk.com
/// </summary>
/// <param name="vk"> Api vk.com </param>
public AudioCategory(IVkApiInvoke vk)
{
_vk = vk;
}
/// <inheritdoc />
public long Add(long audioId, long ownerId, string accessKey = null, long? groupId = null, long? albumId = null)
{
var parameters = new VkParameters
{
{ "audio_id", audioId },
{ "owner_id", ownerId },
{ "access_key", accessKey },
{ "group_id", groupId },
{ "album_id", albumId }
};
return _vk.Call<long>("audio.add", parameters);
}
/// <inheritdoc />
public AudioPlaylist CreatePlaylist(long ownerId, string title, string description = null, IEnumerable<string> audioIds = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "title", title },
{ "description", description },
{ "audio_ids", audioIds }
};
return _vk.Call<AudioPlaylist>("audio.createPlaylist", parameters);
}
/// <inheritdoc />
public bool Delete(long audioId, long ownerId)
{
var parameters = new VkParameters
{
{ "audio_id", audioId },
{ "owner_id", ownerId }
};
return _vk.Call<bool>("audio.delete", parameters);
}
/// <inheritdoc />
public bool DeletePlaylist(long ownerId, long playlistId)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "playlist_id", playlistId }
};
return _vk.Call<bool>("audio.deletePlaylist", parameters);
}
/// <inheritdoc />
public long Edit(AudioEditParams @params)
{
return _vk.Call<long>("audio.edit", new VkParameters
{
{ "owner_id", @params.OwnerId }
, { "audio_id", @params.AudioId }
, { "artist", @params.Artist }
, { "title", @params.Title }
, { "text", @params.Text }
, { "genre_id", @params.GenreId }
, { "no_search", @params.NoSearch }
});
}
/// <inheritdoc />
public bool EditPlaylist(long ownerId, int playlistId, string title, string description = null, IEnumerable<string> audioIds = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "playlist_id", playlistId },
{ "title", title },
{ "description", description },
{ "audio_ids", audioIds }
};
return _vk.Call<bool>("audio.editPlaylist", parameters);
}
/// <inheritdoc />
public VkCollection<Audio> Get(AudioGetParams @params)
{
return _vk.Call<VkCollection<Audio>>("audio.get", new VkParameters
{
{ "owner_id", @params.OwnerId },
{ "album_id", @params.AlbumId },
{ "playlist_id", @params.PlaylistId },
{ "audio_ids", @params.AudioIds },
{ "offset", @params.Offset },
{ "count", @params.Count },
{ "access_key", @params.AccessKey }
});
}
/// <inheritdoc />
public VkCollection<AudioPlaylist> GetPlaylists(long ownerId, uint? count = null, uint? offset = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "offset", offset },
{ "count", count }
};
return _vk.Call<VkCollection<AudioPlaylist>>("audio.getPlaylists", parameters);
}
/// <inheritdoc />
public AudioPlaylist GetPlaylistById(long ownerId, long playlistId)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "playlist_id", playlistId }
};
return _vk.Call<AudioPlaylist>("audio.getPlaylistById", parameters);
}
/// <inheritdoc />
public IEnumerable<object> GetBroadcastList(AudioBroadcastFilter filter = null, bool? active = null)
{
var parameters = new VkParameters
{
{ "filter", filter },
{ "active", active }
};
return _vk.Call<ReadOnlyCollection<object>>("audio.getBroadcastList", parameters);
}
/// <inheritdoc />
public IEnumerable<Audio> GetById(IEnumerable<string> audios)
{
var parameters = new VkParameters
{
{ "audios", audios }
};
return _vk.Call<ReadOnlyCollection<Audio>>("audio.getById", parameters);
}
/// <inheritdoc />
public AudioGetCatalogResult GetCatalog(uint? count, bool? extended, UsersFields fields = null)
{
var parameters = new VkParameters
{
{ "extended", extended },
{ "count", count },
{ "fields", fields }
};
return _vk.Call<AudioGetCatalogResult>("audio.getCatalog", parameters);
}
/// <inheritdoc />
public long GetCount(long ownerId)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId }
};
return _vk.Call<long>("audio.getCount", parameters);
}
/// <inheritdoc />
public Lyrics GetLyrics(long lyricsId)
{
var parameters = new VkParameters
{
{ "lyrics_id", lyricsId }
};
return _vk.Call<Lyrics>("audio.getLyrics", parameters);
}
/// <inheritdoc />
public IEnumerable<Audio> GetPopular(bool onlyEng = false, AudioGenre? genre = null, uint? count = null, uint? offset = null)
{
var parameters = new VkParameters
{
{ "only_eng", onlyEng },
{ "genre_id", genre },
{ "offset", offset },
{ "count", count }
};
return _vk.Call<ReadOnlyCollection<Audio>>("audio.getPopular", parameters);
}
/// <inheritdoc />
public VkCollection<Audio> GetRecommendations(string targetAudio = null, long? userId = null, uint? count = null,
uint? offset = null, bool? shuffle = null)
{
var parameters = new VkParameters
{
{ "target_audio", targetAudio },
{ "user_id", userId },
{ "offset", offset },
{ "count", count },
{ "shuffle", shuffle }
};
return _vk.Call<VkCollection<Audio>>("audio.getRecommendations", parameters);
}
/// <inheritdoc />
public Uri GetUploadServer()
{
var response = _vk.Call("audio.getUploadServer", VkParameters.Empty);
return response["upload_url"];
}
/// <inheritdoc />
public IEnumerable<long> AddToPlaylist(long ownerId, long playlistId, IEnumerable<string> audioIds)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "playlist_id", playlistId },
{ "audio_ids", audioIds }
};
return _vk.Call("audio.addToPlaylist", parameters).ToReadOnlyCollectionOf<long>(x => x["audio_id"]);
}
/// <inheritdoc />
public bool Reorder(long audioId, long? ownerId, long? before, long? after)
{
var parameters = new VkParameters
{
{ "audio_id", audioId },
{ "owner_id", ownerId },
{ "before", before },
{ "after", after }
};
return _vk.Call<bool>("audio.reorder", parameters);
}
/// <inheritdoc />
public Audio Restore(long audioId, long? ownerId = null)
{
var parameters = new VkParameters
{
{ "audio_id", audioId },
{ "owner_id", ownerId }
};
return _vk.Call<Audio>("audio.restore", parameters);
}
/// <inheritdoc />
public Audio Save(string response, string artist = null, string title = null)
{
VkErrors.ThrowIfNullOrEmpty(() => response);
var responseJson = JObject.Parse(response);
var server = responseJson["server"].ToString();
var hash = responseJson["hash"].ToString();
var audio = responseJson["audio"].ToString();
var parameters = new VkParameters
{
{ "server", server },
{ "audio", Uri.EscapeDataString(audio) },
{ "hash", hash },
{ "artist", artist },
{ "title", title }
};
return _vk.Call<Audio>("audio.save", parameters);
}
/// <inheritdoc />
public VkCollection<Audio> Search(AudioSearchParams @params)
{
return _vk.Call<VkCollection<Audio>>("audio.search", new VkParameters
{
{ "q", @params.Query }
, { "auto_complete", @params.Autocomplete }
, { "sort", @params.Sort }
, { "lyrics", @params.Lyrics }
, { "performer_only", @params.PerformerOnly }
, { "search_own", @params.SearchOwn }
, { "count", @params.Count }
, { "offset", @params.Offset }
});
}
/// <inheritdoc />
public IEnumerable<long> SetBroadcast(string audio = null, IEnumerable<long> targetIds = null)
{
var parameters = new VkParameters
{
{ "audio", audio },
{ "target_ids", targetIds }
};
return _vk.Call<ReadOnlyCollection<long>>("audio.setBroadcast", parameters);
}
}
} | 25.175595 | 134 | 0.632344 | [
"MIT"
] | Deeplerg/vk | VkNet/Categories/AudioCategory.cs | 8,459 | C# |
using NHM.Common.Device;
using NHM.Common.Enums;
using System;
namespace NHM.MinerPluginToolkitV1.Interfaces
{
public interface IDriverIsMinimumRecommended
{
(DriverVersionCheckType ret, Version minRequired) IsDriverMinimumRecommended(BaseDevice device);
}
}
| 23.416667 | 104 | 0.779359 | [
"MIT"
] | nicehash/NiceHashMinerLegacy | src/NHM.MinerPluginToolkitV1/Interfaces/IDriverIsMinimumRecommended.cs | 283 | C# |
using System;
class Program
{
static void Main()
{
int year1 = int.Parse(Console.ReadLine());
int year2 = int.Parse(Console.ReadLine());
int magicDate = int.Parse(Console.ReadLine());
DateTime startYear = new DateTime(year1, 1, 1);
DateTime endYear = new DateTime(year2, 12, 31);
bool ind = true;
while(startYear <= endYear)
{
int d1 = startYear.Day / 10;
int d2 = startYear.Day % 10;
int m1 = startYear.Month / 10;
int m2 = startYear.Month % 10;
int y1 = startYear.Year / 1000;
int y2 = (startYear.Year / 100) % 10;
int y3 = (startYear.Year / 10) % 10;
int y4 = startYear.Year % 10;
int pr = 0;
int[] digits = new int[] {d1, d2, m1, m2, y1, y2, y3, y4};
for (int i = 0; i < digits.Length -1; i++)
{
for (int j = i + 1; j < digits.Length; j++)
{
pr += digits[i] * digits[j];
}
}
if(pr == magicDate)
{
Console.WriteLine("{0:d2}-{1:d2}-{2}", startYear.Day, startYear.Month, startYear.Year);
ind = false;
}
startYear = startYear.AddDays(1);
}
if (ind)
{
Console.WriteLine("No");
}
}
} | 31.977273 | 103 | 0.450604 | [
"Apache-2.0"
] | genadi60/SoftUni | SoftUni_Exam/C# Basics Exam 12 April 2014 Morning/04.Magicdates/Magicdates.cs | 1,409 | C# |
// SPDX-License-Identifier: BSD-3-Clause
//
// Copyright 2020 Raritan Inc. All rights reserved.
//
// This file was generated by IdlC from NumericSensor.idl.
using System;
using System.Linq;
using LightJson;
using Com.Raritan.Idl;
using Com.Raritan.JsonRpc;
using Com.Raritan.Util;
#pragma warning disable 0108, 0219, 0414, 1591
namespace Com.Raritan.JsonRpc.sensors.NumericSensor_4_0_3 {
public class ThresholdsChangedEvent_ValObjCodec : Com.Raritan.JsonRpc._event.UserEvent_ValObjCodec {
public static new void Register() {
ValueObjectCodec.RegisterCodec(Com.Raritan.Idl.sensors.NumericSensor_4_0_3.ThresholdsChangedEvent.typeInfo, new ThresholdsChangedEvent_ValObjCodec());
}
public override void EncodeValObj(LightJson.JsonObject json, ValueObject vo) {
base.EncodeValObj(json, vo);
var inst = (Com.Raritan.Idl.sensors.NumericSensor_4_0_3.ThresholdsChangedEvent)vo;
json["oldThresholds"] = inst.oldThresholds.Encode();
json["newThresholds"] = inst.newThresholds.Encode();
}
public override ValueObject DecodeValObj(ValueObject vo, LightJson.JsonObject json, Agent agent) {
Com.Raritan.Idl.sensors.NumericSensor_4_0_3.ThresholdsChangedEvent inst;
if (vo == null) {
inst = new Com.Raritan.Idl.sensors.NumericSensor_4_0_3.ThresholdsChangedEvent();
} else {
inst = (Com.Raritan.Idl.sensors.NumericSensor_4_0_3.ThresholdsChangedEvent)vo;
}
base.DecodeValObj(vo, json, agent);
inst.oldThresholds = Com.Raritan.Idl.sensors.NumericSensor_4_0_3.Thresholds.Decode(json["oldThresholds"], agent);
inst.newThresholds = Com.Raritan.Idl.sensors.NumericSensor_4_0_3.Thresholds.Decode(json["newThresholds"], agent);
return inst;
}
}
}
| 38.911111 | 156 | 0.749857 | [
"BSD-3-Clause"
] | gregoa/raritan-pdu-json-rpc-sdk | pdu-dotnet-api/_idlc_gen/dotnet/Com/Raritan/JsonRpc/sensors/NumericSensor_4_0_3/ThresholdsChangedEvent_ValObjCodec.cs | 1,751 | C# |
using System;
using PactNet;
using PactNet.Mocks.MockHttpService;
namespace CustomerApiServiceConsumer.Tests
{
public class ConsumerCustomerApiPact : IDisposable
{
public IPactBuilder PactBuilder { get; private set; }
public IMockProviderService MockProviderService { get; private set; }
public int MockServerPort => 1234;
public string MockProviderServiceBaseUri => $"http://localhost:{MockServerPort}";
public ConsumerCustomerApiPact()
{
PactBuilder = new PactBuilder();
PactBuilder.ServiceConsumer("CustomerApiServiceConsumer").HasPactWith("CustomerApi.Host");
MockProviderService = PactBuilder.MockService(MockServerPort);
}
public void Dispose()
{
PactBuilder.Build();
}
}
} | 29.464286 | 102 | 0.669091 | [
"MIT"
] | GokGokalp/consumer-driven-contracts-testing-sample | CustomerApiServiceConsumer.Tests/ConsumerCustomerApiPact.cs | 827 | C# |
using Microsoft.Practices.Prism.Interactivity.InteractionRequest;
using Microsoft.Practices.Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrismTest
{
public class ConfirmModel:BindableBase, INotification, IConfirmation
{
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name , value); }
}
private string _value;
public string Value
{
get { return _value; }
set { SetProperty(ref _value, value); }
}
public string Title { get; set; } = "";
public object Content { get; set; } = "";
public bool Confirmed { get; set; } = true;
}
}
| 23.314286 | 72 | 0.607843 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | e-hirakawa/Schematron.Insight | src/cs/PrismTest/PrismTest/ConfirmModel.cs | 818 | C# |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Cacao.Services
{
public abstract class BaseService: BackgroundService
{
private readonly IServiceScopeFactory serviceScope;
private readonly ILogger logger;
protected BaseService(IServiceScopeFactory serviceScope, ILoggerFactory logger)
{
this.serviceScope = serviceScope;
this.logger = logger.CreateLogger("Cacao.Services");
}
protected abstract bool DelayAtStartup { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (DelayAtStartup)
{
await Task.Delay(GetDelayUntilNextRun(), stoppingToken);
}
while (!stoppingToken.IsCancellationRequested)
{
logger.LogInformation($"Executing {GetType().Name} ...");
using (var scope = serviceScope.CreateScope())
{
await Execute(scope);
}
logger.LogInformation("Finished!");
await Task.Delay(GetDelayUntilNextRun(), stoppingToken);
}
}
protected abstract TimeSpan GetDelayUntilNextRun();
protected abstract Task Execute(IServiceScope scope);
}
}
| 30.833333 | 87 | 0.637237 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | TeraNovaLP/Cacao | Cacao.Services/BaseService.cs | 1,665 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IQ180大挑戰2
{
public partial class SYSTEMUSERmessge : Form
{
public SYSTEMUSERmessge()
{
InitializeComponent();
}
private void xButton1_Click(object sender, EventArgs e)
{
this.Close();
}
private void xButton2_Click(object sender, EventArgs e)
{
windhide ww = new windhide();
ww.ShowDialog();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
xButton1.Enabled = true;
radioButton2.Enabled = false;
}
}
}
| 21.72973 | 76 | 0.605721 | [
"MIT"
] | Xanonymous-GitHub/IQ180-challenge-2 | SYSTEMUSERmessge.cs | 812 | C# |
namespace StackExchange.Profiling.Data
{
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.SqlServer;
using System.Data.SqlClient;
/// <summary>
/// Specific implementation of <c>EFProfiledDbProviderFactory<SqlClientFactory></c> to enable profiling
/// </summary>
public class EFProfiledSqlClientDbProviderServices
: EFProfiledDbProviderServices<SqlProviderServices>
{
/// <summary>
/// Every provider factory must have an Instance public field
/// </summary>
public static new EFProfiledSqlClientDbProviderServices Instance = new EFProfiledSqlClientDbProviderServices();
/// <summary>
/// Prevents a default instance of the <see cref="EFProfiledSqlClientDbProviderServices"/> class from being created.
/// </summary>
private EFProfiledSqlClientDbProviderServices()
{
}
}
}
| 36.111111 | 124 | 0.694359 | [
"Apache-2.0"
] | geoforce/MiniProfiler | StackExchange.Profiling.EntityFramework6/EFProfiledSqlClientDbProviderServices.cs | 977 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nomoni.Examples.Basic.AdminModule.Models
{
public class ManagmentViewModel
{
public string PageTitle { get; set; }
public string PageContent { get; set; }
}
}
| 17.588235 | 50 | 0.702341 | [
"MIT"
] | treefishuk/Nomoni | examples/Nomoni.Examples.SecondModule/Nomoni.Examples.Basic.AdminModule/Models/ManagmentViewModel.cs | 301 | C# |
using System;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Renci.SshNet.Channels;
using Renci.SshNet.Messages.Connection;
using Renci.SshNet.Tests.Common;
namespace Renci.SshNet.Tests.Classes.Channels
{
[TestClass]
public class ChannelDirectTcpipTest_Close_SessionIsConnectedAndChannelIsOpen
{
private Mock<ISession> _sessionMock;
private Mock<IForwardedPort> _forwardedPortMock;
private Mock<IConnectionInfo> _connectionInfoMock;
private ChannelDirectTcpip _channel;
private uint _localChannelNumber;
private uint _localWindowSize;
private uint _localPacketSize;
private uint _remoteWindowSize;
private uint _remotePacketSize;
private uint _remoteChannelNumber;
private string _remoteHost;
private uint _port;
private AsyncSocketListener _listener;
private EventWaitHandle _channelBindFinishedWaitHandle;
private EventWaitHandle _clientReceivedFinishedWaitHandle;
private Socket _client;
private Exception _channelException;
[TestInitialize]
public void Initialize()
{
Arrange();
Act();
}
[TestCleanup]
public void CleanUp()
{
if (_client != null)
{
_client.Dispose();
_client = null;
}
if (_listener != null)
{
_listener.Stop();
_listener = null;
}
}
private void Arrange()
{
var random = new Random();
_localChannelNumber = (uint) random.Next(0, int.MaxValue);
_localWindowSize = (uint) random.Next(2000, 3000);
_localPacketSize = (uint) random.Next(1000, 2000);
_remoteHost = random.Next().ToString(CultureInfo.InvariantCulture);
_port = (uint) random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort);
_channelBindFinishedWaitHandle = new ManualResetEvent(false);
_clientReceivedFinishedWaitHandle = new ManualResetEvent(false);
_channelException = null;
_remoteChannelNumber = (uint)random.Next(0, int.MaxValue);
_remoteWindowSize = (uint)random.Next(0, int.MaxValue);
_remotePacketSize = (uint)random.Next(100, 200);
_sessionMock = new Mock<ISession>(MockBehavior.Strict);
_forwardedPortMock = new Mock<IForwardedPort>(MockBehavior.Strict);
_connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict);
var sequence = new MockSequence();
_sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
_sessionMock.InSequence(sequence)
.Setup(p => p.SendMessage(It.Is<ChannelOpenMessage>(m => AssertExpectedMessage(m))));
_sessionMock.InSequence(sequence)
.Setup(p => p.WaitOnHandle(It.IsNotNull<WaitHandle>()))
.Callback<WaitHandle>(
w =>
{
_sessionMock.Raise(
s => s.ChannelOpenConfirmationReceived += null,
new MessageEventArgs<ChannelOpenConfirmationMessage>(
new ChannelOpenConfirmationMessage(
_localChannelNumber,
_remoteWindowSize,
_remotePacketSize,
_remoteChannelNumber)));
w.WaitOne();
});
_sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
_sessionMock.InSequence(sequence)
.Setup(
p => p.TrySendMessage(It.Is<ChannelEofMessage>(m => m.LocalChannelNumber == _remoteChannelNumber)))
.Returns(true);
_sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
_sessionMock.InSequence(sequence)
.Setup(
p => p.TrySendMessage(It.Is<ChannelCloseMessage>(m => m.LocalChannelNumber == _remoteChannelNumber)))
.Returns(true);
_sessionMock.InSequence(sequence)
.Setup(p => p.WaitOnHandle(It.IsNotNull<WaitHandle>()))
.Callback<WaitHandle>(
w =>
{
_sessionMock.Raise(
s => s.ChannelCloseReceived += null,
new MessageEventArgs<ChannelCloseMessage>(new ChannelCloseMessage(_localChannelNumber)));
w.WaitOne();
});
var localEndpoint = new IPEndPoint(IPAddress.Loopback, 8122);
_listener = new AsyncSocketListener(localEndpoint);
_listener.Connected += socket =>
{
try
{
_channel = new ChannelDirectTcpip(
_sessionMock.Object,
_localChannelNumber,
_localWindowSize,
_localPacketSize);
_channel.Open(_remoteHost, _port, _forwardedPortMock.Object, socket);
_channel.Bind();
}
catch (Exception ex)
{
_channelException = ex;
}
finally
{
_channelBindFinishedWaitHandle.Set();
}
};
_listener.Start();
_client = new Socket(localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_client.Connect(localEndpoint);
var clientReceiveThread = new Thread(
() =>
{
var buffer = new byte[16];
var bytesReceived = _client.Receive(buffer, 0, buffer.Length, SocketFlags.None);
if (bytesReceived == 0)
{
_client.Shutdown(SocketShutdown.Send);
_clientReceivedFinishedWaitHandle.Set();
}
}
);
clientReceiveThread.Start();
// give channel time to bind to socket
Thread.Sleep(200);
}
private void Act()
{
if (_channel != null)
{
_channel.Close();
}
}
[TestMethod]
public void BindShouldHaveFinishedWithoutException()
{
Assert.IsTrue(_channelBindFinishedWaitHandle.WaitOne(0));
Assert.IsNull(_channelException, _channelException != null ? _channelException.ToString() : null);
}
[TestMethod]
public void ClientShouldHaveFinished()
{
Assert.IsTrue(_clientReceivedFinishedWaitHandle.WaitOne(0));
}
[TestMethod]
public void ChannelEofMessageShouldBeSentOnce()
{
_sessionMock.Verify(p => p.TrySendMessage(It.Is<ChannelEofMessage>(m => m.LocalChannelNumber == _remoteChannelNumber)), Times.Once);
}
[TestMethod]
public void ChannelCloseMessageShouldBeSentOnce()
{
_sessionMock.Verify(p => p.TrySendMessage(It.Is<ChannelCloseMessage>(m => m.LocalChannelNumber == _remoteChannelNumber)), Times.Once);
}
[TestMethod]
public void IsOpenShouldReturnFalse()
{
Assert.IsFalse(_channel.IsOpen);
}
private bool AssertExpectedMessage(ChannelOpenMessage channelOpenMessage)
{
if (channelOpenMessage == null)
return false;
if (channelOpenMessage.LocalChannelNumber != _localChannelNumber)
return false;
if (channelOpenMessage.InitialWindowSize != _localWindowSize)
return false;
if (channelOpenMessage.MaximumPacketSize != _localPacketSize)
return false;
var directTcpipChannelInfo = channelOpenMessage.Info as DirectTcpipChannelInfo;
if (directTcpipChannelInfo == null)
return false;
if (directTcpipChannelInfo.HostToConnect != _remoteHost)
return false;
if (directTcpipChannelInfo.PortToConnect != _port)
return false;
var clientEndpoint = _client.LocalEndPoint as IPEndPoint;
if (clientEndpoint == null)
return false;
if (directTcpipChannelInfo.OriginatorAddress != clientEndpoint.Address.ToString())
return false;
if (directTcpipChannelInfo.OriginatorPort != clientEndpoint.Port)
return false;
return true;
}
}
}
| 38.987179 | 146 | 0.551354 | [
"MIT"
] | Foreveryone-cz/SSH.NET-for-winsshfs | src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest_Close_SessionIsConnectedAndChannelIsOpen.cs | 9,125 | C# |
// Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
using System.Collections.Generic;
public class FBDemoEditorTarget : TargetRules
{
public FBDemoEditorTarget(TargetInfo Target) : base(Target)
{
Type = TargetType.Editor;
ExtraModuleNames.AddRange( new string[] { "FBDemo" } );
}
}
| 22.8 | 78 | 0.763158 | [
"MIT"
] | PushkinStudio/PsFacebookMobile-Demo | Source/FBDemoEditor.Target.cs | 342 | C# |
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace MultipleDbContextEfCoreDemo.Migrations
{
public partial class Initial_Migration_For_FirstDbContext : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Persons",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
PersonName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Persons", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Persons");
}
}
}
| 32.787879 | 122 | 0.586876 | [
"MIT"
] | OzBob/aspnetboilerplate-samples | MultipleDbContextEfCoreDemo/src/MultipleDbContextEfCoreDemo.EntityFrameworkCore/Migrations/20180321113024_Initial_Migration_For_FirstDbContext.cs | 1,084 | C# |
using System.Collections.Generic;
using CoreLocation;
using HomeKit;
namespace HomeKitCatalog
{
// An `EventTriggerCreator` subclass which allows for the creation of location triggers.
public class LocationTriggerCreator : EventTriggerCreator, IMapViewControllerDelegate
{
HMLocationEvent LocationEvent { get; set; }
public CLCircularRegion TargetRegion { get; set; }
public int TargetRegionStateIndex { get; set; }
public LocationTriggerCreator (HMTrigger trigger, HMHome home)
: base (trigger, home)
{
var eventTrigger = EventTrigger;
if (eventTrigger != null) {
LocationEvent = eventTrigger.LocationEvent ();
if (LocationEvent != null) {
TargetRegion = LocationEvent.Region as CLCircularRegion;
TargetRegionStateIndex = TargetRegion.NotifyOnEntry ? 0 : 1;
}
}
}
protected override void UpdateTrigger ()
{
var region = TargetRegion;
if (region != null) {
PrepareRegion ();
var locationEvent = LocationEvent;
if (locationEvent != null) {
SaveTriggerGroup.Enter ();
locationEvent.UpdateRegion (region, error => {
if (error != null)
Errors.Add (error);
SaveTriggerGroup.Leave ();
});
}
}
SavePredicate ();
}
protected override HMTrigger NewTrigger ()
{
var events = new List<HMLocationEvent> ();
var region = TargetRegion;
if (region != null) {
PrepareRegion ();
events.Add (new HMLocationEvent (region));
}
return new HMEventTrigger (Name, events.ToArray (), NewPredicate ());
}
#region Helper Methods
void PrepareRegion ()
{
var region = TargetRegion;
if (region != null) {
region.NotifyOnEntry = (TargetRegionStateIndex == 0);
region.NotifyOnExit = !region.NotifyOnEntry;
}
}
#endregion
#region IMapViewControllerDelegate implementation
public void MapViewDidUpdateRegion (CLCircularRegion region)
{
TargetRegion = region;
}
#endregion
}
} | 23.695122 | 89 | 0.688111 | [
"MIT"
] | Art-Lav/ios-samples | ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerCreator.cs | 1,945 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Microsoft.MixedReality.Toolkit.Tests.EditMode.Services
{
internal class TestFailService : BaseService, ITestFailService
{
public override string Name => "Fail Service";
}
} | 33.454545 | 92 | 0.728261 | [
"MIT"
] | LocalJoost/BouncyMesh | Assets/MRTK/Tests/EditModeTests/Services/TestFailService.cs | 370 | C# |
using System.IO;
using System.Net.Http;
namespace Rx.Http.MediaTypes.Abstractions
{
public interface IHttpMediaTypeSerializer
{
HttpContent Serialize(object obj);
}
}
| 17.181818 | 45 | 0.719577 | [
"MIT"
] | lucassklp/Rx.Http | Rx.Http/MediaTypes/Abstractions/IHttpMediaTypeSerializer.cs | 191 | C# |
using System;
using System.Diagnostics;
using DotsGame.AI;
using NUnit.Framework;
namespace DotsGame.Tests
{
[TestFixture]
public class AlphaBetaHashAlgoritmTest
{
[Test]
public void AlphaBetaHash_Performance()
{
int startX = 16;
int startY = 16;
var field = new Field(39, 32);
field.MakeMove(startX, startY);
field.MakeMove(startX + 1, startY);
field.MakeMove(startX + 1, startY + 1);
field.MakeMove(startX, startY + 1);
field.MakeMove(startX + 1, startY - 1);
field.MakeMove(startX, startY - 1);
int expectedDestMove = Field.GetPosition(startX + 2, startY);
var stopwatch = new Stopwatch();
byte depth = 6;
var alphaBetaAlgoritm = new AlphaBetaAlgoritm(field);
stopwatch.Start();
int alphaBetaBestMove = alphaBetaAlgoritm.SearchBestMove(depth, DotState.Player0, -AiSettings.InfinityScore, AiSettings.InfinityScore);
stopwatch.Stop();
TimeSpan alphaBetaElapsed = stopwatch.Elapsed;
stopwatch.Reset();
var alphaBetaHashAlgoritm = new AlphaBetaHashAlgoritm(field);
stopwatch.Start();
int alphaBetaHashBestMove = alphaBetaHashAlgoritm.SearchBestMove(depth, DotState.Player0, -AiSettings.InfinityScore, AiSettings.InfinityScore);
stopwatch.Stop();
TimeSpan alphaBetaHashElapsed = stopwatch.Elapsed;
Assert.AreEqual(alphaBetaBestMove, alphaBetaHashBestMove);
//if (depth > 2)
// Assert.IsTrue(alphaBetaHashElapsed < alphaBetaElapsed);
#if DEBUG
Console.WriteLine("Configuration: Debug");
#else
Console.WriteLine("Configuration: Release");
#endif
Console.WriteLine("Depth: {0}", depth);
Console.WriteLine("Usual AlphaBeta time elapsed: {0}", alphaBetaElapsed);
Console.WriteLine("Hash AlphaBeta time elapsed: {0}", alphaBetaHashElapsed);
Console.WriteLine("Ratio: {0}", alphaBetaHashElapsed.Ticks / (double)alphaBetaElapsed.Ticks);
}
}
} | 36.25 | 155 | 0.626207 | [
"Apache-2.0"
] | KvanTTT/Dots-Game-AI | DotsGame.Tests/AlphaBetaHashAlgoritmTest.cs | 2,177 | C# |
using Statiq.Common;
using System.Collections.Generic;
using System.Linq;
namespace Docs
{
public static class DocumentExtensions
{
public static string GetDescription(this IDocument document)
{
return document?.GetString(Constants.Description, string.Empty) ?? string.Empty;
}
public static bool IsVisible(this IDocument document)
{
return document.GetBool(Constants.ShowInSidebar, true);
}
public static bool ShowLink(this IDocument document)
{
return !document.GetBool(Constants.NoLink, false);
}
public static IEnumerable<IDocument> OnlyVisible(this IEnumerable<IDocument> source)
{
return source.Where(x => x.IsVisible());
}
public static IEnumerable<IDocument> OnlyRequirements(this IEnumerable<IDocument> source)
{
return source.Where(x => x.GetString("RuleType", string.Empty) == "Requirement");
}
public static IEnumerable<IDocument> OnlyGuidelines(this IEnumerable<IDocument> source)
{
return source.Where(x => x.GetString("RuleType", string.Empty) == "Guideline");
}
public static IEnumerable<IDocument> OnlySuggestions(this IEnumerable<IDocument> source)
{
return source.Where(x => x.GetString("RuleType", string.Empty) == "Suggestion");
}
public static IEnumerable<IDocument> OnlyNotes(this IEnumerable<IDocument> source)
{
return source.Where(x => x.GetString("RuleType", string.Empty) == "Note");
}
}
} | 33.163265 | 97 | 0.634462 | [
"Apache-2.0"
] | ChronoBank/docs | src/Extensions/DocumentExtensions.cs | 1,625 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public class PlatformHandler_HttpClientHandler : HttpClientHandlerTestBase
{
public PlatformHandler_HttpClientHandler(ITestOutputHelper output) : base(output) { }
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetAsync_TrailingHeaders_Ignored(bool includeTrailerHeader)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClient client = CreateHttpClient(new WinHttpHandler()))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
server.AcceptConnectionSendCustomResponseAndCloseAsync(
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
"Transfer-Encoding: chunked\r\n" +
(includeTrailerHeader ? "Trailer: MyCoolTrailerHeader\r\n" : "") +
"\r\n" +
"4\r\n" +
"data\r\n" +
"0\r\n" +
"MyCoolTrailerHeader: amazingtrailer\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
if (includeTrailerHeader)
{
Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer"));
}
Assert.False(response.Headers.Contains("MyCoolTrailerHeader"), "Trailer should have been ignored");
string data = await response.Content.ReadAsStringAsync();
Assert.Contains("data", data);
Assert.DoesNotContain("MyCoolTrailerHeader", data);
Assert.DoesNotContain("amazingtrailer", data);
}
}
});
}
}
public sealed class PlatformHandler_HttpClientHandler_Asynchrony_Test : HttpClientHandler_Asynchrony_Test
{
public PlatformHandler_HttpClientHandler_Asynchrony_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpProtocolTests : HttpProtocolTests
{
public PlatformHandler_HttpProtocolTests(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpProtocolTests_Dribble : HttpProtocolTests_Dribble
{
public PlatformHandler_HttpProtocolTests_Dribble(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClient_SelectedSites_Test : HttpClient_SelectedSites_Test
{
public PlatformHandler_HttpClient_SelectedSites_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientEKUTest : HttpClientEKUTest
{
public PlatformHandler_HttpClientEKUTest(ITestOutputHelper output) : base(output) { }
}
#if NETCOREAPP
public sealed class PlatformHandler_HttpClientHandler_Decompression_Tests : HttpClientHandler_Decompression_Test
{
public PlatformHandler_HttpClientHandler_Decompression_Tests(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test
{
public PlatformHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test(ITestOutputHelper output) : base(output) { }
}
#endif
public sealed class PlatformHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test
{
public PlatformHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test
{
public PlatformHandler_HttpClientHandler_DefaultProxyCredentials_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test
{
public PlatformHandler_HttpClientHandler_MaxConnectionsPerServer_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test
{
public PlatformHandler_HttpClientHandler_ServerCertificates_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_PostScenarioTest : PostScenarioTest
{
public PlatformHandler_PostScenarioTest(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_ResponseStreamTest : ResponseStreamTest
{
public PlatformHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test
{
public PlatformHandler_HttpClientHandler_SslProtocols_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_Proxy_Test : HttpClientHandler_Proxy_Test
{
public PlatformHandler_HttpClientHandler_Proxy_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest
{
public PlatformHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandlerTest : HttpClientHandlerTest
{
public PlatformHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandlerTest_AutoRedirect : HttpClientHandlerTest_AutoRedirect
{
public PlatformHandlerTest_AutoRedirect(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_DefaultCredentialsTest : DefaultCredentialsTest
{
public PlatformHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_IdnaProtocolTests : IdnaProtocolTests
{
public PlatformHandler_IdnaProtocolTests(ITestOutputHelper output) : base(output) { }
// WinHttp on Win7 does not support IDNA
protected override bool SupportsIdna => !PlatformDetection.IsWindows7;
}
public sealed class PlatformHandler_HttpRetryProtocolTests : HttpRetryProtocolTests
{
public PlatformHandler_HttpRetryProtocolTests(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandlerTest_Cookies : HttpClientHandlerTest_Cookies
{
public PlatformHandlerTest_Cookies(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandlerTest_Cookies_Http11 : HttpClientHandlerTest_Cookies_Http11
{
public PlatformHandlerTest_Cookies_Http11(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test
{
public PlatformHandler_HttpClientHandler_MaxResponseHeadersLength_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_Cancellation_Test : HttpClientHandler_Cancellation_Test
{
public PlatformHandler_HttpClientHandler_Cancellation_Test(ITestOutputHelper output) : base(output) { }
}
public sealed class PlatformHandler_HttpClientHandler_Authentication_Test : HttpClientHandler_Authentication_Test
{
public PlatformHandler_HttpClientHandler_Authentication_Test(ITestOutputHelper output) : base(output) { }
}
// Enable this to run HTTP2 tests on platform handler
#if PLATFORM_HANDLER_HTTP2_TESTS
public sealed class PlatformHandlerTest_Http2 : HttpClientHandlerTest_Http2
{
}
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.SupportsAlpn))]
public sealed class PlatformHandlerTest_Cookies_Http2 : HttpClientHandlerTest_Cookies
{
protected override bool UseHttp2LoopbackServer => true;
}
#endif
}
| 43.555556 | 167 | 0.717059 | [
"MIT"
] | CoffeeFlux/runtime | src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/PlatformHandlerTest.cs | 9,016 | C# |
#if THUNDERKIT_CONFIGURED
using global::RoR2;
namespace PassivePicasso.ThunderKit.Proxy.RoR2
{
public partial class NetworkRuleBook : global::RoR2.NetworkRuleBook {}
}
#endif | 25.428571 | 74 | 0.803371 | [
"MIT"
] | Jarlyk/Rain-of-Stages | Assets/RainOfStages/RoR2/GeneratedProxies/RoR2/NetworkRuleBook.cs | 178 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Iot.Device.Media
{
/// <summary>
/// Represents a communications channel to a video device running on Unix.
/// </summary>
internal class UnixVideoDevice : VideoDevice
{
private const string DefaultDevicePath = "/dev/video";
private const int BufferCount = 4;
private static readonly object s_initializationLock = new object();
private int _deviceFileDescriptor = -1;
/// <summary>
/// Path to video resources located on the platform.
/// </summary>
public override string DevicePath { get; set; }
/// <summary>
/// The connection settings of the video device.
/// </summary>
public override VideoConnectionSettings Settings { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UnixVideoDevice"/> class that will use the specified settings to communicate with the video device.
/// </summary>
/// <param name="settings">The connection settings of a video device.</param>
public UnixVideoDevice(VideoConnectionSettings settings)
{
Settings = settings;
DevicePath = DefaultDevicePath;
}
private static unsafe void UnmappingFrameBuffers(V4l2FrameBuffer* buffers)
{
// Unmapping the applied buffer to user space
for (uint i = 0; i < BufferCount; i++)
{
Interop.munmap(buffers[i].Start, (int)buffers[i].Length);
}
}
/// <summary>
/// Capture a picture from the video device.
/// </summary>
/// <param name="path">Picture save path.</param>
public override void Capture(string path)
{
Initialize();
SetVideoConnectionSettings();
byte[] dataBuffer = ProcessCaptureData();
Close();
using FileStream fs = new FileStream(path, FileMode.Create);
fs.Write(dataBuffer, 0, dataBuffer.Length);
fs.Flush();
}
/// <summary>
/// Capture a picture from the video device.
/// </summary>
/// <returns>Picture stream.</returns>
public override Stream Capture()
{
Initialize();
SetVideoConnectionSettings();
byte[] dataBuffer = ProcessCaptureData();
Close();
return new MemoryStream(dataBuffer);
}
public override void StartCaptureContinuous()
{
Initialize();
SetVideoConnectionSettings();
}
public override Stream CaptureContinuous()
{
byte[] dataBuffer = ProcessCaptureData();
return new MemoryStream(dataBuffer);
}
public override void StopCaptureContinuous()
{
Close();
}
/// <summary>
/// Query controls value from the video device.
/// </summary>
/// <param name="type">The type of a video device's control.</param>
/// <returns>The default and current values of a video device's control.</returns>
public override VideoDeviceValue GetVideoDeviceValue(VideoDeviceValueType type)
{
Initialize();
// Get default value
v4l2_queryctrl query = new v4l2_queryctrl
{
id = type
};
V4l2Struct(V4l2Request.VIDIOC_QUERYCTRL, ref query);
// Get current value
v4l2_control ctrl = new v4l2_control
{
id = type,
};
V4l2Struct(V4l2Request.VIDIOC_G_CTRL, ref ctrl);
return new VideoDeviceValue(
type.ToString(),
query.minimum,
query.maximum,
query.step,
query.default_value,
ctrl.value);
}
/// <summary>
/// Get all the pixel formats supported by the device.
/// </summary>
/// <returns>Supported pixel formats.</returns>
public override IEnumerable<PixelFormat> GetSupportedPixelFormats()
{
Initialize();
v4l2_fmtdesc fmtdesc = new v4l2_fmtdesc
{
index = 0,
type = v4l2_buf_type.V4L2_BUF_TYPE_VIDEO_CAPTURE
};
List<PixelFormat> result = new List<PixelFormat>();
while (V4l2Struct(V4l2Request.VIDIOC_ENUM_FMT, ref fmtdesc) != -1)
{
result.Add(fmtdesc.pixelformat);
fmtdesc.index++;
}
return result;
}
/// <summary>
/// Get all the resolutions supported by the specified pixel format.
/// </summary>
/// <param name="format">Pixel format.</param>
/// <returns>Supported resolution.</returns>
public override IEnumerable<Resolution> GetPixelFormatResolutions(PixelFormat format)
{
Initialize();
v4l2_frmsizeenum size = new v4l2_frmsizeenum()
{
index = 0,
pixel_format = format
};
List<Resolution> result = new List<Resolution>();
while (V4l2Struct(V4l2Request.VIDIOC_ENUM_FRAMESIZES, ref size) != -1)
{
Resolution resolution;
switch (size.type)
{
case v4l2_frmsizetypes.V4L2_FRMSIZE_TYPE_DISCRETE:
resolution = new Resolution
{
Type = ResolutionType.Discrete,
MinHeight = size.discrete.height,
MaxHeight = size.discrete.height,
StepHeight = 0,
MinWidth = size.discrete.width,
MaxWidth = size.discrete.width,
StepWidth = 0,
};
break;
case v4l2_frmsizetypes.V4L2_FRMSIZE_TYPE_CONTINUOUS:
resolution = new Resolution
{
Type = ResolutionType.Continuous,
MinHeight = size.stepwise.min_height,
MaxHeight = size.stepwise.max_height,
StepHeight = 1,
MinWidth = size.stepwise.min_width,
MaxWidth = size.stepwise.max_width,
StepWidth = 1,
};
break;
case v4l2_frmsizetypes.V4L2_FRMSIZE_TYPE_STEPWISE:
resolution = new Resolution
{
Type = ResolutionType.Stepwise,
MinHeight = size.stepwise.min_height,
MaxHeight = size.stepwise.max_height,
StepHeight = size.stepwise.step_height,
MinWidth = size.stepwise.min_width,
MaxWidth = size.stepwise.max_width,
StepWidth = size.stepwise.step_width,
};
break;
default:
resolution = new Resolution
{
Type = ResolutionType.Discrete,
MinHeight = 0,
MaxHeight = 0,
StepHeight = 0,
MinWidth = 0,
MaxWidth = 0,
StepWidth = 0,
};
break;
}
result.Add(resolution);
size.index++;
}
return result;
}
private unsafe byte[] ProcessCaptureData()
{
fixed (V4l2FrameBuffer* buffers = &ApplyFrameBuffers()[0])
{
// Start data stream
v4l2_buf_type type = v4l2_buf_type.V4L2_BUF_TYPE_VIDEO_CAPTURE;
Interop.ioctl(_deviceFileDescriptor, V4l2Request.VIDIOC_STREAMON, new IntPtr(&type));
byte[] dataBuffer = GetFrameData(buffers);
// Close data stream
Interop.ioctl(_deviceFileDescriptor, V4l2Request.VIDIOC_STREAMOFF, new IntPtr(&type));
UnmappingFrameBuffers(buffers);
return dataBuffer;
}
}
private unsafe byte[] GetFrameData(V4l2FrameBuffer* buffers)
{
// Get one frame from the buffer
v4l2_buffer frame = new v4l2_buffer
{
type = v4l2_buf_type.V4L2_BUF_TYPE_VIDEO_CAPTURE,
memory = v4l2_memory.V4L2_MEMORY_MMAP,
};
V4l2Struct(V4l2Request.VIDIOC_DQBUF, ref frame);
// Get data from pointer
IntPtr intptr = buffers[frame.index].Start;
byte[] dataBuffer = new byte[buffers[frame.index].Length];
Marshal.Copy(source: intptr, destination: dataBuffer, startIndex: 0, length: (int)buffers[frame.index].Length);
// Requeue the buffer
V4l2Struct(V4l2Request.VIDIOC_QBUF, ref frame);
return dataBuffer;
}
private unsafe V4l2FrameBuffer[] ApplyFrameBuffers()
{
// Apply for buffers, use memory mapping
v4l2_requestbuffers req = new v4l2_requestbuffers
{
count = BufferCount,
type = v4l2_buf_type.V4L2_BUF_TYPE_VIDEO_CAPTURE,
memory = v4l2_memory.V4L2_MEMORY_MMAP
};
V4l2Struct(V4l2Request.VIDIOC_REQBUFS, ref req);
// Mapping the applied buffer to user space
V4l2FrameBuffer[] buffers = new V4l2FrameBuffer[BufferCount];
for (uint i = 0; i < BufferCount; i++)
{
v4l2_buffer buffer = new v4l2_buffer
{
index = i,
type = v4l2_buf_type.V4L2_BUF_TYPE_VIDEO_CAPTURE,
memory = v4l2_memory.V4L2_MEMORY_MMAP
};
V4l2Struct(V4l2Request.VIDIOC_QUERYBUF, ref buffer);
buffers[i].Length = buffer.length;
buffers[i].Start = Interop.mmap(IntPtr.Zero, (int)buffer.length, MemoryMappedProtections.PROT_READ | MemoryMappedProtections.PROT_WRITE, MemoryMappedFlags.MAP_SHARED, _deviceFileDescriptor, (int)buffer.m.offset);
}
// Put the buffer in the processing queue
for (uint i = 0; i < BufferCount; i++)
{
v4l2_buffer buffer = new v4l2_buffer
{
index = i,
type = v4l2_buf_type.V4L2_BUF_TYPE_VIDEO_CAPTURE,
memory = v4l2_memory.V4L2_MEMORY_MMAP
};
V4l2Struct(V4l2Request.VIDIOC_QBUF, ref buffer);
}
return buffers;
}
private unsafe void SetVideoConnectionSettings()
{
FillVideoConnectionSettings();
// Set capture format
v4l2_format format = new v4l2_format
{
type = v4l2_buf_type.V4L2_BUF_TYPE_VIDEO_CAPTURE,
fmt = new fmt
{
pix = new v4l2_pix_format
{
width = Settings.CaptureSize.Width,
height = Settings.CaptureSize.Height,
pixelformat = Settings.PixelFormat
}
}
};
V4l2Struct(V4l2Request.VIDIOC_S_FMT, ref format);
// Set exposure type
v4l2_control ctrl = new v4l2_control
{
id = VideoDeviceValueType.ExposureType,
value = (int)Settings.ExposureType
};
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set exposure time
// If exposure type is auto, this field is invalid
ctrl.id = VideoDeviceValueType.ExposureTime;
ctrl.value = Settings.ExposureTime;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set brightness
ctrl.id = VideoDeviceValueType.Brightness;
ctrl.value = Settings.Brightness;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set contrast
ctrl.id = VideoDeviceValueType.Contrast;
ctrl.value = Settings.Contrast;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set saturation
ctrl.id = VideoDeviceValueType.Saturation;
ctrl.value = Settings.Saturation;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set sharpness
ctrl.id = VideoDeviceValueType.Sharpness;
ctrl.value = Settings.Sharpness;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set gain
ctrl.id = VideoDeviceValueType.Gain;
ctrl.value = Settings.Gain;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set gamma
ctrl.id = VideoDeviceValueType.Gamma;
ctrl.value = Settings.Gamma;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set power line frequency
ctrl.id = VideoDeviceValueType.PowerLineFrequency;
ctrl.value = (int)Settings.PowerLineFrequency;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set white balance effect
ctrl.id = VideoDeviceValueType.WhiteBalanceEffect;
ctrl.value = (int)Settings.WhiteBalanceEffect;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set white balance temperature
ctrl.id = VideoDeviceValueType.WhiteBalanceTemperature;
ctrl.value = Settings.WhiteBalanceTemperature;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set color effect
ctrl.id = VideoDeviceValueType.ColorEffect;
ctrl.value = (int)Settings.ColorEffect;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set scene mode
ctrl.id = VideoDeviceValueType.SceneMode;
ctrl.value = (int)Settings.SceneMode;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set rotate
ctrl.id = VideoDeviceValueType.Rotate;
ctrl.value = Settings.Rotate;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set horizontal flip
ctrl.id = VideoDeviceValueType.HorizontalFlip;
ctrl.value = Settings.HorizontalFlip ? 1 : 0;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
// Set vertical flip
ctrl.id = VideoDeviceValueType.VerticalFlip;
ctrl.value = Settings.VerticalFlip ? 1 : 0;
V4l2Struct(V4l2Request.VIDIOC_S_CTRL, ref ctrl);
}
private void FillVideoConnectionSettings()
{
if (Settings.ExposureType.Equals(default))
{
Settings.ExposureType = (ExposureType)GetVideoDeviceValue(VideoDeviceValueType.ExposureType).DefaultValue;
}
if (Settings.ExposureTime.Equals(default))
{
Settings.ExposureTime = GetVideoDeviceValue(VideoDeviceValueType.ExposureTime).DefaultValue;
}
if (Settings.Brightness.Equals(default))
{
Settings.Brightness = GetVideoDeviceValue(VideoDeviceValueType.Brightness).DefaultValue;
}
if (Settings.Saturation.Equals(default))
{
Settings.Saturation = GetVideoDeviceValue(VideoDeviceValueType.Saturation).DefaultValue;
}
if (Settings.Sharpness.Equals(default))
{
Settings.Sharpness = GetVideoDeviceValue(VideoDeviceValueType.Sharpness).DefaultValue;
}
if (Settings.Contrast.Equals(default))
{
Settings.Contrast = GetVideoDeviceValue(VideoDeviceValueType.Contrast).DefaultValue;
}
if (Settings.Gain.Equals(default))
{
Settings.Gain = GetVideoDeviceValue(VideoDeviceValueType.Gain).DefaultValue;
}
if (Settings.Gamma.Equals(default))
{
Settings.Gamma = GetVideoDeviceValue(VideoDeviceValueType.Gamma).DefaultValue;
}
if (Settings.Rotate.Equals(default))
{
Settings.Rotate = GetVideoDeviceValue(VideoDeviceValueType.Rotate).DefaultValue;
}
if (Settings.WhiteBalanceTemperature.Equals(default))
{
Settings.WhiteBalanceTemperature = GetVideoDeviceValue(VideoDeviceValueType.WhiteBalanceTemperature).DefaultValue;
}
if (Settings.ColorEffect.Equals(default))
{
Settings.ColorEffect = (ColorEffect)GetVideoDeviceValue(VideoDeviceValueType.ColorEffect).DefaultValue;
}
if (Settings.PowerLineFrequency.Equals(default))
{
Settings.PowerLineFrequency = (PowerLineFrequency)GetVideoDeviceValue(VideoDeviceValueType.PowerLineFrequency).DefaultValue;
}
if (Settings.SceneMode.Equals(default))
{
Settings.SceneMode = (SceneMode)GetVideoDeviceValue(VideoDeviceValueType.SceneMode).DefaultValue;
}
if (Settings.WhiteBalanceEffect.Equals(default))
{
Settings.WhiteBalanceEffect = (WhiteBalanceEffect)GetVideoDeviceValue(VideoDeviceValueType.WhiteBalanceEffect).DefaultValue;
}
if (Settings.HorizontalFlip.Equals(default))
{
Settings.HorizontalFlip = Convert.ToBoolean(GetVideoDeviceValue(VideoDeviceValueType.HorizontalFlip).DefaultValue);
}
if (Settings.VerticalFlip.Equals(default))
{
Settings.VerticalFlip = Convert.ToBoolean(GetVideoDeviceValue(VideoDeviceValueType.VerticalFlip).DefaultValue);
}
}
private void Initialize()
{
if (_deviceFileDescriptor >= 0)
{
return;
}
string deviceFileName = $"{DevicePath}{Settings.BusId}";
lock (s_initializationLock)
{
if (_deviceFileDescriptor >= 0)
{
return;
}
_deviceFileDescriptor = Interop.open(deviceFileName, FileOpenFlags.O_RDWR);
if (_deviceFileDescriptor < 0)
{
throw new IOException($"Error {Marshal.GetLastWin32Error()}. Can not open video device file '{deviceFileName}'.");
}
}
}
private void Close()
{
if (_deviceFileDescriptor >= 0)
{
Interop.close(_deviceFileDescriptor);
_deviceFileDescriptor = -1;
}
}
/// <summary>
/// Get and set v4l2 struct.
/// </summary>
/// <typeparam name="T">V4L2 struct</typeparam>
/// <param name="request">V4L2 request value</param>
/// <param name="struct">The struct need to be read or set</param>
/// <returns>The ioctl result</returns>
private int V4l2Struct<T>(int request, ref T @struct)
where T : struct
{
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(@struct));
Marshal.StructureToPtr(@struct, ptr, true);
int result = Interop.ioctl(_deviceFileDescriptor, (int)request, ptr);
@struct = Marshal.PtrToStructure<T>(ptr);
Marshal.FreeHGlobal(ptr);
return result;
}
protected override void Dispose(bool disposing)
{
Close();
base.Dispose(disposing);
}
}
}
| 36.110721 | 228 | 0.54334 | [
"MIT"
] | Alex-111/iot | src/devices/Media/VideoDevice/Devices/UnixVideoDevice.cs | 20,549 | C# |
/*
* ORY Oathkeeper
*
* ORY Oathkeeper is a reverse proxy that checks the HTTP Authorization for validity against a set of rules. This service uses Hydra to validate access tokens and policies.
*
* The version of the OpenAPI document: v0.0.0-alpha.62
* Contact: hi@ory.am
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Ory.Oathkeeper.Client.Client.OpenAPIDateConverter;
namespace Ory.Oathkeeper.Client.Model
{
/// <summary>
/// CreateRuleForbiddenBody CreateRuleForbiddenBody CreateRuleForbiddenBody CreateRuleForbiddenBody CreateRuleForbiddenBody CreateRuleForbiddenBody CreateRuleForbiddenBody create rule forbidden body
/// </summary>
[DataContract(Name = "CreateRuleForbiddenBody")]
public partial class OathkeeperCreateRuleForbiddenBody : IEquatable<OathkeeperCreateRuleForbiddenBody>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="OathkeeperCreateRuleForbiddenBody" /> class.
/// </summary>
/// <param name="code">code.</param>
/// <param name="details">details.</param>
/// <param name="message">message.</param>
/// <param name="reason">reason.</param>
/// <param name="request">request.</param>
/// <param name="status">status.</param>
public OathkeeperCreateRuleForbiddenBody(long code = default(long), List<Object> details = default(List<Object>), string message = default(string), string reason = default(string), string request = default(string), string status = default(string))
{
this.Code = code;
this.Details = details;
this.Message = message;
this.Reason = reason;
this.Request = request;
this.Status = status;
this.AdditionalProperties = new Dictionary<string, object>();
}
/// <summary>
/// code
/// </summary>
/// <value>code</value>
[DataMember(Name = "code", EmitDefaultValue = false)]
public long Code { get; set; }
/// <summary>
/// details
/// </summary>
/// <value>details</value>
[DataMember(Name = "details", EmitDefaultValue = false)]
public List<Object> Details { get; set; }
/// <summary>
/// message
/// </summary>
/// <value>message</value>
[DataMember(Name = "message", EmitDefaultValue = false)]
public string Message { get; set; }
/// <summary>
/// reason
/// </summary>
/// <value>reason</value>
[DataMember(Name = "reason", EmitDefaultValue = false)]
public string Reason { get; set; }
/// <summary>
/// request
/// </summary>
/// <value>request</value>
[DataMember(Name = "request", EmitDefaultValue = false)]
public string Request { get; set; }
/// <summary>
/// status
/// </summary>
/// <value>status</value>
[DataMember(Name = "status", EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets additional properties
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalProperties { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OathkeeperCreateRuleForbiddenBody {\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" Details: ").Append(Details).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append(" Reason: ").Append(Reason).Append("\n");
sb.Append(" Request: ").Append(Request).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as OathkeeperCreateRuleForbiddenBody);
}
/// <summary>
/// Returns true if OathkeeperCreateRuleForbiddenBody instances are equal
/// </summary>
/// <param name="input">Instance of OathkeeperCreateRuleForbiddenBody to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OathkeeperCreateRuleForbiddenBody input)
{
if (input == null)
return false;
return
(
this.Code == input.Code ||
this.Code.Equals(input.Code)
) &&
(
this.Details == input.Details ||
this.Details != null &&
input.Details != null &&
this.Details.SequenceEqual(input.Details)
) &&
(
this.Message == input.Message ||
(this.Message != null &&
this.Message.Equals(input.Message))
) &&
(
this.Reason == input.Reason ||
(this.Reason != null &&
this.Reason.Equals(input.Reason))
) &&
(
this.Request == input.Request ||
(this.Request != null &&
this.Request.Equals(input.Request))
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
)
&& (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any());
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Code.GetHashCode();
if (this.Details != null)
hashCode = hashCode * 59 + this.Details.GetHashCode();
if (this.Message != null)
hashCode = hashCode * 59 + this.Message.GetHashCode();
if (this.Reason != null)
hashCode = hashCode * 59 + this.Reason.GetHashCode();
if (this.Request != null)
hashCode = hashCode * 59 + this.Request.GetHashCode();
if (this.Status != null)
hashCode = hashCode * 59 + this.Status.GetHashCode();
if (this.AdditionalProperties != null)
hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 38.426009 | 255 | 0.557825 | [
"Apache-2.0"
] | GRoguelon/sdk | clients/oathkeeper/dotnet/src/Ory.Oathkeeper.Client/Model/OathkeeperCreateRuleForbiddenBody.cs | 8,569 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Threading.Tasks;
using Microsoft.NodejsTools.Project;
using Microsoft.NodejsTools.Telemetry;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Workspace;
using Microsoft.VisualStudio.Workspace.Debug;
using Microsoft.VisualStudio.Workspace.Extensions.VS.Debug;
using Microsoft.VisualStudio.Workspace.VSIntegration.Contracts;
using Newtonsoft.Json.Linq;
namespace Microsoft.NodejsTools.Debugger
{
/// <summary>
/// Extension to Vs Launch Debugger to handle js files from a Node Js project
/// </summary>
[ExportVsDebugLaunchTarget(ProviderType, new[] { ".js" }, ProviderPriority.Highest)]
internal class NodeJsDebugLaunchProvider : IVsDebugLaunchTargetProvider
{
private const string ProviderType = "6C01D598-DE83-4D5B-B7E5-757FBA8443DD";
private const string NodeExeKey = "nodeExe";
private const string NodeJsSchema =
@"{
""definitions"": {
""nodejs"": {
""type"": ""object"",
""properties"": {
""type"": {""type"": ""string"",""enum"": [ ""nodejs"" ]},
""nodeExe"": { ""type"": ""string"" }
}
},
""nodejsFile"": {
""allOf"": [
{ ""$ref"": ""#/definitions/default"" },
{ ""$ref"": ""#/definitions/nodejs"" }
]
}
},
""defaults"": {
""nodejs"": { ""$ref"": ""#/definitions/nodejs"" }
},
""configuration"": ""#/definitions/nodejsFile""
}";
[Import]
public SVsServiceProvider ServiceProvider { get; set; }
[Import]
public IVsFolderWorkspaceService WorkspaceService { get; set; }
public void SetupDebugTargetInfo(ref VsDebugTargetInfo vsDebugTargetInfo, DebugLaunchActionContext debugLaunchContext)
{
var nodeExe = debugLaunchContext.LaunchConfiguration.GetValue(NodeExeKey, defaultValue: Nodejs.GetPathToNodeExecutableFromEnvironment());
if (string.IsNullOrEmpty(nodeExe))
{
var workspace = this.WorkspaceService.CurrentWorkspace;
workspace.JTF.Run(async () =>
{
await workspace.JTF.SwitchToMainThreadAsync();
VsShellUtilities.ShowMessageBox(this.ServiceProvider,
string.Format(Resources.NodejsNotInstalledAnyCode, LaunchConfigurationConstants.LaunchJsonFileName),
Resources.NodejsNotInstalledShort,
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
});
// This isn't pretty but the only way to not get an additional
// dialog box, after the one we show.
throw new TaskCanceledException();
}
var nodeVersion = Nodejs.GetNodeVersion(nodeExe);
if (nodeVersion >= new Version(8, 0) || NodejsProjectLauncher.CheckDebugProtocolOption())
{
SetupDebugTargetInfoForWebkitV2Protocol(ref vsDebugTargetInfo, debugLaunchContext, nodeExe);
TelemetryHelper.LogDebuggingStarted("ChromeV2", nodeVersion.ToString(), isProject: false);
}
else
{
this.SetupDebugTargetInfoForNodeProtocol(ref vsDebugTargetInfo, debugLaunchContext, nodeExe);
TelemetryHelper.LogDebuggingStarted("Node6", nodeVersion.ToString(), isProject: false);
}
}
private void SetupDebugTargetInfoForNodeProtocol(ref VsDebugTargetInfo vsDebugTargetInfo, DebugLaunchActionContext debugLaunchContext, string nodeExe)
{
var target = vsDebugTargetInfo.bstrExe;
vsDebugTargetInfo.bstrExe = nodeExe;
var nodeJsArgs = vsDebugTargetInfo.bstrArg;
vsDebugTargetInfo.bstrArg = "\"" + target + "\"";
if (!string.IsNullOrEmpty(nodeJsArgs))
{
vsDebugTargetInfo.bstrArg += " ";
vsDebugTargetInfo.bstrArg += nodeJsArgs;
}
vsDebugTargetInfo.clsidCustom = DebugEngine.AD7Engine.DebugEngineGuid;
vsDebugTargetInfo.bstrOptions = "WAIT_ON_ABNORMAL_EXIT=true";
vsDebugTargetInfo.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd;
}
private void SetupDebugTargetInfoForWebkitV2Protocol(ref VsDebugTargetInfo vsDebugTargetInfo, DebugLaunchActionContext debugLaunchContext, string nodeExe)
{
// todo: refactor the debugging and process starting so we can re-use
var target = vsDebugTargetInfo.bstrExe;
var cwd = Path.GetDirectoryName(target); // Current working directory
var configuration = new JObject(
new JProperty("name", "Debug Node.js program from Visual Studio"),
new JProperty("type", "node2"),
new JProperty("request", "launch"),
new JProperty("program", target),
new JProperty("runtimeExecutable", nodeExe),
new JProperty("cwd", cwd),
new JProperty("console", "externalTerminal"),
new JProperty("trace", NodejsProjectLauncher.CheckEnableDiagnosticLoggingOption()),
new JProperty("sourceMaps", true),
new JProperty("stopOnEntry", true));
var jsonContent = configuration.ToString();
vsDebugTargetInfo.dlo = DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
vsDebugTargetInfo.clsidCustom = NodejsProjectLauncher.WebKitDebuggerV2Guid;
vsDebugTargetInfo.bstrExe = target;
vsDebugTargetInfo.bstrOptions = jsonContent;
vsDebugTargetInfo.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd;
}
[ExportLaunchConfigurationProvider(LaunchConfigurationProviderType, new[] { ".js" }, "nodejs", NodeJsSchema)]
public class LaunchConfigurationProvider : ILaunchConfigurationProvider
{
private const string LaunchConfigurationProviderType = "1DB21619-2C53-4BEF-84E4-B1C4D6771A51";
public void CustomizeLaunchConfiguration(DebugLaunchActionContext debugLaunchActionContext, IPropertySettings launchSettings)
{
// noop
}
/// <inheritdoc />
public bool IsDebugLaunchActionSupported(DebugLaunchActionContext debugLaunchActionContext)
{
throw new NotImplementedException();
}
}
}
}
| 44.363057 | 163 | 0.628859 | [
"Apache-2.0"
] | stefb965/nodejstools | Nodejs/Product/Nodejs/Debugger/NodeDebugProvider.cs | 6,811 | C# |
// Copyright (c) 2018 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public class NamedArguments
{
private class ClassWithNamedArgCtor
{
internal ClassWithNamedArgCtor(bool arg1 = false, bool arg2 = false)
{
}
internal ClassWithNamedArgCtor()
: this(arg2: Get(1) != 1, arg1: Get(2) == 2)
{
}
}
public void Use(int a, int b, int c)
{
}
public static int Get(int i)
{
return i;
}
public void Test()
{
Use(Get(1), Get(2), Get(3));
Use(Get(1), c: Get(2), b: Get(3));
Use(b: Get(1), a: Get(2), c: Get(3));
}
public void NotNamedArgs()
{
int b = Get(1);
Use(Get(2), b, Get(3));
}
}
}
| 30.293103 | 93 | 0.698919 | [
"MIT"
] | 164306530/ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/NamedArguments.cs | 1,759 | C# |
using System.Text.Json;
using JT905.Protocol.Extensions;
using JT905.Protocol.Interfaces;
using JT905.Protocol.MessagePack;
namespace JT905.Protocol.MessageBody
{
/// <summary>
/// 位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报
/// 0x8103_=0x0020
/// </summary>
public class JT905_0x8103_0x0020 : JT905_0x8103_BodyBase, IJT905MessagePackFormatter<JT905_0x8103_0x0020>, IJT905Analyze
{
/// <summary>
/// 参数ID
///位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报
/// 0x0020
/// </summary>
public override ushort ParamId { get; set; } = JT905Constants.JT905_0x8103_0x0020;
/// <summary>
/// 数据长度
/// </summary>
public override byte ParamLength { get; set; } = 4;
public override string Description => "位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报";
/// <summary>
/// 位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报
/// </summary>
public uint ParamValue { get; set; }
/// <summary>
/// 解析数据
/// 位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报
/// 0x8103_0x0020
/// </summary>
/// <param name="reader">JT905消息读取器</param>
/// <param name="writer">消息写入</param>
/// <param name="config">JT905接口配置</param>
public void Analyze(ref JT905MessagePackReader reader, Utf8JsonWriter writer, IJT905Config config)
{
JT905_0x8103_0x0020 JT905_0x8103_0x0020 = new JT905_0x8103_0x0020();
JT905_0x8103_0x0020.ParamId = reader.ReadUInt16();
JT905_0x8103_0x0020.ParamLength = reader.ReadByte();
writer.WriteNumber($"[{JT905_0x8103_0x0020.ParamId.ReadNumber()}]参数ID", JT905_0x8103_0x0020.ParamId);
writer.WriteNumber($"[{JT905_0x8103_0x0020.ParamLength.ReadNumber()}]参数长度", JT905_0x8103_0x0020.ParamLength);
JT905_0x8103_0x0020.ParamValue = reader.ReadUInt32();
writer.WriteNumber($"[{JT905_0x8103_0x0020.ParamValue.ReadNumber()}]参数值[位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报]", JT905_0x8103_0x0020.ParamValue);
}
/// <summary>
/// 消息反序列化
/// 位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报
/// 0x8103_0x0020
/// </summary>
/// <param name="reader"></param>
/// <param name="config"></param>
/// <returns></returns>
public JT905_0x8103_0x0020 Deserialize(ref JT905MessagePackReader reader, IJT905Config config)
{
JT905_0x8103_0x0020 JT905_0x8103_0x0020 = new JT905_0x8103_0x0020();
JT905_0x8103_0x0020.ParamId = reader.ReadUInt16();
JT905_0x8103_0x0020.ParamLength = reader.ReadByte();
JT905_0x8103_0x0020.ParamValue = reader.ReadUInt32();
return JT905_0x8103_0x0020;
}
/// <summary>
/// 消息序列化
/// 位置汇报策略,0:定时汇报;1:定距汇报;2:定时+定距汇报
/// 0x8103_0x0020
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="config"></param>
public void Serialize(ref JT905MessagePackWriter writer, JT905_0x8103_0x0020 value, IJT905Config config)
{
writer.WriteUInt16(value.ParamId);
writer.WriteByte(value.ParamLength);
writer.WriteUInt32(value.ParamValue);
}
}
}
| 38.643678 | 150 | 0.589233 | [
"MIT"
] | SmallChi/JT905 | src/JT905.Protocol/MessageBody/JT905_0x8103_0x0020.cs | 3,866 | C# |
namespace PrimarSql.Data.Planners.Describe
{
internal sealed class DescribeTableQueryInfo : IQueryInfo
{
public string TableName { get; set; }
public DescribeTableQueryInfo(string tableName)
{
TableName = tableName;
}
}
}
| 22.153846 | 61 | 0.614583 | [
"MIT"
] | ScriptBox99/chequer-PrimarSql.Data | PrimarSql.Data/Planners/Describe/DescribeTableQueryInfo.cs | 290 | C# |
using Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PeopleViewer.WebApp.Controllers;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PeopleViewer.WebApp.Tests
{
[TestClass]
public class PeopleControllerTests
{
private IPersonReader GetGoodReader() => new FakeGoodReader();
private IPersonReader GetFaultedReader() => new FakeFaultedReader();
[TestMethod]
public async Task WithTask_OnSuccess_ReturnsViewWithPeople()
{
// Arrange
var reader = GetGoodReader();
var controller = new PeopleController(reader);
// Act
var view = await controller.WithTask();
var result = view.Model as IEnumerable<Person>;
// Assert
Assert.AreEqual(2, result.Count());
}
[TestMethod]
public async Task WithAwait_OnSuccess_ReturnsViewWithPeople()
{
var reader = GetGoodReader();
var controller = new PeopleController(reader);
var view = await controller.WithAwait();
var result = view.Model as IEnumerable<Person>;
Assert.AreEqual(2, result.Count());
}
[TestMethod]
public async Task GetPerson_OnSuccess_ReturnsViewWithPerson()
{
int testId = 2;
var reader = GetGoodReader();
var controller = new PeopleController(reader);
var view = await controller.GetPerson(testId);
var result = view.Model as IEnumerable<Person>;
Assert.AreEqual(testId, result?.First().Id);
}
[TestMethod]
public async Task WithTask_OnFailure_ReturnsErrorView()
{
var reader = GetFaultedReader();
var controller = new PeopleController(reader);
var view = await controller.WithTask();
Assert.AreEqual("Error", view.ViewName);
}
[TestMethod]
public async Task WithAwait_OnFailure_ReturnsErrorView()
{
var reader = GetFaultedReader();
var controller = new PeopleController(reader);
var view = await controller.WithAwait();
Assert.AreEqual("Error", view.ViewName);
}
[TestMethod]
public async Task GetPerson_WithInvalidID_ReturnsErrorView()
{
var testId = -10;
var reader = GetGoodReader();
var controller = new PeopleController(reader);
var view = await controller.GetPerson(testId);
Assert.AreEqual("Error", view.ViewName);
}
}
}
| 29.32967 | 76 | 0.603222 | [
"MIT"
] | sizemj/async-workshop-nov2020 | Samples/Completed/AsyncDependencyInjection/PeopleViewer.WebApp.Tests/PeopleControllerTests.cs | 2,669 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Resources.Areas.Contests.Views {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class ListByCategory {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ListByCategory() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OJS.Web.App_GlobalResources.Areas.Contests.Views.List.ListByCategory", typeof(ListByCategory).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The selected category is empty..
/// </summary>
public static string Category_is_empty {
get {
return ResourceManager.GetString("Category_is_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compete.
/// </summary>
public static string Compete {
get {
return ResourceManager.GetString("Compete", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit.
/// </summary>
public static string Edit {
get {
return ResourceManager.GetString("Edit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The contest has password.
/// </summary>
public static string Has_compete_password {
get {
return ResourceManager.GetString("Has_compete_password", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You need a password to practice.
/// </summary>
public static string Has_practice_password {
get {
return ResourceManager.GetString("Has_practice_password", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The contest has questions to be answered.
/// </summary>
public static string Has_questions_to_be_answered {
get {
return ResourceManager.GetString("Has_questions_to_be_answered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Participant count.
/// </summary>
public static string Participant_count {
get {
return ResourceManager.GetString("Participant_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Practice.
/// </summary>
public static string Practice {
get {
return ResourceManager.GetString("Practice", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Problems.
/// </summary>
public static string Problems {
get {
return ResourceManager.GetString("Problems", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Problems count.
/// </summary>
public static string Problems_count {
get {
return ResourceManager.GetString("Problems_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results.
/// </summary>
public static string Results {
get {
return ResourceManager.GetString("Results", resourceCulture);
}
}
}
}
| 37.576687 | 218 | 0.564571 | [
"MIT"
] | SveGeorgiev/OpenJudgeSystem | Open Judge System/Web/OJS.Web/App_GlobalResources/Areas/Contests/Views/List/ListByCategory.Designer.cs | 6,127 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NuGet.Client.Facts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NuGet.Client.Facts")]
[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("8b8b4a38-79fb-425f-8b57-12365990025d")]
// 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")]
| 38.081081 | 84 | 0.7445 | [
"Apache-2.0"
] | davidvu200401/NuGet.Client | src/NuGet.Client.Facts/Properties/AssemblyInfo.cs | 1,412 | C# |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace dnlib.DotNet {
/// <summary>
/// Compares <see cref="UTF8String"/>s
/// </summary>
public sealed class UTF8StringEqualityComparer : IEqualityComparer<UTF8String> {
/// <summary>
/// The default instance
/// </summary>
public static readonly UTF8StringEqualityComparer Instance = new UTF8StringEqualityComparer();
/// <inheritdoc/>
public bool Equals(UTF8String x, UTF8String y) => UTF8String.Equals(x, y);
/// <inheritdoc/>
public int GetHashCode(UTF8String obj) => UTF8String.GetHashCode(obj);
}
/// <summary>
/// A UTF-8 encoded string where the original data is kept in memory to avoid conversions
/// when the data is not really valid UTF-8 encoded data
/// </summary>
/// <remarks>When comparing strings, a byte compare is performed. The reason is that this
/// is what the CLR does when comparing strings in the #Strings stream.</remarks>
[DebuggerDisplay("{String}")]
public sealed class UTF8String : IEquatable<UTF8String>, IComparable<UTF8String> {
/// <summary>
/// An empty <see cref="UTF8String"/>
/// </summary>
public static readonly UTF8String Empty = new UTF8String(string.Empty);
readonly byte[] data;
string asString;
/// <summary>
/// Gets the value as a UTF8 decoded string. Only use it for display purposes,
/// not for serialization.
/// </summary>
public string String {
get {
if (asString is null)
asString = ConvertFromUTF8(data);
return asString;
}
}
/// <summary>
/// Gets the original encoded data. Don't modify this data.
/// </summary>
public byte[] Data => data;
/// <summary>
/// Gets the length of the this as a <see cref="string"/>. I.e., it's the same as
/// <c>String.Length</c>.
/// </summary>
/// <seealso cref="DataLength"/>
public int Length => String.Length;
/// <summary>
/// Gets the length of the raw data. It's the same as <c>Data.Length</c>
/// </summary>
/// <seealso cref="Length"/>
public int DataLength => data is null ? 0 : data.Length;
/// <summary>
/// Checks whether <paramref name="utf8"/> is <c>null</c> or if its data is <c>null</c>.
/// </summary>
/// <param name="utf8">The instance to check</param>
/// <returns><c>true</c> if <c>null</c> or empty, <c>false</c> otherwise</returns>
public static bool IsNull(UTF8String utf8) => utf8 is null || utf8.data is null;
/// <summary>
/// Checks whether <paramref name="utf8"/> is <c>null</c> or if its data is <c>null</c> or the
/// data is zero length.
/// </summary>
/// <param name="utf8">The instance to check</param>
/// <returns><c>true</c> if <c>null</c> or empty, <c>false</c> otherwise</returns>
public static bool IsNullOrEmpty(UTF8String utf8) => utf8 is null || utf8.data is null || utf8.data.Length == 0;
/// <summary>Implicit conversion from <see cref="UTF8String"/> to <see cref="string"/></summary>
public static implicit operator string(UTF8String s) => UTF8String.ToSystemString(s);
/// <summary>Implicit conversion from <see cref="string"/> to <see cref="UTF8String"/></summary>
public static implicit operator UTF8String(string s) => s is null ? null : new UTF8String(s);
/// <summary>
/// Converts it to a <see cref="string"/>
/// </summary>
/// <param name="utf8">The UTF-8 string instace or <c>null</c></param>
/// <returns>A <see cref="string"/> or <c>null</c> if <paramref name="utf8"/> is <c>null</c></returns>
public static string ToSystemString(UTF8String utf8) {
if (utf8 is null || utf8.data is null)
return null;
if (utf8.data.Length == 0)
return string.Empty;
return utf8.String;
}
/// <summary>
/// Converts it to a <see cref="string"/> or an empty string if <paramref name="utf8"/> is <c>null</c>
/// </summary>
/// <param name="utf8">The UTF-8 string instace or <c>null</c></param>
/// <returns>A <see cref="string"/> (never <c>null</c>)</returns>
public static string ToSystemStringOrEmpty(UTF8String utf8) => ToSystemString(utf8) ?? string.Empty;
/// <summary>
/// Gets the hash code of a <see cref="UTF8String"/>
/// </summary>
/// <param name="utf8">Input</param>
public static int GetHashCode(UTF8String utf8) {
if (IsNullOrEmpty(utf8))
return 0;
return Utils.GetHashCode(utf8.data);
}
/// <inheritdoc/>
public int CompareTo(UTF8String other) => CompareTo(this, other);
/// <summary>
/// Compares two <see cref="UTF8String"/> instances (case sensitive)
/// </summary>
/// <param name="a">Instance #1 or <c>null</c></param>
/// <param name="b">Instance #2 or <c>null</c></param>
/// <returns>< 0 if a < b, 0 if a == b, > 0 if a > b</returns>
public static int CompareTo(UTF8String a, UTF8String b) => Utils.CompareTo(a?.data, b?.data);
/// <summary>
/// Compares two <see cref="UTF8String"/> instances (case insensitive)
/// </summary>
/// <param name="a">Instance #1 or <c>null</c></param>
/// <param name="b">Instance #2 or <c>null</c></param>
/// <returns>< 0 if a < b, 0 if a == b, > 0 if a > b</returns>
public static int CaseInsensitiveCompareTo(UTF8String a, UTF8String b) {
if ((object)a == (object)b)
return 0;
var sa = ToSystemString(a);
var sb = ToSystemString(b);
if ((object)sa == (object)sb)
return 0;
if (sa is null)
return -1;
if (sb is null)
return 1;
return StringComparer.OrdinalIgnoreCase.Compare(sa, sb);
}
/// <summary>
/// Compares two <see cref="UTF8String"/> instances (case insensitive)
/// </summary>
/// <param name="a">Instance #1 or <c>null</c></param>
/// <param name="b">Instance #2 or <c>null</c></param>
/// <returns><c>true</c> if equals, <c>false</c> otherwise</returns>
public static bool CaseInsensitiveEquals(UTF8String a, UTF8String b) => CaseInsensitiveCompareTo(a, b) == 0;
/// <summary>Overloaded operator</summary>
public static bool operator ==(UTF8String left, UTF8String right) => CompareTo(left, right) == 0;
/// <summary>Overloaded operator</summary>
public static bool operator ==(UTF8String left, string right) => ToSystemString(left) == right;
/// <summary>Overloaded operator</summary>
public static bool operator ==(string left, UTF8String right) => left == ToSystemString(right);
/// <summary>Overloaded operator</summary>
public static bool operator !=(UTF8String left, UTF8String right) => CompareTo(left, right) != 0;
/// <summary>Overloaded operator</summary>
public static bool operator !=(UTF8String left, string right) => ToSystemString(left) != right;
/// <summary>Overloaded operator</summary>
public static bool operator !=(string left, UTF8String right) => left != ToSystemString(right);
/// <summary>Overloaded operator</summary>
public static bool operator >(UTF8String left, UTF8String right) => CompareTo(left, right) > 0;
/// <summary>Overloaded operator</summary>
public static bool operator <(UTF8String left, UTF8String right) => CompareTo(left, right) < 0;
/// <summary>Overloaded operator</summary>
public static bool operator >=(UTF8String left, UTF8String right) => CompareTo(left, right) >= 0;
/// <summary>Overloaded operator</summary>
public static bool operator <=(UTF8String left, UTF8String right) => CompareTo(left, right) <= 0;
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">UTF-8 data that this instance now owns</param>
public UTF8String(byte[] data) => this.data = data;
/// <summary>
/// Constructor
/// </summary>
/// <param name="s">The string</param>
public UTF8String(string s)
: this(s is null ? null : Encoding.UTF8.GetBytes(s)) {
}
static string ConvertFromUTF8(byte[] data) {
if (data is null)
return null;
try {
return Encoding.UTF8.GetString(data);
}
catch {
}
return null;
}
/// <summary>
/// Compares two instances
/// </summary>
/// <param name="a">First</param>
/// <param name="b">Second</param>
/// <returns><c>true</c> if equals, <c>false</c> otherwise</returns>
public static bool Equals(UTF8String a, UTF8String b) => CompareTo(a, b) == 0;
/// <inheritdoc/>
public bool Equals(UTF8String other) => CompareTo(this, other) == 0;
/// <inheritdoc/>
public override bool Equals(object obj) {
if (obj is not UTF8String other)
return false;
return CompareTo(this, other) == 0;
}
/// <summary>
/// Checks whether <paramref name="value"/> exists in this string
/// </summary>
/// <param name="value">Value to find</param>
/// <returns><c>true</c> if <paramref name="value"/> exists in string or is the
/// empty string, else <c>false</c></returns>
public bool Contains(string value) => String.Contains(value);
/// <summary>
/// Checks whether <paramref name="value"/> matches the end of this string
/// </summary>
/// <param name="value">Value</param>
/// <returns></returns>
public bool EndsWith(string value) => String.EndsWith(value);
/// <summary>
/// Checks whether <paramref name="value"/> matches the end of this string
/// </summary>
/// <param name="value">Value</param>
/// <param name="ignoreCase"><c>true</c> to ignore case</param>
/// <param name="culture">Culture info</param>
/// <returns></returns>
public bool EndsWith(string value, bool ignoreCase, CultureInfo culture) => String.EndsWith(value, ignoreCase, culture);
/// <summary>
/// Checks whether <paramref name="value"/> matches the end of this string
/// </summary>
/// <param name="value">Value</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns></returns>
public bool EndsWith(string value, StringComparison comparisonType) => String.EndsWith(value, comparisonType);
/// <summary>
/// Checks whether <paramref name="value"/> matches the beginning of this string
/// </summary>
/// <param name="value">Value</param>
/// <returns></returns>
public bool StartsWith(string value) => String.StartsWith(value);
/// <summary>
/// Checks whether <paramref name="value"/> matches the beginning of this string
/// </summary>
/// <param name="value">Value</param>
/// <param name="ignoreCase"><c>true</c> to ignore case</param>
/// <param name="culture">Culture info</param>
/// <returns></returns>
public bool StartsWith(string value, bool ignoreCase, CultureInfo culture) => String.StartsWith(value, ignoreCase, culture);
/// <summary>
/// Checks whether <paramref name="value"/> matches the beginning of this string
/// </summary>
/// <param name="value">Value</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns></returns>
public bool StartsWith(string value, StringComparison comparisonType) => String.StartsWith(value, comparisonType);
/// <summary>
/// Compares this instance with <paramref name="strB"/>
/// </summary>
/// <param name="strB">Other string</param>
/// <returns>< 0 if a < b, 0 if a == b, > 0 if a > b</returns>
public int CompareTo(string strB) => String.CompareTo(strB);
/// <summary>
/// Returns the index of the first character <paramref name="value"/> in this string
/// </summary>
/// <param name="value">Character</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(char value) => String.IndexOf(value);
/// <summary>
/// Returns the index of the first character <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/>
/// </summary>
/// <param name="value">Character</param>
/// <param name="startIndex">Start index</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(char value, int startIndex) => String.IndexOf(value, startIndex);
/// <summary>
/// Returns the index of the first character <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/> for max <paramref name="count"/>
/// characters.
/// </summary>
/// <param name="value">Character</param>
/// <param name="startIndex">Start index</param>
/// <param name="count">Max number of chars to scan</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(char value, int startIndex, int count) => String.IndexOf(value, startIndex, count);
/// <summary>
/// Returns the index of the first sub string <paramref name="value"/> in this string
/// </summary>
/// <param name="value">String</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(string value) => String.IndexOf(value);
/// <summary>
/// Returns the index of the first sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/>
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(string value, int startIndex) => String.IndexOf(value, startIndex);
/// <summary>
/// Returns the index of the first sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/> for max <paramref name="count"/>
/// characters.
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <param name="count">Max number of chars to scan</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(string value, int startIndex, int count) => String.IndexOf(value, startIndex, count);
/// <summary>
/// Returns the index of the first sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/> for max <paramref name="count"/>
/// characters.
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <param name="count">Max number of chars to scan</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType) => String.IndexOf(value, startIndex, count, comparisonType);
/// <summary>
/// Returns the index of the first sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/>
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(string value, int startIndex, StringComparison comparisonType) => String.IndexOf(value, startIndex, comparisonType);
/// <summary>
/// Returns the index of the first sub string <paramref name="value"/> in this string
/// </summary>
/// <param name="value">String</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int IndexOf(string value, StringComparison comparisonType) => String.IndexOf(value, comparisonType);
/// <summary>
/// Returns the index of the last character <paramref name="value"/> in this string
/// </summary>
/// <param name="value">Character</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(char value) => String.LastIndexOf(value);
/// <summary>
/// Returns the index of the last character <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/>
/// </summary>
/// <param name="value">Character</param>
/// <param name="startIndex">Start index</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(char value, int startIndex) => String.LastIndexOf(value, startIndex);
/// <summary>
/// Returns the index of the last character <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/> for max <paramref name="count"/>
/// characters.
/// </summary>
/// <param name="value">Character</param>
/// <param name="startIndex">Start index</param>
/// <param name="count">Max number of chars to scan</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(char value, int startIndex, int count) => String.LastIndexOf(value, startIndex, count);
/// <summary>
/// Returns the index of the last sub string <paramref name="value"/> in this string
/// </summary>
/// <param name="value">String</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(string value) => String.LastIndexOf(value);
/// <summary>
/// Returns the index of the last sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/>
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(string value, int startIndex) => String.LastIndexOf(value, startIndex);
/// <summary>
/// Returns the index of the last sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/> for max <paramref name="count"/>
/// characters.
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <param name="count">Max number of chars to scan</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(string value, int startIndex, int count) => String.LastIndexOf(value, startIndex, count);
/// <summary>
/// Returns the index of the last sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/> for max <paramref name="count"/>
/// characters.
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <param name="count">Max number of chars to scan</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType) => String.LastIndexOf(value, startIndex, count, comparisonType);
/// <summary>
/// Returns the index of the last sub string <paramref name="value"/> in this string
/// starting from index <paramref name="startIndex"/>
/// </summary>
/// <param name="value">String</param>
/// <param name="startIndex">Start index</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(string value, int startIndex, StringComparison comparisonType) => String.LastIndexOf(value, startIndex, comparisonType);
/// <summary>
/// Returns the index of the last sub string <paramref name="value"/> in this string
/// </summary>
/// <param name="value">String</param>
/// <param name="comparisonType">Comparison type</param>
/// <returns>The index of <paramref name="value"/> or <c>-1</c> if not found</returns>
public int LastIndexOf(string value, StringComparison comparisonType) => String.LastIndexOf(value, comparisonType);
/// <summary>
/// Inserts string <paramref name="value"/> at a index <paramref name="startIndex"/>
/// </summary>
/// <param name="startIndex">Start index</param>
/// <param name="value">Value to insert</param>
/// <returns>A new instance with the <paramref name="value"/> inserted at position
/// <paramref name="startIndex"/></returns>
public UTF8String Insert(int startIndex, string value) => new UTF8String(String.Insert(startIndex, value));
/// <summary>
/// Removes all characters starting from position <paramref name="startIndex"/>
/// </summary>
/// <param name="startIndex">Start index</param>
/// <returns>A new instance</returns>
public UTF8String Remove(int startIndex) => new UTF8String(String.Remove(startIndex));
/// <summary>
/// Removes <paramref name="count"/> characters starting from position
/// <paramref name="startIndex"/>
/// </summary>
/// <param name="startIndex">Start index</param>
/// <param name="count">Number of characters to remove</param>
/// <returns>A new instance</returns>
public UTF8String Remove(int startIndex, int count) => new UTF8String(String.Remove(startIndex, count));
/// <summary>
/// Replaces all characters <paramref name="oldChar"/> with <paramref name="newChar"/>
/// </summary>
/// <param name="oldChar">Character to find</param>
/// <param name="newChar">Character to replace all <paramref name="oldChar"/></param>
/// <returns>A new instance</returns>
public UTF8String Replace(char oldChar, char newChar) => new UTF8String(String.Replace(oldChar, newChar));
/// <summary>
/// Replaces all sub strings <paramref name="oldValue"/> with <paramref name="newValue"/>
/// </summary>
/// <param name="oldValue">Sub string to find</param>
/// <param name="newValue">Sub string to replace all <paramref name="oldValue"/></param>
/// <returns>A new instance</returns>
public UTF8String Replace(string oldValue, string newValue) => new UTF8String(String.Replace(oldValue, newValue));
/// <summary>
/// Returns a sub string of this string starting at offset <paramref name="startIndex"/>
/// </summary>
/// <param name="startIndex">Start index</param>
/// <returns>A new instance</returns>
public UTF8String Substring(int startIndex) => new UTF8String(String.Substring(startIndex));
/// <summary>
/// Returns a sub string of this string starting at offset <paramref name="startIndex"/>.
/// Length of sub string is <paramref name="length"/>.
/// </summary>
/// <param name="startIndex">Start index</param>
/// <param name="length">Length of sub string</param>
/// <returns>A new instance</returns>
public UTF8String Substring(int startIndex, int length) => new UTF8String(String.Substring(startIndex, length));
/// <summary>
/// Returns the lower case version of this string
/// </summary>
/// <returns>A new instance</returns>
public UTF8String ToLower() => new UTF8String(String.ToLower());
/// <summary>
/// Returns the lower case version of this string
/// </summary>
/// <param name="culture">Culture info</param>
/// <returns>A new instance</returns>
public UTF8String ToLower(CultureInfo culture) => new UTF8String(String.ToLower(culture));
/// <summary>
/// Returns the lower case version of this string using the invariant culture
/// </summary>
/// <returns>A new instance</returns>
public UTF8String ToLowerInvariant() => new UTF8String(String.ToLowerInvariant());
/// <summary>
/// Returns the upper case version of this string
/// </summary>
/// <returns>A new instance</returns>
public UTF8String ToUpper() => new UTF8String(String.ToUpper());
/// <summary>
/// Returns the upper case version of this string
/// </summary>
/// <param name="culture">Culture info</param>
/// <returns>A new instance</returns>
public UTF8String ToUpper(CultureInfo culture) => new UTF8String(String.ToUpper(culture));
/// <summary>
/// Returns the upper case version of this string using the invariant culture
/// </summary>
/// <returns>A new instance</returns>
public UTF8String ToUpperInvariant() => new UTF8String(String.ToUpperInvariant());
/// <summary>
/// Removes all leading and trailing whitespace characters
/// </summary>
/// <returns>A new instance</returns>
public UTF8String Trim() => new UTF8String(String.Trim());
/// <inheritdoc/>
public override int GetHashCode() => UTF8String.GetHashCode(this);
/// <inheritdoc/>
public override string ToString() => String;
}
}
| 42.557491 | 163 | 0.669887 | [
"MIT"
] | congviet/dnlib | src/DotNet/UTF8String.cs | 24,428 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class ConnectExTest
{
private static void OnConnectAsyncCompleted(object sender, SocketAsyncEventArgs args)
{
ManualResetEvent complete = (ManualResetEvent)args.UserToken;
complete.Set();
}
[Fact]
public void Success()
{
int port;
SocketTestServer server = SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port);
SocketTestServer server6 = SocketTestServer.SocketTestServerFactory(new IPEndPoint(IPAddress.IPv6Loopback, port));
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
Assert.True(sock.ConnectAsync(args));
Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "IPv4: Timed out while waiting for connection");
Assert.True(args.SocketError == SocketError.Success);
sock.Dispose();
sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
args.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port);
complete.Reset();
Assert.True(sock.ConnectAsync(args));
Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "IPv6: Timed out while waiting for connection");
Assert.True(args.SocketError == SocketError.Success);
sock.Dispose();
server.Dispose();
server6.Dispose();
}
#region GC Finalizer test
// This test assumes sequential execution of tests and that it is going to be executed after other tests
// that used Sockets.
[Fact]
public void TestFinalizers()
{
// Making several passes through the FReachable list.
for (int i = 0; i < 3; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
#endregion
}
}
| 34.373333 | 126 | 0.635764 | [
"MIT"
] | benjamin-bader/corefx | src/System.Net.Sockets.Legacy/tests/FunctionalTests/ConnectExTest.cs | 2,578 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Ecs.Transform;
using Aliyun.Acs.Ecs.Transform.V20140526;
using System.Collections.Generic;
namespace Aliyun.Acs.Ecs.Model.V20140526
{
public class DescribeSnapshotPackageRequest : RpcAcsRequest<DescribeSnapshotPackageResponse>
{
public DescribeSnapshotPackageRequest()
: base("Ecs", "2014-05-26", "DescribeSnapshotPackage", "ecs", "openAPI")
{
}
private long? resourceOwnerId;
private string resourceOwnerAccount;
private string regionId;
private string ownerAccount;
private int? pageSize;
private string action;
private long? ownerId;
private int? pageNumber;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string RegionId
{
get
{
return regionId;
}
set
{
regionId = value;
DictionaryUtil.Add(QueryParameters, "RegionId", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString());
}
}
public string Action
{
get
{
return action;
}
set
{
action = value;
DictionaryUtil.Add(QueryParameters, "Action", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public int? PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString());
}
}
public override DescribeSnapshotPackageResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext)
{
return DescribeSnapshotPackageResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
} | 21.372671 | 123 | 0.65388 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-ecs/Ecs/Model/V20140526/DescribeSnapshotPackageRequest.cs | 3,441 | C# |
namespace FileOrganizer
{
public class Folder
{
public const string Downloads = @"C:\Users\admin\Downloads";
public const string Documents = @"C:\Users\admin\Documents";
}
}
| 22.555556 | 68 | 0.64532 | [
"MIT"
] | mekk1t/file-organizer | FileOrganizer/FileOrganizer/Folder.cs | 205 | C# |
using System;
namespace FontAwesome
{
/// <summary>
/// The unicode values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Unicode
{
/// <summary>
/// fa-table-tennis unicode value ("\uf45d").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/table-tennis
/// </summary>
public const string TableTennis = "\uf45d";
}
/// <summary>
/// The Css values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Css
{
/// <summary>
/// TableTennis unicode value ("fa-table-tennis").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/table-tennis
/// </summary>
public const string TableTennis = "fa-table-tennis";
}
/// <summary>
/// The Icon names for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Icon
{
/// <summary>
/// fa-table-tennis unicode value ("\uf45d").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/table-tennis
/// </summary>
public const string TableTennis = "TableTennis";
}
} | 36.606557 | 154 | 0.596507 | [
"MIT"
] | michaelswells/FontAwesomeAttribute | FontAwesome/FontAwesome.TableTennis.cs | 2,233 | C# |
namespace Laconic.Demo
{
static class WebViewPage
{
public static WebView Content() => new WebView { Source = "https://google.com" };
}
} | 22.571429 | 90 | 0.620253 | [
"MIT"
] | shirshov/laconic | demo/app/WebViewPage.cs | 158 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Snakes_and_Shillelaghs
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmInstructions());
}
}
}
| 23.086957 | 65 | 0.627119 | [
"MIT"
] | abhatia25/Computer-Programming-2 | Snakes and Shillelaghs/Snakes and Shillelaghs/Program.cs | 533 | C# |
using UnityEngine;
using UniRx;
public class ReactivePropertyBase<T> : ScriptableObject
{
[SerializeField] protected T m_startValue;
protected ReactiveProperty<T> m_property;
public ReadOnlyReactiveProperty<T> Property {
get { return m_property.ToReadOnlyReactiveProperty(); } }
public T GetStartValue()
{
return m_startValue;
}
// Todo: evaluate potential problems, if it is possible to access the property before OnEnable is called
private void OnEnable()
{
m_property = new ReactiveProperty<T>(m_startValue);
}
public void OnNext(T a_value)
{
m_property.Value = a_value;
}
public System.IDisposable Subscribe(System.Action<T> a_callback)
{
return m_property.Subscribe(a_callback);
}
}
| 24.212121 | 108 | 0.687109 | [
"MIT"
] | TanTanDev/ScriptableReactive | Code/Core/ReactivePropertyBase.cs | 801 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ManiaPlanetSharp.GameBox.Parsing.Chunks
{
[Chunk(0x03043029)]
public class MapPasswordChunk
: Chunk
{
[Property, Array(2)]
public ulong[] Password { get; set; }
[Property]
public uint CRC { get; set; }
}
}
| 19 | 49 | 0.622807 | [
"MIT"
] | stefan-baumann/ManiaPlanetSharp | src/ManiaPlanetSharp/GameBox/Parsing/Chunks/Map/MapPasswordChunk.cs | 344 | C# |
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xenko.Core.Annotations;
namespace Xenko.Core.Presentation.Quantum.Presenters
{
public abstract class NodePresenterCommandBase : INodePresenterCommand
{
public abstract string Name { get; }
public virtual CombineMode CombineMode => CombineMode.CombineOnlyForAll;
public abstract bool CanAttach(INodePresenter nodePresenter);
public virtual bool CanExecute(IReadOnlyCollection<INodePresenter> nodePresenters, object parameter)
{
return true;
}
[NotNull]
public virtual Task<object> PreExecute(IReadOnlyCollection<INodePresenter> nodePresenters, object parameter)
{
return Task.FromResult<object>(null);
}
public abstract Task Execute(INodePresenter nodePresenter, object parameter, object preExecuteResult);
[NotNull]
public virtual Task PostExecute(IReadOnlyCollection<INodePresenter> nodePresenters, object parameter)
{
return Task.CompletedTask;
}
}
}
| 35.026316 | 116 | 0.715252 | [
"MIT"
] | Aminator/xenko | sources/presentation/Xenko.Core.Presentation.Quantum/Presenters/NodePresenterCommandBase.cs | 1,331 | C# |
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
namespace WpfSamples.ViewModels
{
public class LoginWindowViewModel : BindableBase
{
public LoginWindowViewModel()
{
}
}
}
| 15.823529 | 52 | 0.687732 | [
"MIT"
] | okadabasso/wpf-sample-prism6 | WpfSamples/ViewModels/LoginWindowViewModel.cs | 271 | C# |
using UnityEngine;
using System.Collections.Generic;
namespace RTG
{
public class CameraViewVolume
{
public enum VPoint
{
NearTopLeft = 0,
NearTopRight,
NearBottomRight,
NearBottomLeft,
FarTopLeft,
FarTopRight,
FarBottomRight,
FarBottomLeft
}
public enum VPlane
{
Left = 0,
Right,
Bottom,
Top,
Near,
Far
}
private const int _numWorldPoints = 8;
private const int _numWorldPlanes = 6;
private Vector3[] _worldPoints = new Vector3[_numWorldPoints];
private Plane[] _worldPlanes = new Plane[_numWorldPlanes];
private Vector2 _farPlaneSize = Vector2.zero;
private Vector2 _nearPlaneSize = Vector2.zero;
private AABB _worldAABB;
private OBB _worldOBB;
public Plane LeftPlane { get { return _worldPlanes[(int)VPlane.Left];} }
public Plane RightPlane { get { return _worldPlanes[(int)VPlane.Right]; } }
public Plane BottomPlane { get { return _worldPlanes[(int)VPlane.Bottom]; } }
public Plane TopPlane { get { return _worldPlanes[(int)VPlane.Top]; } }
public Plane NearPlane { get { return _worldPlanes[(int)VPlane.Near]; } }
public Plane FarPlane { get { return _worldPlanes[(int)VPlane.Far]; } }
public Vector3 NearTopLeft { get { return _worldPoints[(int)VPoint.NearTopLeft]; } }
public Vector3 NearTopRight { get { return _worldPoints[(int)VPoint.NearTopRight]; } }
public Vector3 NearBottomRight { get { return _worldPoints[(int)VPoint.NearBottomRight]; } }
public Vector3 NearBottomLeft { get { return _worldPoints[(int)VPoint.NearBottomLeft]; } }
public Vector3 FarTopLeft { get { return _worldPoints[(int)VPoint.FarTopLeft]; } }
public Vector3 FarTopRight { get { return _worldPoints[(int)VPoint.FarTopRight]; } }
public Vector3 FarBottomRight { get { return _worldPoints[(int)VPoint.FarBottomRight]; } }
public Vector3 FarBottomLeft { get { return _worldPoints[(int)VPoint.FarBottomLeft]; } }
public Vector2 FarPlaneSize { get { return _farPlaneSize; } }
public Vector2 NearPlaneSize { get { return _nearPlaneSize; } }
public AABB WorldAABB { get { return _worldAABB; } }
public OBB WorldOBB { get { return _worldOBB; } }
public CameraViewVolume()
{
}
public CameraViewVolume(Camera camera)
{
FromCamera(camera);
}
public void FromCamera(Camera camera)
{
// Extract the world space planes and then use them to also calculate the world space points
_worldPlanes = GeometryUtility.CalculateFrustumPlanes(camera.projectionMatrix * camera.worldToCameraMatrix);
CalculateWorldPoints(camera);
// Calculate the near and far plane sizes in view space
_farPlaneSize.x = (FarTopLeft - FarTopRight).magnitude;
_farPlaneSize.y = (FarTopLeft - FarBottomLeft).magnitude;
_nearPlaneSize.x = (NearTopLeft - NearTopRight).magnitude;
_nearPlaneSize.y = (NearTopLeft - NearBottomLeft).magnitude;
// Calculate the volume's AABB
_worldAABB = new AABB(_worldPoints);
// Calculate the volume's OBB. Start with the size.
Vector3 obbSize = new Vector3();
obbSize.x = _farPlaneSize.x;
obbSize.y = _farPlaneSize.y;
obbSize.z = camera.farClipPlane - camera.nearClipPlane;
// Calculate the OBB's center. In order to do this, we have to move from the
// camera position along the view vector until we find ourselves in the middle
// of the frustum.
Transform cameraTransform = camera.transform;
Vector3 obbCenter = cameraTransform.position + cameraTransform.forward * (camera.nearClipPlane + obbSize.z * 0.5f);
_worldOBB = new OBB(obbCenter, obbSize, cameraTransform.rotation);
}
/// <summary>
/// Returns a list of all points which make up the near plane. The points
/// are stored in the following order: top-left, top-right, bottom-right,
/// bottom-left.
/// </summary>
public List<Vector3> GetNearPlanePoints()
{
return new List<Vector3>
{
NearTopLeft, NearTopRight,
NearBottomRight, NearBottomLeft,
};
}
public static Plane[] GetCameraWorldPlanes(Camera camera)
{
return GeometryUtility.CalculateFrustumPlanes(camera.projectionMatrix * camera.worldToCameraMatrix); ;
}
public bool CheckAABB(AABB aabb)
{
return GeometryUtility.TestPlanesAABB(_worldPlanes, aabb.ToBounds());
}
public static bool CheckAABB(Camera camera, AABB aabb)
{
var planes = GeometryUtility.CalculateFrustumPlanes(camera.projectionMatrix * camera.worldToCameraMatrix);
return GeometryUtility.TestPlanesAABB(planes, aabb.ToBounds());
}
public static bool CheckAABB(Camera camera, AABB aabb, Plane[] cameraWorldPlanes)
{
return GeometryUtility.TestPlanesAABB(cameraWorldPlanes, aabb.ToBounds());
}
/// <summary>
/// Calculates the volume world space points for the specified camera.
/// Must be called after the world planes have been calculated.
/// </summary>
private void CalculateWorldPoints(Camera camera)
{
Transform camTransform = camera.transform;
// Cast a ray from the camera position towards the far plane. The intersection point
// bewteen the ray and the plane represents the far plane middle point. We have to
// take into account that all volume planes point inside the volume, so the ray will
// be cast along the reverse of the far plane normal.
Plane farPlane = FarPlane;
Ray ray = new Ray(camTransform.position, -farPlane.normal);
float t;
if (farPlane.Raycast(ray, out t))
{
Vector3 ptOnMidFar = ray.GetPoint(t);
Vector3 ptOnMidTopFar = Vector3.zero, ptOnMidRightFar = Vector3.zero;
// We have the point which sits in the middle of the far plane. The next step is
// to calculate the points which sit to the right and up of this point. These will
// be used to calculate the half dimension of the far plane.
ray = new Ray(ptOnMidFar, camTransform.up);
if (TopPlane.Raycast(ray, out t)) ptOnMidTopFar = ray.GetPoint(t);
ray = new Ray(ptOnMidFar, camTransform.right);
if (RightPlane.Raycast(ray, out t)) ptOnMidRightFar = ray.GetPoint(t);
// Calculate the half plane dimensions using the points we calculated earlier
float planeHalfWidth = (ptOnMidRightFar - ptOnMidFar).magnitude;
float planeHalfHeight = (ptOnMidTopFar - ptOnMidFar).magnitude;
// Move from the far plane middle point left/right and bottom/top to calculate the
// far plane corner points. Because the camera volume is rotated along with the camera
// coordinate system, the camera local axes are used to move left/right and top/bottom.
_worldPoints[(int)VPoint.FarTopLeft] = ptOnMidFar - camTransform.right * planeHalfWidth + camTransform.up * planeHalfHeight;
_worldPoints[(int)VPoint.FarTopRight] = ptOnMidFar + camTransform.right * planeHalfWidth + camTransform.up * planeHalfHeight;
_worldPoints[(int)VPoint.FarBottomRight] = ptOnMidFar + camTransform.right * planeHalfWidth - camTransform.up * planeHalfHeight;
_worldPoints[(int)VPoint.FarBottomLeft] = ptOnMidFar - camTransform.right * planeHalfWidth - camTransform.up * planeHalfHeight;
}
// Do the same for the near plane.
// Note: For an ortho camera, the near plane can reside behind the camera position. So an additional
// step is needed to identify the ray direction vector. We check if the distance from the plane
// to the camera position is >= 0. If it is, it means the camera position is in front of the plane.
// Considering that the plane points inwards, it means we have to travel along the reverse of the
// plane normal to hit the plane. If the distance is negative, the camera position lies behind the
// plane and we can travel along the plane normal to hit the plane.
Plane nearPlane = NearPlane;
bool camInFrontOfNearPlane = nearPlane.GetDistanceToPoint(camTransform.position) >= 0.0f;
Vector3 rayDir = camInFrontOfNearPlane ? -nearPlane.normal : nearPlane.normal;
ray = new Ray(camTransform.position, rayDir);
if(nearPlane.Raycast(ray, out t))
{
Vector3 ptOnMidNear = ray.GetPoint(t);
Vector3 ptOnMidTopNear = Vector3.zero, ptOnMidRightFar = Vector3.zero;
ray = new Ray(ptOnMidNear, camTransform.up);
if (TopPlane.Raycast(ray, out t)) ptOnMidTopNear = ray.GetPoint(t);
ray = new Ray(ptOnMidNear, camTransform.right);
if (RightPlane.Raycast(ray, out t)) ptOnMidRightFar = ray.GetPoint(t);
float planeHalfWidth = (ptOnMidRightFar - ptOnMidNear).magnitude;
float planeHalfHeight = (ptOnMidTopNear - ptOnMidNear).magnitude;
_worldPoints[(int)VPoint.NearTopLeft] = ptOnMidNear - camTransform.right * planeHalfWidth + camTransform.up * planeHalfHeight;
_worldPoints[(int)VPoint.NearTopRight] = ptOnMidNear + camTransform.right * planeHalfWidth + camTransform.up * planeHalfHeight;
_worldPoints[(int)VPoint.NearBottomRight] = ptOnMidNear + camTransform.right * planeHalfWidth - camTransform.up * planeHalfHeight;
_worldPoints[(int)VPoint.NearBottomLeft] = ptOnMidNear - camTransform.right * planeHalfWidth - camTransform.up * planeHalfHeight;
}
}
}
}
| 50.728571 | 147 | 0.61945 | [
"MIT"
] | ambid17/PlanarWorlds | Assets/ThirdParty/Runtime Transform Gizmos/Scripts/Runtime Package Common/Camera/CameraViewVolume.cs | 10,655 | C# |
using System;
namespace Gateway.API.Authentication
{
/// <summary>
/// A static class defining the available gateway user roles
/// </summary>
public static class UserRoles
{
public const string GatewayAdministrator = "GatewayAdministrator";
public const string GatewayMerchantUser = "GatewayMerchantUser";
}
}
| 25.428571 | 75 | 0.685393 | [
"MIT"
] | marcu91/CheckoutChallenge-IM | GatewayBackEnd/Gateway.API/Authentication/UserRoles.cs | 358 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using System.Threading;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Game.Configuration;
namespace osu.Game.IO
{
public class OsuStorage : WrappedStorage
{
private readonly GameHost host;
private readonly StorageConfigManager storageConfig;
internal static readonly string[] IGNORE_DIRECTORIES = { "cache" };
internal static readonly string[] IGNORE_FILES =
{
"framework.ini",
"storage.ini"
};
public OsuStorage(GameHost host)
: base(host.Storage, string.Empty)
{
this.host = host;
storageConfig = new StorageConfigManager(host.Storage);
var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath);
if (!string.IsNullOrEmpty(customStoragePath))
ChangeTargetStorage(host.GetStorage(customStoragePath));
}
protected override void ChangeTargetStorage(Storage newStorage)
{
base.ChangeTargetStorage(newStorage);
Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs");
}
public void Migrate(string newLocation)
{
var source = new DirectoryInfo(GetFullPath("."));
var destination = new DirectoryInfo(newLocation);
// using Uri is the easiest way to check equality and contains (https://stackoverflow.com/a/7710620)
var sourceUri = new Uri(source.FullName + Path.DirectorySeparatorChar);
var destinationUri = new Uri(destination.FullName + Path.DirectorySeparatorChar);
if (sourceUri == destinationUri)
throw new ArgumentException("Destination provided is already the current location", nameof(newLocation));
if (sourceUri.IsBaseOf(destinationUri))
throw new ArgumentException("Destination provided is inside the source", nameof(newLocation));
// ensure the new location has no files present, else hard abort
if (destination.Exists)
{
if (destination.GetFiles().Length > 0 || destination.GetDirectories().Length > 0)
throw new ArgumentException("Destination provided already has files or directories present", nameof(newLocation));
deleteRecursive(destination);
}
copyRecursive(source, destination);
ChangeTargetStorage(host.GetStorage(newLocation));
storageConfig.Set(StorageConfig.FullPath, newLocation);
storageConfig.Save();
deleteRecursive(source);
}
private static void deleteRecursive(DirectoryInfo target, bool topLevelExcludes = true)
{
foreach (System.IO.FileInfo fi in target.GetFiles())
{
if (topLevelExcludes && IGNORE_FILES.Contains(fi.Name))
continue;
attemptOperation(() => fi.Delete());
}
foreach (DirectoryInfo dir in target.GetDirectories())
{
if (topLevelExcludes && IGNORE_DIRECTORIES.Contains(dir.Name))
continue;
attemptOperation(() => dir.Delete(true));
}
if (target.GetFiles().Length == 0 && target.GetDirectories().Length == 0)
attemptOperation(target.Delete);
}
private static void copyRecursive(DirectoryInfo source, DirectoryInfo destination, bool topLevelExcludes = true)
{
// based off example code https://docs.microsoft.com/en-us/dotnet/api/system.io.directoryinfo
Directory.CreateDirectory(destination.FullName);
foreach (System.IO.FileInfo fi in source.GetFiles())
{
if (topLevelExcludes && IGNORE_FILES.Contains(fi.Name))
continue;
attemptOperation(() => fi.CopyTo(Path.Combine(destination.FullName, fi.Name), true));
}
foreach (DirectoryInfo dir in source.GetDirectories())
{
if (topLevelExcludes && IGNORE_DIRECTORIES.Contains(dir.Name))
continue;
copyRecursive(dir, destination.CreateSubdirectory(dir.Name), false);
}
}
/// <summary>
/// Attempt an IO operation multiple times and only throw if none of the attempts succeed.
/// </summary>
/// <param name="action">The action to perform.</param>
/// <param name="attempts">The number of attempts (250ms wait between each).</param>
private static void attemptOperation(Action action, int attempts = 10)
{
while (true)
{
try
{
action();
return;
}
catch (Exception)
{
if (attempts-- == 0)
throw;
}
Thread.Sleep(250);
}
}
}
}
| 36.315436 | 135 | 0.571059 | [
"MIT"
] | BananeVolante/osu | osu.Game/IO/OsuStorage.cs | 5,263 | C# |
using Seed.Data;
using SeedModules.OpenId.Domain;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SeedModules.OpenId
{
public class EntityTypeConfigurations : IEntityTypeConfigurationProvider
{
public Task<IEnumerable<object>> GetEntityTypeConfigurationsAsync()
{
return Task.FromResult(new object[]
{
new OpenIdApplicationTypeConfiguration(),
new OpenIdAuthorizationTypeConfiguration(),
new OpenIdScopeTypeConfiguration(),
new OpenIdTokenTypeConfiguration()
}.AsEnumerable());
}
}
}
| 29 | 76 | 0.661169 | [
"MIT"
] | fyl080801/dotnet-seed | modules/SeedModules.OpenId/EntityTypeConfigurations.cs | 669 | C# |
// (c) 2018 IndiegameGarden.com. Distributed under the FreeBSD license in LICENSE.txt
using Microsoft.Xna.Framework;
using Artemis.Interface;
namespace TTengine.Comps
{
/// <summary>Newtonian forces that influence the Velocity through acceleration.</summary>
public class ForcesComp : IComponent
{
/// <summary>Initializes a new instance with zero force.</summary>
public ForcesComp()
: this(0f, 0f, 0f)
{
}
/// <summary>Initializes a new instance.</summary>
public ForcesComp(float x, float y, float z = 0f)
{
Force = new Vector3(x, y, z);
}
/// <summary>Total force acting upon the Entity in this update round.</summary>
public Vector3 Force;
/// <summary>Maximum force that is possible for Entity.</summary>
public float MaxForce = float.MaxValue;
public float Mass = 1f;
/// <summary>Gets or sets the Force X and Y components.</summary>
public Vector2 ForceXY
{
get
{
return new Vector2(Force.X, Force.Y);
}
set
{
Force.X = value.X;
Force.Y = value.Y;
}
}
public float X { get { return Force.X; } set { Force.X = value; } }
public float Y { get { return Force.Y; } set { Force.Y = value; } }
public float Z { get { return Force.Z; } set { Force.Z = value; } }
/// <summary>Get or change the magnitude of the force vector.</summary>
public float Magnitude
{
get
{
return Force.Length();
}
set
{
Force.Normalize();
Force *= value;
}
}
}
} | 28.076923 | 93 | 0.521096 | [
"BSD-2-Clause"
] | IndiegameGarden/Goatic | TTengine/Comps/ForcesComp.cs | 1,827 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
namespace Analyzer.Utilities
{
/// <summary>
/// Represents a type with a single value. This type is often used to denote the successful completion of a void-returning method (C#) or a Sub procedure (Visual Basic).
/// </summary>
/// <remarks>
/// This class is a duplicate from "https://github.com/dotnet/reactive/blob/master/Rx.NET/Source/src/System.Reactive/Unit.cs
/// </remarks>
internal struct Unit : IEquatable<Unit>
{
/// <summary>
/// Determines whether the specified <see cref="Unit"/> value is equal to the current <see cref="Unit"/>. Because <see cref="Unit"/> has a single value, this always returns <c>true</c>.
/// </summary>
/// <param name="other">An object to compare to the current <see cref="Unit"/> value.</param>
/// <returns>Because <see cref="Unit"/> has a single value, this always returns <c>true</c>.</returns>
public bool Equals(Unit other) => true;
/// <summary>
/// Determines whether the specified System.Object is equal to the current <see cref="Unit"/>.
/// </summary>
/// <param name="obj">The System.Object to compare with the current <see cref="Unit"/>.</param>
/// <returns><c>true</c> if the specified System.Object is a <see cref="Unit"/> value; otherwise, <c>false</c>.</returns>
public override bool Equals(object? obj) => obj is Unit;
/// <summary>
/// Returns the hash code for the current <see cref="Unit"/> value.
/// </summary>
/// <returns>A hash code for the current <see cref="Unit"/> value.</returns>
public override int GetHashCode() => 0;
/// <summary>
/// Returns a string representation of the current <see cref="Unit"/> value.
/// </summary>
/// <returns>String representation of the current <see cref="Unit"/> value.</returns>
public override string ToString() => "()";
/// <summary>
/// Determines whether the two specified <see cref="Unit"/> values are equal. Because <see cref="Unit"/> has a single value, this always returns <c>true</c>.
/// </summary>
/// <param name="first">The first <see cref="Unit"/> value to compare.</param>
/// <param name="second">The second <see cref="Unit"/> value to compare.</param>
/// <returns>Because <see cref="Unit"/> has a single value, this always returns <c>true</c>.</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "first", Justification = "Parameter required for operator overloading.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "second", Justification = "Parameter required for operator overloading.")]
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Parameter required for operator overloading.")]
public static bool operator ==(Unit first, Unit second) => true;
/// <summary>
/// Determines whether the two specified <see cref="Unit"/> values are not equal. Because <see cref="Unit"/> has a single value, this always returns <c>false</c>.
/// </summary>
/// <param name="first">The first <see cref="Unit"/> value to compare.</param>
/// <param name="second">The second <see cref="Unit"/> value to compare.</param>
/// <returns>Because <see cref="Unit"/> has a single value, this always returns <c>false</c>.</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "first", Justification = "Parameter required for operator overloading.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "second", Justification = "Parameter required for operator overloading.")]
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Parameter required for operator overloading.")]
public static bool operator !=(Unit first, Unit second) => false;
/// <summary>
/// Gets the single <see cref="Unit"/> value.
/// </summary>
public static Unit Default => default;
}
}
| 62.6 | 193 | 0.647878 | [
"Apache-2.0"
] | Atrejoe/roslyn-analyzers | src/Utilities/Compiler/Options/Unit.cs | 4,384 | C# |
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.TeamServices.Samples.Client.Build
{
[ClientSample(BuildResourceIds.AreaName, BuildResourceIds.BuildsResource)]
public class BuildsSample : ClientSample
{
[ClientSampleMethod]
public IEnumerable<BuildDefinitionReference> ListBuildDefinitions()
{
string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;
// Get a build client instance
VssConnection connection = Context.Connection;
BuildHttpClient buildClient = connection.GetClient<BuildHttpClient>();
List<BuildDefinitionReference> buildDefinitions = new List<BuildDefinitionReference>();
// Iterate (as needed) to get the full set of build definitions
string continuationToken = null;
do
{
IPagedList<BuildDefinitionReference> buildDefinitionsPage = buildClient.GetDefinitionsAsync2(
project: projectName,
continuationToken: continuationToken).Result;
buildDefinitions.AddRange(buildDefinitionsPage);
continuationToken = buildDefinitionsPage.ContinuationToken;
} while (!String.IsNullOrEmpty(continuationToken));
// Show the build definitions
foreach (BuildDefinitionReference definition in buildDefinitions)
{
Console.WriteLine("{0} {1}", definition.Id.ToString().PadLeft(6), definition.Name);
}
return buildDefinitions;
}
}
}
| 36.204082 | 109 | 0.669673 | [
"MIT"
] | GiridharanNarayanan/vsts-dotnet-samples | ClientLibrary/Snippets/Microsoft.TeamServices.Samples.Client/Build/BuildsSample.cs | 1,776 | C# |
using Sharpen;
namespace android.renderscript
{
[Sharpen.NakedStub]
public class Short3
{
}
}
| 9.9 | 30 | 0.737374 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/android/renderscript/Short3.cs | 99 | C# |
using Microsoft.VisualBasic;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Solnet.Wallet.Utilities;
using System;
using System.Collections.Generic;
using System.Text;
namespace Solnet.Wallet.Test
{
[TestClass]
public class Base58Test
{
public static IEnumerable<object[]> DataSet
{
get
{
return new[] {
new object[]{string.Empty, ""},
new object[]{"61", "2g"},
new object[]{"626262", "a3gV"},
new object[]{"636363", "aPEr"},
new object[]{"73696d706c792061206c6f6e6720737472696e67", "2cFupjhnEsSn59qHXstmK2ffpLv2"},
new object[]{"00eb15231dfceb60925886b67d065299925915aeb172c06647", "1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L"},
new object[]{"516b6fcd0f", "ABnLTmg"},
new object[]{"bf4f89001e670274dd", "3SEo3LWLoPntC"},
new object[]{"572e4794", "3EFU7m"},
new object[]{"ecac89cad93923c02321", "EJDM8drfXA6uyA"},
new object[]{"10c8511e", "Rt5zm"},
new object[]{"00000000000000000000", "1111111111"}
};
}
}
[TestMethod]
public void ShouldEncodeProperly()
{
foreach (var i in DataSet)
{
string data = (string)i[0];
string encoded = (string)i[1];
var testBytes = FromHexString(data);
Assert.AreEqual(encoded, Encoders.Base58.EncodeData(testBytes));
}
}
[TestMethod]
public void ShouldDecodeProperly()
{
foreach (var i in DataSet)
{
string data = (string)i[0];
string encoded = (string)i[1];
var testBytes = Encoders.Base58.DecodeData(encoded);
CollectionAssert.AreEqual(FromHexString(data), testBytes);
}
}
[TestMethod]
public void ShouldThrowFormatExceptionOnInvalidBase58()
{
try
{
_ = Encoders.Base58.DecodeData("invalid");
Assert.Fail("invalid base58 string");
}
catch
{
}
try
{
_ = Encoders.Base58.DecodeData(" \t\n\v\f\r skip \r\f\v\n\t a");
Assert.Fail("invalid base58 string");
}
catch
{
}
var result = Encoders.Base58.DecodeData(" \t\n\v\f\r skip \r\f\v\n\t ");
var expected2 = FromHexString("971a55");
CollectionAssert.AreEqual(result, expected2);
}
public static byte[] FromHexString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return bytes; // returns: "Hello world" for "48656C6C6F20776F726C64"
}
}
} | 31.94 | 125 | 0.509393 | [
"MIT"
] | BAISGame/Solnet-lib-for-BAIS | test/Solnet.Wallet.Test/Base58Test.cs | 3,194 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Halcyon.Phlox.Types;
using Halcyon.Phlox.VM;
using Halcyon.Phlox.Util;
using Antlr.Runtime;
using OpenMetaverse;
namespace Halcyon.Phlox.ByteCompiler
{
public class BytecodeGenerator
{
private Dictionary<string, OpCode> _instructionOpCodeMap = new Dictionary<string, OpCode>();
private Dictionary<string, LabelSymbol> _labels = new Dictionary<string, LabelSymbol>();
private Dictionary<string, FunctionSymbol> _functions = new Dictionary<string, FunctionSymbol>();
private Dictionary<string, EventSymbol> _events = new Dictionary<string, EventSymbol>();
private Dictionary<string, int> _states = new Dictionary<string, int>();
private List<object> _constPool = new List<object>();
private const int INITIAL_BYTECODE_SZ = 1024;
private int _ip = 0;
private byte[] _code = new byte[INITIAL_BYTECODE_SZ];
private int _globalsSize = 0;
private int _nextStateId = 0;
public CompiledScript Result
{
get
{
this.CheckForUnresolvedReferences();
CompiledScript script = new CompiledScript();
script.ByteCode = new byte[_ip];
Array.Copy(_code, script.ByteCode, _ip);
script.ConstPool = this.FinalizeConstPool();
script.NumGlobals = _globalsSize;
script.StateEvents = this.CreateStateEventList();
return script;
}
}
private EventInfo[][] CreateStateEventList()
{
if (_states.Count == 0)
{
throw new GenerationException(String.Format("Script must contain a default state"));
}
EventInfo[][] outEvents = new EventInfo[_states.Count][];
for (int i = 0; i < _states.Count; ++i)
{
List<EventSymbol> stateEvents = this.FindEventsForState(i);
if (stateEvents.Count == 0)
{
//find the name of this state
foreach (var stateKvp in _states)
{
if (stateKvp.Value == i)
{
throw new GenerationException(String.Format("State {0} must contain at least 1 event", stateKvp.Key));
}
}
}
outEvents[i] = new EventInfo[stateEvents.Count];
for (int j = 0; j < stateEvents.Count; ++j)
{
outEvents[i][j] = stateEvents[j].ToEventInfo();
}
}
return outEvents;
}
private List<EventSymbol> FindEventsForState(int i)
{
List<EventSymbol> events = new List<EventSymbol>();
foreach (EventSymbol evt in _events.Values)
{
if (evt.State == i)
{
events.Add(evt);
}
}
return events;
}
/// <summary>
/// Transform FunctionSymbol(s) to the more compact FuncInfo structure
/// </summary>
/// <returns></returns>
private object[] FinalizeConstPool()
{
object[] finalConstPool = new object[_constPool.Count];
for (int i = 0; i < _constPool.Count; ++i)
{
object obj = _constPool[i];
FunctionSymbol fs = obj as FunctionSymbol;
if (fs != null)
{
finalConstPool[i] = fs.ToFunctionInfo();
}
else
{
finalConstPool[i] = obj;
}
}
return finalConstPool;
}
public BytecodeGenerator(IEnumerable<FunctionSig> systemMethods)
{
foreach (OpCode code in Enum.GetValues(typeof(OpCode)))
{
_instructionOpCodeMap.Add(code.ToString().Replace('_', '.'), code);
}
foreach (FunctionSig sig in systemMethods)
{
_functions.Add(sig.FunctionName, new FunctionSymbol(sig.FunctionName, sig.TableIndex));
}
}
public void Gen(IToken instrToken)
{
OpCode code;
if (!_instructionOpCodeMap.TryGetValue(instrToken.Text, out code))
{
throw new GenerationException("Unknown opcode " + instrToken.Text);
}
EnsureCapacity(_ip + 1);
_code[_ip++] = (byte)code;
}
public void Gen(IToken instrToken, IToken operandToken)
{
Gen(instrToken);
GenOperand(operandToken);
}
public void Gen(IToken instrToken, IToken oToken1, IToken oToken2)
{
Gen(instrToken, oToken1);
GenOperand(oToken2);
}
public void Gen(IToken instrToken, IToken oToken1, IToken oToken2, IToken oToken3)
{
Gen(instrToken, oToken1, oToken2);
GenOperand(oToken3);
}
public int GetConstantPoolIndex(object obj)
{
int index = _constPool.IndexOf(obj);
if (index == -1)
{
_constPool.Add(obj);
return _constPool.Count - 1;
}
else
{
return index;
}
}
public int GetFunctionIndex(string funcId)
{
FunctionSymbol searchSym;
if (_functions.TryGetValue(funcId, out searchSym))
{
if (searchSym.IsFwdRef)
{
searchSym.AddFwdRef(_ip);
}
return searchSym.ConstIndex;
}
else
{
searchSym = new FunctionSymbol(funcId, _constPool.Count);
_functions.Add(funcId, searchSym);
_constPool.Add(searchSym);
searchSym.AddFwdRef(_ip);
return searchSym.ConstIndex;
}
}
public int GetLabelAddress(string labelId)
{
LabelSymbol label;
if (_labels.TryGetValue(labelId, out label))
{
if (label.IsFwdRef)
{
label.AddFwdRef(_ip);
}
return label.Address;
}
else
{
LabelSymbol newLab = new LabelSymbol(labelId);
newLab.AddFwdRef(_ip);
_labels.Add(labelId, newLab);
return 0;
}
}
public int ConvertToInt(string symbolText)
{
try
{
if (symbolText.StartsWith("0x") || symbolText.StartsWith("-0x"))
{
string strippedText = symbolText;
if (symbolText.StartsWith("-"))
{
strippedText = symbolText.Substring(1);
}
int num = Int32.Parse(strippedText.Substring(2), System.Globalization.NumberStyles.HexNumber);
if (symbolText.StartsWith("-"))
{
return -num;
}
else
{
return num;
}
}
else
{
return Int32.Parse(symbolText);
}
}
catch (OverflowException)
{
return -1;
}
}
public string UnescapeStringChars(string txt)
{
if (string.IsNullOrEmpty(txt)) return txt;
StringBuilder retval = new StringBuilder(txt.Length);
for (int ix = 0; ix < txt.Length; )
{
int jx = txt.IndexOf('\\', ix);
if (jx < 0 || jx == txt.Length - 1) jx = txt.Length;
retval.Append(txt, ix, jx - ix);
if (jx >= txt.Length) break;
switch (txt[jx + 1])
{
case 'n': retval.Append('\n'); break; // Line feed
case 'r': retval.Append('\r'); break; // Carriage return
case 't': retval.Append(" "); break; // Tab
case '"': retval.Append('"'); break; // Double quote
case '\\': retval.Append('\\'); break; // Don't escape
default: // Unrecognized, copy as-is
retval.Append('\\').Append(txt[jx + 1]); break;
}
ix = jx + 2;
}
return retval.ToString();
}
public void GenOperand(IToken operand)
{
int val = 0;
switch (operand.Type)
{
case AssemblerParser.INT: val = ConvertToInt(operand.Text); break;
case AssemblerParser.FLOAT: val = GetConstantPoolIndex(Convert.ToSingle(operand.Text)); break;
case AssemblerParser.STRING: val = GetConstantPoolIndex(UnescapeStringChars(operand.Text)); break;
case AssemblerParser.VECTOR: val = GetConstantPoolIndex(Vector3.Parse(operand.Text)); break;
case AssemblerParser.ROTATION: val = GetConstantPoolIndex(Quaternion.Parse(operand.Text)); break;
case AssemblerParser.FUNC: val = GetFunctionIndex(operand.Text); break;
case AssemblerParser.ID: val = GetLabelAddress(operand.Text); break;
case AssemblerParser.STATE_ID: val = GetStateId(operand.Text); break;
default: throw new GenerationException(String.Format("Invalid operand type {0} in GenOperand()", operand.Type));
}
EnsureCapacity(_ip + 4);
Util.Encoding.WriteInt(_code, _ip, val);
_ip += 4;
}
private int GetStateId(string stateName)
{
int id;
if (_states.TryGetValue(stateName, out id))
{
return id;
}
else
{
throw new GenerationException("Invalid state " + stateName);
}
}
private void EnsureCapacity(int index)
{
if (index >= _code.Length)
{ // expand
int newSize = Math.Max(index, _code.Length) * 2;
byte[] bigger = new byte[newSize];
Array.Copy(_code, 0, bigger, 0, _code.Length);
_code = bigger;
}
}
public void CheckForUnresolvedReferences()
{
bool hasUndeffed = false;
StringBuilder undeffed = new StringBuilder("Undefined references: ");
foreach (LabelSymbol label in _labels.Values)
{
if (label.IsFwdRef)
{
undeffed.Append(label.Name);
undeffed.Append(",");
hasUndeffed = true;
}
}
foreach (object obj in _constPool.Where(p => p is FunctionSymbol))
{
FunctionSymbol sym = (FunctionSymbol)obj;
if (sym.IsFwdRef)
{
undeffed.Append(sym.Name);
undeffed.Append(",");
hasUndeffed = true;
}
}
if (hasUndeffed)
{
throw new GenerationException(undeffed.ToString());
}
}
public void DefineFunction(IToken idToken, int nargs, int nlocals)
{
FunctionSymbol searchSym;
if (_functions.TryGetValue(idToken.Text, out searchSym))
{
if (searchSym.IsFwdRef)
{
searchSym.Define(_ip, nargs, nlocals);
searchSym.ResolveFwdRefs(_code);
}
else
{
throw new GenerationException(String.Format("Function '{0}' already defined", idToken.Text));
}
}
else
{
searchSym = new FunctionSymbol(idToken.Text, _ip, _constPool.Count, nargs, nlocals);
_functions.Add(idToken.Text, searchSym);
_constPool.Add(searchSym);
}
}
public void DefineLabel(IToken idToken)
{
LabelSymbol label;
if (_labels.TryGetValue(idToken.Text, out label))
{
if (label.IsFwdRef)
{
//label exists, patch up references
label.Define(_ip);
label.ResolveFwdRefs(_code);
}
else
{
throw new GenerationException(String.Format("line {0}:{1} Label '{2}' already defined", idToken.Line,
idToken.CharPositionInLine, idToken.Text));
}
}
else
{
label = new LabelSymbol(idToken.Text, _ip);
_labels.Add(label.Name, label);
}
}
public void DefineEventHandler(IToken stateIdToken, IToken idToken, int nargs, int nlocals)
{
int stateId;
if (!_states.TryGetValue(stateIdToken.Text, out stateId))
{
throw new GenerationException(String.Format("line {0}:{1} Invalid state {2}", stateIdToken.Line,
stateIdToken.CharPositionInLine, stateIdToken.Text));
}
if (_events.ContainsKey(stateIdToken.Text + "." + idToken.Text))
{
throw new GenerationException(String.Format("line {0}:{1} Event '{2}.{3}' already defined", idToken.Line,
idToken.CharPositionInLine, stateIdToken.Text, idToken.Text));
}
else
{
EventSymbol evt = new EventSymbol(stateId, idToken.Text, _ip, nargs, nlocals);
_events.Add(stateIdToken.Text + "." + idToken.Text, evt);
}
}
public void DefineState(IToken stateId)
{
if (_states.ContainsKey(stateId.Text))
{
throw new GenerationException(String.Format("line {0}:{1} State {2} already defined", stateId.Line,
stateId.CharPositionInLine, stateId.Text));
}
else
{
_states.Add(stateId.Text, _nextStateId++);
}
}
public void DefineDataSize(int n)
{
_globalsSize = n;
}
}
}
| 32.958057 | 130 | 0.483724 | [
"Apache-2.0"
] | HalcyonGrid/phlox | Source/Halcyon.Phlox/ByteCompiler/BytecodeGenerator.cs | 14,932 | C# |
using System;
using System.Collections.Generic;
namespace DataBoss.Data
{
public class SqlQuerySelect
{
readonly KeyValuePair<string, SqlQueryColumn>[] selectList;
internal SqlQuerySelect(KeyValuePair<string, SqlQueryColumn>[] selectList) { this.selectList = selectList; }
public SqlQueryFrom From(string table) => new SqlQueryFrom(this, table);
public override string ToString() => ToString(SqlQueryFormatting.Default);
public string ToString(SqlQueryFormatting formatting) => AppendTo(new SqlStringBuilder { Formatting = formatting }).ToString();
public SqlStringBuilder AppendTo(SqlStringBuilder query) {
query.BeginBlock("select").EndElement().BeginIndent();
if (selectList.Length == 0)
query.Append("*");
else {
var parts = Array.ConvertAll(selectList, x => $"[{x.Key}] = {x.Value}");
query.Begin(parts[0]);
for(var i = 1; i != parts.Length; ++i)
query.Append(",").EndElement().Begin(parts[i]);
}
return query.EndIndent().EndBlock();
}
}
}
| 33.387097 | 131 | 0.688889 | [
"MIT"
] | drunkcod/DataBoss | Source/DataBoss/Data/SqlQuerySelect.cs | 1,035 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static partial class TypeSymbolExtensions
{
static public NamedTypeSymbol AsUnboundGenericType(this NamedTypeSymbol type)
{
if (!type.IsGenericType)
{
// This exception is part of the public contract of NamedTypeSymbol.ConstructUnboundGenericType
throw new InvalidOperationException();
}
var original = type.OriginalDefinition;
int n = original.Arity;
NamedTypeSymbol originalContainingType = original.ContainingType;
var constructedFrom = ((object)originalContainingType == null) ?
original :
original.AsMember(originalContainingType.IsGenericType ? originalContainingType.AsUnboundGenericType() : originalContainingType);
if (n == 0)
{
return constructedFrom;
}
var typeArguments = UnboundArgumentErrorTypeSymbol.CreateTypeArguments(
constructedFrom.TypeParameters,
n,
new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName));
return constructedFrom.Construct(typeArguments, unbound: true);
}
}
internal sealed class UnboundArgumentErrorTypeSymbol : ErrorTypeSymbol
{
public static ImmutableArray<TypeWithAnnotations> CreateTypeArguments(ImmutableArray<TypeParameterSymbol> typeParameters, int n, DiagnosticInfo errorInfo)
{
var result = ArrayBuilder<TypeWithAnnotations>.GetInstance();
for (int i = 0; i < n; i++)
{
string name = (i < typeParameters.Length) ? typeParameters[i].Name : string.Empty;
result.Add(TypeWithAnnotations.Create(new UnboundArgumentErrorTypeSymbol(name, errorInfo)));
}
return result.ToImmutableAndFree();
}
public static readonly ErrorTypeSymbol Instance = new UnboundArgumentErrorTypeSymbol(string.Empty, new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName));
private readonly string _name;
private readonly DiagnosticInfo _errorInfo;
private UnboundArgumentErrorTypeSymbol(string name, DiagnosticInfo errorInfo)
{
_name = name;
_errorInfo = errorInfo;
}
public override string Name
{
get
{
return _name;
}
}
internal override bool MangleName
{
get
{
Debug.Assert(Arity == 0);
return false;
}
}
internal override DiagnosticInfo ErrorInfo
{
get
{
return _errorInfo;
}
}
internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison, IReadOnlyDictionary<TypeParameterSymbol, bool> isValueTypeOverrideOpt = null)
{
Debug.Assert(isValueTypeOverrideOpt == null);
if ((object)t2 == (object)this)
{
return true;
}
UnboundArgumentErrorTypeSymbol other = t2 as UnboundArgumentErrorTypeSymbol;
return (object)other != null && string.Equals(other._name, _name, StringComparison.Ordinal) && object.Equals(other._errorInfo, _errorInfo);
}
public override int GetHashCode()
{
return _errorInfo == null
? _name.GetHashCode()
: Hash.Combine(_name, _errorInfo.Code);
}
}
}
| 35.53913 | 173 | 0.62711 | [
"Apache-2.0"
] | 20chan/roslyn | src/Compilers/CSharp/Portable/Symbols/UnboundGenericType.cs | 4,089 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SampleApp.WinPhone")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SampleApp.WinPhone")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("10461538-0a7f-45bb-852b-d5a257a18e63")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| 38.105263 | 84 | 0.753453 | [
"MIT"
] | Kimmax/Xamarin.Forms.Plugins | ExtendedListview/SampleApp/SampleApp/SampleApp.WinPhone/Properties/AssemblyInfo.cs | 1,451 | C# |
using HSDRaw.Common;
using HSDRaw.Common.Animation;
using HSDRaw.Tools;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace MexTK.Tools
{
public class AnimationBakery
{
/// <summary>
///
/// </summary>
/// <param name="figatree"></param>
/// <param name="jobjFrom"></param>
/// <param name="jobjTo"></param>
/// <param name="bmFrom"></param>
/// <param name="bmTo"></param>
/// <returns></returns>
public static HSD_FigaTree Port(HSD_FigaTree figatree, HSD_JOBJ jobjFrom, HSD_JOBJ jobjTo, BoneMap bmFrom, BoneMap bmTo)
{
AnimationPlayer sourceAnim = new AnimationPlayer(jobjFrom, figatree);
AnimationPlayer targetAnim = new AnimationPlayer(jobjTo, figatree.FrameCount);
int jobjIndex = 0;
foreach(var to in jobjTo.BreathFirstList)
{
var name = bmTo.GetName(jobjIndex);
var index = bmFrom.GetIndex(name);
FigaTreeNode node = new FigaTreeNode();
if (index != -1)
{
var jfrom = jobjFrom.BreathFirstList[index];
if(targetAnim.PortBoneTo(to, sourceAnim, jfrom))
{
Debug.WriteLine($"Retargeting {name}");
}
}
jobjIndex++;
}
return targetAnim.ToFigaTree(); ;
}
}
/// <summary>
///
/// </summary>
public class AnimationPlayer
{
private Dictionary<HSD_JOBJ, TrackNode> jobjToTrack = new Dictionary<HSD_JOBJ, TrackNode>();
private Dictionary<HSD_JOBJ, HSD_JOBJ> jobjToParent = new Dictionary<HSD_JOBJ, HSD_JOBJ>();
public int FrameCount { get; internal set; } = 0;
/// <summary>
///
/// </summary>
/// <param name="jobj"></param>
/// <param name="figatree"></param>
public AnimationPlayer(HSD_JOBJ jobj, float frameCount)
{
FrameCount = (int)frameCount;
foreach (var j in jobj.BreathFirstList)
{
TrackNode t = new TrackNode(j);
jobjToTrack.Add(j, t);
}
LoadParents(jobj);
}
/// <summary>
///
/// </summary>
/// <param name="jobj"></param>
/// <param name="figatree"></param>
public AnimationPlayer(HSD_JOBJ jobj, HSD_FigaTree figatree)
{
FrameCount = (int)figatree.FrameCount;
int jobjIndex = 0;
foreach(var j in jobj.BreathFirstList)
{
TrackNode t = new TrackNode(j);
var node = figatree.Nodes[jobjIndex];
foreach(var track in node.Tracks)
{
var fobj = track.ToFOBJ();
switch (fobj.JointTrackType)
{
case JointTrackType.HSD_A_J_TRAX: t.X.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_TRAY: t.Y.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_TRAZ: t.Z.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_ROTX: t.RX.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_ROTY: t.RY.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_ROTZ: t.RZ.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_SCAX: t.SX.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_SCAY: t.SY.Keys = fobj.GetDecodedKeys(); break;
case JointTrackType.HSD_A_J_SCAZ: t.SZ.Keys = fobj.GetDecodedKeys(); break;
}
}
jobjToTrack.Add(j, t);
jobjIndex++;
}
LoadParents(jobj);
}
/// <summary>
///
/// </summary>
/// <param name="jobj"></param>
/// <param name="parent"></param>
private void LoadParents(HSD_JOBJ jobj, HSD_JOBJ parent = null)
{
jobjToParent.Add(jobj, parent);
foreach (var c in jobj.Children)
LoadParents(c, jobj);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Matrix4x4 GetAnimatedTransform(HSD_JOBJ jobj, int frame)
{
return jobjToTrack[jobj].GetTransformAt(frame);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Matrix4x4 GetAnimatedWorldTransform(HSD_JOBJ jobj, int frame)
{
return jobjToTrack[jobj].GetTransformAt(frame) * (jobjToParent[jobj] != null ? GetAnimatedWorldTransform(jobjToParent[jobj], frame) : Matrix4x4.Identity);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Matrix4x4 GetWorldTransform(HSD_JOBJ jobj)
{
return TrackNode.CalculateMatrix(jobj) * (jobjToParent[jobj] != null ? GetWorldTransform(jobjToParent[jobj]) : Matrix4x4.Identity);
}
/// <summary>
///
/// </summary>
/// <param name="jobj"></param>
/// <param name="source"></param>
/// <param name="source_jobj"></param>
public bool PortBoneTo(HSD_JOBJ jobj, AnimationPlayer source, HSD_JOBJ source_jobj)
{
if (jobjToParent[jobj] == null)
return false;
var targetWorld = GetWorldTransform(jobj);
var sourceWorld = source.GetWorldTransform(source_jobj);
Matrix4x4.Invert(sourceWorld, out Matrix4x4 invSourceWorld);
var targetRotation = TrackNode.FromEulerAngles(jobj.RZ, jobj.RY, jobj.RX);
var sourceRotation = TrackNode.FromEulerAngles(source_jobj.RZ, source_jobj.RY, source_jobj.RX);
sourceRotation = Quaternion.Inverse(sourceRotation);
// if bones have same orientation we can copy keys directly?
if (ApproximatelySameOrientation(targetWorld, sourceWorld))
{
jobjToTrack[jobj] = source.jobjToTrack[source_jobj];
return false;
}
// otherwise bake
List<Matrix4x4> transforms = new List<Matrix4x4>();
for (int i = 0; i <= FrameCount; i++)
{
var inTargetParentWorld = GetAnimatedWorldTransform(jobjToParent[jobj], i);
Matrix4x4.Invert(inTargetParentWorld, out inTargetParentWorld);
var sourceAnimatedWorld = source.GetAnimatedWorldTransform(source_jobj, i);
var rel = targetWorld * invSourceWorld * sourceAnimatedWorld;
var newT = rel * inTargetParentWorld;
var relTranslate = (new Vector3(source_jobj.TX, source_jobj.TY, source_jobj.TZ) - source.GetAnimatedTransform(source_jobj, i).Translation);
relTranslate = Vector3.Transform(relTranslate, sourceRotation);
relTranslate = Vector3.Transform(relTranslate, targetRotation);
//newT.Translation = new Vector3(jobj.TX, jobj.TY, jobj.TZ);// + relTranslate;
transforms.Add(newT);
}
// then optimize
jobjToTrack[jobj] = new TrackNode(transforms, source.jobjToTrack[source_jobj], source_jobj, jobj);
return true;
}
/// <summary>
///
/// </summary>
/// <param name="m1"></param>
/// <param name="m2"></param>
/// <returns></returns>
private static bool ApproximatelySameOrientation(Matrix4x4 m1, Matrix4x4 m2)
{
var error = 0.01f;
var q1 = Quaternion.CreateFromRotationMatrix(m1);
var q2 = Quaternion.CreateFromRotationMatrix(m2);
return Math.Abs(q1.X - q2.X) < error && Math.Abs(q1.Y - q2.Y) < error && Math.Abs(q1.Z - q2.Z) < error && Math.Abs(q1.W - q2.W) < error;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public HSD_FigaTree ToFigaTree()
{
List<FigaTreeNode> nodes = new List<FigaTreeNode>();
foreach(var v in jobjToTrack)
{
FigaTreeNode node = new FigaTreeNode();
CreateTrack(node, JointTrackType.HSD_A_J_TRAX, v.Value.X.Keys, v.Key.TX);
CreateTrack(node, JointTrackType.HSD_A_J_TRAY, v.Value.Y.Keys, v.Key.TY);
CreateTrack(node, JointTrackType.HSD_A_J_TRAZ, v.Value.Z.Keys, v.Key.TZ);
CreateTrack(node, JointTrackType.HSD_A_J_ROTX, v.Value.RX.Keys, v.Key.RX);
CreateTrack(node, JointTrackType.HSD_A_J_ROTY, v.Value.RY.Keys, v.Key.RY);
CreateTrack(node, JointTrackType.HSD_A_J_ROTZ, v.Value.RZ.Keys, v.Key.RZ);
CreateTrack(node, JointTrackType.HSD_A_J_SCAX, v.Value.SX.Keys, v.Key.SX);
CreateTrack(node, JointTrackType.HSD_A_J_SCAY, v.Value.SY.Keys, v.Key.SY);
CreateTrack(node, JointTrackType.HSD_A_J_SCAZ, v.Value.SZ.Keys, v.Key.SZ);
nodes.Add(node);
}
HSD_FigaTree tree = new HSD_FigaTree();
tree.Type = 1;
tree.FrameCount = FrameCount;
tree.Nodes = nodes;
return tree;
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
/// <param name="type"></param>
/// <param name="keys"></param>
/// <param name="defaultValue"></param>
private void CreateTrack(FigaTreeNode node, JointTrackType type, List<FOBJKey> keys, float defaultValue)
{
// empty track
if (keys.Count == 0)
return;
// skip constant tracks
if (keys.Count == 1 && Math.Abs(keys[0].Value - defaultValue) < 0.001f)
return;
// skip constant tracks
if (keys.Count == 2 && Math.Abs(keys[0].Value - defaultValue) < 0.001f)
return;
HSD_FOBJ fobj = new HSD_FOBJ();
fobj.SetKeys(keys, type);
HSD_Track track = new HSD_Track();
track.FromFOBJ(fobj);
node.Tracks.Add(track);
}
}
public class TrackNode
{
public FOBJ_Player X = new FOBJ_Player();
public FOBJ_Player Y = new FOBJ_Player();
public FOBJ_Player Z = new FOBJ_Player();
public FOBJ_Player RX = new FOBJ_Player();
public FOBJ_Player RY = new FOBJ_Player();
public FOBJ_Player RZ = new FOBJ_Player();
public FOBJ_Player SX = new FOBJ_Player();
public FOBJ_Player SY = new FOBJ_Player();
public FOBJ_Player SZ = new FOBJ_Player();
/// <summary>
///
/// </summary>
/// <param name="joint"></param>
public TrackNode(HSD_JOBJ joint)
{
X.Keys = GenerateKEY(joint.TX);
Y.Keys = GenerateKEY(joint.TY);
Z.Keys = GenerateKEY(joint.TZ);
RX.Keys = GenerateKEY(joint.RX);
RY.Keys = GenerateKEY(joint.RY);
RZ.Keys = GenerateKEY(joint.RZ);
SX.Keys = GenerateKEY(joint.SX);
SY.Keys = GenerateKEY(joint.SY);
SZ.Keys = GenerateKEY(joint.SZ);
}
/// <summary>
///
/// </summary>
/// <param name="mat"></param>
public TrackNode(List<Matrix4x4> transforms, TrackNode sourceTrack, HSD_JOBJ source, HSD_JOBJ dest)
{
List<float> x = new List<float>();
List<float> y = new List<float>();
List<float> z = new List<float>();
List<float> rx = new List<float>();
List<float> ry = new List<float>();
List<float> rz = new List<float>();
List<float> sx = new List<float>();
List<float> sy = new List<float>();
List<float> sz = new List<float>();
foreach (var t in transforms)
{
Vector3 sca, tra;
Quaternion quat;
Matrix4x4.Decompose(t, out sca, out quat, out tra);
Vector3 rot = ToEulerAngles(quat);
tra = t.Translation;
x.Add(tra.X); y.Add(tra.Y); z.Add(tra.Z);
rx.Add(rot.X); ry.Add(rot.Y); rz.Add(rot.Z);
sx.Add(sca.X); sy.Add(sca.Y); sz.Add(sca.Z);
}
// check if any existing tracks match up and use those tracks when possible
var xtrack = sourceTrack.GetExistingTrack(x, source, dest);
var ytrack = sourceTrack.GetExistingTrack(y, source, dest);
var ztrack = sourceTrack.GetExistingTrack(z, source, dest);
var rxtrack = sourceTrack.GetExistingTrack(rx, source, dest);
var rytrack = sourceTrack.GetExistingTrack(ry, source, dest);
var rztrack = sourceTrack.GetExistingTrack(rz, source, dest);
var sxtrack = sourceTrack.GetExistingTrack(sx, source, dest);
var sytrack = sourceTrack.GetExistingTrack(sy, source, dest);
var sztrack = sourceTrack.GetExistingTrack(sz, source, dest);
/*if (dest.ClassName != null && dest.ClassName == "RLegJA")
{
System.Diagnostics.Debug.WriteLine(dest.ClassName);
System.Diagnostics.Debug.WriteLine($"{source.RX} {source.RY} {source.RZ}");
System.Diagnostics.Debug.WriteLine($"{dest.RX} {dest.RY} {dest.RZ}");
Matrix4x4.Decompose(transforms[0], out Vector3 relScale, out Quaternion rot, out Vector3 trans);
System.Diagnostics.Debug.WriteLine($"{TrackNode.ToEulerAngles(rot).ToString()}");
System.Diagnostics.Debug.WriteLine($"{sourceTrack.RX.Keys[0].Value} {sourceTrack.RY.Keys[0].Value} {sourceTrack.RZ.Keys[0].Value}");
System.Diagnostics.Debug.WriteLine($"{rxtrack != null} {rytrack != null} {rztrack != null}");
}*/
if (xtrack != null || ytrack != null || ztrack != null ||
rxtrack != null || rytrack != null || rztrack != null ||
sxtrack != null || sytrack != null || sztrack != null)
{
//System.Diagnostics.Debug.WriteLine("Found Existing Track");
}
// otherwise we have to approximate
var trans_error = 0.05f;
var rot_error = 0.01f;
var scale_error = 0.1f;
X.Keys = xtrack != null ? xtrack : LineSimplification.Simplify(x, trans_error);
Y.Keys = ytrack != null ? ytrack : LineSimplification.Simplify(y, trans_error);
Z.Keys = ztrack != null ? ztrack : LineSimplification.Simplify(z, trans_error);
RX.Keys = rxtrack != null ? rxtrack : LineSimplification.Simplify(rx, rot_error);
RY.Keys = rytrack != null ? rytrack : LineSimplification.Simplify(ry, rot_error);
RZ.Keys = rztrack != null ? rztrack : LineSimplification.Simplify(rz, rot_error);
SX.Keys = sxtrack != null ? sxtrack : LineSimplification.Simplify(sx, scale_error, true);
SY.Keys = sytrack != null ? sytrack : LineSimplification.Simplify(sy, scale_error, true);
SZ.Keys = sztrack != null ? sztrack : LineSimplification.Simplify(sz, scale_error, true);
/*
X.Keys = xtrack != null && xtrack.Count < transforms.Count * 0.85f ? xtrack : LineSimplification.Simplify(x, trans_error);
Y.Keys = ytrack != null && ytrack.Count < transforms.Count * 0.85f ? ytrack : LineSimplification.Simplify(y, trans_error);
Z.Keys = ztrack != null && ztrack.Count < transforms.Count * 0.85f ? ztrack : LineSimplification.Simplify(z, trans_error);
RX.Keys = rxtrack != null && rxtrack.Count < transforms.Count * 0.85f ? rxtrack : LineSimplification.Simplify(rx, rot_error);
RY.Keys = rytrack != null && rytrack.Count < transforms.Count * 0.85f ? rytrack : LineSimplification.Simplify(ry, rot_error);
RZ.Keys = rztrack != null && rztrack.Count < transforms.Count * 0.85f ? rztrack : LineSimplification.Simplify(rz, rot_error);
SX.Keys = sxtrack != null && sxtrack.Count < transforms.Count * 0.85f ? sxtrack : LineSimplification.Simplify(sx, scale_error, true);
SY.Keys = sytrack != null && sytrack.Count < transforms.Count * 0.85f ? sytrack : LineSimplification.Simplify(sy, scale_error, true);
SZ.Keys = sztrack != null && sztrack.Count < transforms.Count * 0.85f ? sztrack : LineSimplification.Simplify(sz, scale_error, true);
*/
}
/// <summary>
///
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
private List<FOBJKey> GetExistingTrack(List<float> keys, HSD_JOBJ source, HSD_JOBJ dest)
{
/*if (KeysEqual(keys, X, source.TX, dest.TX)) return X.Keys;
if (KeysEqual(keys, Y, source.TY, dest.TY)) return Y.Keys;
if (KeysEqual(keys, Z, source.TZ, dest.TZ)) return Z.Keys;
if (KeysEqual(keys, RX, source.RX, dest.RX)) return RX.Keys;
if (KeysEqual(keys, RY, source.RY, dest.RY)) return RY.Keys;
if (KeysEqual(keys, RZ, source.RZ, dest.RZ)) return RZ.Keys;
if (KeysEqual(keys, SX, source.SX, dest.SX)) return SX.Keys;
if (KeysEqual(keys, SY, source.SY, dest.SY)) return SY.Keys;
if (KeysEqual(keys, SZ, source.SZ, dest.SZ)) return SZ.Keys;*/
return null;
}
/// <summary>
///
/// </summary>
/// <param name="keys1"></param>
/// <param name="keys2"></param>
/// <returns></returns>
private bool KeysEqual(List<float> keys, FOBJ_Player player, float source, float dest)
{
if(keys.Count == 0)
return false;
var negPass = true;
var pass = true;
for (int i = 0; i < keys.Count; i++)
{
if (Math.Abs(keys[i] - player.GetValue(i)) > 0.05f)
pass = false;
if (Math.Abs(keys[i] + player.GetValue(i)) > 0.05f)
negPass = false;
if (!pass && !negPass)
break;
}
if (pass) return true;
//if (negPass) return true;
return false;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Matrix4x4 GetTransformAt(int frame)
{
return Matrix4x4.CreateScale(SX.GetValue(frame), SY.GetValue(frame), SZ.GetValue(frame)) *
Matrix4x4.CreateFromQuaternion(FromEulerAngles(RZ.GetValue(frame), RY.GetValue(frame), RX.GetValue(frame))) *
Matrix4x4.CreateTranslation(X.GetValue(frame), Y.GetValue(frame), Z.GetValue(frame));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static Matrix4x4 CalculateMatrix(HSD_JOBJ jobj)
{
return Matrix4x4.CreateScale(jobj.SX, jobj.SY, jobj.SZ) *
Matrix4x4.CreateFromQuaternion(FromEulerAngles(jobj.RZ, jobj.RY, jobj.RX)) *
Matrix4x4.CreateTranslation(jobj.TX, jobj.TY, jobj.TZ);
}
/// <summary>
///
/// </summary>
/// <param name="q"></param>
/// <returns></returns>
public static Vector3 ToEulerAngles(Quaternion q)
{
q = Quaternion.Inverse(q);
Matrix4x4 mat = Matrix4x4.CreateFromQuaternion(q);
float x, y, z;
y = (float)Math.Asin(-Clamp(mat.M31, -1, 1));
if (Math.Abs(mat.M31) < 0.99999)
{
x = (float)Math.Atan2(mat.M32, mat.M33);
z = (float)Math.Atan2(mat.M21, mat.M11);
}
else
{
x = 0;
z = (float)Math.Atan2(-mat.M12, mat.M22);
}
return new Vector3(x, y, z);
}
/// <summary>
///
/// </summary>
/// <param name="v"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static float Clamp(float v, float min, float max)
{
if (v < min) return min;
if (v > max) return max;
return v;
}
/// <summary>
///
/// </summary>
/// <param name="z"></param>
/// <param name="y"></param>
/// <param name="x"></param>
/// <returns></returns>
public static Quaternion FromEulerAngles(float z, float y, float x)
{
Quaternion xRotation = Quaternion.CreateFromAxisAngle(Vector3.UnitX, x);
Quaternion yRotation = Quaternion.CreateFromAxisAngle(Vector3.UnitY, y);
Quaternion zRotation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, z);
Quaternion q = (zRotation * yRotation * xRotation);
return q;
}
/// <summary>
///
/// </summary>
/// <param name="trackType"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
private List<FOBJKey> GenerateKEY(float defaultValue)
{
List<FOBJKey> keys = new List<FOBJKey>();
keys.Add(new FOBJKey() { Value = defaultValue, InterpolationType = GXInterpolationType.HSD_A_OP_KEY });
return keys;
}
}
}
| 38.473776 | 167 | 0.543645 | [
"MIT"
] | akaneia/MexFF | MexFF/Tools/AnimationBakery.cs | 22,009 | C# |
namespace BCnEncoder.Encoder
{
/// <summary>
///
/// </summary>
public enum CompressionQuality
{
/// <summary>
/// Fast, but low quality. Especially bad with gradients.
/// </summary>
Fast,
/// <summary>
/// Strikes a balance between speed and quality. Good enough for most purposes.
/// </summary>
Balanced,
/// <summary>
/// Aims for best quality encoding. Can be very slow.
/// </summary>
BestQuality
}
}
| 24.090909 | 87 | 0.522642 | [
"MIT",
"Unlicense"
] | Tape-Worm/BCnEncoder.NET | BCnEnc.Net/Encoder/CompressionQuality.cs | 532 | C# |
// MIT License
//
// Copyright (c) 2019 WhetstoneTechnologies
//
// 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.Text;
using Newtonsoft.Json;
namespace Whetstone.Alexa
{
[JsonObject("reprompt")]
public class RepromptAttributes
{
[JsonProperty("outputSpeech")]
public OutputSpeechAttributes OutputSpeech { get; set; }
public RepromptAttributes()
{
OutputSpeech = new OutputSpeechAttributes();
}
}
}
| 38 | 81 | 0.735558 | [
"MIT"
] | WhetstoneTechnologies/Whetstone.Alexa | src/Whetstone.Alexa/RepromptAttributes.cs | 1,560 | C# |
using ERPAPI.Auth;
using ERPAPI.Models;
using GlobalLib.DataContext;
using GlobalLib.Models.V_EIP;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Mime;
using System.Threading.Tasks;
using wsSSOReference;
using static wsSSOReference.wsSSOSoapClient;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace ERPAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
/// <summary>
/// DB Connection Strings
/// </summary>
private IConfiguration _configuration { get; }
/// <summary>
/// Log
/// </summary>
private ILogger<LoginController> _logger { get; }
/// <summary>
/// Jwt Handler
/// </summary>
private JwtHandler _jwtHandler { get; }
/// <summary>
/// V_EIP Entities
/// </summary>
private readonly V_EIPContext _context;
/// <summary>
/// Init
/// </summary>
/// <param name="c"></param>
/// <param name="logger"></param>
public LoginController(IConfiguration configuration,
ILogger<LoginController> logger,
JwtHandler jwtHandler,
V_EIPContext context)
{
_configuration = configuration;
_logger = logger;
// step 4-1, generate token by using JwtSecurityTokenHandler
_jwtHandler = jwtHandler;
_context = context;
}
#if true
/// <summary>
/// Create tblAdmissionInfo data
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// Phone
/// Screen_bytNum
/// ScreenD_strPhyRowId
/// ScreenD_strSeatId
/// DBName
/// }
/// </remarks>
/// <param name="data"></param>
/// <returns></returns>
/// <response code="201"></response>
/// <response code="400"></response>
[HttpPost]
[AllowAnonymous]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Post([FromBody] UserForAuthentication data)
{
string BadMessage = string.Empty;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Error Message
// Task<wsSSOReference.LoginByUserResponse> rs = null;
// string[] userRoles = (string[])Session["UserRoles"];
try
{
_logger.LogInformation($"Start:{data.Username}/{data.Password}");
if (!String.IsNullOrEmpty(data.Password))
{
// Consuming ASMX Web Services in ASP.NET Core
// https://www.thecodebuzz.com/consuming-asmx-web-services-in-asp-net-core/
// Consuming soap service in net core
// https://www.codepoc.io/blog/c-sharp/6092/consuming-soap-service-in-net-core
/////////////////////////////////////////////////////////////////////////////////////////
// Web References
LoginDetail wsLD = new LoginDetail()
{
strUserID = data.Username,
strUserPWD = data.Password
};
// SSO API
wsSSOSoapClient wsSSOR = new wsSSOSoapClient(EndpointConfiguration.wsSSOSoap);
LoginByUserResponse rs = wsSSOR.LoginByUserAsync(wsLD).Result;
if (string.IsNullOrEmpty(rs.Body.LoginByUserResult))
{
/////////////////////////////////////////////////////////////////////////////////////////
// Get DepartID
tblUser tblUserInfo = _context.tblUser.Find(wsLD.strUserID);
// var user = await _userManager.FindByNameAsync(userForAuthentication.Email);
//if (user == null || !await _userManager.CheckPasswordAsync(user, userForAuthentication.Password))
// return Unauthorized(new AuthResponseDto { ErrorMessage = "Invalid Authentication" });
var signingCredentials = _jwtHandler.GetSigningCredentials();
IdentityUser user = new IdentityUser()
{
UserName = data.Username
};
var claims = _jwtHandler.GetClaims(user);
// the SecurityTokenDescriptor is based on Configuration in Startup.cs
var tokenOptions = _jwtHandler.GenerateTokenOptions(signingCredentials, claims);
// step 4-2, serializes a JwtSecurityToken into a JWT in compact serialization format
var token = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
return Ok(new AuthResponse { IsAuthSuccessful = true, Token = token });
}
else
{
BadMessage = rs.Body.LoginByUserResult;
}
#if fa
_logger.LogInformation($"Start {tblUserInfo.cUser_ID}");
if (string.IsNullOrEmpty(rs))
{
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, input.Username),
},
DefaultAuthenticationTypes.ApplicationCookie,
ClaimTypes.Name,
ClaimTypes.Role);
// if you want roles, just add as many as you want here (for loop maybe?)
identity.AddClaim(new Claim(ClaimTypes.Role, input.Username.ToLower()));
identity.AddClaim(new Claim(ClaimTypes.Role, tblUserInfo.cDepart_ID));
this.Session["role_id"] = input.Username;
// tell OWIN the identity provider, optional
// identity.AddClaim(new Claim(IdentityProvider, "Simplest Auth"));
Authentication.SignIn(new AuthenticationProperties
{
IsPersistent = input.RememberMe
}, identity);
var user = await _userManager.FindByNameAsync(userForAuthentication.Email);
if (user == null || !await _userManager.CheckPasswordAsync(user, userForAuthentication.Password))
return Unauthorized(new AuthResponseDto { ErrorMessage = "Invalid Authentication" });
var signingCredentials = _jwtHandler.GetSigningCredentials();
var claims = _jwtHandler.GetClaims(user);
var tokenOptions = _jwtHandler.GenerateTokenOptions(signingCredentials, claims);
var token = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
return Ok(new AuthResponse { IsAuthSuccessful = true, Token = token });
}
#endif
}
}
catch (Exception ex)
{
_logger.LogError($"{ex}");
return BadRequest(ex);
}
return BadRequest(new AuthResponse { IsAuthSuccessful = false, ErrorMessage = BadMessage, Token = null } );
}
#endif
}
}
| 42.061856 | 123 | 0.517647 | [
"MIT"
] | LiuLyndon/ERPAPI | ERPAPI/Controllers/LoginController.cs | 8,162 | C# |
/*
* FigmaViewContent.cs
*
* Author:
* Jose Medrano <josmed@microsoft.com>
*
* Copyright (C) 2018 Microsoft, Corp
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace FigmaSharp.Designer
{
public interface IMainWindowWrapper : IWindowWrapper
{
InspectorViewMode ViewMode { get; set; }
}
} | 39.742857 | 78 | 0.726815 | [
"MIT"
] | berlamont/FigmaSharp | FigmaSharp.Tools/FigmaSharp.Designer/IMainWindowWrapper.cs | 1,393 | C# |
using System;
namespace FontAwesome
{
/// <summary>
/// The unicode values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Unicode
{
/// <summary>
/// fa-arrow-circle-right unicode value ("\uf0a9").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/arrow-circle-right
/// </summary>
public const string ArrowCircleRight = "\uf0a9";
}
/// <summary>
/// The Css values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Css
{
/// <summary>
/// ArrowCircleRight unicode value ("fa-arrow-circle-right").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/arrow-circle-right
/// </summary>
public const string ArrowCircleRight = "fa-arrow-circle-right";
}
/// <summary>
/// The Icon names for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Icon
{
/// <summary>
/// fa-arrow-circle-right unicode value ("\uf0a9").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/arrow-circle-right
/// </summary>
public const string ArrowCircleRight = "ArrowCircleRight";
}
} | 37.704918 | 154 | 0.605217 | [
"MIT"
] | michaelswells/FontAwesomeAttribute | FontAwesome/FontAwesome.ArrowCircleRight.cs | 2,300 | C# |
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using NPOI.OpenXmlFormats.Shared;
using NPOI.OpenXml4Net.Util;
using System.IO;
using System.Collections;
using System.Linq;
namespace NPOI.OpenXmlFormats.Wordprocessing
{
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot("glossaryDocument", Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = false)]
public class CT_GlossaryDocument : CT_DocumentBase
{
private CT_DocParts docPartsField;
public CT_GlossaryDocument()
{
this.docPartsField = new CT_DocParts();
}
[XmlElement(Order = 0)]
public CT_DocParts docParts
{
get
{
return this.docPartsField;
}
set
{
this.docPartsField = value;
}
}
}
[XmlInclude(typeof(CT_GlossaryDocument))]
[XmlInclude(typeof(CT_Document))]
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocumentBase
{
private CT_Background backgroundField;
public CT_DocumentBase()
{
//this.backgroundField = new CT_Background();
}
[XmlElement(Order = 0)]
public CT_Background background
{
get
{
return this.backgroundField;
}
set
{
this.backgroundField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot("document", Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = false)]
public class CT_Document : CT_DocumentBase
{
public static CT_Document Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_Document ctObj = new CT_Document();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "body")
ctObj.body = CT_Body.Parse(childNode, namespaceManager);
else if (childNode.LocalName == "background")
ctObj.background = CT_Background.Parse(childNode, namespaceManager);
}
return ctObj;
}
internal void Write(StreamWriter sw)
{
sw.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
sw.Write("<w:document xmlns:ve=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
sw.Write("xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" ");
sw.Write("xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" ");
sw.Write("xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ");
//sw.Write("xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" ");
sw.Write("xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">");
//sw.Write("mc:Ignorable=\"w14\">");
if (this.body != null)
this.body.Write(sw, "body");
if (this.background != null)
this.background.Write(sw, "background");
sw.Write("</w:document>");
}
private CT_Body bodyField;
public CT_Document()
{
this.bodyField = new CT_Body();
}
[XmlElement(Order = 0)]
public CT_Body body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
public void AddNewBody()
{
this.bodyField = new CT_Body();
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_Body
{
private ArrayList itemsField;
private List<DocumentBodyItemChoiceType> itemsElementNameField;
private CT_SectPr sectPrField;
public CT_Body()
{
this.itemsElementNameField = new List<DocumentBodyItemChoiceType>();
this.itemsField = new ArrayList();
}
public static CT_Body Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_Body ctObj = new CT_Body();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.LocalName == "moveTo")
{
ctObj.Items.Add(CT_RunTrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.moveTo);
}
else if (childNode.LocalName == "sectPr")
{
ctObj.sectPr = CT_SectPr.Parse(childNode, namespaceManager);
}
else if (childNode.LocalName == "oMathPara")
{
ctObj.Items.Add(CT_OMathPara.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.oMathPara);
}
else if (childNode.LocalName == "customXml")
{
ctObj.Items.Add(CT_CustomXmlBlock.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXml);
}
else if (childNode.LocalName == "oMath")
{
ctObj.Items.Add(CT_OMath.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.oMath);
}
else if (childNode.LocalName == "altChunk")
{
ctObj.Items.Add(CT_AltChunk.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.altChunk);
}
else if (childNode.LocalName == "bookmarkEnd")
{
ctObj.Items.Add(CT_MarkupRange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.bookmarkEnd);
}
else if (childNode.LocalName == "bookmarkStart")
{
ctObj.Items.Add(CT_Bookmark.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.bookmarkStart);
}
else if (childNode.LocalName == "commentRangeEnd")
{
ctObj.Items.Add(CT_MarkupRange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.commentRangeEnd);
}
else if (childNode.LocalName == "commentRangeStart")
{
ctObj.Items.Add(CT_MarkupRange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.commentRangeStart);
}
else if (childNode.LocalName == "customXmlDelRangeEnd")
{
ctObj.Items.Add(CT_Markup.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlDelRangeEnd);
}
else if (childNode.LocalName == "customXmlDelRangeStart")
{
ctObj.Items.Add(CT_TrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlDelRangeStart);
}
else if (childNode.LocalName == "customXmlInsRangeEnd")
{
ctObj.Items.Add(CT_Markup.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlInsRangeEnd);
}
else if (childNode.LocalName == "customXmlInsRangeStart")
{
ctObj.Items.Add(CT_TrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlInsRangeStart);
}
else if (childNode.LocalName == "customXmlMoveFromRangeEnd")
{
ctObj.Items.Add(CT_Markup.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlMoveFromRangeEnd);
}
else if (childNode.LocalName == "customXmlMoveFromRangeStart")
{
ctObj.Items.Add(CT_TrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlMoveFromRangeStart);
}
else if (childNode.LocalName == "customXmlMoveToRangeEnd")
{
ctObj.Items.Add(CT_Markup.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlMoveToRangeEnd);
}
else if (childNode.LocalName == "customXmlMoveToRangeStart")
{
ctObj.Items.Add(CT_TrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.customXmlMoveToRangeStart);
}
else if (childNode.LocalName == "del")
{
ctObj.Items.Add(CT_RunTrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.del);
}
else if (childNode.LocalName == "ins")
{
ctObj.Items.Add(CT_RunTrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.ins);
}
else if (childNode.LocalName == "moveFrom")
{
ctObj.Items.Add(CT_RunTrackChange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.moveFrom);
}
else if (childNode.LocalName == "moveFromRangeEnd")
{
ctObj.Items.Add(CT_MarkupRange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.moveFromRangeEnd);
}
else if (childNode.LocalName == "moveFromRangeStart")
{
ctObj.Items.Add(CT_MoveBookmark.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.moveFromRangeStart);
}
else if (childNode.LocalName == "moveToRangeEnd")
{
ctObj.Items.Add(CT_MarkupRange.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.moveToRangeEnd);
}
else if (childNode.LocalName == "moveToRangeStart")
{
ctObj.Items.Add(CT_MoveBookmark.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.moveToRangeStart);
}
else if (childNode.LocalName == "p")
{
ctObj.Items.Add(CT_P.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.p);
}
else if (childNode.LocalName == "permEnd")
{
ctObj.Items.Add(CT_Perm.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.permEnd);
}
else if (childNode.LocalName == "permStart")
{
ctObj.Items.Add(CT_PermStart.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.permStart);
}
else if (childNode.LocalName == "proofErr")
{
ctObj.Items.Add(CT_ProofErr.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.proofErr);
}
else if (childNode.LocalName == "sdt")
{
ctObj.Items.Add(CT_SdtBlock.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.sdt);
}
else if (childNode.LocalName == "tbl")
{
ctObj.Items.Add(CT_Tbl.Parse(childNode, namespaceManager));
ctObj.ItemsElementName.Add(DocumentBodyItemChoiceType.tbl);
}
}
return ctObj;
}
public int SizeOfPArray()
{
return this.itemsElementNameField.Count(p => p == DocumentBodyItemChoiceType.p);
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<w:{0}", nodeName));
sw.Write(">");
int i=0;
foreach (object o in this.Items)
{
if (o is CT_RunTrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.moveTo)
((CT_RunTrackChange)o).Write(sw, "moveTo");
else if (o is CT_OMathPara)
((CT_OMathPara)o).Write(sw, "oMathPara");
else if (o is CT_CustomXmlBlock)
((CT_CustomXmlBlock)o).Write(sw, "customXml");
else if (o is CT_OMath)
((CT_OMath)o).Write(sw, "oMath");
else if (o is CT_AltChunk)
((CT_AltChunk)o).Write(sw, "altChunk");
else if ((o is CT_MarkupRange)&&this.itemsElementNameField[i]== DocumentBodyItemChoiceType.bookmarkEnd)
((CT_MarkupRange)o).Write(sw, "bookmarkEnd");
else if (o is CT_Bookmark && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.bookmarkStart)
((CT_Bookmark)o).Write(sw, "bookmarkStart");
else if (o is CT_MarkupRange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.commentRangeEnd)
((CT_MarkupRange)o).Write(sw, "commentRangeEnd");
else if (o is CT_MarkupRange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.commentRangeStart)
((CT_MarkupRange)o).Write(sw, "commentRangeStart");
else if (o is CT_Markup && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlDelRangeEnd)
((CT_Markup)o).Write(sw, "customXmlDelRangeEnd");
else if (o is CT_TrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlDelRangeStart)
((CT_TrackChange)o).Write(sw, "customXmlDelRangeStart");
else if (o is CT_Markup && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlInsRangeEnd)
((CT_Markup)o).Write(sw, "customXmlInsRangeEnd");
else if (o is CT_TrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlInsRangeStart)
((CT_TrackChange)o).Write(sw, "customXmlInsRangeStart");
else if (o is CT_Markup && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlMoveFromRangeEnd)
((CT_Markup)o).Write(sw, "customXmlMoveFromRangeEnd");
else if (o is CT_TrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlMoveFromRangeStart)
((CT_TrackChange)o).Write(sw, "customXmlMoveFromRangeStart");
else if (o is CT_Markup && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlMoveToRangeEnd)
((CT_Markup)o).Write(sw, "customXmlMoveToRangeEnd");
else if (o is CT_TrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.customXmlMoveToRangeStart)
((CT_TrackChange)o).Write(sw, "customXmlMoveToRangeStart");
else if (o is CT_RunTrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.del)
((CT_RunTrackChange)o).Write(sw, "del");
else if (o is CT_RunTrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.ins)
((CT_RunTrackChange)o).Write(sw, "ins");
else if (o is CT_RunTrackChange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.moveFrom)
((CT_RunTrackChange)o).Write(sw, "moveFrom");
else if (o is CT_MarkupRange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.moveFromRangeEnd)
((CT_MarkupRange)o).Write(sw, "moveFromRangeEnd");
else if (o is CT_MoveBookmark && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.moveFromRangeStart)
((CT_MoveBookmark)o).Write(sw, "moveFromRangeStart");
else if (o is CT_MarkupRange && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.moveToRangeEnd)
((CT_MarkupRange)o).Write(sw, "moveToRangeEnd");
else if (o is CT_MoveBookmark && this.itemsElementNameField[i] == DocumentBodyItemChoiceType.moveToRangeStart)
((CT_MoveBookmark)o).Write(sw, "moveToRangeStart");
else if (o is CT_P)
((CT_P)o).Write(sw, "p");
else if (o is CT_Perm)
((CT_Perm)o).Write(sw, "permEnd");
else if (o is CT_PermStart)
((CT_PermStart)o).Write(sw, "permStart");
else if (o is CT_ProofErr)
((CT_ProofErr)o).Write(sw, "proofErr");
else if (o is CT_SdtBlock)
((CT_SdtBlock)o).Write(sw, "sdt");
else if (o is CT_Tbl)
((CT_Tbl)o).Write(sw, "tbl");
i++;
}
if (this.sectPr != null)
this.sectPr.Write(sw, "sectPr");
sw.Write(string.Format("</w:{0}>", nodeName));
}
public void AddNewSectPr()
{
this.sectPrField = new CT_SectPr();
//return this.sectPrField;
}
public bool IsSetSectPr()
{
return this.sectPrField != null;
}
[XmlElement("oMath", typeof(CT_OMath), Namespace = "http://schemas.openxmlformats.org/officeDocument/2006/math", Order = 0)]
[XmlElement("oMathPara", typeof(CT_OMathPara), Namespace = "http://schemas.openxmlformats.org/officeDocument/2006/math", Order = 0)]
[XmlElement("altChunk", typeof(CT_AltChunk), Order = 0)]
[XmlElement("bookmarkEnd", typeof(CT_MarkupRange), Order = 0)]
[XmlElement("bookmarkStart", typeof(CT_Bookmark), Order = 0)]
[XmlElement("commentRangeEnd", typeof(CT_MarkupRange), Order = 0)]
[XmlElement("commentRangeStart", typeof(CT_MarkupRange), Order = 0)]
[XmlElement("customXml", typeof(CT_CustomXmlBlock), Order = 0)]
[XmlElement("customXmlDelRangeEnd", typeof(CT_Markup), Order = 0)]
[XmlElement("customXmlDelRangeStart", typeof(CT_TrackChange), Order = 0)]
[XmlElement("customXmlInsRangeEnd", typeof(CT_Markup), Order = 0)]
[XmlElement("customXmlInsRangeStart", typeof(CT_TrackChange), Order = 0)]
[XmlElement("customXmlMoveFromRangeEnd", typeof(CT_Markup), Order = 0)]
[XmlElement("customXmlMoveFromRangeStart", typeof(CT_TrackChange), Order = 0)]
[XmlElement("customXmlMoveToRangeEnd", typeof(CT_Markup), Order = 0)]
[XmlElement("customXmlMoveToRangeStart", typeof(CT_TrackChange), Order = 0)]
[XmlElement("del", Type = typeof(CT_RunTrackChange), Order = 0)]
[XmlElement("ins", Type = typeof(CT_RunTrackChange), Order = 0)]
[XmlElement("moveFrom", typeof(CT_RunTrackChange), Order = 0)]
[XmlElement("moveFromRangeEnd", typeof(CT_MarkupRange), Order = 0)]
[XmlElement("moveFromRangeStart", typeof(CT_MoveBookmark), Order = 0)]
[XmlElement("moveTo", typeof(CT_RunTrackChange), Order = 0)]
[XmlElement("moveToRangeEnd", typeof(CT_MarkupRange), Order = 0)]
[XmlElement("moveToRangeStart", typeof(CT_MoveBookmark), Order = 0)]
[XmlElement("p", typeof(CT_P), Order = 0)]
[XmlElement("permEnd", typeof(CT_Perm), Order = 0)]
[XmlElement("permStart", typeof(CT_PermStart), Order = 0)]
[XmlElement("proofErr", typeof(CT_ProofErr), Order = 0)]
[XmlElement("sdt", typeof(CT_SdtBlock), Order = 0)]
[XmlElement("tbl", typeof(CT_Tbl), Order = 0)]
[XmlChoiceIdentifier("ItemsElementName")]
public ArrayList Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
public CT_P AddNewP()
{
CT_P p = new CT_P();
lock (this)
{
this.itemsField.Add(p);
this.itemsElementNameField.Add(DocumentBodyItemChoiceType.p);
}
return p;
}
[XmlElement("ItemsElementName", Order = 1)]
[XmlIgnore]
public List<DocumentBodyItemChoiceType> ItemsElementName
{
get
{
return this.itemsElementNameField;
}
set
{
this.itemsElementNameField = value;
}
}
[XmlElement(Order = 2)]
public CT_SectPr sectPr
{
get
{
return this.sectPrField;
}
set
{
this.sectPrField = value;
}
}
public CT_Tbl AddNewTbl()
{
CT_Tbl tbl = new CT_Tbl();
lock (this)
{
this.itemsField.Add(tbl);
this.itemsElementNameField.Add(DocumentBodyItemChoiceType.tbl);
}
return tbl;
}
public int sizeOfTblArray()
{
return SizeOfArray(DocumentBodyItemChoiceType.tbl);
}
public List<CT_Tbl> getTblArray()
{
return GetObjectList<CT_Tbl>(DocumentBodyItemChoiceType.tbl);
}
public CT_Tbl insertNewTbl(int paramInt)
{
throw new NotImplementedException();
}
public void removeTbl(int paramInt)
{
throw new NotImplementedException();
}
public CT_Tbl GetTblArray(int i)
{
return GetObjectArray<CT_Tbl>(i, DocumentBodyItemChoiceType.tbl);
}
public void SetTblArray(int pos, CT_Tbl cT_Tbl)
{
SetObject<CT_Tbl>(DocumentBodyItemChoiceType.tbl, pos, cT_Tbl);
}
public CT_Tbl[] GetTblArray()
{
return GetObjectList<CT_Tbl>(DocumentBodyItemChoiceType.tbl).ToArray();
}
public CT_P GetPArray(int p)
{
return GetObjectArray<CT_P>(p, DocumentBodyItemChoiceType.p);
}
public void RemoveP(int paraPos)
{
RemoveObject(DocumentBodyItemChoiceType.p, paraPos);
}
public void RemoveTbl(int tablePos)
{
RemoveObject(DocumentBodyItemChoiceType.tbl, tablePos);
}
public CT_SdtBlock AddNewSdt()
{
return AddNewObject<CT_SdtBlock>(DocumentBodyItemChoiceType.sdt);
}
#region Generic methods for object operation
private List<T> GetObjectList<T>(DocumentBodyItemChoiceType type) where T : class
{
lock (this)
{
List<T> list = new List<T>();
for (int i = 0; i < itemsElementNameField.Count; i++)
{
if (itemsElementNameField[i] == type)
list.Add(itemsField[i] as T);
}
return list;
}
}
private int SizeOfArray(DocumentBodyItemChoiceType type)
{
lock (this)
{
int size = 0;
for (int i = 0; i < itemsElementNameField.Count; i++)
{
if (itemsElementNameField[i] == type)
size++;
}
return size;
}
}
private T GetObjectArray<T>(int p, DocumentBodyItemChoiceType type) where T : class
{
lock (this)
{
int pos = GetObjectIndex(type, p);
if (pos < 0 || pos >= this.itemsField.Count)
return null;
return itemsField[pos] as T;
}
}
private T AddNewObject<T>(DocumentBodyItemChoiceType type) where T : class, new()
{
T t = new T();
lock (this)
{
this.itemsElementNameField.Add(type);
this.itemsField.Add(t);
}
return t;
}
private void SetObject<T> (DocumentBodyItemChoiceType type, int p, T obj) where T : class
{
lock (this)
{
int pos = GetObjectIndex(type, p);
if (pos < 0 || pos >= this.itemsField.Count)
return;
if (this.itemsField[pos] is T)
this.itemsField[pos] = obj;
else
throw new Exception(string.Format(@"object types are difference, itemsField[{0}] is {1}, and parameter obj is {2}",
pos, this.itemsField[pos].GetType().Name, typeof(T).Name));
}
}
private int GetObjectIndex(DocumentBodyItemChoiceType type, int p)
{
int index = -1;
int pos = 0;
for (int i = 0; i < itemsElementNameField.Count; i++)
{
if (itemsElementNameField[i] == type)
{
if (pos == p)
{
index = i;
break;
}
else
pos++;
}
}
return index;
}
private void RemoveObject(DocumentBodyItemChoiceType type, int p)
{
lock (this)
{
int pos = GetObjectIndex(type, p);
if (pos < 0 || pos >= this.itemsField.Count)
return;
itemsElementNameField.RemoveAt(pos);
itemsField.RemoveAt(pos);
}
}
#endregion
public void SetPArray(int pos, CT_P cT_P)
{
SetObject<CT_P>(DocumentBodyItemChoiceType.p, pos, cT_P);
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IncludeInSchema = false)]
public enum DocumentBodyItemChoiceType
{
[XmlEnum("http://schemas.openxmlformats.org/officeDocument/2006/math:oMath")]
oMath,
[XmlEnum("http://schemas.openxmlformats.org/officeDocument/2006/math:oMathPara")]
oMathPara,
altChunk,
bookmarkEnd,
bookmarkStart,
commentRangeEnd,
commentRangeStart,
customXml,
customXmlDelRangeEnd,
customXmlDelRangeStart,
customXmlInsRangeEnd,
customXmlInsRangeStart,
customXmlMoveFromRangeEnd,
customXmlMoveFromRangeStart,
customXmlMoveToRangeEnd,
customXmlMoveToRangeStart,
del,
ins,
moveFrom,
moveFromRangeEnd,
moveFromRangeStart,
moveTo,
moveToRangeEnd,
moveToRangeStart,
/// <summary>
/// Paragraph
/// </summary>
p,
permEnd,
permStart,
proofErr,
sdt,
tbl,
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocParts
{
private List<CT_DocPart> itemsField;
public CT_DocParts()
{
this.itemsField = new List<CT_DocPart>();
}
[XmlElement("docPart", Order = 0)]
public List<CT_DocPart> Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPart
{
private CT_DocPartPr docPartPrField;
private CT_Body docPartBodyField;
public CT_DocPart()
{
//this.docPartBodyField = new CT_Body();
//this.docPartPrField = new CT_DocPartPr();
}
[XmlElement(Order = 0)]
public CT_DocPartPr docPartPr
{
get
{
return this.docPartPrField;
}
set
{
this.docPartPrField = value;
}
}
[XmlElement(Order = 1)]
public CT_Body docPartBody
{
get
{
return this.docPartBodyField;
}
set
{
this.docPartBodyField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartPr
{
private object[] itemsField;
private ItemsChoiceType11[] itemsElementNameField;
public CT_DocPartPr()
{
this.itemsElementNameField = new ItemsChoiceType11[0];
this.itemsField = new object[0];
}
[XmlElement("behaviors", typeof(CT_DocPartBehaviors), Order = 0)]
[XmlElement("category", typeof(CT_DocPartCategory), Order = 0)]
[XmlElement("description", typeof(CT_String), Order = 0)]
[XmlElement("guid", typeof(CT_Guid), Order = 0)]
[XmlElement("name", typeof(CT_DocPartName), Order = 0)]
[XmlElement("style", typeof(CT_String), Order = 0)]
[XmlElement("types", typeof(CT_DocPartTypes), Order = 0)]
[XmlChoiceIdentifier("ItemsElementName")]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
[XmlElement("ItemsElementName", Order = 1)]
[XmlIgnore]
public ItemsChoiceType11[] ItemsElementName
{
get
{
return this.itemsElementNameField;
}
set
{
this.itemsElementNameField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartBehaviors
{
private List<CT_DocPartBehavior> itemsField;
public CT_DocPartBehaviors()
{
this.itemsField = new List<CT_DocPartBehavior>();
}
[XmlElement("behavior", Order = 0)]
public List<CT_DocPartBehavior> Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartBehavior
{
private ST_DocPartBehavior valField;
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public ST_DocPartBehavior val
{
get
{
return this.valField;
}
set
{
this.valField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public enum ST_DocPartBehavior
{
content,
p,
pg,
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartCategory
{
private CT_String nameField;
private CT_DocPartGallery galleryField;
public CT_DocPartCategory()
{
this.galleryField = new CT_DocPartGallery();
this.nameField = new CT_String();
}
[XmlElement(Order = 0)]
public CT_String name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
[XmlElement(Order = 1)]
public CT_DocPartGallery gallery
{
get
{
return this.galleryField;
}
set
{
this.galleryField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartGallery
{
private ST_DocPartGallery valField;
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public ST_DocPartGallery val
{
get
{
return this.valField;
}
set
{
this.valField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public enum ST_DocPartGallery
{
placeholder,
any,
@default,
docParts,
coverPg,
eq,
ftrs,
hdrs,
pgNum,
tbls,
watermarks,
autoTxt,
txtBox,
pgNumT,
pgNumB,
pgNumMargins,
tblOfContents,
bib,
custQuickParts,
custCoverPg,
custEq,
custFtrs,
custHdrs,
custPgNum,
custTbls,
custWatermarks,
custAutoTxt,
custTxtBox,
custPgNumT,
custPgNumB,
custPgNumMargins,
custTblOfContents,
custBib,
custom1,
custom2,
custom3,
custom4,
custom5,
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartName
{
private string valField;
private ST_OnOff decoratedField;
private bool decoratedFieldSpecified;
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public string val
{
get
{
return this.valField;
}
set
{
this.valField = value;
}
}
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public ST_OnOff decorated
{
get
{
return this.decoratedField;
}
set
{
this.decoratedField = value;
}
}
[XmlIgnore]
public bool decoratedSpecified
{
get
{
return this.decoratedFieldSpecified;
}
set
{
this.decoratedFieldSpecified = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartTypes
{
private List<CT_DocPartType> itemsField;
private ST_OnOff allField;
private bool allFieldSpecified;
public CT_DocPartTypes()
{
this.itemsField = new List<CT_DocPartType>();
}
[XmlElement("type", Order = 0)]
public List<CT_DocPartType> Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public ST_OnOff all
{
get
{
return this.allField;
}
set
{
this.allField = value;
}
}
[XmlIgnore]
public bool allSpecified
{
get
{
return this.allFieldSpecified;
}
set
{
this.allFieldSpecified = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocPartType
{
private ST_DocPartType valField;
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public ST_DocPartType val
{
get
{
return this.valField;
}
set
{
this.valField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public enum ST_DocPartType
{
none,
normal,
autoExp,
toolbar,
speller,
formFld,
bbPlcHdr,
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IncludeInSchema = false)]
public enum ItemsChoiceType11
{
behaviors,
category,
description,
guid,
name,
style,
types,
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocGrid
{
private ST_DocGrid typeField;
private bool typeFieldSpecified;
private string linePitchField;
private string charSpaceField;
public CT_DocGrid()
{
this.type = ST_DocGrid.@default;
}
public static CT_DocGrid Parse(XmlNode node, XmlNamespaceManager namespaceManager)
{
if (node == null)
return null;
CT_DocGrid ctObj = new CT_DocGrid();
if (node.Attributes["w:type"] != null)
ctObj.type = (ST_DocGrid)Enum.Parse(typeof(ST_DocGrid), node.Attributes["w:type"].Value);
ctObj.linePitch = XmlHelper.ReadString(node.Attributes["w:linePitch"]);
ctObj.charSpace = XmlHelper.ReadString(node.Attributes["w:charSpace"]);
return ctObj;
}
internal void Write(StreamWriter sw, string nodeName)
{
sw.Write(string.Format("<w:{0}", nodeName));
if(this.type!= ST_DocGrid.@default)
XmlHelper.WriteAttribute(sw, "w:type", this.type.ToString());
XmlHelper.WriteAttribute(sw, "w:linePitch", this.linePitch);
XmlHelper.WriteAttribute(sw, "w:charSpace", this.charSpace);
sw.Write("/>");
}
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public ST_DocGrid type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
[XmlIgnore]
public bool typeSpecified
{
get
{
return this.typeFieldSpecified;
}
set
{
this.typeFieldSpecified = value;
}
}
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, DataType = "integer")]
public string linePitch
{
get
{
return this.linePitchField;
}
set
{
this.linePitchField = value;
}
}
[XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, DataType = "integer")]
public string charSpace
{
get
{
return this.charSpaceField;
}
set
{
this.charSpaceField = value;
}
}
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public enum ST_DocGrid
{
@default,
lines,
linesAndChars,
snapToChars,
}
[Serializable]
[XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)]
public class CT_DocVars
{
private List<CT_DocVar> docVarField;
public CT_DocVars()
{
this.docVarField = new List<CT_DocVar>();
}
[XmlElement("docVar", Order = 0)]
public List<CT_DocVar> docVar
{
get
{
return this.docVarField;
}
set
{
this.docVarField = value;
}
}
}
}
| 30.276378 | 176 | 0.540179 | [
"Apache-2.0"
] | Yvees/npoi | OpenXmlFormats/Wordprocessing/Document.cs | 44,478 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Irony.Parsing;
namespace NCTU
{
public class Resolver : NCTU.IASTResolver
{
#region IASTResolver Members
public IList<NCTU.Declaration> FindCompletions(object result, int line, int col)
{
// Used for intellisense.
List<NCTU.Declaration> declarations = new List<NCTU.Declaration>();
// Add keywords defined by grammar
foreach (KeyTerm key in Configuration.Grammar.KeyTerms.Values)
{
if (key.OptionIsSet(TermOptions.IsKeyword))
{
declarations.Add(new Declaration("", key.Name, 206, key.Name));
}
}
declarations.Sort();
return declarations;
}
public IList<NCTU.Declaration> FindMembers(object result, int line, int col)
{
List<NCTU.Declaration> members = new List<NCTU.Declaration>();
return members;
}
public string FindQuickInfo(object result, int line, int col)
{
return "unknown";
}
public IList<NCTU.Method> FindMethods(object result, int line, int col, string name)
{
return new List<NCTU.Method>();
}
#endregion
}
}
| 27.235294 | 93 | 0.550036 | [
"Unlicense",
"MIT"
] | OpenISDM/R-TIBS | source code/gpl language/gpl language/Integration/Resolver.cs | 1,389 | C# |
using System.Diagnostics;
using EcsRx.Components;
using EcsRx.Components.Database;
using EcsRx.Components.Lookups;
using EcsRx.Groups;
using EcsRx.Plugins.Batching.Batches;
using EcsRx.Plugins.Batching.Builders;
using EcsRx.Plugins.Batching.Factories;
using EcsRx.Threading;
namespace EcsRx.Plugins.Batching.Systems
{
public abstract unsafe class BatchedSystem<T1, T2> : ManualBatchedSystem
where T1 : unmanaged, IComponent
where T2 : unmanaged, IComponent
{
public override IGroup Group { get; } = new Group(typeof(T1), typeof(T2));
private readonly IBatchBuilder<T1, T2> _batchBuilder;
protected Batch<T1, T2>[] _batches;
protected abstract void Process(int entityId, ref T1 component1, ref T2 component2);
protected BatchedSystem(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup,
IBatchBuilderFactory batchBuilderFactory, IThreadHandler threadHandler) : base(componentDatabase,
componentTypeLookup, threadHandler)
{
_batchBuilder = batchBuilderFactory.Create<T1, T2>();
}
protected override void RebuildBatch()
{ _batches = _batchBuilder.Build(ObservableGroup); }
protected override void ProcessBatch()
{
if (ShouldParallelize)
{
ThreadHandler.For(0, _batches.Length, i =>
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2);
});
return;
}
for (var i = 0; i < _batches.Length; i++)
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2);
}
}
}
public abstract unsafe class BatchedSystem<T1, T2, T3> : ManualBatchedSystem
where T1 : unmanaged, IComponent
where T2 : unmanaged, IComponent
where T3 : unmanaged, IComponent
{
public override IGroup Group { get; } = new Group(typeof(T1), typeof(T2), typeof(T3));
private readonly IBatchBuilder<T1, T2, T3> _batchBuilder;
protected Batch<T1, T2, T3>[] _batches;
protected abstract void Process(int entityId, ref T1 component1, ref T2 component2, ref T3 component3);
protected BatchedSystem(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup,
IBatchBuilderFactory batchBuilderFactory, IThreadHandler threadHandler) : base(componentDatabase,
componentTypeLookup, threadHandler)
{
_batchBuilder = batchBuilderFactory.Create<T1, T2, T3>();
}
protected override void RebuildBatch()
{ _batches = _batchBuilder.Build(ObservableGroup); }
protected override void ProcessBatch()
{
if (ShouldParallelize)
{
ThreadHandler.For(0, _batches.Length, i =>
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2, ref *batch.Component3);
});
return;
}
for (var i = 0; i < _batches.Length; i++)
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2, ref *batch.Component3);
}
}
}
public abstract unsafe class BatchedSystem<T1, T2, T3, T4> : ManualBatchedSystem
where T1 : unmanaged, IComponent
where T2 : unmanaged, IComponent
where T3 : unmanaged, IComponent
where T4 : unmanaged, IComponent
{
public override IGroup Group { get; } = new Group(typeof(T1), typeof(T2), typeof(T3), typeof(T4));
private readonly IBatchBuilder<T1, T2, T3, T4> _batchBuilder;
protected Batch<T1, T2, T3, T4>[] _batches;
protected abstract void Process(int entityId, ref T1 component1, ref T2 component2, ref T3 component3, ref T4 component4);
protected BatchedSystem(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup,
IBatchBuilderFactory batchBuilderFactory, IThreadHandler threadHandler) : base(componentDatabase,
componentTypeLookup, threadHandler)
{
_batchBuilder = batchBuilderFactory.Create<T1, T2, T3, T4>();
}
protected override void RebuildBatch()
{ _batches = _batchBuilder.Build(ObservableGroup); }
protected override void ProcessBatch()
{
if (ShouldParallelize)
{
ThreadHandler.For(0, _batches.Length, i =>
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2,
ref *batch.Component3, ref *batch.Component4);
});
return;
}
for (var i = 0; i < _batches.Length; i++)
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2,
ref *batch.Component3, ref *batch.Component4);
}
}
}
public abstract unsafe class BatchedSystem<T1, T2, T3, T4, T5> : ManualBatchedSystem
where T1 : unmanaged, IComponent
where T2 : unmanaged, IComponent
where T3 : unmanaged, IComponent
where T4 : unmanaged, IComponent
where T5 : unmanaged, IComponent
{
public override IGroup Group { get; } = new Group(typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5));
private readonly IBatchBuilder<T1, T2, T3, T4, T5> _batchBuilder;
protected Batch<T1, T2, T3, T4, T5>[] _batches;
protected abstract void Process(int entityId, ref T1 component1, ref T2 component2, ref T3 component3, ref T4 component4, ref T5 component5);
protected BatchedSystem(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup,
IBatchBuilderFactory batchBuilderFactory, IThreadHandler threadHandler) : base(componentDatabase,
componentTypeLookup, threadHandler)
{
_batchBuilder = batchBuilderFactory.Create<T1, T2, T3, T4, T5>();
}
protected override void RebuildBatch()
{ _batches = _batchBuilder.Build(ObservableGroup); }
protected override void ProcessBatch()
{
if (ShouldParallelize)
{
ThreadHandler.For(0, _batches.Length, i =>
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2,
ref *batch.Component3, ref *batch.Component4, ref *batch.Component5);
});
return;
}
for (var i = 0; i < _batches.Length; i++)
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2,
ref *batch.Component3, ref *batch.Component4, ref *batch.Component5);
}
}
}
public abstract unsafe class BatchedSystem<T1, T2, T3, T4, T5, T6> : ManualBatchedSystem
where T1 : unmanaged, IComponent
where T2 : unmanaged, IComponent
where T3 : unmanaged, IComponent
where T4 : unmanaged, IComponent
where T5 : unmanaged, IComponent
where T6 : unmanaged, IComponent
{
public override IGroup Group { get; } = new Group(typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6));
private readonly IBatchBuilder<T1, T2, T3, T4, T5, T6> _batchBuilder;
protected Batch<T1, T2, T3, T4, T5, T6>[] _batches;
protected abstract void Process(int entityId, ref T1 component1, ref T2 component2, ref T3 component3, ref T4 component4, ref T5 component5, ref T6 component6);
protected BatchedSystem(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup,
IBatchBuilderFactory batchBuilderFactory, IThreadHandler threadHandler) : base(componentDatabase,
componentTypeLookup, threadHandler)
{
_batchBuilder = batchBuilderFactory.Create<T1, T2, T3, T4, T5, T6>();
}
protected override void RebuildBatch()
{ _batches = _batchBuilder.Build(ObservableGroup); }
protected override void ProcessBatch()
{
if (ShouldParallelize)
{
ThreadHandler.For(0, _batches.Length, i =>
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2,
ref *batch.Component3, ref *batch.Component4, ref *batch.Component5,
ref *batch.Component6);
});
return;
}
for (var i = 0; i < _batches.Length; i++)
{
ref var batch = ref _batches[i];
Process(batch.EntityId, ref *batch.Component1, ref *batch.Component2,
ref *batch.Component3, ref *batch.Component4, ref *batch.Component5,
ref *batch.Component6);
}
}
}
} | 41.114894 | 168 | 0.593769 | [
"MIT"
] | BCKWorks/ecsrx | Runtime/EcsRx.Plugins.Batching/Systems/BatchedSystem.cs | 9,662 | C# |
#region Copyright
/*
--------------------------------------------------------------------------------
This source file is part of Xenocide
by Project Xenocide Team
For the latest info on Xenocide, see http://www.projectxenocide.com/
This work is licensed under the Creative Commons
Attribution-NonCommercial-ShareAlike 2.5 License.
To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/2.5/
or send a letter to Creative Commons, 543 Howard Street, 5th Floor,
San Francisco, California, 94105, USA.
--------------------------------------------------------------------------------
*/
/*
* @file GameOverGeoEvent.cs
* @date Created: 2007/11/12
* @author File creator: dteviot
* @author Credits: none
*/
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using ProjectXenocide.Utils;
using ProjectXenocide.UI.Dialogs;
using ProjectXenocide.UI.Screens;
#endregion
namespace ProjectXenocide.Model.Geoscape.GeoEvents
{
/// <summary>
/// Geoevent that tells user Game is over
/// </summary>
[Serializable]
public class GameOverGeoEvent : GeoEvent
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="format">Message to show including formatting</param>
/// <param name="args">values to inject into formatting string</param>
public GameOverGeoEvent(string format, params Object[] args)
{
this.message = Util.StringFormat(format, args);
}
/// <summary>
/// Called to get the event to do whatever processing is necessary
/// </summary>
public override void Process()
{
Xenocide.GameState.GeoData.GeoTime.StopTime();
MessageBoxDialog dialog = new MessageBoxDialog(message);
dialog.OkAction += delegate()
{
Xenocide.ScreenManager.ScheduleScreen(new StartScreen());
// ToDo, may need to purge the Geoevent queue
};
Xenocide.ScreenManager.ShowDialog(dialog);
}
#region Fields
/// <summary>
/// Message to show
/// </summary>
private String message;
#endregion
}
}
| 28.463415 | 81 | 0.580548 | [
"MIT"
] | astyanax/Project-Xenocide | xna/branches/Unreviewed_Patches_branch/Xenocide/Source/Model/Geoscape/GeoEvents/GameOverGeoEvent.cs | 2,334 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
public class GitHub_18144
{
[MethodImpl(MethodImplOptions.NoInlining)]
static void dummy(Vector256<byte> v1, Vector256<byte> v2, Vector256<byte> v3, Vector256<byte> v4,
Vector256<byte> v5, Vector256<byte> v6, Vector256<byte> v7, Vector256<byte> v8)
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void DoThis()
{
var vA = Vector256.Create((byte)0xa);
var vB = Vector256.Create((byte)0xb);
var vC = Vector256.Create((byte)0xc);
var vD = Vector256.Create((byte)0xd);
var vE = Vector256.Create((byte)0xe);
var vF = Vector256.Create((byte)0xf);
var vG = Vector256.Create((byte)0x8);
var vH = Vector256.Create((byte)0x9);
dummy(vA, vB, vC, vD, vE, vF, vG, vH);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void DoThat() { }
[MethodImpl(MethodImplOptions.NoInlining)]
static void dummy128(Vector128<byte> v1, Vector128<byte> v2, Vector128<byte> v3, Vector128<byte> v4,
Vector128<byte> v5, Vector128<byte> v6, Vector128<byte> v7, Vector128<byte> v8)
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void DoThis128()
{
var vA = Vector128.Create((byte)0xa);
var vB = Vector128.Create((byte)0xb);
var vC = Vector128.Create((byte)0xc);
var vD = Vector128.Create((byte)0xd);
var vE = Vector128.Create((byte)0xe);
var vF = Vector128.Create((byte)0xf);
var vG = Vector128.Create((byte)0x8);
var vH = Vector128.Create((byte)0x9);
dummy128(vA, vB, vC, vD, vE, vF, vG, vH);
}
static int Main(string[] args)
{
int returnVal = 100;
var xA = Vector256<byte>.Zero;
var xB = Vector256<byte>.Zero;
var xC = Vector256<byte>.Zero;
var xD = Vector256<byte>.Zero;
var xE = Vector256<byte>.Zero;
var xF = Vector256<byte>.Zero;
var xG = Vector256<byte>.Zero;
var xH = Vector256<byte>.Zero;
DoThis();
DoThat();
Console.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7}", xA, xB, xC, xD, xE, xF, xG, xH);
if (!xA.Equals(Vector256<byte>.Zero) || !xB.Equals(Vector256<byte>.Zero) || !xC.Equals(Vector256<byte>.Zero) || !xD.Equals(Vector256<byte>.Zero) ||
!xE.Equals(Vector256<byte>.Zero) || !xF.Equals(Vector256<byte>.Zero) || !xG.Equals(Vector256<byte>.Zero) || !xH.Equals(Vector256<byte>.Zero))
{
returnVal = -1;
}
var vA = Vector128<byte>.Zero;
var vB = Vector128<byte>.Zero;
var vC = Vector128<byte>.Zero;
var vD = Vector128<byte>.Zero;
var vE = Vector128<byte>.Zero;
var vF = Vector128<byte>.Zero;
var vG = Vector128<byte>.Zero;
var vH = Vector128<byte>.Zero;
DoThis128();
DoThat();
Console.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7}", vA, vB, vC, vD, vE, vF, vG, vH);
if (!vA.Equals(Vector128<byte>.Zero) || !vB.Equals(Vector128<byte>.Zero) || !vC.Equals(Vector128<byte>.Zero) || !vD.Equals(Vector128<byte>.Zero) ||
!vE.Equals(Vector128<byte>.Zero) || !vF.Equals(Vector128<byte>.Zero) || !vG.Equals(Vector128<byte>.Zero) || !vH.Equals(Vector128<byte>.Zero))
{
returnVal = -1;
}
return returnVal;
}
}
| 36.87 | 155 | 0.598047 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/JIT/Regression/JitBlue/GitHub_18144/GitHub_18144.cs | 3,687 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class frmBookEdition : DBUtility
{
string strQry = "";
DataSet dsObj = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fGrid();
}
}
protected void fGrid()
{
strQry = "usp_BookEdition @command='select',@intSchool_id='" + Convert.ToString(Session["School_id"]) + "'";
dsObj = sGetDataset(strQry);
if (dsObj.Tables[0].Rows.Count > 0)
{
grvDetail.DataSource = dsObj;
grvDetail.DataBind();
txtName.Text = "";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text == "")
{
MessageBox("Please Insert book Edition!");
txtName.Focus();
return;
}
if (btnSubmit.Text == "Submit")
{
strQry = "usp_BookEdition @command='checkExist',@vchBookEdition_name='" + Convert.ToString(txtName.Text.Trim()) + "',@intSchool_id='" + Convert.ToString(Session["School_id"]) + "'";
dsObj = sGetDataset(strQry);
if (dsObj.Tables[0].Rows.Count > 0)
{
MessageBox("Record Already Exists");
return;
}
else
{
strQry = "exec [usp_BookEdition] @command='insert',@vchBookEdition_name='" + Convert.ToString(txtName.Text.Trim()) + "',@intSchool_id='" + Convert.ToString(Session["School_id"]) + "',@intInsertedBy='" + Session["User_id"] + "',@insertIP='" + GetSystemIP() + "'";
if (sExecuteQuery(strQry) != -1)
{
fGrid();
MessageBox("Record Inserted Successfully!");
}
}
}
else
{
strQry = "usp_BookEdition @command='checkExist',@vchBookEdition_name='" + Convert.ToString(txtName.Text.Trim()) + "',@intSchool_id='" + Convert.ToString(Session["School_id"]) + "'";
dsObj = sGetDataset(strQry);
if (dsObj.Tables[0].Rows.Count > 0)
{
MessageBox("Record Already Exists");
return;
}
else
{
strQry = "exec [usp_BookEdition] @command='update',@vchBookEdition_name='" + Convert.ToString(txtName.Text.Trim()) + "',@intBookEdition_id='" + Convert.ToString(Session["BookEditionID"]) + "',@intSchool_id='" + Convert.ToString(Session["School_id"]) + "',@intUpdatedBy='" + Session["User_id"] + "',@UpdatedIP='" + GetSystemIP() + "'";
if (sExecuteQuery(strQry) != -1)
{
fGrid();
MessageBox("Record Updated Successfully!");
TabContainer1.ActiveTabIndex = 0;
btnSubmit.Text = "Submit";
}
}
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
txtName.Text = "";
btnSubmit.Text = "Submit";
}
public void MessageBox(string msg)
{
try
{
string script = "alert(\"" + msg + "\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
catch (Exception)
{
// return msg;
}
}
protected void grvDetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
Session["BookEditionID"] = Convert.ToString(grvDetail.DataKeys[e.RowIndex].Value);
strQry = "";
strQry = "exec [usp_BookEdition] @command='delete',@intBookEdition_id='" + Convert.ToString(Session["BookEditionID"]) + "',@intSchool_id='" + Convert.ToString(Session["School_id"]) + "',@intDeletedBy='" + Session["User_Id"] + "',@deletedIP='" + GetSystemIP() + "'";
if (sExecuteQuery(strQry) != -1)
{
fGrid();
MessageBox("Record Deleted Successfully!");
}
}
catch
{
}
}
protected void grvDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
Session["BookEditionID"] = Convert.ToString(grvDetail.DataKeys[e.NewEditIndex].Value);
strQry = "";
strQry = "exec usp_BookEdition @command='edit',@intBookEdition_id='" + Convert.ToString(Session["BookEditionID"]) + "',@intSchool_id='" + Convert.ToString(Session["School_id"]) + "'";
dsObj = sGetDataset(strQry);
if (dsObj.Tables[0].Rows.Count > 0)
{
txtName.Text = Convert.ToString(dsObj.Tables[0].Rows[0]["vchBookEdition_name"]);
TabContainer1.ActiveTabIndex = 1;
btnSubmit.Text = "Update";
}
}
catch
{
}
}
}
| 35.464789 | 350 | 0.532367 | [
"MIT"
] | EfficaciousIT/CMS_WEB | frmBookEdition.aspx.cs | 5,038 | C# |
using System.ComponentModel.DataAnnotations;
using CourseLibrary.API.ValidationAttributes;
namespace CourseLibrary.API.Models
{
[CourseTitleDescription(ErrorMessage = "The provided description should be different from the title")]
public abstract class CourseForManipulationDto
{
[Required(ErrorMessage = "You should fill out a title")]
[MaxLength(100)]
public string Title { get; set; }
[MaxLength(1500)]
public virtual string Description { get; set; }
}
} | 34.266667 | 106 | 0.712062 | [
"MIT"
] | nhalflants/Courses-Library-API | Models/CourseForManipulationDto.cs | 514 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour
{
public float lookRadius = 10f;
public bool isAttack;
public Player_Dodge_Hit_Die player_Dodge;
public Transform target;
//public HealthBar healthbar;
NavMeshAgent agent;
public Animator animator;
public float coolDown = 1f;
public float coolDownTimer = 1f;
public int maxhealth = 100;
public int currenthealth;
public GameObject gameobject;
public float deathCoolDown = 1f;
public float deathTimer;
bool isDead = false;
public GameObject Object;
// Start is called before the first frame update
void Start()
{
currenthealth = maxhealth;
target = PlayerManager.instance.player.transform;
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate()
{
float distance = Vector3.Distance(target.position, transform.position);
if(distance <=lookRadius && !isDead)
{
agent.SetDestination(target.position);
animator.SetBool("attack_short_001", false);
animator.SetBool("idle_combat", true);
if (distance <=agent.stoppingDistance)
{
FaceTarget();
//animator.SetBool("attack", true);
if(coolDownTimer >0)
{
coolDownTimer -= Time.deltaTime;
}
else if(coolDownTimer<=0)
{
coolDownTimer = 0;
}
if(coolDownTimer ==0)
{
animator.SetBool("idle_combat", false);
EnemyAttack();
coolDownTimer = coolDown;
}
}
}
}
public void EnemyAttack()
{
isAttack = true;
animator.SetBool("attack_short_001", true);
player_Dodge.takeDamage(25);
}
public void FaceTarget()
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
public void TakeDamage()
{
currenthealth -= 40;
if(currenthealth<=0)
{
currenthealth = 0;
Death();
}
animator.SetBool("damage_001", true);
}
public void Death()
{
animator.SetBool("dead", true);
Score_card.score += 250;
isDead = true;
}
}
| 25.973684 | 100 | 0.566025 | [
"MIT"
] | abhisheksangwan/The-Lost-Princess | Assets/Scripts/Controllers/Enemies/EnemyController.cs | 2,961 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace UserExcercise
{
class UserManager
{
IProvideData DataProvider;
SelectionMenu SelectionMenu;
User ActiveUser;
public UserManager(IProvideData dataprovider,User activeuser)
{
DataProvider = dataprovider;
SelectionMenu = new SelectionMenu();
ActiveUser = activeuser;
}
public void ShowDetails()
{
Console.Clear();
Console.WriteLine("Details");
Console.WriteLine("Username : " + ActiveUser.Username + Environment.NewLine + "Password : " + ActiveUser.Password + Environment.NewLine + "As : " + ActiveUser.UsersPrivilege.ToString("g"));
Console.ReadKey();
return;
}
public void UpdateUser()
{
List<string> ListOfPossibleUsers = DataProvider.ReadUsers().Select(u => u.Username).ToList();
ListOfPossibleUsers.Remove(ActiveUser.Username);
if (ListOfPossibleUsers.Count==0)
{
Console.WriteLine("No user found");
Console.ReadKey();
return;
}
else
{
ListOfPossibleUsers.Add("Back");
string UserToBeUpdated = SelectionMenu.Vertical(ListOfPossibleUsers).NameOfChoice;
List<User> ListOfAllUsers = DataProvider.ReadUsers();
if (UserToBeUpdated == "Back")
{
return;
}
else
{
User selecteduser = DataProvider.ReadUsers().Single(us => us.Username == UserToBeUpdated);
Privilege NewUserPrivilege = (Privilege)SelectionMenu.Vertical(new List<string> { "admin", "user", "guest" }, $"Choose the privileges of {selecteduser.Username}").IndexOfChoice;
DataProvider.UpdateUserAccess(selecteduser, NewUserPrivilege);
}
}
}
public void CreateUser()
{
LoginOrSignup CreateNewUser = new LoginOrSignup(DataProvider);
User u2 = new User()
{
Username = CreateNewUser.ReadUsername(),
Password = CreateNewUser.ReadPassword(),
UsersPrivilege = Privilege.user
};
DataProvider.CreateUser(u2);
Console.WriteLine($"User \"{u2.Username}\" has been created!");
}
public void Disable()
{
List<string> usersList = DataProvider.ReadUsers().Where(u=>u.UserId!= ActiveUser.UserId).Select(u => u.Username).ToList();
if (usersList.Count==0)
{
Console.WriteLine("No user found");
Console.ReadKey();
return;
}
else
{
usersList.Add("Back");
string userToDelete = SelectionMenu.Vertical(usersList).NameOfChoice;
if (userToDelete == "Back")
{
return;
}
else
{
User selecteduser = DataProvider.ReadUsers().Single(us => us.Username == userToDelete);
DataProvider.DeleteSelectedUser(selecteduser);
}
}
}
}
}
| 34.918367 | 201 | 0.528054 | [
"Apache-2.0"
] | MelinaPapadopoulou/User-Communication | UserExcercise/Actions/UserManager.cs | 3,424 | C# |
using System.ComponentModel;
namespace Cake.AppCenter.Enums
{
public enum Platform
{
Java = 0,
[Description("Objective-C-Swift")]
ObjectiveC_Swift,
UWP,
Cordova,
[Description("React-Native")]
ReactNative,
Xamarin
}
public enum OperatingSystem
{
Android = 0,
iOS,
macOS,
Tizen,
tvOS,
Windows
}
public enum ErrorCode
{
BadRequest = 0,
Conflict,
NotAcceptable,
NotFound,
InternalServerError,
Unauthorized,
TooManyRequests
}
public enum Origin
{
[Description("mobile-center")]
mobile_center=0,
hockeyapp,
codepush
}
public enum OwnerType
{
Org = 0,
User
}
public enum MemberType
{
Manager = 0,
Developer,
Viewer,
Tester
}
} | 15.783333 | 42 | 0.501584 | [
"MIT"
] | AnthonyArzola/Cake.AppCenter | Cake.AppCenter/Enums/Enums.cs | 949 | C# |
using System.Linq;
namespace T4TW.Syntax
{
partial class Scanner
{
private readonly char[] whitespaceChars =
new char[] {
' ', '\t', '\r', '\n'
};
private bool IsWhitespaceChar(char chr) => this.whitespaceChars.Contains(chr);
}
} | 16.733333 | 80 | 0.641434 | [
"MIT"
] | aikixd/T4TheWin | T4TW.VS.Syntax/AutoGenerated/T4TW.Syntax/Scanner.ext.cs | 253 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace eRestoran.Data.Migrations
{
public partial class AddedOpisJela : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Opis",
table: "Meni",
nullable: false,
defaultValue: 0);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Opis",
table: "Meni");
}
}
}
| 25.5 | 71 | 0.55719 | [
"MIT"
] | nukicbelma/eRestaurant | eRestoran/Data/Migrations/20210301144540_AddedOpisJela.cs | 614 | C# |
using System.Web;
using System.Web.Optimization;
namespace TestWebApp
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 38.548387 | 113 | 0.582427 | [
"MIT"
] | ashwinmEnvitics/NewTestProject | TestWebApp/TestWebApp/App_Start/BundleConfig.cs | 1,197 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EmpowerBusiness
{
using System;
public partial class Eval_ReportSalesByRep_Result
{
public string RepName { get; set; }
public string LocationName { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string ProductName { get; set; }
public int SalesCount { get; set; }
}
}
| 34.740741 | 85 | 0.52452 | [
"Apache-2.0"
] | HaloImageEngine/EmpowerClaim-hotfix-1.25.1 | EmpowerBusiness/Eval_ReportSalesByRep_Result.cs | 938 | C# |
using System;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using Xappy.Content.Scenarios.OtherLogin.Controls;
using Xappy.iOS.Renderers;
[assembly: ExportRenderer(typeof(PressableView), typeof(PressableViewRenderer))]
namespace Xappy.iOS.Renderers
{
public class PressableViewRenderer : VisualElementRenderer<PressableView>
{
public PressableViewRenderer()
{
UserInteractionEnabled = true;
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
Element?.RaisePressed();
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
Element?.RaiseReleased();
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
Element?.RaiseReleased();
}
}
}
| 24.285714 | 80 | 0.648039 | [
"MIT"
] | Arturo-Aguilar/Fast-Fud- | Xappy/Xappy.iOS/Renderers/PressableViewRenderer.cs | 1,022 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace OpenMetaverse.TestClient
{
public enum CommandCategory : int
{
Parcel,
Appearance,
Movement,
Simulator,
Communication,
Inventory,
Objects,
Voice,
TestClient,
Friends,
Groups,
Other,
Unknown
}
public abstract class Command : IComparable
{
public string Name;
public string Description;
public CommandCategory Category;
public TestClient Client;
public abstract string Execute(string[] args, UUID fromAgentID);
/// <summary>
/// When set to true, think will be called.
/// </summary>
public bool Active;
/// <summary>
/// Called twice per second, when Command.Active is set to true.
/// </summary>
public virtual void Think()
{
}
public int CompareTo(object obj)
{
if (obj is Command)
{
Command c2 = (Command)obj;
return Category.CompareTo(c2.Category);
}
else
throw new ArgumentException("Object is not of type Command.");
}
}
}
| 20.442623 | 78 | 0.584603 | [
"BSD-3-Clause"
] | jhs/libopenmetaverse | Programs/examples/TestClient/Command.cs | 1,247 | C# |
using JetBrains.Annotations;
using UnityEditor;
namespace UGF.CustomSettings.Editor.Tests
{
public static class TestSettingsEditorPackage
{
public static CustomSettingsEditorPackage<TestSettingsEditorData> Settings { get; } = new CustomSettingsEditorPackage<TestSettingsEditorData>
(
"UGF.Test.Editor.Package",
"TestEditorPackageSettings",
CustomSettingsEditorUtility.DEFAULT_PACKAGE_FOLDER
)
{
ForceCreation = true
};
[SettingsProvider, UsedImplicitly]
private static SettingsProvider GetSettingsProvider()
{
return new CustomSettingsProvider<TestSettingsEditorData>("Project/Test/Editor Package", Settings, SettingsScope.Project);
}
}
}
| 31.4 | 149 | 0.68535 | [
"MIT"
] | unity-game-framework/ugf-customsettings | Assets/UGF.CustomSettings.Editor.Tests/TestSettingsEditorPackage.cs | 785 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list of conditions
// and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// - Neither the name of Daniel Kollmann nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using Brainiac.Design;
using DesignMode.Properties;
namespace DesignMode
{
public class DesignMode : Plugin
{
public DesignMode()
{
// register resource manager
AddResourceManager(Resources.ResourceManager);
NodeGroup design= new NodeGroup("Design", NodeIcon.FlagRed, null);
_nodeGroups.Add(design);
design.Items.Add(typeof(Nodes.ActionDesign));
design.Items.Add(typeof(Nodes.CompositeDesign));
design.Items.Add(typeof(Nodes.ConditionDesign));
design.Items.Add(typeof(Nodes.DecoratorDesign));
design.Items.Add(typeof(Nodes.ImpulseDesign));
design.Items.Add(typeof(Events.EventDesign));
// register all the file managers
_fileManagers.Add( new FileManagerInfo(typeof(Brainiac.Design.FileManagers.FileManagerXML), "Behaviour XML (*.xml)|*.xml", ".xml") );
}
}
}
| 45.362069 | 136 | 0.708476 | [
"MIT"
] | MattFiler/TextAdventure | Story Tool/Source/Brainiac Designer/Design Mode/DesignMode.cs | 2,631 | C# |
// Copyright (c) Imazen LLC.
// No part of this project, including this file, may be copied, modified,
// propagated, or distributed except as permitted in COPYRIGHT.txt.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Collections.Generic;
using System.Text;
namespace ImageResizer.Plugins.Security.Cryptography {
internal class VolatileKeyProvider: IKeyProvider {
private object syncLock = new object{};
private Dictionary<string, byte[]> keys = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
public byte[] GetKey(string name, int sizeInBytes) {
name += "_" + sizeInBytes;
lock (syncLock) {
byte[] val;
if (!keys.TryGetValue(name, out val)){
val = new byte[sizeInBytes];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(val);
keys[name] = val;
}
return val;
}
}
}
}
| 33.612903 | 115 | 0.609405 | [
"MIT"
] | 2sic/resizer | Plugins/Security/Cryptography/VolatileKeyProvider.cs | 1,044 | C# |
using System;
namespace TheTruth.DataAnnotation
{
/// <summary>
///
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
public class HostNameAttribute : Attribute
{
public string Url { get; set; }
public string Name { get; set; }
public HostNameAttribute(string url)
{
Url = url;
}
public HostNameAttribute(string url, string name)
{
Url = url;
Name = name;
}
}
} | 22.2 | 92 | 0.547748 | [
"Apache-2.0"
] | nhusnullin/TheTruth.DataAnnotation | TheTruth.DataAnnotation/HostNameAttribute.cs | 555 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Wallee.Client;
using Wallee.Model;
namespace Wallee.Service
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IStaticValueService : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// All
/// </summary>
/// <remarks>
/// This operation returns all entities which are available.
/// </remarks>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>List<StaticValue></returns>
List<StaticValue> All ();
/// <summary>
/// All
/// </summary>
/// <remarks>
/// This operation returns all entities which are available.
/// </remarks>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of List<StaticValue></returns>
ApiResponse<List<StaticValue>> AllWithHttpInfo ();
/// <summary>
/// Read
/// </summary>
/// <remarks>
/// Reads the entity with the given 'id' and returns it.
/// </remarks>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">The id of the static value which should be returned.</param>
/// <returns>StaticValue</returns>
StaticValue Read (long? id);
/// <summary>
/// Read
/// </summary>
/// <remarks>
/// Reads the entity with the given 'id' and returns it.
/// </remarks>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">The id of the static value which should be returned.</param>
/// <returns>ApiResponse of StaticValue</returns>
ApiResponse<StaticValue> ReadWithHttpInfo (long? id);
#endregion Synchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class StaticValueService : IStaticValueService
{
private Wallee.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="StaticValueService"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public StaticValueService(Wallee.Client.Configuration configuration = null)
{
if(configuration == null){
throw new ArgumentException("Parameter cannot be null", "configuration");
}
this.Configuration = configuration;
ExceptionFactory = Wallee.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Wallee.Client.Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Wallee.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// All This operation returns all entities which are available.
/// </summary>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>List<StaticValue></returns>
public List<StaticValue> All ()
{
ApiResponse<List<StaticValue>> localVarResponse = AllWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// All This operation returns all entities which are available.
/// </summary>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of List<StaticValue></returns>
public ApiResponse< List<StaticValue> > AllWithHttpInfo ()
{
var localVarPath = "/static-value-service/all";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"*/*"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json;charset=utf-8"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
this.Configuration.ApiClient.ResetTimeout();
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("All", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<StaticValue>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<StaticValue>) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<StaticValue>)));
}
/// <summary>
/// Read Reads the entity with the given 'id' and returns it.
/// </summary>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">The id of the static value which should be returned.</param>
/// <returns>StaticValue</returns>
public StaticValue Read (long? id)
{
ApiResponse<StaticValue> localVarResponse = ReadWithHttpInfo(id);
return localVarResponse.Data;
}
/// <summary>
/// Read Reads the entity with the given 'id' and returns it.
/// </summary>
/// <exception cref="Wallee.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">The id of the static value which should be returned.</param>
/// <returns>ApiResponse of StaticValue</returns>
public ApiResponse< StaticValue > ReadWithHttpInfo (long? id)
{
// verify the required parameter 'id' is set
if (id == null)
throw new ApiException(400, "Missing required parameter 'id' when calling StaticValueService->Read");
var localVarPath = "/static-value-service/read";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"*/*"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json;charset=utf-8"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (id != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "id", id)); // query parameter
this.Configuration.ApiClient.ResetTimeout();
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("Read", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<StaticValue>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(StaticValue) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(StaticValue)));
}
}
}
| 43.942857 | 145 | 0.621308 | [
"Apache-2.0"
] | aurecchia/csharp-sdk | src/Wallee/Service/StaticValueService.cs | 10,766 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks.Sources;
namespace Pipelines.Sockets.Unofficial.Threading
{
public partial class MutexSlim
{
internal static class LockState
{ // using this as a glorified enum; can't use enum directly because
// or Interlocked etc support
public const int
Timeout = 0, // we want "completed with failure" to be the implicit zero default, so default(LockToken) is a miss
Pending = 1,
Success = 2, // note: careful choice of numbers here allows IsCompletedSuccessfully to check whether the LSB is set
Canceled = 3;
//Pending = 0,
//Canceled = 1,
//Success = 2, // note: we make use of the fact that Success/Timeout use the
//Timeout = 3; // 2nd bit for IsCompletedSuccessfully; don't change casually!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetNextToken(int token)
// 2 low bits are status; 30 high bits are counter
=> (int)((((uint)token >> 2) + 1) << 2) | Success;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int ChangeState(int token, int state)
=> (token & ~3) | state; // retain counter portion; swap state portion
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetState(int token) => token & 3;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ValueTaskSourceStatus GetStatus(ref int token)
{
switch (LockState.GetState(Volatile.Read(ref token)))
{
case LockState.Canceled:
return ValueTaskSourceStatus.Canceled;
case LockState.Pending:
return ValueTaskSourceStatus.Pending;
default: // LockState.Success, LockState.Timeout (we only have 4 bits for status)
return ValueTaskSourceStatus.Succeeded;
}
}
// "completed", in Task/ValueTask terms, includes cancelation - only omits pending
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsCompleted(int token) => (token & 3) != Pending;
// note that "successfully" here doesn't mean "with the lock"; as per Task/ValueTask IsCompletedSuccessfully,
// it means "completed, and not faulted or canceled"; see LockState - we can check that by testing the
// second bit (Success=2,Timeout=3)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsCompletedSuccessfully(int token) => (token & 1) == 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TrySetResult(ref int token, int value)
{
int oldValue = Volatile.Read(ref token);
return LockState.GetState(oldValue) == LockState.Pending
&& Interlocked.CompareExchange(ref token, value, oldValue) == oldValue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryCancel(ref int token)
{
int oldValue;
do
{
// depends on the current state...
oldValue = Volatile.Read(ref token);
if (LockState.GetState(oldValue) != LockState.Pending)
{
// already fixed
return false;
}
// otherwise, attempt to change the field; in case of conflict; re-do from start
} while (Interlocked.CompareExchange(ref token, LockState.ChangeState(oldValue, LockState.Canceled), oldValue) != oldValue);
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetResult(ref int token)
{ // if already complete: returns the token; otherwise, dooms the operation
int oldValue, newValue;
do
{
oldValue = Volatile.Read(ref token);
if (LockState.GetState(oldValue) != LockState.Pending)
{
// value is already fixed; just return it
return oldValue;
}
// we don't ever want to report different values from GetResult, so
// if you called GetResult prematurely: you doomed it to failure
newValue = LockState.ChangeState(oldValue, LockState.Timeout);
// if something changed while we were thinking, redo from start
} while (Interlocked.CompareExchange(ref token, newValue, oldValue) != oldValue);
return newValue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Reset(ref int token) => Volatile.Write(ref token, LockState.Pending);
internal static string ToString(int token)
{
var id = ((uint)token) >> 2;
switch(GetState(token))
{
case Timeout:
var reason = (LockToken.TimeoutReason)id;
return $"(timeout:{reason})";
case Pending: return "(pending)";
case Success: return $"(#{id},success)";
default: return "(canceled)";
}
}
}
}
}
| 46.18254 | 140 | 0.556625 | [
"Apache-2.0"
] | RendleLabs/Pipelines.Sockets.Unofficial | src/Pipelines.Sockets.Unofficial/Threading/MutexSlim.LockState.cs | 5,821 | C# |
using DiceRollerPro.Models;
using UnityEditor;
using UnityEngine;
namespace DiceRollerPro.Editor
{
class DiceCreator
{
[MenuItem("Assets/Create/Dice Roller Pro/Fate Dice")]
public static void CreateFateDice()
{
var dice = ScriptableObject.CreateInstance<FateDice>();
CreateAsset(dice, "Fate Dice");
}
[MenuItem("Assets/Create/Dice Roller Pro/Group")]
public static void CreateGroup()
{
var dice = ScriptableObject.CreateInstance<Group>();
CreateAsset(dice, "Group");
}
[MenuItem("Assets/Create/Dice Roller Pro/Normal Dice")]
public static void CreateNormalDice()
{
var dice = ScriptableObject.CreateInstance<NormalDice>();
CreateAsset(dice, "Normal Dice");
}
[MenuItem("Assets/Create/Dice Roller Pro/Number")]
public static void CreateNumber()
{
var dice = ScriptableObject.CreateInstance<Number>();
CreateAsset(dice, "Number");
}
[MenuItem("Assets/Create/Dice Roller Pro/Sequence")]
public static void CreateSequence()
{
var dice = ScriptableObject.CreateInstance<Sequence>();
CreateAsset(dice, "Sequence");
}
private static void CreateAsset(ScriptableObject scriptableObject, string assetName)
{
var parentPath = AssetDatabase.GetAssetPath(Selection.activeObject);
var assetPath = parentPath +
$"/{assetName}.asset";
//$"Assets/{Selection.activeObject.name}/{assetName}.asset";
assetPath = AssetDatabase.GenerateUniqueAssetPath(assetPath);
AssetDatabase.CreateAsset(scriptableObject, assetPath);
AssetDatabase.SaveAssets();
EditorUtility.FocusProjectWindow();
Selection.activeObject = scriptableObject;
}
}
} | 32.95 | 92 | 0.602934 | [
"MIT"
] | Manzanero/bardo | Assets/Scripts/DiceRollerPro/Editor/DiceCreator.cs | 1,979 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Registration.Persistence.Data;
#nullable disable
namespace Registration.Persistence.Migrations
{
[DbContext(typeof(RegistrationContext))]
partial class RegistrationContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Registration.Domain.Entities.Companies.Company", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Company", (string)null);
});
modelBuilder.Entity("Registration.Domain.Entities.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<long>("CompanyId")
.HasColumnType("bigint");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("User", (string)null);
});
modelBuilder.Entity("Registration.Domain.Entities.Users.User", b =>
{
b.HasOne("Registration.Domain.Entities.Companies.Company", "Company")
.WithMany("Users")
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.Navigation("Company");
});
modelBuilder.Entity("Registration.Domain.Entities.Companies.Company", b =>
{
b.Navigation("Users");
});
#pragma warning restore 612, 618
}
}
}
| 34.495146 | 103 | 0.500422 | [
"MIT"
] | dusanmiljkovic/Registration | Registration.Persistence/Migrations/RegistrationContextModelSnapshot.cs | 3,555 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using EmergeTk.Widgets.Html;
namespace EmergeTk.Model.Workflow
{
public class Process : AbstractRecord, ISingular
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private IRecordList<Operation> operations;
public IRecordList<Operation> Operations
{
get {
if( operations == null )
lazyLoadProperty<Operation>("Operations");
return operations; }
set { operations = value; }
}
private IRecordList<State> permittedStates;
public IRecordList<State> PermittedStates
{
get {
if( permittedStates == null )
lazyLoadProperty<State>("PermittedStates");
return permittedStates; }
set { permittedStates = value; }
}
private string payloadTypeFriendlyName;
public string PayloadTypeFriendlyName {
get {
return payloadTypeFriendlyName;
}
set {
payloadTypeFriendlyName = value;
}
}
private string payloadType;
public string PayloadType {
get {
return payloadType;
}
set {
payloadType = value;
}
}
public override Widget GetPropertyEditWidget(Widget parent, ColumnInfo column, IRecordList records)
{
switch (column.Name)
{
case "PayloadType":
LabeledWidget<DropDown> dd = Context.Current.CreateWidget<LabeledWidget<DropDown>>();
dd.LabelText = "Task Type";
dd.Widget.Options = getTaskTypes();
dd.Widget.OnChanged += new EventHandler<EmergeTk.ChangedEventArgs>(delegate(object sender, ChangedEventArgs ea )
{
string opt = dd.Widget.SelectedOption;
this.payloadType = opt != "--SELECT--" ? opt : null;
});
dd.Widget.SelectedOption = this.payloadType;
return dd;
default:
return base.GetPropertyEditWidget(parent, column, records);
}
}
List<string> taskTypes = null;
private List<string> getTaskTypes()
{
if( taskTypes != null )
return taskTypes;
Type[] types = TypeLoader.GetTypesOfBaseType(typeof(Task));
taskTypes = new List<string>();
taskTypes.Add("--SELECT--");
foreach ( Type t in types )
taskTypes.Add( t.FullName );
return taskTypes;
}
public override string ToString()
{
return name;
}
}
}
| 30.135417 | 132 | 0.526097 | [
"MIT"
] | bennidhamma/EmergeTk | server/Model/Workflow/Process.cs | 2,893 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20200601
{
/// <summary>
/// Bastion Host resource.
/// </summary>
public partial class BastionHost : Pulumi.CustomResource
{
/// <summary>
/// FQDN for the endpoint on which bastion host is accessible.
/// </summary>
[Output("dnsName")]
public Output<string?> DnsName { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// IP configuration of the Bastion Host resource.
/// </summary>
[Output("ipConfigurations")]
public Output<ImmutableArray<Outputs.BastionHostIPConfigurationResponse>> IpConfigurations { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the bastion host resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a BastionHost resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public BastionHost(string name, BastionHostArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20200601:BastionHost", name, args ?? new BastionHostArgs(), MakeResourceOptions(options, ""))
{
}
private BastionHost(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20200601:BastionHost", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/latest:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:BastionHost"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:BastionHost"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing BastionHost resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static BastionHost Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new BastionHost(name, id, options);
}
}
public sealed class BastionHostArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the Bastion Host.
/// </summary>
[Input("bastionHostName", required: true)]
public Input<string> BastionHostName { get; set; } = null!;
/// <summary>
/// FQDN for the endpoint on which bastion host is accessible.
/// </summary>
[Input("dnsName")]
public Input<string>? DnsName { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
[Input("ipConfigurations")]
private InputList<Inputs.BastionHostIPConfigurationArgs>? _ipConfigurations;
/// <summary>
/// IP configuration of the Bastion Host resource.
/// </summary>
public InputList<Inputs.BastionHostIPConfigurationArgs> IpConfigurations
{
get => _ipConfigurations ?? (_ipConfigurations = new InputList<Inputs.BastionHostIPConfigurationArgs>());
set => _ipConfigurations = value;
}
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public BastionHostArgs()
{
}
}
}
| 39.222826 | 136 | 0.582375 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Network/V20200601/BastionHost.cs | 7,217 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TutorialState : GameState
{
}
| 13.888889 | 38 | 0.8 | [
"MIT"
] | Electrified-Wolf-Runners/Unity3d-NFT-Project | Assets/Scripts/GameManager/TutorialState.cs | 127 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace Ixy.Web
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| 21.76 | 64 | 0.568015 | [
"MIT"
] | sgwzxg/Ixy | src/Ixy.Web/Program.cs | 546 | C# |
using System;
using System.IO;
using NUnit.Framework;
namespace GitLib.Tests
{
using static libgit2;
public partial class RevparseTests
{
[Test]
public void Test_git_revparse_single()
{
Assert.Fail($"Tests for method `{nameof(git_revparse_single)}` are not yet implemented");
}
[Test]
public void Test_git_revparse_ext()
{
Assert.Fail($"Tests for method `{nameof(git_revparse_ext)}` are not yet implemented");
}
[Test]
public void Test_git_revparse()
{
Assert.Fail($"Tests for method `{nameof(git_revparse)}` are not yet implemented");
}
}
}
| 22.375 | 101 | 0.576816 | [
"BSD-2-Clause"
] | xoofx/GitLib.NET | src/GitLib.Tests/revparse.cs | 716 | C# |
// ----------------------------------------------------------------------------
// The MIT License
// Simple Entity Component System framework https://github.com/Leopotam/ecs
// Copyright (c) 2017-2020 Leopotam <leopotam@gmail.com>
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Blast.ECS {
/// <summary>
/// Ecs data context.
/// </summary>
#if ENABLE_IL2CPP
[Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)]
[Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)]
#endif
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
public class World {
protected EcsEntityData[] Entities;
protected int EntitiesCount;
protected readonly ECSGrowList<int> FreeEntities;
protected readonly ECSGrowList<ComponentFilter> Filters;
protected readonly Dictionary<int, ECSGrowList<ComponentFilter>> FilterByIncludedComponents;
protected readonly Dictionary<int, ECSGrowList<ComponentFilter>> FilterByExcludedComponents;
// just for world stats.
int _usedComponentsCount;
internal readonly WorldConfig Config;
readonly object[] _filterCtor;
/// <summary>
/// Creates new ecs-world instance.
/// </summary>
/// <param name="config">Optional config for default cache sizes. On zero or negative value - default value will be used.</param>
public World (WorldConfig config = default) {
var finalConfig = new WorldConfig {
EntityComponentsCacheSize = config.EntityComponentsCacheSize <= 0
? WorldConfig.DefaultEntityComponentsCacheSize
: config.EntityComponentsCacheSize,
FilterEntitiesCacheSize = config.FilterEntitiesCacheSize <= 0
? WorldConfig.DefaultFilterEntitiesCacheSize
: config.FilterEntitiesCacheSize,
WorldEntitiesCacheSize = config.WorldEntitiesCacheSize <= 0
? WorldConfig.DefaultWorldEntitiesCacheSize
: config.WorldEntitiesCacheSize,
WorldFiltersCacheSize = config.WorldFiltersCacheSize <= 0
? WorldConfig.DefaultWorldFiltersCacheSize
: config.WorldFiltersCacheSize,
WorldComponentPoolsCacheSize = config.WorldComponentPoolsCacheSize <= 0
? WorldConfig.DefaultWorldComponentPoolsCacheSize
: config.WorldComponentPoolsCacheSize
};
Config = finalConfig;
Entities = new EcsEntityData[Config.WorldEntitiesCacheSize];
FreeEntities = new ECSGrowList<int> (Config.WorldEntitiesCacheSize);
Filters = new ECSGrowList<ComponentFilter> (Config.WorldFiltersCacheSize);
FilterByIncludedComponents = new Dictionary<int, ECSGrowList<ComponentFilter>> (Config.WorldFiltersCacheSize);
FilterByExcludedComponents = new Dictionary<int, ECSGrowList<ComponentFilter>> (Config.WorldFiltersCacheSize);
ComponentPools = new IEcsComponentPool[Config.WorldComponentPoolsCacheSize];
_filterCtor = new object[] { this };
}
/// <summary>
/// Component pools cache.
/// </summary>
public IEcsComponentPool[] ComponentPools;
protected bool IsDestroyed;
#if DEBUG
internal readonly List<IEcsWorldDebugListener> DebugListeners = new List<IEcsWorldDebugListener> (4);
readonly ECSGrowList<Entity> _leakedEntities = new ECSGrowList<Entity> (256);
bool _inDestroying;
/// <summary>
/// Adds external event listener.
/// </summary>
/// <param name="listener">Event listener.</param>
public void AddDebugListener (IEcsWorldDebugListener listener) {
if (listener == null) { throw new Exception ("Listener is null."); }
DebugListeners.Add (listener);
}
/// <summary>
/// Removes external event listener.
/// </summary>
/// <param name="listener">Event listener.</param>
public void RemoveDebugListener (IEcsWorldDebugListener listener) {
if (listener == null) { throw new Exception ("Listener is null."); }
DebugListeners.Remove (listener);
}
#endif
/// <summary>
/// Destroys world and exist entities.
/// </summary>
public virtual void Dispose () {
#if DEBUG
if (IsDestroyed || _inDestroying) { throw new Exception ("EcsWorld already destroyed."); }
_inDestroying = true;
CheckForLeakedEntities ("Destroy");
#endif
Entity entity;
entity.Owner = this;
for (var i = EntitiesCount - 1; i >= 0; i--) {
ref var entityData = ref Entities[i];
if (entityData.ComponentsCountX2 > 0) {
entity.Id = i;
entity.Gen = entityData.Gen;
entity.Destroy ();
}
}
IsDestroyed = true;
#if DEBUG
for (var i = DebugListeners.Count - 1; i >= 0; i--) {
DebugListeners[i].OnWorldDestroyed (this);
}
#endif
}
/// <summary>
/// Is world not destroyed.
/// </summary>
[MethodImpl (MethodImplOptions.AggressiveInlining)]
public bool IsAlive () {
return !IsDestroyed;
}
/// <summary>
/// Creates new entity.
/// </summary>
[MethodImpl (MethodImplOptions.AggressiveInlining)]
public Entity NewEntity () {
#if DEBUG
if (IsDestroyed) { throw new Exception ("EcsWorld already destroyed."); }
#endif
Entity entity;
entity.Owner = this;
// try to reuse entity from pool.
if (FreeEntities.Count > 0) {
entity.Id = FreeEntities.Items[--FreeEntities.Count];
ref var entityData = ref Entities[entity.Id];
entity.Gen = entityData.Gen;
entityData.ComponentsCountX2 = 0;
} else {
// create new entity.
if (EntitiesCount == Entities.Length) {
Array.Resize (ref Entities, EntitiesCount << 1);
}
entity.Id = EntitiesCount++;
ref var entityData = ref Entities[entity.Id];
entityData.Components = new int[Config.EntityComponentsCacheSize * 2];
entityData.Gen = 1;
entity.Gen = entityData.Gen;
entityData.ComponentsCountX2 = 0;
}
#if DEBUG
_leakedEntities.Add (entity);
foreach (var debugListener in DebugListeners) {
debugListener.OnEntityCreated (entity);
}
#endif
return entity;
}
/// <summary>
/// Restores EcsEntity from internal id and gen. For internal use only!
/// </summary>
/// <param name="id">Internal id.</param>
/// <param name="gen">Generation. If less than 0 - will be filled from current generation value.</param>
[MethodImpl (MethodImplOptions.AggressiveInlining)]
public Entity RestoreEntityFromInternalId (int id, int gen = -1) {
Entity entity;
entity.Owner = this;
entity.Id = id;
if (gen < 0) {
entity.Gen = 0;
ref var entityData = ref GetEntityData (entity);
entity.Gen = entityData.Gen;
} else {
entity.Gen = (ushort) gen;
}
return entity;
}
/// <summary>
/// Request exist filter or create new one. For internal use only!
/// </summary>
/// <param name="filterType">Filter type.</param>
/// <param name="createIfNotExists">Create filter if not exists.</param>
public ComponentFilter GetFilter (Type filterType, bool createIfNotExists = true) {
#if DEBUG
if (filterType == null) { throw new Exception ("FilterType is null."); }
if (!filterType.IsSubclassOf (typeof (ComponentFilter))) { throw new Exception ($"Invalid filter type: {filterType}."); }
if (IsDestroyed) { throw new Exception ("EcsWorld already destroyed."); }
#endif
// check already exist filters.
for (int i = 0, iMax = Filters.Count; i < iMax; i++) {
if (Filters.Items[i].GetType () == filterType) {
return Filters.Items[i];
}
}
if (!createIfNotExists) {
return null;
}
// create new filter.
var filter = (ComponentFilter) Activator.CreateInstance (filterType, BindingFlags.NonPublic | BindingFlags.Instance, null, _filterCtor, CultureInfo.InvariantCulture);
#if DEBUG
for (var filterIdx = 0; filterIdx < Filters.Count; filterIdx++) {
if (filter.AreComponentsSame (Filters.Items[filterIdx])) {
throw new Exception (
$"Invalid filter \"{filter.GetType ()}\": Another filter \"{Filters.Items[filterIdx].GetType ()}\" already has same components, but in different order.");
}
}
#endif
Filters.Add (filter);
// add to component dictionaries for fast compatibility scan.
for (int i = 0, iMax = filter.IncludedTypeIndices.Length; i < iMax; i++) {
if (!FilterByIncludedComponents.TryGetValue (filter.IncludedTypeIndices[i], out var filtersList)) {
filtersList = new ECSGrowList<ComponentFilter> (8);
FilterByIncludedComponents[filter.IncludedTypeIndices[i]] = filtersList;
}
filtersList.Add (filter);
}
if (filter.ExcludedTypeIndices != null) {
for (int i = 0, iMax = filter.ExcludedTypeIndices.Length; i < iMax; i++) {
if (!FilterByExcludedComponents.TryGetValue (filter.ExcludedTypeIndices[i], out var filtersList)) {
filtersList = new ECSGrowList<ComponentFilter> (8);
FilterByExcludedComponents[filter.ExcludedTypeIndices[i]] = filtersList;
}
filtersList.Add (filter);
}
}
#if DEBUG
foreach (var debugListener in DebugListeners) {
debugListener.OnFilterCreated (filter);
}
#endif
return filter;
}
/// <summary>
/// Gets stats of internal data.
/// </summary>
public EcsWorldStats GetStats () {
var stats = new EcsWorldStats () {
ActiveEntities = EntitiesCount - FreeEntities.Count,
ReservedEntities = FreeEntities.Count,
Filters = Filters.Count,
Components = _usedComponentsCount
};
return stats;
}
/// <summary>
/// Recycles internal entity data to pool.
/// </summary>
/// <param name="id">Entity id.</param>
/// <param name="entityData">Entity internal data.</param>
protected internal void RecycleEntityData (int id, ref EcsEntityData entityData) {
#if DEBUG
if (entityData.ComponentsCountX2 != 0) { throw new Exception ("Cant recycle invalid entity."); }
#endif
entityData.ComponentsCountX2 = -2;
entityData.Gen++;
if (entityData.Gen == 0) { entityData.Gen = 1; }
FreeEntities.Add (id);
}
#if DEBUG
/// <summary>
/// Checks exist entities but without components.
/// </summary>
/// <param name="errorMsg">Prefix for error message.</param>
public bool CheckForLeakedEntities (string errorMsg) {
if (_leakedEntities.Count > 0) {
for (int i = 0, iMax = _leakedEntities.Count; i < iMax; i++) {
if (GetEntityData (_leakedEntities.Items[i]).ComponentsCountX2 == 0) {
if (errorMsg != null) {
throw new Exception ($"{errorMsg}: Empty entity detected, possible memory leak.");
}
return true;
}
}
_leakedEntities.Count = 0;
}
return false;
}
#endif
/// <summary>
/// Updates filters.
/// </summary>
/// <param name="typeIdx">Component type index.abstract Positive for add operation, negative for remove operation.</param>
/// <param name="entity">Target entity.</param>
/// <param name="entityData">Target entity data.</param>
[MethodImpl (MethodImplOptions.AggressiveInlining)]
protected internal void UpdateFilters (int typeIdx, in Entity entity, in EcsEntityData entityData) {
#if DEBUG
if (IsDestroyed) { throw new Exception ("EcsWorld already destroyed."); }
#endif
ECSGrowList<ComponentFilter> filters;
if (typeIdx < 0) {
// remove component.
if (FilterByIncludedComponents.TryGetValue (-typeIdx, out filters)) {
for (int i = 0, iMax = filters.Count; i < iMax; i++) {
if (filters.Items[i].IsCompatible (entityData, 0)) {
#if DEBUG
if (!filters.Items[i].GetInternalEntitiesMap ().TryGetValue (entity.GetInternalId (), out var filterIdx)) { filterIdx = -1; }
if (filterIdx < 0) { throw new Exception ("Entity not in filter."); }
#endif
filters.Items[i].OnRemoveEntity (entity);
}
}
}
if (FilterByExcludedComponents.TryGetValue (-typeIdx, out filters)) {
for (int i = 0, iMax = filters.Count; i < iMax; i++) {
if (filters.Items[i].IsCompatible (entityData, typeIdx)) {
#if DEBUG
if (!filters.Items[i].GetInternalEntitiesMap ().TryGetValue (entity.GetInternalId (), out var filterIdx)) { filterIdx = -1; }
if (filterIdx >= 0) { throw new Exception ("Entity already in filter."); }
#endif
filters.Items[i].OnAddEntity (entity);
}
}
}
} else {
// add component.
if (FilterByIncludedComponents.TryGetValue (typeIdx, out filters)) {
for (int i = 0, iMax = filters.Count; i < iMax; i++) {
if (filters.Items[i].IsCompatible (entityData, 0)) {
#if DEBUG
if (!filters.Items[i].GetInternalEntitiesMap ().TryGetValue (entity.GetInternalId (), out var filterIdx)) { filterIdx = -1; }
if (filterIdx >= 0) { throw new Exception ("Entity already in filter."); }
#endif
filters.Items[i].OnAddEntity (entity);
}
}
}
if (FilterByExcludedComponents.TryGetValue (typeIdx, out filters)) {
for (int i = 0, iMax = filters.Count; i < iMax; i++) {
if (filters.Items[i].IsCompatible (entityData, -typeIdx)) {
#if DEBUG
if (!filters.Items[i].GetInternalEntitiesMap ().TryGetValue (entity.GetInternalId (), out var filterIdx)) { filterIdx = -1; }
if (filterIdx < 0) { throw new Exception ("Entity not in filter."); }
#endif
filters.Items[i].OnRemoveEntity (entity);
}
}
}
}
}
/// <summary>
/// Returns internal state of entity. For internal use!
/// </summary>
/// <param name="entity">Entity.</param>
[MethodImpl (MethodImplOptions.AggressiveInlining)]
public ref EcsEntityData GetEntityData (in Entity entity) {
#if DEBUG
if (IsDestroyed) { throw new Exception ("EcsWorld already destroyed."); }
if (entity.Id < 0 || entity.Id > EntitiesCount) { throw new Exception ($"Invalid entity {entity.Id}"); }
#endif
return ref Entities[entity.Id];
}
/// <summary>
/// Internal state of entity.
/// </summary>
[StructLayout (LayoutKind.Sequential, Pack = 2)]
public struct EcsEntityData {
public ushort Gen;
public short ComponentsCountX2;
public int[] Components;
}
[MethodImpl (MethodImplOptions.AggressiveInlining)]
public EcsComponentPool<T> GetPool<T> () where T : struct {
var typeIdx = EcsComponentType<T>.TypeIndex;
if (ComponentPools.Length < typeIdx) {
var len = ComponentPools.Length << 1;
while (len <= typeIdx) {
len <<= 1;
}
Array.Resize (ref ComponentPools, len);
}
var pool = (EcsComponentPool<T>) ComponentPools[typeIdx];
if (pool == null) {
pool = new EcsComponentPool<T> ();
ComponentPools[typeIdx] = pool;
_usedComponentsCount++;
}
return pool;
}
}
/// <summary>
/// Stats of EcsWorld instance.
/// </summary>
public struct EcsWorldStats {
/// <summary>
/// Amount of active entities.
/// </summary>
public int ActiveEntities;
/// <summary>
/// Amount of cached (not in use) entities.
/// </summary>
public int ReservedEntities;
/// <summary>
/// Amount of registered filters.
/// </summary>
public int Filters;
/// <summary>
/// Amount of registered component types.
/// </summary>
public int Components;
}
/// <summary>
/// World config to setup default caches.
/// </summary>
public struct WorldConfig {
/// <summary>
/// World.Entities cache size.
/// </summary>
public int WorldEntitiesCacheSize;
/// <summary>
/// World.Filters cache size.
/// </summary>
public int WorldFiltersCacheSize;
/// <summary>
/// World.ComponentPools cache size.
/// </summary>
public int WorldComponentPoolsCacheSize;
/// <summary>
/// Entity.Components cache size (not doubled).
/// </summary>
public int EntityComponentsCacheSize;
/// <summary>
/// Filter.Entities cache size.
/// </summary>
public int FilterEntitiesCacheSize;
/// <summary>
/// World.Entities default cache size.
/// </summary>
public const int DefaultWorldEntitiesCacheSize = 1024;
/// <summary>
/// World.Filters default cache size.
/// </summary>
public const int DefaultWorldFiltersCacheSize = 128;
/// <summary>
/// World.ComponentPools default cache size.
/// </summary>
public const int DefaultWorldComponentPoolsCacheSize = 512;
/// <summary>
/// Entity.Components default cache size (not doubled).
/// </summary>
public const int DefaultEntityComponentsCacheSize = 8;
/// <summary>
/// Filter.Entities default cache size.
/// </summary>
public const int DefaultFilterEntitiesCacheSize = 256;
}
#if DEBUG
/// <summary>
/// Debug interface for world events processing.
/// </summary>
public interface IEcsWorldDebugListener {
void OnEntityCreated (Entity entity);
void OnEntityDestroyed (Entity entity);
void OnFilterCreated (ComponentFilter filter);
void OnComponentListChanged (Entity entity);
void OnWorldDestroyed (World world);
}
#endif
} | 42.010309 | 178 | 0.557693 | [
"MIT"
] | STUDIOCRAFTapps/OUTERBLAST | Assets/_Project/Scripts/Systems/_ECS/src/EcsWorld.cs | 20,375 | C# |
namespace DoctrineShips.Web.Controllers
{
using System;
using System.Reflection;
using System.Web.Mvc;
using Tools;
public class ErrorController : Controller
{
private readonly ISystemLogger logger;
public ErrorController(ISystemLogger logger)
{
this.logger = logger;
}
public ActionResult Error(int statusCode, Exception e)
{
// Ignore '404 Not Found' Errors.
if (statusCode != 404)
{
// Log any other status codes & exception.
logger.LogMessage("Status Code: " + statusCode + " Exception: " + e.ToString(), 0, "Exception", MethodBase.GetCurrentMethod().Name);
}
Response.StatusCode = statusCode;
return View();
}
}
}
| 26.580645 | 148 | 0.567961 | [
"MIT"
] | bravecollective/doctrine-contracts | DoctrineShips.Web/Controllers/ErrorController.cs | 826 | C# |
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: Oauth2Authentication.tt
// Build date: 2017-10-08
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Logging v2beta1 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Writes log entries and manages your Stackdriver Logging configuration.
// API Documentation Link https://cloud.google.com/logging/docs/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Logging/v2beta1/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Logging.v2beta1/
// Install Command: PM> Install-Package Google.Apis.Logging.v2beta1
//
//------------------------------------------------------------------------------
using Google.Apis.Auth.OAuth2;
using Google.Apis.Logging.v2beta1;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
namespace GoogleSamplecSharpSample.Loggingv2beta1.Auth
{
public static class Oauth2Example
{
/// <summary>
/// ** Installed Aplication only **
/// This method requests Authentcation from a user using Oauth2.
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <param name="scopes">Array of Google scopes</param>
/// <returns>LoggingService used to make requests against the Logging API</returns>
public static LoggingService GetLoggingService(string clientSecretJson, string userName, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
var cred = GetUserCredential(clientSecretJson, userName, scopes);
return GetService(cred);
}
catch (Exception ex)
{
throw new Exception("Get Logging service failed.", ex);
}
}
/// <summary>
/// ** Installed Aplication only **
/// This method requests Authentcation from a user using Oauth2.
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <param name="scopes">Array of Google scopes</param>
/// <returns>authencated UserCredential</returns>
private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
credential.GetAccessTokenForRequestAsync();
return credential;
}
}
catch (Exception ex)
{
throw new Exception("Get user credentials failed.", ex);
}
}
/// <summary>
/// This method get a valid service
/// </summary>
/// <param name="credential">Authecated user credentail</param>
/// <returns>LoggingService used to make requests against the Logging API</returns>
private static LoggingService GetService(UserCredential credential)
{
try
{
if (credential == null)
throw new ArgumentNullException("credential");
// Create Logging API service.
return new LoggingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Logging Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
throw new Exception("Get Logging service failed.", ex);
}
}
}
} | 47.69281 | 140 | 0.580787 | [
"Apache-2.0"
] | AhmerRaza/Google-Dotnet-Samples | Samples/Stackdriver Logging API/v2beta1/Oauth2Authentication.cs | 7,299 | C# |
namespace Computers.Logic.Manufacturers
{
using ComputerTypes;
using Cpus;
using VideoCards;
public class LenovoComputerFactory : IComputersFactory
{
public Laptop CreateLaptop()
{
var ram = new Ram(16);
var videoCard = new ColorfulVideoCard();
var battery = new LaptopBattery();
var laptop = new Laptop(new Cpu64(2, ram, videoCard), ram, new[] { new HardDrive(1000, false, 1) }, videoCard, battery);
return laptop;
}
public PersonalComputer CreatePersonalComputer()
{
var ram = new Ram(16);
var videoCard = new ColorfulVideoCard();
var pc = new PersonalComputer(new Cpu64(2, ram, videoCard), ram, new[] { new HardDrive(1000, false, 1) }, videoCard);
return pc;
}
public Server CreateServer()
{
var ram = new Ram(64);
var videoCard = new ColorfulVideoCard();
var server = new Server(new Cpu64(2, ram, videoCard), ram, new[] { new HardDrive(1000, false, 1) }, videoCard);
return server;
}
}
}
| 31.081081 | 132 | 0.570435 | [
"MIT"
] | VVoev/Telerik-Academy | 11.High-Quality-Code-Part-2/High-Quality-Code-Exam-Computers/Problem/Computers.Logic/Manufacturers/LenovoComputerFactory.cs | 1,152 | C# |
using System;
using System.Diagnostics;
using System.IO;
using BlazeSnes.Core.Common;
using BlazeSnes.Core.External;
namespace BlazeSnes.Core.Bus {
/// <summary>
/// CPUからのメモリアクセスを適切にリマップします
/// ref: https://problemkaputt.de/fullsnes.htm#snesmemorycontrol
/// </summary>
public class Mmu : IBusAccessible {
/// <summary>
/// WRAM
/// 00-3f: 0000-1fff: 8Kbytes
/// 7e-7f: 0000-ffff: 128Kbytes all
/// 80-bf: 0000-1fff: 8Kbytes
/// </summary>
/// <value></value>
public IBusAccessible Wram { get; internal set; }
/// <summary>
/// PPU
/// 00-3f, 80-bf: 2100-213f
/// </summary>
/// <value></value>
public IBusAccessible PpuControlReg { get; internal set; }
/// <summary>
/// APU
/// 00-3f, 80-bf: 2134-217f
/// </summary>
/// <value></value>
public IBusAccessible ApuControlReg { get; internal set; }
/// <summary>
/// Joypad, Clock Div, Timer, etc.!--.!--.
/// 00-3f, 80-bf: 4000-42ff
/// </summary>
/// <value></value>
public IBusAccessible OnChipIoPort { get; internal set; }
/// <summary>
/// DMA Channle(0..7)
/// 00-3f, 80-bf: 4300--5fff
/// </summary>
/// <value></value>
public IBusAccessible DmaControlReg { get; internal set; }
/// Cartridge ROM/RAM
/// 00-3f: 8000-ffff: WS1 LoROM 2048Kbytes
/// 40-7f: 0000-ffff: WS1 HiROM 3968Kbytes
/// 80-bf: 8000-ffff: WS2 LoROM 2048Kbytes
/// c0-ff: 0000-ffff: WS2 HiROM 3968Kbytes
/// Expansion port
/// 00-3f: 6000-7ffff
/// 80-bf: 6000-7ffff
/// </summary>
/// <value></value>
public IBusAccessible Cartridge { get; internal set; }
/// <summary>
/// 最後のRead値、OpenBusアクセス時に返す値
/// </summary>
/// <value></value>
public byte LatestReadData { get; internal set; } = 0x0;
public Mmu(IBusAccessible wram, IBusAccessible ppu, IBusAccessible apu, IBusAccessible onchip, IBusAccessible dma, IBusAccessible cartridge) {
this.Wram = wram;
this.PpuControlReg = ppu;
this.ApuControlReg = apu;
this.OnChipIoPort = onchip;
this.DmaControlReg = dma;
this.Cartridge = cartridge;
}
/// <summary>
/// バスにつながるすべてのデバイスをクリアします
/// </summary>
public void Reset() {
Wram.Reset();
PpuControlReg.Reset();
ApuControlReg.Reset();
ApuControlReg.Reset();
OnChipIoPort.Reset();
DmaControlReg.Reset();
Cartridge.Reset();
}
/// <summary>
/// アクセス先のアドレスから対象のペリフェラルとバス種別を取得します
/// </summary>
/// <param name="addr"></param>
/// <returns></returns>
public IBusAccessible GetTarget(uint addr) {
Debug.Assert((addr & 0xff00_0000) == 0x0); // 24bit以上のアクセスは存在しないはず
var bank = (addr >> 16) & 0xff;
var offset = (addr & 0xffff);
var target = bank switch
{
var b when ((b <= 0x3f) || ((0x80 <= b) && (b <= 0xbf))) => offset switch
{
var o when (o <= 0x1fff) => Wram,
var o when (o <= 0x20ff) => null, // unused
var o when (o <= 0x213f) => PpuControlReg,
var o when (o <= 0x217f) => ApuControlReg,
var o when (o <= 0x2183) => Wram,
var o when (o <= 0x21ff) => Cartridge, // Expansion(B-Bus)
var o when (o <= 0x3fff) => Cartridge, // unused, Expansion(A-Bus)
var o when (o <= 0x42ff) => OnChipIoPort,
var o when (o <= 0x5fff) => DmaControlReg, // DMA Channel 0..7
_ => Cartridge, // 6000-7fff: Expansion(e.g. Battery Backed RAM), 8000 - ffff: ROM
},
var b when ((b <= 0x7d) || (0xc0 <= b)) => Cartridge, // 40-7d, c0-ff
var b when (b <= 0x7f) => Wram, // 7e-7f
_ => null, // open bus
};
return target;
}
public bool Read(uint addr, byte[] data, bool isNondestructive = false) {
Debug.Assert(data.Length > 0);
var target = GetTarget(addr);
// OpenBus対応
if (!target?.Read(addr, data, isNondestructive) ?? false) {
Debug.Fail($"Open Bus Readを検出 ${addr:x}"); // TODO: デバッグ用に入れてあるが適正なOpen Busアクセスであれば外す
// OpenBusは最後に読めたデータを返す
Debug.Assert(data.Length == 1);
Array.Fill(data, LatestReadData); // すべて最後に読めた値で埋める
return false;
}
LatestReadData = data[^1]; // 最後に読めたデータを控える
return true;
}
public bool Write(uint addr, in byte[] data) {
Debug.Assert(data.Length > 0);
var target = GetTarget(addr);
// OpenBus対応
if (!target?.Write(addr, data) ?? false) {
Debug.Fail($"Open Bus Writeを検出 ${addr:x}"); // TODO: デバッグ用に入れてあるが適正なOpen Busアクセスであれば外す
return false;
}
return true;
}
}
} | 36.60274 | 150 | 0.50131 | [
"MIT"
] | kamiyaowl/blaze-snes | BlazeSnes.Core/Bus/Mmu.cs | 5,752 | C# |
using AdventOfCode2017.App;
using NUnit.Framework;
namespace AdventOfCode2017.Tests
{
public class Day1Tests
{
[TestCase("1122", 3)]
[TestCase("1111", 4)]
[TestCase("1234", 0)]
[TestCase("91212129", 9)]
public void Solve1Tests(string input, int expected)
{
var actual = Day1.Solve1(input);
Assert.AreEqual(expected, actual);
}
[TestCase("1212", 6)]
[TestCase("1221", 0)]
[TestCase("123425", 4)]
[TestCase("123123", 12)]
[TestCase("12131415", 4)]
public void Solve2Tests(string input, int expected)
{
var actual = Day1.Solve2(input);
Assert.AreEqual(expected, actual);
}
}
} | 26.310345 | 59 | 0.541284 | [
"MIT"
] | takemyoxygen/playground | cs/AdventOfCode2017/AdventOfCode2017.Tests/Day1Tests.cs | 763 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MicroserviceTemplate
{
public static class Features
{
public const string HttpLogger = "HttpLogger";
public const string Healthz = "Healthz";
public const string Swagger = "Swagger";
public const string ForwardedHeaders = "ForwardedHeaders";
public const string Metrics = "Metrics";
public const string DeveloperDashboard = "DeveloperDashboard";
}
}
| 28.833333 | 70 | 0.705202 | [
"MIT"
] | Bishoymly/CoreX.Extensions | src/MicroserviceTemplate/Features.cs | 521 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CovidTrackUS_Web.Models
{
public class CookieProtectionOptions
{
/// <summary>
/// Path to a public certificate to encrypt the data protection keys at rest.
/// The pfx file is adequate for the job.
/// </summary>
public string CertificatePath { get; set; }
}
}
| 25.823529 | 86 | 0.640091 | [
"MIT"
] | walkerworks/CovidTrack_US | Models/CookieProtectionOptions.cs | 441 | C# |
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MonoEngine.core
{
public class Agent : SpriteObject, IDamagable
{
public float Speed = 100;
private float maxHealth;
private float curHealth;
private GameObject baseClass;
public float CurMeleeAttackCoolDown = 1;
public float MaxMeleeAttackCoolDown = 1;
public int Team = 0;
public Agent TargetAgent;
public bool Dead = false;
public Agent(Vector2 position, float health)
{
maxHealth = health;
curHealth = maxHealth;
baseClass = this;
}
public float MaxHealth { get { return maxHealth; } set { maxHealth = value; } }
public float CurHealth { get { return curHealth; } set { curHealth = value; } }
public GameObject BaseClass { get {return baseClass; } set { baseClass = value; } }
public void Die()
{
Dead = true;
ShouldDraw = false;
// flagForRemoval = true;
}
public void TakeDamage(float dmg)
{
CurHealth -= dmg;
if(CurHealth <= 0)
{
Die();
}
}
public override void Update(float dt)
{
CurMeleeAttackCoolDown -= dt;
base.Update(dt);
}
}
}
| 25.734375 | 92 | 0.554341 | [
"MIT"
] | JoelWhittle/MonoGOAP | core/Agent.cs | 1,649 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\shared\d3dkmddi.h(2031,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct _DXGK_GPUMMUCAPS
{
public _DXGK_GPUMMUCAPS__union_0 __union_0;
public _DXGK_PAGETABLEUPDATEMODE PageTableUpdateMode;
public uint VirtualAddressBitCount;
public uint LeafPageTableSizeFor64KPagesInBytes;
public uint PageTableLevelCount;
public _DXGK_GPUMMUCAPS__struct_1 LegacyBehaviors;
}
}
| 33 | 90 | 0.732323 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/_DXGK_GPUMMUCAPS.cs | 596 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.