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.Threading;
using System.Threading.Tasks;
using Domain.Patients;
using Domain.Patients.Repositories;
using MapsterMapper;
namespace Application.Patients.Create
{
public class PatientCreator
{
private readonly IPatientsRepository _repository;
private readonly IMapper _mapper;
public PatientCreator(IPatientsRepository repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
public async Task CreatePatient(CreatePatientCommand patientCommand,
CancellationToken cancellation)
{
await _repository.Save(
_mapper.From(patientCommand).AdaptToType<Patient>(),
cancellation
);
}
}
}
| 26.533333 | 77 | 0.638191 | [
"MIT"
] | afgalvan/Tilia | src/Server/Application/Patients/Create/PatientCreator.cs | 798 | C# |
/*
Copyright (C) 2014-2016 de4dot@gmail.com
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Windows;
using System.Windows.Controls;
namespace dnSpy.AsmEditor.MethodBody {
sealed partial class MethodBodyControl : UserControl {
LocalsListHelper localsListHelper;
InstructionsListHelper instructionsListHelper;
ExceptionHandlersListHelper exceptionHandlersListHelper;
public MethodBodyControl() {
InitializeComponent();
DataContextChanged += MethodBodyControl_DataContextChanged;
Loaded += MethodBodyControl_Loaded;
}
void MethodBodyControl_Loaded(object sender, RoutedEventArgs e) {
Loaded -= MethodBodyControl_Loaded;
SetFocusToControl();
}
void SetFocusToControl() {
var data = DataContext as MethodBodyVM;
if (data == null)
return;
if (data.IsCilBody)
instructionsListView.Focus();
else
rvaTextBox.Focus();
}
void MethodBodyControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
var data = DataContext as MethodBodyVM;
if (data == null)
return;
var ownerWindow = Window.GetWindow(this);
localsListHelper = new LocalsListHelper(localsListView, ownerWindow);
instructionsListHelper = new InstructionsListHelper(instructionsListView, ownerWindow);
exceptionHandlersListHelper = new ExceptionHandlersListHelper(ehListView, ownerWindow);
localsListHelper.OnDataContextChanged(data);
instructionsListHelper.OnDataContextChanged(data);
exceptionHandlersListHelper.OnDataContextChanged(data);
}
}
}
| 32.223881 | 98 | 0.765169 | [
"MIT"
] | blackunixteam/dnSpy | AsmEditor/MethodBody/MethodBodyControl.xaml.cs | 2,161 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Identity.UI.V3.Pages.Account.Manage.Internal
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[IdentityDefaultUI(typeof(DeletePersonalDataModel<>))]
public abstract class DeletePersonalDataModel : PageModel
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[BindProperty]
public InputModel Input { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class InputModel
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public bool RequirePassword { get; set; }
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Task<IActionResult> OnGet() => throw new NotImplementedException();
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Task<IActionResult> OnPostAsync() => throw new NotImplementedException();
}
internal class DeletePersonalDataModel<TUser> : DeletePersonalDataModel where TUser : class
{
private readonly UserManager<TUser> _userManager;
private readonly SignInManager<TUser> _signInManager;
private readonly ILogger<DeletePersonalDataModel> _logger;
public DeletePersonalDataModel(
UserManager<TUser> userManager,
SignInManager<TUser> signInManager,
ILogger<DeletePersonalDataModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
public override async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
return Page();
}
public override async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
if (RequirePassword)
{
if (!await _userManager.CheckPasswordAsync(user, Input.Password))
{
ModelState.AddModelError(string.Empty, "Incorrect password.");
return Page();
}
}
var result = await _userManager.DeleteAsync(user);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user.");
}
await _signInManager.SignOutAsync();
_logger.LogInformation("User deleted themselves.");
return Redirect("~/");
}
}
}
| 40.694215 | 120 | 0.6184 | [
"Apache-2.0"
] | O4obsie/aspnetcore | src/Identity/UI/src/Areas/Identity/Pages/V3/Account/Manage/DeletePersonalData.cshtml.cs | 4,924 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookShop.Models.Enums;
using Remotion.Linq.Clauses;
namespace BookShop
{
using Data;
using Initializer;
public class StartUp
{
public static void Main()
{
using (var db = new BookShopContext())
{
Console.WriteLine(RemoveBooks(db));
}
}
public static int RemoveBooks(BookShopContext db)
{
var booksToRemove = db.Books
.Where(b => b.Copies < 4200)
.ToList();
var count = booksToRemove.Count;
db.Books.RemoveRange(booksToRemove);
db.SaveChanges();
return count;
}
public static void IncreasePrices(BookShopContext db)
{
var books = db.Books
.Where(b => b.ReleaseDate.Value.Year < 2010)
.ToList();
foreach (var book in books)
{
book.Price += 5;
}
db.SaveChanges();
}
public static string GetMostRecentBooks(BookShopContext db)
{
var sb = new StringBuilder();
var categories = db.Categories
.Select(c => new
{
c.Name,
Books = c.CategoryBooks
.OrderByDescending(b => b.Book.ReleaseDate.Value)
.Take(3)
.Select(b => new
{
b.Book.Title,
b.Book.ReleaseDate.Value.Year
})
.ToList()
})
.OrderBy(c => c.Name)
.ToList();
foreach (var category in categories)
{
sb.AppendLine($"--{category.Name}");
foreach (var book in category.Books)
{
sb.AppendLine($"{book.Title} ({book.Year})");
}
}
return sb.ToString().TrimEnd();
}
public static string GetTotalProfitByCategory(BookShopContext db)
{
var sb = new StringBuilder();
var categories = db.Categories
.Select(c => new
{
c.Name,
Profit = c.CategoryBooks.Sum(b => b.Book.Price * b.Book.Copies)
})
.OrderByDescending(c => c.Profit)
.ThenBy(c => c.Name)
.ToList();
foreach (var category in categories)
{
sb.AppendLine($"{category.Name} ${category.Profit:f2}");
}
return sb.ToString().TrimEnd();
}
public static string CountCopiesByAuthor(BookShopContext db)
{
var sb = new StringBuilder();
var authors = db.Authors
.Select(a => new
{
FullName = a.FirstName + " " + a.LastName,
Copies = a.Books.Sum(b => b.Copies)
})
.OrderByDescending(a => a.Copies)
.ToList();
foreach (var author in authors)
{
sb.AppendLine($"{author.FullName} - {author.Copies}");
}
return sb.ToString().TrimEnd();
}
public static int CountBooks(BookShopContext db, int lengthCheck)
{
return db.Books
.Count(b => b.Title.Length > lengthCheck);
}
public static string GetBooksByAuthor(BookShopContext db, string input)
{
var sb = new StringBuilder();
var books = db.Books
.Where(b => b.Author.LastName.ToLower().StartsWith(input.ToLower()))
.OrderBy(b => b.BookId)
.Select(b => new
{
b.Title,
AuthorFullName = b.Author.FirstName + " " + b.Author.LastName
})
.ToList();
foreach (var book in books)
{
sb.AppendLine($"{book.Title} ({book.AuthorFullName})");
}
return sb.ToString().TrimEnd();
}
public static string GetBookTitlesContaining(BookShopContext db, string input)
{
var sb = new StringBuilder();
var books = db.Books
.Select(b => b.Title)
.Where(b => b.ToLower().Contains(input.ToLower()))
.OrderBy(b => b)
.ToList();
foreach (var title in books)
{
sb.AppendLine($"{title}");
}
return sb.ToString().TrimEnd();
}
public static string GetAuthorNamesEndingIn(BookShopContext db, string nameEnding)
{
var sb = new StringBuilder();
var authors = db.Authors
.Select(a => new
{
a.FirstName,
a.LastName
})
.Where(a => a.FirstName.EndsWith(nameEnding))
.OrderBy(a => a.FirstName)
.ThenBy(a => a.LastName)
.ToList();
foreach (var a in authors)
{
sb.AppendLine($"{a.FirstName} {a.LastName}");
}
return sb.ToString().TrimEnd();
}
public static string GetBooksReleasedBefore(BookShopContext db, string date)
{
var sb = new StringBuilder();
var dateParams = date.Split("-").Select(int.Parse).ToList();
var day = dateParams[0];
var month = dateParams[1];
var year = dateParams[2];
var books = db.Books
.Where(b => b.ReleaseDate.Value < new DateTime(year, month, day))
.OrderByDescending(b => b.ReleaseDate.Value)
.Select(b => new {
b.Title,
b.EditionType,
b.Price
})
.ToList();
foreach (var book in books)
{
sb.AppendLine($"{book.Title} - {book.EditionType} - ${book.Price:f2}");
}
return sb.ToString().TrimEnd();
}
public static string GetBooksByCategory(BookShopContext db, string input)
{
var sb = new StringBuilder();
var categories = input.Split(" ");
var totalBooks = new List<string>();
foreach (var category in categories)
{
var books = db.Books
.Where(b => b.BookCategories.Any(c => c.Category.Name.ToLower() == category.ToLower()))
.Select(b => b.Title)
.ToList();
totalBooks.AddRange(books);
}
foreach (var book in totalBooks.OrderBy(b => b))
{
sb.AppendLine($"{book}");
}
return sb.ToString().TrimEnd();
}
public static string GetBooksNotReleasedIn(BookShopContext db, int year)
{
var sb = new StringBuilder();
var books = db.Books
.Where(b => b.ReleaseDate.Value.Year != year)
.OrderBy(b => b.BookId)
.Select(b => b.Title)
.ToList();
foreach (var book in books)
{
sb.AppendLine($"{book}");
}
return sb.ToString().TrimEnd();
}
public static string GetBooksByPrice(BookShopContext db)
{
var sb = new StringBuilder();
var books = db.Books
.Where(b => b.Price > 40)
.OrderByDescending(b => b.Price)
.Select(b => new
{
b.Title,
b.Price
})
.ToList();
foreach (var book in books)
{
sb.AppendLine($"{book.Title} - ${book.Price:f2}");
}
return sb.ToString().TrimEnd();
}
public static string GetGoldenBooks(BookShopContext db)
{
var sb = new StringBuilder();
var goldenBooks = db.Books
.Where(b => b.EditionType == EditionType.Gold && b.Copies < 5000)
.OrderBy(b => b.BookId)
.Select(b => b.Title)
.ToList();
foreach (var book in goldenBooks)
{
sb.AppendLine($"{book}");
}
return sb.ToString().TrimEnd();
}
public static string GetBooksByAgeRestriction(BookShopContext db, string command)
{
var sb = new StringBuilder();
var books = new List<string>();
if (command.ToLower() == "minor")
{
books = db.Books
.Where(b => b.AgeRestriction == AgeRestriction.Minor)
.Select(b => b.Title)
.OrderBy(t => t)
.ToList();
}else if (command.ToLower() == "teen")
{
books = db.Books
.Where(b => b.AgeRestriction == AgeRestriction.Teen)
.Select(b => b.Title)
.OrderBy(t => t)
.ToList();
}else if (command.ToLower() == "adult")
{
books = db.Books
.Where(b => b.AgeRestriction == AgeRestriction.Adult)
.Select(b => b.Title)
.OrderBy(t => t)
.ToList();
}
foreach (var title in books)
{
sb.AppendLine($"{title}");
}
return sb.ToString().TrimEnd();
}
}
}
| 29.104956 | 107 | 0.439748 | [
"Apache-2.0"
] | KostadinovK/CSharp-DB | 02-Entity Framework Core/06-Advanced Quering/Homework/BookShop/StartUp.cs | 9,985 | C# |
namespace JoinRpg.Dal.Impl.Migrations
{
using System.Data.Entity.Migrations;
public partial class SplitPlots : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.PlotElementTexts",
c => new
{
PlotElementId = c.Int(nullable: false),
Content_Contents = c.String(),
TodoField = c.String(),
})
.PrimaryKey(t => t.PlotElementId)
.ForeignKey("dbo.PlotElements", t => t.PlotElementId)
.Index(t => t.PlotElementId);
Sql(@"INSERT INTO [dbo].[PlotElementTexts] ([PlotElementId] ,[Content_Contents], [TodoField])
SELECT PlotElementId, Content_Contents, [TodoField] FROM [dbo].[PlotElements]
");
DropColumn("dbo.PlotElements", "MasterSummary_Contents");
DropColumn("dbo.PlotElements", "Content_Contents");
DropColumn("dbo.PlotElements", "TodoField");
}
public override void Down()
{
AddColumn("dbo.PlotElements", "TodoField", c => c.String());
AddColumn("dbo.PlotElements", "Content_Contents", c => c.String());
AddColumn("dbo.PlotElements", "MasterSummary_Contents", c => c.String());
DropForeignKey("dbo.PlotElementTexts", "PlotElementId", "dbo.PlotElements");
DropIndex("dbo.PlotElementTexts", new[] { "PlotElementId" });
DropTable("dbo.PlotElementTexts");
}
}
}
| 38.8 | 99 | 0.556701 | [
"MIT"
] | FulcrumVlsM/joinrpg-net | JoinRpg.Dal.Impl/Migrations/201605081122204_SplitPlots.cs | 1,552 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static Root;
public struct BinaryEval<K,T,R>
{
public K Kind;
public T A;
public T B;
public R Result;
}
public struct BinaryEval<T> : IBinaryEval<T>
{
public T A {get;}
public T B {get;}
public bit Result {get;}
[MethodImpl(Inline)]
public BinaryEval(T a, T b, bit success)
{
A = a;
B = b;
Result = success;
}
[MethodImpl(Inline)]
public static bool operator true(BinaryEval<T> src)
=> src.Result;
[MethodImpl(Inline)]
public static bool operator false(BinaryEval<T> src)
=> !src.Result;
}
} | 21.595745 | 79 | 0.436453 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/check/src/eval/models/BinaryEval.cs | 1,015 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Areas operations.
/// </summary>
public partial interface IAreas
{
/// <summary>
/// Get entities from adoxio_areas
/// </summary>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioAreaCollection>> GetWithHttpMessagesAsync(int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add new entity to adoxio_areas
/// </summary>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation
/// of the object.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioArea>> CreateWithHttpMessagesAsync(MicrosoftDynamicsCRMadoxioArea body, string prefer = "return=representation", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get entity from adoxio_areas by key
/// </summary>
/// <param name='adoxioAreaid'>
/// key: adoxio_areaid of adoxio_area
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioArea>> GetByKeyWithHttpMessagesAsync(string adoxioAreaid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update entity in adoxio_areas
/// </summary>
/// <param name='adoxioAreaid'>
/// key: adoxio_areaid of adoxio_area
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string adoxioAreaid, MicrosoftDynamicsCRMadoxioArea body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete entity from adoxio_areas
/// </summary>
/// <param name='adoxioAreaid'>
/// key: adoxio_areaid of adoxio_area
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string adoxioAreaid, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 44.916667 | 515 | 0.609533 | [
"Apache-2.0"
] | brianorwhatever/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/IAreas.cs | 7,007 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyWebServer.Server.Http
{
public class HttpRequest
{
private const string NewLine = "\r\n";
public HttpMethod Method { get; private set; }
public string Path { get; private set; }
public Dictionary<string, string> Query { get; private set; }
public IReadOnlyDictionary<string, HttpCookie> Cookies = new Dictionary<string, HttpCookie>();
public HttpHeaderCollection Headers { get; private set; }
public string Body { get; private set; }
public static HttpRequest Parse(string request)
{
var lines = request.Split(NewLine);
var startLine = lines.First().Split(" ");
var method = ParseHttpMethod(startLine[0]);
var url = startLine[1];
var (path, query) = ParseUrl(url);
var headers = ParseHttpHeaders(lines.Skip(1));
var bodyLines = lines.Skip(headers.Count + 2).ToArray();
var body = string.Join(NewLine, bodyLines);
return new HttpRequest
{
Method = method,
Path = path,
Query = query,
Headers = headers,
Body = body
};
}
private static HttpMethod ParseHttpMethod(string method)
=> method.ToUpper() switch
{
"GET" => HttpMethod.Get,
"POST" => HttpMethod.Post,
"PUT" => HttpMethod.Put,
"DELETE" => HttpMethod.Delete,
_ => throw new InvalidOperationException($"Method '{method}' is not supported."),
};
private static (string, Dictionary<string, string>) ParseUrl(string url)
{
var urlParts = url.Split('?', 2);
var path = urlParts[0];
var query = urlParts.Length > 1
? ParseQuery(urlParts[1])
: new Dictionary<string, string>();
return (path, query);
}
private static Dictionary<string, string> ParseQuery(string queryString)
=> queryString
.Split('&')
.Select(part => part.Split('='))
.Where(part => part.Length == 2)
.ToDictionary(part => part[0], part => part[1]);
private static HttpHeaderCollection ParseHttpHeaders(IEnumerable<string> headerLines)
{
var headerCollection = new HttpHeaderCollection();
foreach (var headerLine in headerLines)
{
if (headerLine == string.Empty)
{
break;
}
var headerParts = headerLine.Split(":", 2);
if (headerParts.Length != 2)
{
throw new InvalidOperationException("Request is not valid.");
}
var headerName = headerParts[0];
var headerValue = headerParts[1].Trim();
headerCollection.Add(headerName, headerValue);
}
return headerCollection;
}
}
}
| 29.794393 | 102 | 0.522898 | [
"MIT"
] | vasiltatarov/CSharp-Web-Server | MyWebServer.Server/Http/HttpRequest.cs | 3,190 | C# |
namespace HtmlDocument.UnitTests
{
using System.Text;
using HtmlStringWriter.Attributes.Style.Border;
using HtmlStringWriter.StaticClasses;
using NUnit.Framework;
public class BorderNoneTests
{
private BorderNone _borderNone;
[SetUp]
public void Setup()
{
_borderNone = new BorderNone();
}
[Test]
public void ToHtmlString_WhenCalled_ReturnsString()
{
var result = _borderNone.ToHtmlString();
AssertBoarderNone(result);
}
[Test]
public void ToHtmlString_WhenCalled_FillsStringBuilders()
{
var sb = new StringBuilder();
_borderNone.ToHtmlString(sb);
var result = sb.ToString();
AssertBoarderNone(result);
}
private static void AssertBoarderNone(string result)
{
Assert.That(result, Does.StartWith("border: "));
Assert.That(result, Does.EndWith($"{Constants.None};"));
}
}
} | 25.585366 | 68 | 0.581506 | [
"MIT"
] | UltimateHardCoder/html-string-writer | HtmlStringWriterTests/BorderNoneTests.cs | 1,049 | C# |
namespace Logger.Factories
{
using Contracts;
using Enums;
using Appenders;
using System;
public class AppenderFactory
{
const string DEFAULT_FILE = "logFile{0}.txt";
private int fileAppenders = 0;
private LayoutFactory layouts;
public AppenderFactory(LayoutFactory layouts)
{
this.layouts = layouts;
}
public IAppender CreateAppender(string appenderType, string errorString, string layoutType)
{
var layout = this.layouts.CreateLayout(layoutType);
var errorLevel = default(ErrorLevel);
var success = Enum.TryParse(errorString, true, out errorLevel);
if (!success)
{
throw new ArgumentException("Invalid error level type!");
}
if (appenderType == nameof(ConsoleAppender))
{
return new ConsoleAppender(layout, errorLevel);
}
else if (appenderType == nameof(FileLogger))
{
return new FileLogger(string.Format(DEFAULT_FILE, ++fileAppenders));
}
else
{
throw new ArgumentException("Invalid appender type!");
}
}
}
}
| 27.717391 | 99 | 0.559216 | [
"MIT"
] | spzvtbg/03-Fundamentals | 03 OOP advanced/01. SOLID/Logger/Factories/AppenderFactory.cs | 1,277 | C# |
using BeyondEarthApp.Data.Entities;
namespace BeyondEarthApp.Data.QueryProcessors
{
public interface IAddGameQueryProcessor
{
void AddGame(Game game);
}
}
| 17.7 | 45 | 0.728814 | [
"MIT"
] | camjm/BeyondEarthApp | src/BeyondEarthApp.Data/QueryProcessors/IAddGameQueryProcessor.cs | 179 | C# |
using System.Collections.Generic;
using Abp.Application.Services.Dto;
using SPA.DocumentManager.PlanProjects;
namespace SPA.DocumentManager.PlanProjects.Dtos
{
public class GetPlanProjectForEditOutput
{
////BCC/ BEGIN CUSTOM CODE SECTION
////ECC/ END CUSTOM CODE SECTION
public PlanProjectEditDto PlanProject { get; set; }
}
} | 24.357143 | 59 | 0.774194 | [
"MIT"
] | lzhm216/dmproject | aspnet-core/src/SPA.DocumentManager.Application/PlanProjects/Dtos/GetPlanProjectForEditOutput.cs | 343 | C# |
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.Orleans.SwaggerGen;
namespace Microsoft.Extensions.DependencyInjection
{
public static class SwaggerGenServiceCollectionExtensions
{
public static IServiceCollection AddOrleansSwaggerGen(
this IServiceCollection services,
Action<OrleansSwaggerGenOptions> orleansOption, Action<SwaggerGenOptions> swaggerAction = null)
{
OrleansSwaggerGenOptions swaggerGenOptions = new OrleansSwaggerGenOptions();
orleansOption.Invoke(swaggerGenOptions);
services.AddSwaggerGen(opt =>
{
opt.ParameterFilter<GrainKeyParmeterFilter>(swaggerGenOptions);
swaggerAction?.Invoke(opt);
});
services.Configure<OrleansSwaggerGenOptions>(orleansOption);
services.AddSingleton<IApiDescriptionGroupCollectionProvider, OrleansApiDescriptionGroupCollectionProvider>();
return services;
}
}
}
| 35.666667 | 122 | 0.722175 | [
"Apache-2.0"
] | aqa510415008/Swashbuckle.Orleans.SwaggerGen | src/Swashbuckle.Orleans.SwaggerGen/SwaggerGenServiceCollectionExtensions.cs | 1,179 | C# |
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class InteractiveSnowTarget : TargetRules
{
public InteractiveSnowTarget( TargetInfo Target) : base(Target)
{
Type = TargetType.Game;
DefaultBuildSettings = BuildSettingsVersion.V2;
ExtraModuleNames.AddRange( new string[] { "InteractiveSnow" } );
}
}
| 25.133333 | 66 | 0.771883 | [
"MIT"
] | Zhibade/interactive-snow-unreal | Source/InteractiveSnow.Target.cs | 377 | C# |
using System.Web;
using System.Web.Mvc;
namespace OrderSystem
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 18.857143 | 80 | 0.655303 | [
"MIT"
] | plamengeorgiev/OrderSystem | OrderSystem/OrderSystem/App_Start/FilterConfig.cs | 266 | C# |
using NUnit.Framework;
using GVDCore.Common.Maths;
namespace GVDCore_Test.Common.Maths
{
[TestFixture]
[Category( "CommonMaths" )]
public class CommonMaths_Test
{
//-------------------------------------------------------------------------
[Test]
public void Lerp()
{
Assert.AreEqual(
10.0,
CommonMaths.Lerp( 10.0, 20.0, 0.0 ) );
Assert.AreEqual(
12.0,
CommonMaths.Lerp( 10.0, 20.0, 0.2 ) );
Assert.AreEqual(
20.0,
CommonMaths.Lerp( 10.0, 20.0, 1.0 ) );
// Go out-of-range with clamping.
Assert.AreEqual(
20.0,
CommonMaths.Lerp( 10.0, 20.0, 1.1 ) );
// Go out-of-range without clamping.
Assert.AreEqual(
21.0,
CommonMaths.Lerp( 10.0, 20.0, 1.1, false ) );
}
//-------------------------------------------------------------------------
[Test]
public void RangeLerp()
{
Assert.AreEqual(
100.0,
CommonMaths.Lerp(
0.0,
0.0, 10.0,
100.0, 200.0 ) );
Assert.AreEqual(
180.0,
CommonMaths.Lerp(
8.0,
0.0, 10.0,
100.0, 200.0 ) );
Assert.AreEqual(
200.0,
CommonMaths.Lerp(
10.0,
0.0, 10.0,
100.0, 200.0 ) );
// Go out-of-range with clamping.
Assert.AreEqual(
200.0,
CommonMaths.Lerp(
11.0,
0.0, 10.0,
100.0, 200.0 ) );
// Go out-of-range without clamping.
Assert.AreEqual(
210.0,
CommonMaths.Lerp(
11.0,
0.0, 10.0,
100.0, 200.0,
false ) );
}
//-------------------------------------------------------------------------
}
}
| 20.952941 | 79 | 0.408198 | [
"MIT"
] | grae22/GroundVehicleDynamics | GVDCore_Test/Common/Maths/CommonMaths_Test.cs | 1,783 | C# |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using Microsoft.WindowsAzure.MobileServices.TestFramework;
namespace Microsoft.WindowsAzure.MobileServices.Test
{
[Tag("authentication")]
[Tag("unit")]
public class AuthenticationBrokerTest : TestBase
{
[TestMethod]
public void GetUrlWithQueryStringParameter_StartUrlContainsNoQueryParameters()
{
GetUrlWithQueryStringParameter_Setup(
startUrl: "https://foobar.azurewebsites.net/.auth/login/aad",
param: "param",
paramValue: "value",
expectedResult: "https://foobar.azurewebsites.net/.auth/login/aad?param=value");
}
[TestMethod]
public void GetUrlWithQueryStringParameter_StartUrlContainsOneQueryParameter()
{
GetUrlWithQueryStringParameter_Setup(
startUrl: "https://foobar.azurewebsites.net/.auth/login/aad?param1=value1",
param: "param2",
paramValue: "value2",
expectedResult: "https://foobar.azurewebsites.net/.auth/login/aad?param1=value1¶m2=value2");
}
[TestMethod]
public void GetUrlWithQueryStringParameter_StartUrlContainsTwoQueryParameters()
{
GetUrlWithQueryStringParameter_Setup(
startUrl: "https://foobar.azurewebsites.net/.auth/login/aad?param1=value1¶m2=value2",
param: "param3",
paramValue: "value3",
expectedResult: "https://foobar.azurewebsites.net/.auth/login/aad?param1=value1¶m2=value2¶m3=value3");
}
[TestMethod]
public void GetUrlWithQueryStringParameter_Throws_WhenArgumentIsNull()
{
AssertEx.Throws<ArgumentNullException>(() => new AuthenticationBroker().GetUrlWithQueryStringParameter(url: null, queryParameter: "param", queryValue: "value"));
AssertEx.Throws<ArgumentNullException>(() => new AuthenticationBroker().GetUrlWithQueryStringParameter(url: new Uri("https://foobar.azurewebsites.net/.auth/login/aad"), queryParameter: null, queryValue: "value"));
AssertEx.Throws<ArgumentNullException>(() => new AuthenticationBroker().GetUrlWithQueryStringParameter(url: new Uri("https://foobar.azurewebsites.net/.auth/login/aad"), queryParameter: "param", queryValue: null));
}
private static void GetUrlWithQueryStringParameter_Setup(string startUrl, string param, string paramValue, string expectedResult)
{
Uri result = new AuthenticationBroker().GetUrlWithQueryStringParameter(new Uri(startUrl), param, paramValue);
Assert.AreEqual(expectedResult, result.AbsoluteUri);
}
}
}
| 48.666667 | 225 | 0.638699 | [
"Apache-2.0"
] | AndreyMitsyk/azure-mobile-apps-net-client | unittest/Microsoft.WindowsAzure.MobileServices.UWP.Test/UnitTests/AuthenticationBroker.Test.cs | 2,922 | C# |
using System;
using VehicleRegistrationService.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace VehicleRegistrationService
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IVehicleInfoRepository, InMemoryVehicleInfoRepository>();
var daprHttpPort = Environment.GetEnvironmentVariable("DAPR_HTTP_PORT") ?? "3602";
var daprGrpcPort = Environment.GetEnvironmentVariable("DAPR_GRPC_PORT") ?? "60002";
services.AddDaprClient(builder => builder
.UseHttpEndpoint($"http://localhost:{daprHttpPort}")
.UseGrpcEndpoint($"http://localhost:{daprGrpcPort}"));
services.AddControllers().AddDapr();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCloudEvents();
// app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 32.127273 | 106 | 0.642332 | [
"Apache-2.0"
] | EdwinVW/dapr-traffic-control | src/VehicleRegistrationService/Startup.cs | 1,767 | C# |
using Backfy.Albums.Query.Result;
using Backfy.Common.Infra.Helpers;
using Backfy.Common.Infra.Services.Interfaces;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Backfy.Albums.Query.Handler
{
/// <summary>
/// QueryHandler to get a specified album
/// </summary>
public class GetAlbumQueryHandler : IRequestHandler<GetAlbumQuery, GetAlbumQueryResult>
{
private readonly ISpotifyService spotifyService;
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumQueryHandler"/> class.
/// </summary>
/// <param name="spotifyService">The spotify service depencency</param>
public GetAlbumQueryHandler(ISpotifyService spotifyService)
{
this.spotifyService = spotifyService;
}
/// <summary>
/// The handle to get requested album
/// </summary>
/// <param name="request">The request with filter params</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The task with the requested album</returns>
public async Task<GetAlbumQueryResult> Handle(GetAlbumQuery request, CancellationToken cancellationToken)
{
BusinessValidation(request);
var album = await spotifyService.GetAlbumAsync(request.Id);
return await Task.FromResult(new GetAlbumQueryResult(album.Id, album.Name, album.ReleaseDate, album.TotalTracks, RandomPricesHelper.GetPrice()));
}
private void BusinessValidation(GetAlbumQuery request)
{
if (string.IsNullOrEmpty(request?.Id))
throw new Exception("Id inválido");
}
}
}
| 35.469388 | 157 | 0.666858 | [
"MIT"
] | gsGabriel/backfy | src/Albums/Backfy.Albums.Query/Handler/GetAlbumQueryHandler.cs | 1,741 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler
{
class Problem41
{
private Sieve s;
private string pandigital;
private long upper;
public Problem41()
{
upper = 987654321;
pandigital = "123456789";
s = new Sieve(upper + 1);
Console.WriteLine("Sieve populated");
}
private string Integers(long n)
{
List<int> intList = new List<int>();
string strN = n.ToString();
for (int i = 0; i < strN.Length; i++)
{
intList.Add(int.Parse(strN[i].ToString()));
}
intList.Sort();
string res = "";
foreach (int item in intList)
{
res += item.ToString();
}
return res;
}
public string Run()
{
long number = upper;
while (number > 0)
{
if (s.prime[number])
{
if (Integers(number) == pandigital.Substring(0, number.ToString().Length))
{
return number.ToString();
}
}
number--;
}
return "Not found";
}
}
}
| 23.40678 | 94 | 0.426503 | [
"MIT"
] | fireheadmx/ProjectEuler | Problems/Problem41.cs | 1,381 | 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("DecoupledWcfServices")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DecoupledWcfServices")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("0f8f7908-8891-45ff-b1cd-2972b208b6b9")]
// 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.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("DecoupledWcfServices.Tests")] | 38.789474 | 84 | 0.751696 | [
"BSD-2-Clause"
] | rhyous/DecoupledWcfServices | src/DecoupledWcfServices/Properties/AssemblyInfo.cs | 1,477 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace shapeCalculator.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.516129 | 151 | 0.583178 | [
"MIT"
] | moehawamdeh/C-sharp-playground | shapeCalculator/shapeCalculator/Properties/Settings.Designer.cs | 1,072 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the personalize-2018-05-22.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Personalize.Model
{
/// <summary>
/// Container for the parameters to the CreateDatasetImportJob operation.
/// Creates a job that imports training data from your data source (an Amazon S3 bucket)
/// to an Amazon Personalize dataset. To allow Amazon Personalize to import the training
/// data, you must specify an AWS Identity and Access Management (IAM) role that has permission
/// to read from the data source, as Amazon Personalize makes a copy of your data and
/// processes it in an internal AWS system.
///
/// <important>
/// <para>
/// The dataset import job replaces any existing data in the dataset that you imported
/// in bulk.
/// </para>
/// </important>
/// <para>
/// <b>Status</b>
/// </para>
///
/// <para>
/// A dataset import job can be in one of the following states:
/// </para>
/// <ul> <li>
/// <para>
/// CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
/// </para>
/// </li> </ul>
/// <para>
/// To get the status of the import job, call <a>DescribeDatasetImportJob</a>, providing
/// the Amazon Resource Name (ARN) of the dataset import job. The dataset import is complete
/// when the status shows as ACTIVE. If the status shows as CREATE FAILED, the response
/// includes a <code>failureReason</code> key, which describes why the job failed.
/// </para>
/// <note>
/// <para>
/// Importing takes time. You must wait until the status shows as ACTIVE before training
/// a model using the dataset.
/// </para>
/// </note> <p class="title"> <b>Related APIs</b>
/// </para>
/// <ul> <li>
/// <para>
/// <a>ListDatasetImportJobs</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeDatasetImportJob</a>
/// </para>
/// </li> </ul>
/// </summary>
public partial class CreateDatasetImportJobRequest : AmazonPersonalizeRequest
{
private string _datasetArn;
private DataSource _dataSource;
private string _jobName;
private string _roleArn;
/// <summary>
/// Gets and sets the property DatasetArn.
/// <para>
/// The ARN of the dataset that receives the imported data.
/// </para>
/// </summary>
[AWSProperty(Required=true, Max=256)]
public string DatasetArn
{
get { return this._datasetArn; }
set { this._datasetArn = value; }
}
// Check to see if DatasetArn property is set
internal bool IsSetDatasetArn()
{
return this._datasetArn != null;
}
/// <summary>
/// Gets and sets the property DataSource.
/// <para>
/// The Amazon S3 bucket that contains the training data to import.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public DataSource DataSource
{
get { return this._dataSource; }
set { this._dataSource = value; }
}
// Check to see if DataSource property is set
internal bool IsSetDataSource()
{
return this._dataSource != null;
}
/// <summary>
/// Gets and sets the property JobName.
/// <para>
/// The name for the dataset import job.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=63)]
public string JobName
{
get { return this._jobName; }
set { this._jobName = value; }
}
// Check to see if JobName property is set
internal bool IsSetJobName()
{
return this._jobName != null;
}
/// <summary>
/// Gets and sets the property RoleArn.
/// <para>
/// The ARN of the IAM role that has permissions to read from the Amazon S3 data source.
/// </para>
/// </summary>
[AWSProperty(Required=true, Max=256)]
public string RoleArn
{
get { return this._roleArn; }
set { this._roleArn = value; }
}
// Check to see if RoleArn property is set
internal bool IsSetRoleArn()
{
return this._roleArn != null;
}
}
} | 32.054878 | 109 | 0.585505 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/Personalize/Generated/Model/CreateDatasetImportJobRequest.cs | 5,257 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace PaperMarioBattleSystem
{
/// <summary>
/// The Sequence for Mario's Mega Smash move.
/// </summary>
public sealed class MegaSmashSequence : HammerSequence
{
private AfterImageVFX AfterImages = null;
//Mega Smash adds 4 damage
public MegaSmashSequence(MoveAction moveAction) : base(moveAction, 4)
{
}
protected override void OnStart()
{
base.OnStart();
//Add after-images to the user
AfterImages = new AfterImageVFX(User, 4, 4, .2f,
AfterImageVFX.AfterImageAlphaSetting.FadeOff, AfterImageVFX.AfterImageAnimSetting.Current);
//Update as many times as there are after-images to add several after-images in place
//This prevents them from suddenly popping in while the BattleEntity is walking towards the target
for (int i = 0; i < AfterImages.MaxAfterImages; i++)
{
AfterImages.Update();
}
User.BManager.battleObjManager.AddBattleObject(AfterImages);
}
protected override void OnEnd()
{
base.OnEnd();
//Remove if somehow not removed by now
RemoveAfterImages();
}
protected override void OnInterruption(Enumerations.Elements element)
{
//Remove after-images if interrupted
RemoveAfterImages();
base.OnInterruption(element);
}
protected override void CommandSuccess()
{
RemoveAfterImages();
base.CommandSuccess();
}
protected override void CommandFailed()
{
RemoveAfterImages();
base.CommandFailed();
}
private void RemoveAfterImages()
{
if (AfterImages != null)
{
User.BManager.battleObjManager.RemoveBattleObject(AfterImages);
AfterImages = null;
}
}
}
}
| 27.839506 | 111 | 0.561863 | [
"Unlicense"
] | kimimaru4000/PaperMarioBattleSystem | PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/Sequences/Mario/MegaSmashSequence.cs | 2,257 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HopfieldNetwork.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.516129 | 151 | 0.583178 | [
"MIT"
] | michael-novikov/hopfield-network | hopfield-network/Properties/Settings.Designer.cs | 1,072 | C# |
namespace EFCorePowerTools.ViewModels
{
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Contracts.EventArgs;
using Contracts.ViewModels;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using Shared.DAL;
using Shared.Models;
public class PickServerDatabaseViewModel : ViewModelBase, IPickServerDatabaseViewModel
{
private readonly IVisualStudioAccess _visualStudioAccess;
private DatabaseConnectionModel _selectedDatabaseConnection;
private DatabaseDefinitionModel _selectedDatabaseDefinition;
public event EventHandler<CloseRequestedEventArgs> CloseRequested;
public ICommand LoadedCommand { get; }
public ICommand AddDatabaseConnectionCommand { get; }
public ICommand OkCommand { get; }
public ICommand CancelCommand { get; }
public ObservableCollection<DatabaseConnectionModel> DatabaseConnections { get; }
public ObservableCollection<DatabaseDefinitionModel> DatabaseDefinitions { get; }
public DatabaseConnectionModel SelectedDatabaseConnection
{
get => _selectedDatabaseConnection;
set
{
if (Equals(value, _selectedDatabaseConnection)) return;
_selectedDatabaseConnection = value;
RaisePropertyChanged();
if (_selectedDatabaseConnection != null)
SelectedDatabaseDefinition = null;
}
}
public DatabaseDefinitionModel SelectedDatabaseDefinition
{
get => _selectedDatabaseDefinition;
set
{
if (Equals(value, _selectedDatabaseDefinition)) return;
_selectedDatabaseDefinition = value;
RaisePropertyChanged();
if (_selectedDatabaseDefinition != null)
SelectedDatabaseConnection = null;
}
}
public PickServerDatabaseViewModel(IVisualStudioAccess visualStudioAccess)
{
_visualStudioAccess = visualStudioAccess ?? throw new ArgumentNullException(nameof(visualStudioAccess));
LoadedCommand = new RelayCommand(Loaded_Executed);
AddDatabaseConnectionCommand = new RelayCommand(AddDatabaseConnection_Executed);
OkCommand = new RelayCommand(Ok_Executed, Ok_CanExecute);
CancelCommand = new RelayCommand(Cancel_Executed);
DatabaseConnections = new ObservableCollection<DatabaseConnectionModel>();
DatabaseDefinitions = new ObservableCollection<DatabaseDefinitionModel>();
DatabaseDefinitions.CollectionChanged += (sender, args) => RaisePropertyChanged(nameof(DatabaseDefinitions));
}
private void Loaded_Executed()
{
if (DatabaseConnections.Any())
SelectedDatabaseConnection = DatabaseConnections.First();
}
private void AddDatabaseConnection_Executed()
{
DatabaseConnectionModel newDatabaseConnection;
try
{
newDatabaseConnection = _visualStudioAccess.PromptForNewDatabaseConnection();
}
catch (Exception e)
{
_visualStudioAccess.ShowMessage("Unable to add connection, maybe the provider is not supported: " + e.Message);
return;
}
if (newDatabaseConnection == null)
return;
DatabaseConnections.Add(newDatabaseConnection);
SelectedDatabaseConnection = newDatabaseConnection;
}
private void Ok_Executed()
{
CloseRequested?.Invoke(this, new CloseRequestedEventArgs(true));
}
private bool Ok_CanExecute() => SelectedDatabaseConnection != null || SelectedDatabaseDefinition != null;
private void Cancel_Executed()
{
SelectedDatabaseConnection = null;
SelectedDatabaseDefinition = null;
CloseRequested?.Invoke(this, new CloseRequestedEventArgs(false));
}
}
} | 36.849558 | 127 | 0.649856 | [
"MIT"
] | Superflemme/EFCorePowerTools | src/GUI/EFCorePowerTools/ViewModels/PickServerDatabaseViewModel.cs | 4,166 | C# |
using Unity.Entities;
using UnityEngine;
namespace Example.Danmaku
{
//attaches to the spawner prefab.
//tells the spawner what bullet to spawn.
[GenerateAuthoringComponent]
public struct BulletBlobIndexData : IComponentData
{
[HideInInspector] public int index;
}
} | 23.076923 | 54 | 0.716667 | [
"MIT"
] | DOTS-Discord/Example-Bullet-Hell-game | Assets/Game_Assets/Danmaku/Scripts/Component/Data/BulletBlobIndexData.cs | 302 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicPlate : MonoBehaviour
{
public bool flag = true;
}
| 17 | 39 | 0.777778 | [
"MIT"
] | SoliShim/Open-Source-Programming-2021 | EffectDemo/Assets/Scripts/Plate/BasicPlate.cs | 153 | C# |
using System;
using System.ComponentModel;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions;
using BizHawk.Emulation.Cores.Nintendo.NES;
using BizHawk.Emulation.Cores.PCEngine;
using BizHawk.Emulation.Cores.Sega.MasterSystem;
using BizHawk.Emulation.Cores.WonderSwan;
using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES;
using NLua;
namespace BizHawk.Client.Common
{
[Description("A library for interacting with the currently loaded emulator core")]
public sealed class EmulatorLuaLibrary : LuaLibraryBase
{
[RequiredService]
private IEmulator Emulator { get; set; }
[OptionalService]
private IDebuggable DebuggableCore { get; set; }
[OptionalService]
private IDisassemblable DisassemblableCore { get; set; }
[OptionalService]
private IMemoryDomains MemoryDomains { get; set; }
[OptionalService]
private IInputPollable InputPollableCore { get; set; }
[OptionalService]
private IRegionable RegionableCore { get; set; }
[OptionalService]
private IBoardInfo BoardInfo { get; set; }
public Action FrameAdvanceCallback { get; set; }
public Action YieldCallback { get; set; }
public EmulatorLuaLibrary(Lua lua)
: base(lua) { }
public EmulatorLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { }
public override string Name => "emu";
[LuaMethodExample("emu.displayvsync( true );")]
[LuaMethod("displayvsync", "Sets the display vsync property of the emulator")]
public static void DisplayVsync(bool enabled)
{
Global.Config.VSync = enabled;
}
[LuaMethodExample("emu.frameadvance( );")]
[LuaMethod("frameadvance", "Signals to the emulator to resume emulation. Necessary for any lua script while loop or else the emulator will freeze!")]
public void FrameAdvance()
{
FrameAdvanceCallback();
}
[LuaMethodExample("local inemufra = emu.framecount( );")]
[LuaMethod("framecount", "Returns the current frame count")]
public int FrameCount()
{
return Emulator.Frame;
}
[LuaMethodExample("local obemudis = emu.disassemble( 0x8000 );")]
[LuaMethod("disassemble", "Returns the disassembly object (disasm string and length int) for the given PC address. Uses System Bus domain if no domain name provided")]
public object Disassemble(uint pc, string name = "")
{
try
{
if (DisassemblableCore == null)
{
throw new NotImplementedException();
}
int l;
MemoryDomain domain = MemoryDomains.SystemBus;
if (!string.IsNullOrEmpty(name))
{
domain = MemoryDomains[name];
}
var d = DisassemblableCore.Disassemble(domain, pc, out l);
return new { disasm = d, length = l };
}
catch (NotImplementedException)
{
Log($"Error: {Emulator.Attributes().CoreName} does not yet implement {nameof(IDisassemblable.Disassemble)}()");
return null;
}
}
// TODO: what about 64 bit registers?
[LuaMethodExample("local inemuget = emu.getregister( emu.getregisters( )[ 0 ] );")]
[LuaMethod("getregister", "returns the value of a cpu register or flag specified by name. For a complete list of possible registers or flags for a given core, use getregisters")]
public int GetRegister(string name)
{
try
{
if (DebuggableCore == null)
{
throw new NotImplementedException();
}
var registers = DebuggableCore.GetCpuFlagsAndRegisters();
return registers.ContainsKey(name)
? (int)registers[name].Value
: 0;
}
catch (NotImplementedException)
{
Log($"Error: {Emulator.Attributes().CoreName} does not yet implement {nameof(IDebuggable.GetCpuFlagsAndRegisters)}()");
return 0;
}
}
[LuaMethodExample("local nlemuget = emu.getregisters( );")]
[LuaMethod("getregisters", "returns the complete set of available flags and registers for a given core")]
public LuaTable GetRegisters()
{
var table = Lua.NewTable();
try
{
if (DebuggableCore == null)
{
throw new NotImplementedException();
}
foreach (var kvp in DebuggableCore.GetCpuFlagsAndRegisters())
{
table[kvp.Key] = kvp.Value.Value;
}
}
catch (NotImplementedException)
{
Log($"Error: {Emulator.Attributes().CoreName} does not yet implement {nameof(IDebuggable.GetCpuFlagsAndRegisters)}()");
}
return table;
}
[LuaMethodExample("emu.setregister( emu.getregisters( )[ 0 ], -1000 );")]
[LuaMethod("setregister", "sets the given register name to the given value")]
public void SetRegister(string register, int value)
{
try
{
if (DebuggableCore == null)
{
throw new NotImplementedException();
}
DebuggableCore.SetCpuRegister(register, value);
}
catch (NotImplementedException)
{
Log($"Error: {Emulator.Attributes().CoreName} does not yet implement {nameof(IDebuggable.SetCpuRegister)}()");
}
}
[LuaMethodExample("local inemutot = emu.totalexecutedcycles( );")]
[LuaMethod("totalexecutedcycles", "gets the total number of executed cpu cycles")]
public long TotalExecutedycles()
{
try
{
if (DebuggableCore == null)
{
throw new NotImplementedException();
}
return DebuggableCore.TotalExecutedCycles;
}
catch (NotImplementedException)
{
Log($"Error: {Emulator.Attributes().CoreName} does not yet implement {nameof(IDebuggable.TotalExecutedCycles)}()");
return 0;
}
}
[LuaMethodExample("local stemuget = emu.getsystemid( );")]
[LuaMethod("getsystemid", "Returns the ID string of the current core loaded. Note: No ROM loaded will return the string NULL")]
public static string GetSystemId()
{
return Global.Game.System;
}
[LuaMethodExample("if ( emu.islagged( ) ) then\r\n\tconsole.log( \"Returns whether or not the current frame is a lag frame\" );\r\nend;")]
[LuaMethod("islagged", "Returns whether or not the current frame is a lag frame")]
public bool IsLagged()
{
if (InputPollableCore != null)
{
return InputPollableCore.IsLagFrame;
}
Log($"Can not get lag information, {Emulator.Attributes().CoreName} does not implement {nameof(IInputPollable)}");
return false;
}
[LuaMethodExample("emu.setislagged( true );")]
[LuaMethod("setislagged", "Sets the lag flag for the current frame. If no value is provided, it will default to true")]
public void SetIsLagged(bool value = true)
{
if (InputPollableCore != null)
{
InputPollableCore.IsLagFrame = value;
}
else
{
Log($"Can not set lag information, {Emulator.Attributes().CoreName} does not implement {nameof(IInputPollable)}");
}
}
[LuaMethodExample("local inemulag = emu.lagcount( );")]
[LuaMethod("lagcount", "Returns the current lag count")]
public int LagCount()
{
if (InputPollableCore != null)
{
return InputPollableCore.LagCount;
}
Log($"Can not get lag information, {Emulator.Attributes().CoreName} does not implement {nameof(IInputPollable)}");
return 0;
}
[LuaMethodExample("emu.setlagcount( 50 );")]
[LuaMethod("setlagcount", "Sets the current lag count")]
public void SetLagCount(int count)
{
if (InputPollableCore != null)
{
InputPollableCore.LagCount = count;
}
else
{
Log($"Can not set lag information, {Emulator.Attributes().CoreName} does not implement {nameof(IInputPollable)}");
}
}
[LuaMethodExample("emu.limitframerate( true );")]
[LuaMethod("limitframerate", "sets the limit framerate property of the emulator")]
public static void LimitFramerate(bool enabled)
{
Global.Config.ClockThrottle = enabled;
}
[LuaMethodExample("emu.minimizeframeskip( true );")]
[LuaMethod("minimizeframeskip", "Sets the autominimizeframeskip value of the emulator")]
public static void MinimizeFrameskip(bool enabled)
{
Global.Config.AutoMinimizeSkipping = enabled;
}
[LuaMethodExample("emu.setrenderplanes( true, false );")]
[LuaMethod("setrenderplanes", "Toggles the drawing of sprites and background planes. Set to false or nil to disable a pane, anything else will draw them")]
public void SetRenderPlanes(params bool[] luaParam)
{
if (Emulator is NES)
{
// in the future, we could do something more arbitrary here.
// but this isn't any worse than the old system
var nes = Emulator as NES;
var s = nes.GetSettings();
s.DispSprites = luaParam[0];
s.DispBackground = luaParam[1];
nes.PutSettings(s);
}
else if (Emulator is QuickNES)
{
var quicknes = Emulator as QuickNES;
var s = quicknes.GetSettings();
// this core doesn't support disabling BG
bool showsp = GetSetting(0, luaParam);
if (showsp && s.NumSprites == 0)
{
s.NumSprites = 8;
}
else if (!showsp && s.NumSprites > 0)
{
s.NumSprites = 0;
}
quicknes.PutSettings(s);
}
else if (Emulator is PCEngine)
{
var pce = Emulator as PCEngine;
var s = pce.GetSettings();
s.ShowOBJ1 = GetSetting(0, luaParam);
s.ShowBG1 = GetSetting(1, luaParam);
if (luaParam.Length > 2)
{
s.ShowOBJ2 = GetSetting(2, luaParam);
s.ShowBG2 = GetSetting(3, luaParam);
}
pce.PutSettings(s);
}
else if (Emulator is SMS)
{
var sms = Emulator as SMS;
var s = sms.GetSettings();
s.DispOBJ = GetSetting(0, luaParam);
s.DispBG = GetSetting(1, luaParam);
sms.PutSettings(s);
}
else if (Emulator is WonderSwan)
{
var ws = Emulator as WonderSwan;
var s = ws.GetSettings();
s.EnableSprites = GetSetting(0, luaParam);
s.EnableFG = GetSetting(1, luaParam);
s.EnableBG = GetSetting(2, luaParam);
ws.PutSettings(s);
}
}
private static bool GetSetting(int index, bool[] settings)
{
if (index < settings.Length)
{
return settings[index];
}
return true;
}
[LuaMethodExample("emu.yield( );")]
[LuaMethod("yield", "allows a script to run while emulation is paused and interact with the gui/main window in realtime ")]
public void Yield()
{
YieldCallback();
}
[LuaMethodExample("local stemuget = emu.getdisplaytype();")]
[LuaMethod("getdisplaytype", "returns the display type (PAL vs NTSC) that the emulator is currently running in")]
public string GetDisplayType()
{
if (RegionableCore != null)
{
return RegionableCore.Region.ToString();
}
return "";
}
[LuaMethodExample("local stemuget = emu.getboardname();")]
[LuaMethod("getboardname", "returns (if available) the board name of the loaded ROM")]
public string GetBoardName()
{
if (BoardInfo != null)
{
return BoardInfo.BoardName;
}
return "";
}
[LuaMethod("getluacore", "returns the name of the Lua core currently in use")]
public string GetLuaBackend()
{
return Lua.WhichLua;
}
}
}
| 28.277045 | 180 | 0.685453 | [
"MIT"
] | invertedcode/Bizhawk-Vanguard | Real-Time Corruptor/BizHawk_RTC/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs | 10,719 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OR_M_Data_Entities.Data.Definition;
namespace OR_M_Data_Entities.Tests.Testing.Base
{
public static class ContextMembers
{
public static void OnOnSqlGeneration(string sql, List<SqlDbParameter> parameters)
{
const string path = "C:\\users\\jdemeuse\\desktop\\OR-M Data Entities Tests\\";
var fileName = string.Format("OR-M Sql_{0}.txt", DateTime.Now.ToString("MM-dd-yyyy"));
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
using (var writetext = File.AppendText(string.Format("{0}{1}", path, fileName)))
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("-----------------");
stringBuilder.AppendLine("----- START -----");
stringBuilder.AppendLine("-----------------");
stringBuilder.AppendLine(string.Format("TIME: {0}", DateTime.Now));
stringBuilder.AppendLine(sql);
stringBuilder.AppendLine("-----------------");
stringBuilder.AppendLine("----- END -----");
stringBuilder.AppendLine("-----------------\r");
writetext.WriteLine(stringBuilder.ToString());
}
}
}
}
| 39.885714 | 99 | 0.549427 | [
"MIT"
] | jdemeuse1204/OR-M-Data-Entities | OR-M Data Entities/OR-M Data Entities.Tests/Testing/Base/ContextMembers.cs | 1,398 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FlubuCore.Context;
using FlubuCore.Tasks;
using FlubuCore.Tasks.Process;
namespace FlubuCore.Azure.Tasks.Network
{
public partial class AzureNetworkLbInboundNatRuleTask : ExternalProcessTaskBase<AzureNetworkLbInboundNatRuleTask>
{
/// <summary>
/// Manage inbound NAT rules of a load balancer.
/// </summary>
public AzureNetworkLbInboundNatRuleTask()
{
WithArguments("az network lb inbound-nat-rule");
}
protected override string Description { get; set; }
}
}
| 24.5 | 118 | 0.67033 | [
"MIT"
] | flubu-core/FlubuCore.Azure | FlubuCore.Azure/Tasks/Network/AzureNetworkLbInboundNatRuleTask.cs | 637 | C# |
using System.Threading.Tasks;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Utility;
namespace Content.Shared.Construction
{
public interface IEdgeCondition : IExposeData
{
Task<bool> Condition(IEntity entity);
void DoExamine(IEntity entity, FormattedMessage message, bool inExamineRange) { }
}
}
| 27.928571 | 89 | 0.762148 | [
"MIT"
] | DTanxxx/space-station-14 | Content.Shared/Construction/IEdgeCondition.cs | 393 | 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("TestHttpClient.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestHttpClient.Tests")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
| 35.448276 | 84 | 0.742218 | [
"MIT"
] | mrlacey/TestHttpClient | TestHttpClient.Tests/Properties/AssemblyInfo.cs | 1,031 | C# |
// Copyright 2004-2012 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.DynamicProxy.Tests
{
using CastleTests.GenInterfaces;
using NUnit.Framework;
[TestFixture]
public class GenericConstraintsTestCase : BasePEVerifyTestCase
{
[Test]
public void Non_generic_type_generic_method_with_class_struct_and_new_constraints()
{
CreateProxyFor<IHaveGenericMethodWithNewClassStructConstraints>();
}
[Test]
public void Generic_type_generic_method_with_struct_base_Method_base_Type_constraints()
{
CreateProxyFor<IConstraint_Method1IsTypeStructAndMethod2<object>>();
}
private T CreateProxyFor<T>(params IInterceptor[] interceptors) where T : class
{
return generator.CreateInterfaceProxyWithoutTarget<T>(interceptors);
}
}
} | 33.463415 | 90 | 0.753644 | [
"Apache-2.0"
] | balefrost/CastleProject.Core | src/Castle.Core.Tests/GenericConstraintsTestCase.cs | 1,372 | C# |
using Xamarin.Forms;
namespace AzureTranslator
{
public class MyEntry : Entry
{
}
}
| 10.888889 | 32 | 0.653061 | [
"Unlicense"
] | YogaJi/AzureTranslator | AzureTranslator/AzureTranslator/MyEntry.cs | 100 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library_system.Database
{
interface IUser
{
string Id { get; set; }
string Username { get; set; }
string Password { get; set; }
DateTime Created { get; set; }
}
class User:IUser
{
public string Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public DateTime Created { get; set; }
}
}
| 21.76 | 45 | 0.602941 | [
"MIT"
] | smallproject/library_system | source/Library_system/Library_system/Database/User.cs | 546 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace FLS.Data.WebApi.Licensing
{
public class LicenseTrainingStateResult
{
public LicenseTrainingStateRequest Request { get; set; }
public DateTime DateTimeOfLicenseTrainingStateCalculation { get; set; }
public LicenseTrainingStateListItem CurrentLicenseTrainingState { get; set; }
}
}
| 25.933333 | 85 | 0.753213 | [
"MIT"
] | flightlog/flsserver | src/FLS.Data.WebApi/Licensing/LicenseTrainingStateResult.cs | 389 | C# |
using DataMigrations.EntityFramework;
namespace DataMigrations.IntegrationTests.EF.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Inserts : DbMigration
{
public override void Up()
{
Insert.Into("Person")
.Set("Name", "Michal Ciechan")
.Execute(Sql); // <-- Extension method which executes SQL
}
public override void Down()
{
Delete.From("Person")
.Where("Name", "Michal Ciechan")
.Execute(Sql); // <-- Extension method which executes SQL
}
}
}
| 26.12 | 73 | 0.552833 | [
"MIT"
] | michal-ciechan/DataMigrations | DataMigrations.IntegrationTests.EF/Migrations/201606022121018_Inserts.cs | 653 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace Vestris.ResourceLib
{
/// <summary>
/// This structure depicts the organization of data in a file-version resource.
/// It contains version information not dependent on a particular language and code page combination.
/// http://msdn.microsoft.com/en-us/library/aa909193.aspx
/// </summary>
public class VarFileInfo : ResourceTableHeader
{
Dictionary<string, VarTable> _vars = new Dictionary<string, VarTable>();
/// <summary>
/// A hardware independent dictionary of language and code page identifier tables.
/// </summary>
public Dictionary<string, VarTable> Vars
{
get
{
return _vars;
}
}
/// <summary>
/// A new hardware independent dictionary of language and code page identifier tables.
/// </summary>
public VarFileInfo()
: base("VarFileInfo")
{
_header.wType = (UInt16)Kernel32.RESOURCE_HEADER_TYPE.StringData;
}
/// <summary>
/// An existing hardware independent dictionary of language and code page identifier tables.
/// </summary>
/// <param name="lpRes">Pointer to the beginning of data.</param>
internal VarFileInfo(IntPtr lpRes)
{
Read(lpRes);
}
/// <summary>
/// Read a hardware independent dictionary of language and code page identifier tables.
/// </summary>
/// <param name="lpRes">Pointer to the beginning of data.</param>
/// <returns>Pointer to the end of data.</returns>
internal override IntPtr Read(IntPtr lpRes)
{
_vars.Clear();
IntPtr pChild = base.Read(lpRes);
while (pChild.ToInt64() < (lpRes.ToInt64() + _header.wLength))
{
VarTable res = new VarTable(pChild);
_vars.Add(res.Key, res);
pChild = ResourceUtil.Align(pChild.ToInt64() + res.Header.wLength);
}
return new IntPtr(lpRes.ToInt64() + _header.wLength);
}
/// <summary>
/// Write the hardware independent dictionary of language and code page identifier tables to a binary stream.
/// </summary>
/// <param name="w">Binary stream.</param>
internal override void Write(BinaryWriter w)
{
long headerPos = w.BaseStream.Position;
base.Write(w);
Dictionary<string, VarTable>.Enumerator varsEnum = _vars.GetEnumerator();
while (varsEnum.MoveNext())
{
varsEnum.Current.Value.Write(w);
}
ResourceUtil.WriteAt(w, w.BaseStream.Position - headerPos, headerPos);
}
/// <summary>
/// The default language and code page identifier table.
/// </summary>
public VarTable Default
{
get
{
Dictionary<string, VarTable>.Enumerator varsEnum = _vars.GetEnumerator();
if (varsEnum.MoveNext()) return varsEnum.Current.Value;
return null;
}
}
/// <summary>
/// Returns a language and code page identifier table.
/// </summary>
/// <param name="language">Language ID.</param>
/// <returns>A language and code page identifier table.</returns>
public UInt16 this[UInt16 language]
{
get
{
return Default[language];
}
set
{
Default[language] = value;
}
}
/// <summary>
/// String representation of VarFileInfo.
/// </summary>
/// <param name="indent">Indent.</param>
/// <returns>String in the VarFileInfo format.</returns>
public override string ToString(int indent)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("{0}BEGIN", new String(' ', indent)));
foreach(VarTable var in _vars.Values)
{
sb.Append(var.ToString(indent + 1));
}
sb.AppendLine(string.Format("{0}END", new String(' ', indent)));
return sb.ToString();
}
}
}
| 33.345865 | 117 | 0.552875 | [
"MIT"
] | mwsrc/DotNetObfuscator | ResourceLib/VarFileInfo.cs | 4,435 | C# |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.InteropServices;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Collections.Generic;
using System.Xml;
using System.IO;
using System.Security.Cryptography;
using SimpleUtils;
using SimpleUtils.Win;
using Microsoft.Win32;
using System.Diagnostics;
using System.Drawing;
namespace SimpleAssemblyExplorer
{
public class PathUtils
{
public static bool IsExt(string fileName, string extName)
{
string ext = Path.GetExtension(fileName);
return ext.ToLowerInvariant() == extName.ToLowerInvariant();
}
public static bool IsDll(string fileName)
{
return IsExt(fileName, ".dll");
}
public static bool IsExe(string fileName)
{
return IsExt(fileName, ".exe");
}
public static bool IsNetModule(string fileName)
{
return IsExt(fileName, ".netmodule");
}
public static bool IsAssembly(string fileName)
{
bool isAssembly = false;
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case ".dll":
case ".exe":
case ".netmodule":
isAssembly = true;
break;
default:
break;
}
return isAssembly;
}
//static Regex regexValidFileName = new Regex(@"^[0-9a-zA-Z_$.\u4E00-\u9FA5]+$");
//static Regex regexInvalidFileNameChars = new Regex("[^0-9a-zA-Z_$.\u4E00-\u9FA5]+");
public static string FixFileName(string fileName)
{
string s = fileName;
char[] invalidChars = Path.GetInvalidFileNameChars();
foreach (char ch in invalidChars)
{
s = s.Replace(ch, '_');
}
return s;
//return regexInvalidFileNameChars.Replace(fileName, "_");
}
public static bool IsValidFileName(string fileName)
{
char[] invalidChars = Path.GetInvalidFileNameChars();
return fileName.IndexOfAny(invalidChars) == -1;
//return regexValidFileName.IsMatch(fileName);
}
public static string GetFileSizeInfo(string fileName)
{
string info = String.Empty;
if (!File.Exists(fileName))
return info;
FileInfo fi = new FileInfo(fileName);
if (fi.Length > 1024 * 1024 * 1024)
{
info = String.Format("{0:N2}GB", Math.Round(fi.Length / 1024.0 / 1024.0 / 1024.0, 2));
}
else if (fi.Length > 1024 * 1024)
{
info = String.Format("{0:N2}MB", Math.Round(fi.Length / 1024.0 / 1024.0, 2));
}
else
{
info = String.Format("{0:N2}KB", Math.Round(fi.Length / 1024.0, 2));
}
return info;
}
public static string GetTempDir()
{
string tempDir = null;
tempDir = Environment.GetEnvironmentVariable("TEMP");
if (tempDir == null)
{
tempDir = Environment.GetEnvironmentVariable("TMP");
if (tempDir == null)
{
string winDir = Environment.GetEnvironmentVariable("WINDIR");
if (winDir != null)
{
tempDir = winDir + @"\TEMP";
if (!Directory.Exists(tempDir))
tempDir = null;
}
}
if (tempDir == null)
tempDir = @"C:\TEMP";
if (!Directory.Exists(tempDir))
tempDir = @"C:\";
}
return tempDir;
}
public static string[] GetFullFileNames(IList list, string sourceDir)
{
string[] strs = new string[list.Count];
for (int i = 0; i < strs.Length; i++)
{
strs[i] = GetFullFileName(list, i, sourceDir);
}
return strs;
}
public static string GetFullFileName(IList list, int i, string sourceDir)
{
string fileName = null;
if (list == null || list.Count <= i)
return fileName;
object o = list[i];
if (o is DataGridViewRow)
{
DataGridViewRow row = (DataGridViewRow)o;
fileName = GetFileName(row, sourceDir);
}
else if (o is string)
{
fileName = (string)o;
}
else if (o is FileInfo)
{
FileInfo fi = (FileInfo)o;
fileName = fi.FullName;
}
return fileName;
}
public static string GetFileName(DataGridViewRow row)
{
return row.Cells["dgcFileName"].Value.ToString();
}
public static string GetFileName(DataGridViewRow row, string sourceDir)
{
return Path.Combine(SimplePath.GetFullPath(sourceDir), GetFileName(row));
}
//public static bool IsImageExt(string name)
//{
// return
// name.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".ico", StringComparison.OrdinalIgnoreCase) ||
// name.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) ||
// name.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
// name.EndsWith(".tif", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".tiff", StringComparison.OrdinalIgnoreCase) ||
// name.EndsWith(".emf", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".wmf", StringComparison.OrdinalIgnoreCase)
// ;
//}
//public static bool IsTextExt(string name)
//{
// return name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) ||
// name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) ||
// name.EndsWith(".xsd", StringComparison.OrdinalIgnoreCase) ||
// name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase);
//}
public static bool IsStringExt(string name)
{
return name.EndsWith(".string", StringComparison.OrdinalIgnoreCase);
}
public static bool IsIconExt(string name)
{
return name.EndsWith(".ico", StringComparison.OrdinalIgnoreCase);
}
public static bool IsCursorExt(string name)
{
return name.EndsWith(".cur", StringComparison.OrdinalIgnoreCase);
}
public static bool IsResourceExt(string name)
{
return name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase);
}
public static bool IsResxExt(string name)
{
return name.EndsWith(".resx", StringComparison.OrdinalIgnoreCase);
}
public static bool IsBamlExt(string name)
{
return name.EndsWith(".baml", StringComparison.OrdinalIgnoreCase);
}
public static int IndexOfDot(string s, int count)
{
int p = s.IndexOf('.', 0);
while (p > 0 && count > 1 && p + 1 < s.Length)
{
p = s.IndexOf('.', p + 1);
count--;
}
return p;
}
#region Framework Directories
[DllImport("mscoree.dll")]
private static extern int GetCORSystemDirectory(
[MarshalAs(UnmanagedType.LPWStr)]StringBuilder pbuffer, int cchBuffer, ref int dwlength);
public static string GetFrameworkInstalledDir()
{
string dir = String.Empty;
try
{
int MAX_PATH = 260;
StringBuilder sb = new StringBuilder(MAX_PATH);
GetCORSystemDirectory(sb, MAX_PATH, ref MAX_PATH);
//sb.Remove(sb.Length - 1, 1);
dir = sb.ToString();
}
catch
{
}
return dir;
}
public static string GetFrameworkSDKInstalledDir()
{
string dir = null;
string name = "InstallationFolder";
string regKey;
RegistryKey key;
//3.5, 4.0, 4.5
regKey = @"SOFTWARE\Microsoft\Microsoft SDKs\Windows";
key = Registry.LocalMachine.OpenSubKey(regKey);
if (key != null)
{
var subKeyNames = key.GetSubKeyNames();
if (subKeyNames != null && subKeyNames.Length > 0)
{
Array.Sort<string>(subKeyNames);
var subKey = key.OpenSubKey(subKeyNames[subKeyNames.Length - 1]);
var o = subKey.GetValue(name);
if (o != null)
{
dir = o.ToString();
}
subKey.Close();
}
key.Close();
}
if (Directory.Exists(dir))
return dir;
//2.0, 3.0
regKey = @"SOFTWARE\Microsoft\.NETFramework";
name = "sdkInstallRootv2.0";
key = Registry.LocalMachine.OpenSubKey(regKey);
if (key != null)
{
var o = key.GetValue(name);
if (o != null)
{
dir = o.ToString();
}
key.Close();
}
if (Directory.Exists(dir))
return dir;
return String.Empty;
}
public static string GetFrameworkSDKBinDir()
{
string dir = GetFrameworkSDKInstalledDir();
if(String.IsNullOrEmpty(dir))
return dir;
var files = Directory.GetFiles(Path.Combine(dir, "bin"), "peverify.exe", SearchOption.AllDirectories);
if(files != null && files.Length>0) {
return Path.GetDirectoryName(files[0]);
}
return String.Empty;
}
public static void SetupFrameworkSDKPath()
{
#region Set Path
StringBuilder sb = new StringBuilder();
string dir;
dir = PathUtils.GetFrameworkSDKBinDir();
if (!String.IsNullOrEmpty(dir))
{
sb.Append(dir);
sb.Append(";");
}
dir = PathUtils.GetFrameworkInstalledDir();
if (!String.IsNullOrEmpty(dir))
{
sb.Append(dir);
sb.Append(";");
}
sb.Append(Environment.GetEnvironmentVariable("PATH"));
Environment.SetEnvironmentVariable("PATH", sb.ToString());
#endregion Set Path
}
#endregion Framework Directories
}//end of class
}
| 33.162921 | 141 | 0.497205 | [
"MIT"
] | GreenDamTan/simple-assembly-exploror | SimpleAssemblyExplorer.Core/Common/PathUtils.cs | 11,806 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
namespace FoxTool.Fox.Types.Values
{
public class FoxUInt32 : IFoxValueType
{
public uint Value { get; set; }
public void Read(Stream input)
{
BinaryReader reader = new BinaryReader(input, Encoding.Default, true);
Value = reader.ReadUInt32();
}
public void Write(Stream output)
{
BinaryWriter writer = new BinaryWriter(output, Encoding.Default, true);
writer.Write(Value);
}
public int Size()
{
return sizeof (uint);
}
public void ResolveStringLiterals(FoxLookupTable lookupTable)
{
}
public void CalculateHashes()
{
}
public void CollectStringLookupLiterals(List<FoxStringLookupLiteral> literals)
{
}
public void ReadXml(XmlReader reader)
{
var isEmptyElement = reader.IsEmptyElement;
reader.ReadStartElement("value");
if (isEmptyElement == false)
{
string value = reader.ReadString();
Value = value.StartsWith("0x")
? uint.Parse(value.Substring(2, value.Length - 2), NumberStyles.AllowHexSpecifier)
: uint.Parse(value);
reader.ReadEndElement();
}
}
public XmlSchema GetSchema()
{
return null;
}
public void WriteXml(XmlWriter writer)
{
writer.WriteString(ToString());
}
public override string ToString()
{
return Value.ToString();
}
public object Unwrap()
{
return Value;
}
}
}
| 23.898734 | 102 | 0.544492 | [
"MIT"
] | youarebritish/FoxKitPrototype | Assets/Lib/FoxTool/FoxTool.Core/Fox/Types/Values/FoxUInt32.cs | 1,890 | C# |
namespace FineBot.API.Models
{
public class Profile
{
public string first_name { get; set; }
public string last_name { get; set; }
public string real_name { get; set; }
public string email { get; set; }
public string skype { get; set; }
public string phone { get; set; }
public string image24 { get; set; }
public string image32 { get; set; }
public string image48 { get; set; }
public string image72 { get; set; }
public string image192 { get; set; }
}
}
| 30.944444 | 46 | 0.574506 | [
"MIT"
] | prinzo/Attack-Of-The-Fines-TA15 | FineBot/FineBot.API/Models/Profile.cs | 559 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) 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 Stride.Core;
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Engine.Events;
using Stride.Physics;
namespace ThirdPersonPlatformer.Player
{
public class PlayerController : SyncScript
{
[Display("Run Speed")]
public float MaxRunSpeed { get; set; } = 10;
public static readonly EventKey<bool> IsGroundedEventKey = new EventKey<bool>();
public static readonly EventKey<float> RunSpeedEventKey = new EventKey<float>();
// This component is the physics representation of a controllable character
private CharacterComponent character;
private Entity modelChildEntity;
private float yawOrientation;
private readonly EventReceiver<Vector3> moveDirectionEvent = new EventReceiver<Vector3>(PlayerInput.MoveDirectionEventKey);
private readonly EventReceiver<bool> jumpEvent = new EventReceiver<bool>(PlayerInput.JumpEventKey);
/// <summary>
/// Allow for some latency from the user input to make jumping appear more natural
/// </summary>
[Display("Jump Time Limit")]
public float JumpReactionThreshold { get; set; } = 0.3f;
// When the character falls off a surface, allow for some reaction time
private float jumpReactionRemaining;
// Allow some inertia to the movement
private Vector3 moveDirection = Vector3.Zero;
/// <summary>
/// Called when the script is first initialized
/// </summary>
public override void Start()
{
base.Start();
jumpReactionRemaining = JumpReactionThreshold;
// Will search for an CharacterComponent within the same entity as this script
character = Entity.Get<CharacterComponent>();
if (character == null) throw new ArgumentException("Please add a CharacterComponent to the entity containing PlayerController!");
modelChildEntity = Entity.GetChild(0);
}
/// <summary>
/// Called on every frame update
/// </summary>
public override void Update()
{
// var dt = Game.UpdateTime.Elapsed.Milliseconds * 0.001;
Move(MaxRunSpeed);
Jump();
}
/// <summary>
/// Jump makes the character jump and also accounts for the player's reaction time, making jumping feel more natural by
/// allowing jumps within some limit of the last time the character was on the ground
/// </summary>
private void Jump()
{
var dt = this.GetSimulation().FixedTimeStep;
// Check if conditions allow the character to jump
if (JumpReactionThreshold <= 0)
{
// No reaction threshold. The character can only jump if grounded
if (!character.IsGrounded)
{
IsGroundedEventKey.Broadcast(false);
return;
}
}
else
{
// If there is still enough time left for jumping allow the character to jump even when not grounded
if (jumpReactionRemaining > 0)
jumpReactionRemaining -= dt;
// If the character on the ground reset the jumping reaction time
if (character.IsGrounded)
jumpReactionRemaining = JumpReactionThreshold;
// If there is no more reaction time left don't allow the character to jump
if (jumpReactionRemaining <= 0)
{
IsGroundedEventKey.Broadcast(character.IsGrounded);
return;
}
}
// If the player didn't press a jump button we don't need to jump
bool didJump;
jumpEvent.TryReceive(out didJump);
if (!didJump)
{
IsGroundedEventKey.Broadcast(true);
return;
}
// Jump!!
jumpReactionRemaining = 0;
character.Jump();
// Broadcast that the character is jumping!
IsGroundedEventKey.Broadcast(false);
}
private void Move(float speed)
{
// Character speed
Vector3 newMoveDirection;
moveDirectionEvent.TryReceive(out newMoveDirection);
// Allow very simple inertia to the character to make animation transitions more fluid
moveDirection = moveDirection*0.85f + newMoveDirection *0.15f;
character.SetVelocity(moveDirection * speed);
// Broadcast speed as per cent of the max speed
RunSpeedEventKey.Broadcast(moveDirection.Length());
// Character orientation
if (moveDirection.Length() > 0.001)
{
yawOrientation = MathUtil.RadiansToDegrees((float) Math.Atan2(-moveDirection.Z, moveDirection.X) + MathUtil.PiOverTwo);
}
modelChildEntity.Transform.Rotation = Quaternion.RotationYawPitchRoll(MathUtil.DegreesToRadians(yawOrientation), 0, 0);
}
}
}
| 37.287671 | 164 | 0.606172 | [
"MIT"
] | Alan-love/xenko | samples/Templates/ThirdPersonPlatformer/ThirdPersonPlatformer/ThirdPersonPlatformer.Game/Player/PlayerController.cs | 5,446 | 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.Threading.Tasks;
namespace DebuggerTests
{
public class EvaluateTestsClass
{
public class TestEvaluate
{
public int a;
public int b;
public int c;
public DateTime dt = new DateTime(2000, 5, 4, 3, 2, 1);
public TestEvaluate NullIfAIsNotZero => a != 0 ? null : this;
public void run(int g, int h, string a, string valString, int this_a)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
int i = d + e + f;
var local_dt = new DateTime(2010, 9, 8, 7, 6, 5);
this.a = 1;
b = 2;
c = 3;
this.a = this.a + 1;
b = b + 1;
c = c + 1;
}
}
public static void EvaluateLocals()
{
TestEvaluate f = new TestEvaluate();
f.run(100, 200, "9000", "test", 45);
var f_s = new EvaluateTestsStructWithProperties();
f_s.InstanceMethod(100, 200, "test", f_s);
f_s.GenericInstanceMethod<int>(100, 200, "test", f_s);
var f_g_s = new EvaluateTestsGenericStruct<int>();
f_g_s.EvaluateTestsGenericStructInstanceMethod(100, 200, "test");
}
}
public struct EvaluateTestsGenericStruct<T>
{
public int a;
public int b;
public int c;
DateTime dateTime;
public void EvaluateTestsGenericStructInstanceMethod(int g, int h, string valString)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
T t = default(T);
a = a + 1;
b = b + 2;
c = c + 3;
}
}
public class EvaluateTestsClassWithProperties
{
public int a;
public int b;
public int c { get; set; }
public DateTime dateTime;
public DateTime DTProp => dateTime.AddMinutes(10);
public int IntProp => a + 5;
public string SetOnlyProp { set { a = value.Length; } }
public EvaluateTestsClassWithProperties NullIfAIsNotZero => a != 1908712 ? null : new EvaluateTestsClassWithProperties(0);
public EvaluateTestsClassWithProperties NewInstance => new EvaluateTestsClassWithProperties(3);
public EvaluateTestsClassWithProperties(int bias)
{
a = 4;
b = 0;
c = 0;
dateTime = new DateTime(2010, 9, 8, 7, 6, 5 + bias);
}
public static async Task run()
{
var obj = new EvaluateTestsClassWithProperties(0);
var obj2 = new EvaluateTestsClassWithProperties(0);
obj.InstanceMethod(400, 123, "just a test", obj2);
new EvaluateTestsClassWithProperties(0).GenericInstanceMethod<int>(400, 123, "just a test", obj2);
new EvaluateTestsClassWithProperties(0).EvaluateShadow(new DateTime(2020, 3, 4, 5, 6, 7), obj.NewInstance);
await new EvaluateTestsClassWithProperties(0).InstanceMethodAsync(400, 123, "just a test", obj2);
await new EvaluateTestsClassWithProperties(0).GenericInstanceMethodAsync<int>(400, 123, "just a test", obj2);
await new EvaluateTestsClassWithProperties(0).EvaluateShadowAsync(new DateTime(2020, 3, 4, 5, 6, 7), obj.NewInstance);
}
public void EvaluateShadow(DateTime dateTime, EvaluateTestsClassWithProperties me)
{
string a = "hello";
Console.WriteLine($"Evaluate - break here");
SomeMethod(dateTime, me);
}
public async Task EvaluateShadowAsync(DateTime dateTime, EvaluateTestsClassWithProperties me)
{
string a = "hello";
Console.WriteLine($"EvaluateShadowAsync - break here");
await Task.CompletedTask;
}
public void SomeMethod(DateTime me, EvaluateTestsClassWithProperties dateTime)
{
Console.WriteLine($"break here");
var DTProp = "hello";
Console.WriteLine($"dtProp: {DTProp}");
}
public async Task InstanceMethodAsync(int g, int h, string valString, EvaluateTestsClassWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
await Task.CompletedTask;
}
public void InstanceMethod(int g, int h, string valString, EvaluateTestsClassWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
}
public void GenericInstanceMethod<T>(int g, int h, string valString, EvaluateTestsClassWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
T t = default(T);
}
public async Task<T> GenericInstanceMethodAsync<T>(int g, int h, string valString, EvaluateTestsClassWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
T t = default(T);
return await Task.FromResult(default(T));
}
}
public struct EvaluateTestsStructWithProperties
{
public int a;
public int b;
public int c { get; set; }
public DateTime dateTime;
public DateTime DTProp => dateTime.AddMinutes(10);
public int IntProp => a + 5;
public string SetOnlyProp { set { a = value.Length; } }
public EvaluateTestsClassWithProperties NullIfAIsNotZero => a != 1908712 ? null : new EvaluateTestsClassWithProperties(0);
public EvaluateTestsStructWithProperties NewInstance => new EvaluateTestsStructWithProperties(3);
public EvaluateTestsStructWithProperties(int bias)
{
a = 4;
b = 0;
c = 0;
dateTime = new DateTime(2010, 9, 8, 7, 6, 5 + bias);
}
public static async Task run()
{
var obj = new EvaluateTestsStructWithProperties(0);
var obj2 = new EvaluateTestsStructWithProperties(0);
obj.InstanceMethod(400, 123, "just a test", obj2);
new EvaluateTestsStructWithProperties(0).GenericInstanceMethod<int>(400, 123, "just a test", obj2);
new EvaluateTestsStructWithProperties(0).EvaluateShadow(new DateTime(2020, 3, 4, 5, 6, 7), obj.NewInstance);
await new EvaluateTestsStructWithProperties(0).InstanceMethodAsync(400, 123, "just a test", obj2);
await new EvaluateTestsStructWithProperties(0).GenericInstanceMethodAsync<int>(400, 123, "just a test", obj2);
await new EvaluateTestsStructWithProperties(0).EvaluateShadowAsync(new DateTime(2020, 3, 4, 5, 6, 7), obj.NewInstance);
}
public void EvaluateShadow(DateTime dateTime, EvaluateTestsStructWithProperties me)
{
string a = "hello";
Console.WriteLine($"Evaluate - break here");
SomeMethod(dateTime, me);
}
public async Task EvaluateShadowAsync(DateTime dateTime, EvaluateTestsStructWithProperties me)
{
string a = "hello";
Console.WriteLine($"EvaluateShadowAsync - break here");
await Task.CompletedTask;
}
public void SomeMethod(DateTime me, EvaluateTestsStructWithProperties dateTime)
{
Console.WriteLine($"break here");
var DTProp = "hello";
Console.WriteLine($"dtProp: {DTProp}");
}
public async Task InstanceMethodAsync(int g, int h, string valString, EvaluateTestsStructWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
await Task.CompletedTask;
}
public void InstanceMethod(int g, int h, string valString, EvaluateTestsStructWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
}
public void GenericInstanceMethod<T>(int g, int h, string valString, EvaluateTestsStructWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
T t = default(T);
}
public async Task<T> GenericInstanceMethodAsync<T>(int g, int h, string valString, EvaluateTestsStructWithProperties me)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
var local_dt = new DateTime(2025, 3, 5, 7, 9, 11);
a = 1;
b = 2;
c = 3;
dateTime = new DateTime(2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
T t = default(T);
return await Task.FromResult(default(T));
}
}
}
| 34.738019 | 131 | 0.51421 | [
"MIT"
] | 2m0nd/runtime | src/mono/wasm/debugger/tests/debugger-evaluate-test.cs | 10,873 | C# |
using Newtonsoft.Json.Linq;
namespace Puppy.Elastic.ContextSearch.SearchModel.AggModel
{
public class StatsMetricAggregationsResult : AggregationResult<StatsMetricAggregationsResult>
{
public double Count { get; set; }
public double Min { get; set; }
public double Max { get; set; }
public double Avg { get; set; }
public double Sum { get; set; }
// "count": 9, "min": 72, "max": 99, "avg": 86, "sum": 774,
public override StatsMetricAggregationsResult GetValueFromJToken(JToken result)
{
return result.ToObject<StatsMetricAggregationsResult>();
}
}
} | 34.157895 | 97 | 0.644068 | [
"Unlicense"
] | stssoftware/Puppy | Puppy.Elastic/ContextSearch/SearchModel/AggModel/StatsMetricAggregationsResult.cs | 649 | C# |
namespace AnimalFarm
{
using AnimalFarm.Models;
using System;
public class Engine
{
public void Run()
{
try
{
string name = Console.ReadLine();
int age = int.Parse(Console.ReadLine());
Chicken chicken = new Chicken(name, age);
Console.WriteLine(
"Chicken {0} (age {1}) can produce {2} eggs per day.",
chicken.Name,
chicken.Age,
chicken.ProductPerDay);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
}
} | 25.962963 | 74 | 0.439372 | [
"MIT"
] | PhilShishov/Software-University | C# OOP/Homeworks/03.Encapsulation_Exercise/AnimalFarm/Engine.cs | 703 | C# |
using Newtonsoft.Json.Linq;
using OCM.API.Common.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OCM.Import.Providers
{
public class ImportProvider_CarStations : BaseImportProvider, IImportProvider
{
public ImportProvider_CarStations()
{
ProviderName = "carstations.com";
OutputNamePrefix = "carstations";
AutoRefreshURL = "http://carstations.com/jsonresults.txt";
IsAutoRefreshed = true;
IsProductionReady = true;
SourceEncoding = Encoding.GetEncoding("UTF-8");
DataProviderID = 15; //carstations.com
}
public List<API.Common.Model.ChargePoint> Process(CoreReferenceData coreRefData)
{
List<ChargePoint> outputList = new List<ChargePoint>();
string source = InputData;
JObject o = JObject.Parse(source);
var dataList = o["locations"].ToArray();
var submissionStatus = coreRefData.SubmissionStatusTypes.First(s => s.ID == (int)StandardSubmissionStatusTypes.Imported_UnderReview);//imported and under review
var operationalStatus = coreRefData.StatusTypes.First(os => os.ID == 50);
var unknownStatus = coreRefData.StatusTypes.First(os => os.ID == 0);
var usageTypePublic = coreRefData.UsageTypes.First(u => u.ID == 1);
var usageTypePrivate = coreRefData.UsageTypes.First(u => u.ID == 2);
var operatorUnknown = coreRefData.Operators.First(opUnknown => opUnknown.ID == 1);
int itemCount = 0;
foreach (var item in dataList)
{
ChargePoint cp = new ChargePoint();
cp.DataProvider = new DataProvider() { ID = this.DataProviderID }; //carstations.com
cp.DataProvidersReference = item["post_id"].ToString();
cp.DateLastStatusUpdate = DateTime.UtcNow;
cp.AddressInfo = new AddressInfo();
//carstations.com have requested we not use the station names from their data, so we use address
//cp.AddressInfo.Title = item["name"] != null ? item["name"].ToString() : item["address"].ToString();
cp.AddressInfo.Title = item["address"] != null ? item["address"].ToString() : item["post_id"].ToString();
cp.AddressInfo.Title = cp.AddressInfo.Title.Trim().Replace("&", "&");
cp.AddressInfo.RelatedURL = "http://carstations.com/" + cp.DataProvidersReference;
cp.DateLastStatusUpdate = DateTime.UtcNow;
cp.AddressInfo.AddressLine1 = item["address"].ToString().Trim();
cp.AddressInfo.Town = item["city"].ToString().Trim();
cp.AddressInfo.StateOrProvince = item["region"].ToString().Trim();
cp.AddressInfo.Postcode = item["postal_code"].ToString().Trim();
cp.AddressInfo.Latitude = double.Parse(item["latitude"].ToString().Trim());
cp.AddressInfo.Longitude = double.Parse(item["longitude"].ToString().Trim());
cp.AddressInfo.ContactTelephone1 = item["phone"].ToString();
if (!String.IsNullOrEmpty(item["country"].ToString()))
{
string country = item["country"].ToString();
int? countryID = null;
var countryVal = coreRefData.Countries.FirstOrDefault(c => c.Title.ToLower() == country.Trim().ToLower());
if (countryVal == null)
{
country = country.ToUpper();
//match country
if (country == "UNITED STATES" || country == "US" || country == "USA" || country == "U.S." || country == "U.S.A.") countryID = 2;
if (country == "UK" || country == "GB" || country == "GREAT BRITAIN" || country == "UNITED KINGDOM") countryID = 1;
}
else
{
countryID = countryVal.ID;
}
if (countryID == null)
{
this.Log("Country Not Matched, will require Geolocation:" + item["country"].ToString());
}
else
{
cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(cy => cy.ID == countryID);
}
}
else
{
//default to US if no country identified
//cp.AddressInfo.Country = cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(cy => cy.ID == 2);
}
//System.Diagnostics.Debug.WriteLine(item.ToString());
string publicCount = item["public"].ToString();
string privateCount = item["private"].ToString();
if (!String.IsNullOrEmpty(publicCount) && publicCount != "0")
{
try
{
cp.NumberOfPoints = int.Parse(publicCount);
}
catch (Exception) { }
cp.UsageType = usageTypePublic;
}
else
{
if (!String.IsNullOrEmpty(privateCount) && privateCount != "0")
{
try
{
cp.NumberOfPoints = int.Parse(privateCount);
}
catch (Exception) { }
cp.UsageType = usageTypePrivate;
}
}
string verifiedFlag = item["verified_flag"].ToString();
if (!string.IsNullOrEmpty(verifiedFlag) && verifiedFlag != "0")
{
cp.StatusType = operationalStatus;
}
else
{
cp.StatusType = unknownStatus;
}
//TODO: allow for multiple operators?
var operatorsNames = item["brands"].ToArray();
if (operatorsNames.Count() > 0)
{
var operatorName = operatorsNames[0].ToString();
var opDetails = coreRefData.Operators.FirstOrDefault(op => op.Title.ToLower().Contains(operatorName.ToString().ToLower()));
if (opDetails != null)
{
cp.OperatorInfo = opDetails;
}
else
{
Log("Operator not matched:" + operatorName);
}
}
else
{
cp.OperatorInfo = operatorUnknown;
}
var connectorTypes = item["techs"].ToArray();
foreach (var conn in connectorTypes)
{
ConnectionInfo cinfo = new ConnectionInfo() { };
ConnectionType cType = new ConnectionType { ID = 0 };
ChargerType level = null;
cinfo.Reference = conn.ToString();
if (conn.ToString().ToUpper() == "J1772")
{
cType = new ConnectionType();
cType.ID = 1; //J1772
level = new ChargerType { ID = 2 };//default to level 2
}
if (conn.ToString().ToUpper() == "CHADEMO")
{
cType = new ConnectionType();
cType.ID = 2; //CHadeMO
level = new ChargerType { ID = 3 };//default to level 3
}
if (conn.ToString().ToUpper() == "NEMA5")
{
cType = new ConnectionType();
cType.ID = 9; //NEMA5-20R
level = new ChargerType { ID = 1 };//default to level 1
}
if (cType.ID == 0)
{
var conType = coreRefData.ConnectionTypes.FirstOrDefault(ct => ct.Title.ToLower().Contains(conn.ToString().ToLower()));
if (conType != null) cType = conType;
}
cinfo.ConnectionType = cType;
cinfo.Level = level;
if (cp.Connections == null)
{
cp.Connections = new List<ConnectionInfo>();
if (!IsConnectionInfoBlank(cinfo))
{
cp.Connections.Add(cinfo);
}
}
}
if (cp.DataQualityLevel == null) cp.DataQualityLevel = 2;
cp.SubmissionStatus = submissionStatus;
if (IsPOIValidForImport(cp))
{
outputList.Add(cp);
}
itemCount++;
}
return outputList;
}
}
} | 42.516129 | 172 | 0.473228 | [
"MIT"
] | cybersol795/ocm-system | Import/OCM.Import.Common/Providers/ImportProvider_CarStations.cs | 9,228 | C# |
namespace ClassLib008
{
public class Class042
{
public static string Property => "ClassLib008";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib008/Class042.cs | 120 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
#if NET452
using System.Runtime.Serialization;
#endif
namespace MongoDB.Driver
{
/// <summary>
/// Represents a MongoDB internal exception (almost surely the result of a bug).
/// </summary>
#if NET452
[Serializable]
#endif
public class MongoInternalException : MongoException
{
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="MongoInternalException"/> class.
/// </summary>
/// <param name="message">The error message.</param>
public MongoInternalException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MongoInternalException"/> class.
/// </summary>
/// <param name="message">The error message.</param>
/// <param name="innerException">The inner exception.</param>
public MongoInternalException(string message, Exception innerException)
: base(message, innerException)
{
}
#if NET452
/// <summary>
/// Initializes a new instance of the <see cref="MongoInternalException"/> class.
/// </summary>
/// <param name="info">The SerializationInfo.</param>
/// <param name="context">The StreamingContext.</param>
public MongoInternalException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 33.265625 | 90 | 0.632691 | [
"MIT"
] | naivetang/2019MiniGame22 | Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/MongoInternalException.cs | 2,129 | C# |
namespace Meziantou.Framework.Globbing.Internals
{
internal sealed class MatchAnyCharacterSegment : Segment
{
private MatchAnyCharacterSegment()
{
}
public static MatchAnyCharacterSegment Instance { get; } = new MatchAnyCharacterSegment();
public override bool IsMatch(ref PathReader pathReader)
{
if (pathReader.IsPathSeparator())
return false;
pathReader.ConsumeInSegment(1);
return true;
}
public override string ToString()
{
return "?";
}
}
}
| 23.384615 | 98 | 0.585526 | [
"MIT"
] | DomLatr/Meziantou.Framework | src/Meziantou.Framework.Globbing/Internals/Segments/MatchAnyCharacterSegment.cs | 610 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
public bool isPaused { get; private set; }
public bool optionsOpened { get; private set; }
public bool exitOpened { get; private set; }
private UIElementGroup pauseGroup = null;
private UIElementGroup optionsGroup = null;
private UIElementGroup exitGroup = null;
private Player player = null;
private void Start()
{
player = FindObjectOfType<Player>();
pauseGroup = player.playerCanvas.FindElementGroupByID("PauseGroup");
optionsGroup = player.playerCanvas.FindElementGroupByID("OptionsGroup");
exitGroup = player.playerCanvas.FindElementGroupByID("ExitGameGroup");
}
public void PauseGame()
{
if (optionsOpened)
{
player.playerCanvas.HideElementGroup(optionsGroup);
optionsOpened = false;
return;
}
if (isPaused)
{
ResumeGame();
return;
}
if (exitOpened)
{
player.playerCanvas.HideElementGroup(exitGroup);
exitOpened = false;
Time.timeScale = 1f;
return;
}
pauseGroup.UpdateElements(0, 0, true);
Time.timeScale = 0f;
isPaused = true;
}
public void ResumeGame()
{
if(optionsOpened)
optionsGroup.UpdateElements(0, 0, false);
pauseGroup.UpdateElements(0, 0, false);
Time.timeScale = 1f;
isPaused = false;
}
public void ToggleOptions()
{
optionsGroup.UpdateElements(0, 0, true);
optionsOpened = true;
}
public void ExitGame()
{
PauseGame();
player.playerCanvas.ShowElementGroup(exitGroup, true);
Time.timeScale = 0f;
exitOpened = true;
}
public void Exit(bool desktop)
{
if (desktop)
GameManager.instance.ExitGame();
else
GameManager.instance.LoadMainMenu();
Time.timeScale = 1f;
}
}
| 24.633333 | 81 | 0.575101 | [
"MIT"
] | RIGG-Studios/Haunted-Mine | Assets/Scripts/Misc/PauseMenu.cs | 2,217 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using WebShoes.Domain.Entities;
namespace WebShoes.Services.Interfaces
{
public interface IPaymentSlipService
{
bool Insert(long salesOrderId, String paymentSlip);
List<PaymentSlip> Select();
PaymentSlip GetByReference(string reference);
}
}
| 21.75 | 59 | 0.732759 | [
"MIT"
] | EdimilsonBomfim/DEMO-PADRAO-PROJETO | src/WebShoes.Services/Interfaces/IPaymentSlipService.cs | 350 | 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("01. Graph")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("01. Graph")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("142e04ac-c1ff-4a4c-ac8f-a48972570bc3")]
// 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 | [
"MIT"
] | jsdelivrbot/Telerik_Academy | CSharp/CSharp Part 2/Training/Breadth First Search (BFS)/01. Graph/Properties/AssemblyInfo.cs | 1,412 | C# |
using Windows.ApplicationModel.Resources;
namespace MagicLockScreen_Service_OceanPODService.Resources
{
public class ResourcesLoader
{
private static ResourcesLoader _loader;
private readonly ResourceLoader resourceLoader;
private ResourcesLoader()
{
resourceLoader = ResourceLoader.GetForViewIndependentUse(@"MagicLockScreen_Service_OceanPODService/Resources");
}
public static ResourcesLoader Loader
{
get
{
if (_loader == null)
_loader = new ResourcesLoader();
return _loader;
}
}
public string this[string name]
{
get
{
string result = resourceLoader.GetString(name);
if (!string.IsNullOrEmpty(result))
return result;
else
return name;
}
}
}
} | 25.710526 | 123 | 0.54043 | [
"MIT"
] | Jarrey/MagicLockScreen | src/MagicLockScreen.Service.OceanPODService/Resources/ResourcesLoader.cs | 979 | C# |
using HoneyDo.Domain.Enums;
using HoneyDo.Domain.Interfaces;
namespace HoneyDo.Domain.Values.Errors
{
public class SuccessResult<T> : IDomainResult<T>
{
public DomainResultCode Code => DomainResultCode.Success;
public T Value { get; private set; }
public bool HasError => false;
public string Message => "";
public SuccessResult(T value)
{
Value = value;
}
}
public class SuccessResult : IDomainResult
{
public DomainResultCode Code => DomainResultCode.Success;
public bool HasError => false;
public string Message => "";
}
}
| 24.807692 | 65 | 0.624806 | [
"MIT"
] | honey-do/web | HoneyDo.Domain/Values/Errors/SuccessResult.cs | 645 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the backup-2018-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Backup.Model
{
/// <summary>
/// Container for the parameters to the GetBackupSelection operation.
/// Returns selection metadata and a document in JSON format that specifies a list of
/// resources that are associated with a backup plan.
/// </summary>
public partial class GetBackupSelectionRequest : AmazonBackupRequest
{
private string _backupPlanId;
private string _selectionId;
/// <summary>
/// Gets and sets the property BackupPlanId.
/// <para>
/// Uniquely identifies a backup plan.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string BackupPlanId
{
get { return this._backupPlanId; }
set { this._backupPlanId = value; }
}
// Check to see if BackupPlanId property is set
internal bool IsSetBackupPlanId()
{
return this._backupPlanId != null;
}
/// <summary>
/// Gets and sets the property SelectionId.
/// <para>
/// Uniquely identifies the body of a request to assign a set of resources to a backup
/// plan.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string SelectionId
{
get { return this._selectionId; }
set { this._selectionId = value; }
}
// Check to see if SelectionId property is set
internal bool IsSetSelectionId()
{
return this._selectionId != null;
}
}
} | 31.481481 | 105 | 0.612157 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Backup/Generated/Model/GetBackupSelectionRequest.cs | 2,550 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Network.Models
{
public partial class ExpressRouteCircuitPeeringId : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(Id))
{
writer.WritePropertyName("id");
writer.WriteStringValue(Id);
}
writer.WriteEndObject();
}
internal static ExpressRouteCircuitPeeringId DeserializeExpressRouteCircuitPeeringId(JsonElement element)
{
Optional<string> id = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("id"))
{
id = property.Value.GetString();
continue;
}
}
return new ExpressRouteCircuitPeeringId(id.Value);
}
}
}
| 27.853659 | 113 | 0.584063 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Models/ExpressRouteCircuitPeeringId.Serialization.cs | 1,142 | C# |
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Text;
namespace Axaprj.WordToVecDB
{
/// <summary>
/// Abstract DB context (base class)
/// </summary>
public abstract class DbContext : IDisposable
{
readonly SQLiteConnection _conn;
public DbContext(string db_file, bool foreign_keys = true)
{
var conn_str = $"Data Source=\"{db_file}\";Version=3;";
if (foreign_keys)
conn_str += "foreign keys=true;";
_conn = new SQLiteConnection(conn_str);
_conn.Open();
}
public void Dispose()
{
_conn.Close();
_conn.Dispose();
}
internal static int CreateDB(string db_file, string ddl_script, bool if_not_exists = false)
{
if (if_not_exists && File.Exists(db_file))
return 0;
SQLiteConnection.CreateFile(db_file);
using (var conn = new SQLiteConnection($"Data Source=\"{db_file}\";Version=3;"))
{
conn.Open();
var cmd = new SQLiteCommand(ddl_script, conn);
return cmd.ExecuteNonQuery();
}
}
public long LastInsertRowId { get { return _conn.LastInsertRowId; } }
public SQLiteTransaction BeginTransaction() => _conn.BeginTransaction();
public SQLiteCommand CreateCmd(string sql) => new SQLiteCommand(sql, _conn);
}
}
| 29.509804 | 99 | 0.578738 | [
"MIT"
] | Axaprj/FastTextProcess | Axaprj.WordToVecDB/abstract/DbContext.cs | 1,507 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.AspNet.SignalR.Json;
using Newtonsoft.Json;
namespace Microsoft.AspNet.SignalR.Hubs
{
public class DefaultJavaScriptProxyGenerator : IJavaScriptProxyGenerator
{
private static readonly Lazy<string> _templateFromResource = new Lazy<string>(GetTemplateFromResource);
private static readonly Type[] _numberTypes = new[] { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(decimal), typeof(double) };
private static readonly Type[] _dateTypes = new[] { typeof(DateTime), typeof(DateTimeOffset) };
private const string ScriptResource = "Microsoft.AspNet.SignalR.Scripts.hubs.js";
private readonly IHubManager _manager;
private readonly IJavaScriptMinifier _javaScriptMinifier;
private readonly Lazy<string> _generatedTemplate;
public DefaultJavaScriptProxyGenerator(IDependencyResolver resolver) :
this(resolver.Resolve<IHubManager>(),
resolver.Resolve<IJavaScriptMinifier>())
{
}
public DefaultJavaScriptProxyGenerator(IHubManager manager, IJavaScriptMinifier javaScriptMinifier)
{
_manager = manager;
_javaScriptMinifier = javaScriptMinifier ?? NullJavaScriptMinifier.Instance;
_generatedTemplate = new Lazy<string>(() => GenerateProxy(_manager, _javaScriptMinifier, includeDocComments: false));
}
public string GenerateProxy(string serviceUrl)
{
serviceUrl = JavaScriptEncode(serviceUrl);
var generateProxy = _generatedTemplate.Value;
return generateProxy.Replace("{serviceUrl}", serviceUrl);
}
public string GenerateProxy(string serviceUrl, bool includeDocComments)
{
serviceUrl = JavaScriptEncode(serviceUrl);
string generateProxy = GenerateProxy(_manager, _javaScriptMinifier, includeDocComments);
return generateProxy.Replace("{serviceUrl}", serviceUrl);
}
private static string GenerateProxy(IHubManager hubManager, IJavaScriptMinifier javaScriptMinifier, bool includeDocComments)
{
string script = _templateFromResource.Value;
var hubs = new StringBuilder();
var first = true;
foreach (var descriptor in hubManager.GetHubs().OrderBy(h => h.Name))
{
if (!first)
{
hubs.AppendLine(";");
hubs.AppendLine();
hubs.Append(" ");
}
GenerateType(hubManager, hubs, descriptor, includeDocComments);
first = false;
}
if (hubs.Length > 0)
{
hubs.Append(";");
}
script = script.Replace("/*hubs*/", hubs.ToString());
javaScriptMinifier.Minify(script);
return script;
}
private static void GenerateType(IHubManager hubManager, StringBuilder sb, HubDescriptor descriptor, bool includeDocComments)
{
// Get only actions with minimum number of parameters.
var methods = GetMethods(hubManager, descriptor);
var hubName = GetDescriptorName(descriptor);
sb.AppendFormat(" proxies.{0} = this.createHubProxy('{1}'); ", hubName, hubName).AppendLine();
sb.AppendFormat(" proxies.{0}.client = {{ }};", hubName).AppendLine();
sb.AppendFormat(" proxies.{0}.server = {{", hubName);
bool first = true;
foreach (var method in methods)
{
if (!first)
{
sb.Append(",").AppendLine();
}
GenerateMethod(sb, method, includeDocComments, hubName);
first = false;
}
sb.AppendLine();
sb.Append(" }");
}
private static string GetDescriptorName(Descriptor descriptor)
{
if (descriptor == null)
{
throw new ArgumentNullException("descriptor");
}
string name = descriptor.Name;
// If the name was not specified then do not camel case
if (!descriptor.NameSpecified)
{
name = JsonUtility.CamelCase(name);
}
return name;
}
private static IEnumerable<MethodDescriptor> GetMethods(IHubManager manager, HubDescriptor descriptor)
{
return from method in manager.GetHubMethods(descriptor.Name)
group method by method.Name into overloads
let oload = (from overload in overloads
orderby overload.Parameters.Count
select overload).FirstOrDefault()
orderby oload.Name
select oload;
}
private static void GenerateMethod(StringBuilder sb, MethodDescriptor method, bool includeDocComments, string hubName)
{
var parameterNames = method.Parameters.Select(p => p.Name).ToList();
sb.AppendLine();
sb.AppendFormat(" {0}: function ({1}) {{", GetDescriptorName(method), Commas(parameterNames)).AppendLine();
if (includeDocComments)
{
sb.AppendFormat(Resources.DynamicComment_CallsMethodOnServerSideDeferredPromise, method.Name, method.Hub.Name).AppendLine();
var parameterDoc = method.Parameters.Select(p => String.Format(CultureInfo.CurrentCulture, Resources.DynamicComment_ServerSideTypeIs, p.Name, MapToJavaScriptType(p.ParameterType), p.ParameterType)).ToList();
if (parameterDoc.Any())
{
sb.AppendLine(String.Join(Environment.NewLine, parameterDoc));
}
}
sb.AppendFormat(" return proxies.{0}.invoke.apply(proxies.{0}, $.merge([\"{1}\"], $.makeArray(arguments)));", hubName, method.Name).AppendLine();
sb.Append(" }");
}
private static string MapToJavaScriptType(Type type)
{
if (!type.IsPrimitive && !(type == typeof(string)))
{
return "Object";
}
if (type == typeof(string))
{
return "String";
}
if (_numberTypes.Contains(type))
{
return "Number";
}
if (typeof(IEnumerable).IsAssignableFrom(type))
{
return "Array";
}
if (_dateTypes.Contains(type))
{
return "Date";
}
return String.Empty;
}
private static string Commas(IEnumerable<string> values)
{
return Commas(values, v => v);
}
private static string Commas<T>(IEnumerable<T> values, Func<T, string> selector)
{
return String.Join(", ", values.Select(selector));
}
private static string GetTemplateFromResource()
{
using (Stream resourceStream = typeof(DefaultJavaScriptProxyGenerator).Assembly.GetManifestResourceStream(ScriptResource))
{
var reader = new StreamReader(resourceStream);
return reader.ReadToEnd();
}
}
private static string JavaScriptEncode(string value)
{
value = JsonConvert.SerializeObject(value);
// Remove the quotes
return value.Substring(1, value.Length - 2);
}
}
}
| 37.345794 | 223 | 0.578203 | [
"Apache-2.0"
] | MacawNL/SignalR | src/Microsoft.AspNet.SignalR.Core/Hubs/DefaultJavaScriptProxyGenerator.cs | 7,994 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Macros;
namespace Umbraco.Tests.Configurations.UmbracoSettings
{
[TestFixture]
public class ContentElementTests : UmbracoSettingsTests
{
[Test]
public void EmailAddress()
{
Assert.AreEqual("robot@umbraco.dk", SettingsSection.Content.NotificationEmailAddress);
}
[Test]
public virtual void DisableHtmlEmail()
{
Assert.IsTrue(SettingsSection.Content.DisableHtmlEmail);
}
[Test]
public virtual void Can_Set_Multiple()
{
Assert.AreEqual(3, SettingsSection.Content.Error404Collection.Count());
Assert.AreEqual("default", SettingsSection.Content.Error404Collection.ElementAt(0).Culture);
Assert.AreEqual(1047, SettingsSection.Content.Error404Collection.ElementAt(0).ContentId);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(0).HasContentId);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(0).HasContentKey);
Assert.AreEqual("en-US", SettingsSection.Content.Error404Collection.ElementAt(1).Culture);
Assert.AreEqual("$site/error [@name = 'error']", SettingsSection.Content.Error404Collection.ElementAt(1).ContentXPath);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(1).HasContentId);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(1).HasContentKey);
Assert.AreEqual("en-UK", SettingsSection.Content.Error404Collection.ElementAt(2).Culture);
Assert.AreEqual(new Guid("8560867F-B88F-4C74-A9A4-679D8E5B3BFC"), SettingsSection.Content.Error404Collection.ElementAt(2).ContentKey);
Assert.IsTrue(SettingsSection.Content.Error404Collection.ElementAt(2).HasContentKey);
Assert.IsFalse(SettingsSection.Content.Error404Collection.ElementAt(2).HasContentId);
}
[Test]
public void ImageFileTypes()
{
Assert.IsTrue(SettingsSection.Content.ImageFileTypes.All(x => "jpeg,jpg,gif,bmp,png,tiff,tif".Split(',').Contains(x)));
}
[Test]
public virtual void ImageAutoFillProperties()
{
Assert.AreEqual(2, SettingsSection.Content.ImageAutoFillProperties.Count());
Assert.AreEqual("umbracoFile", SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).Alias);
Assert.AreEqual("umbracoWidth", SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).WidthFieldAlias);
Assert.AreEqual("umbracoHeight", SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).HeightFieldAlias);
Assert.AreEqual("umbracoBytes", SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).LengthFieldAlias);
Assert.AreEqual("umbracoExtension", SettingsSection.Content.ImageAutoFillProperties.ElementAt(0).ExtensionFieldAlias);
Assert.AreEqual("umbracoFile2", SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).Alias);
Assert.AreEqual("umbracoWidth2", SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).WidthFieldAlias);
Assert.AreEqual("umbracoHeight2", SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).HeightFieldAlias);
Assert.AreEqual("umbracoBytes2", SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).LengthFieldAlias);
Assert.AreEqual("umbracoExtension2", SettingsSection.Content.ImageAutoFillProperties.ElementAt(1).ExtensionFieldAlias);
}
[Test]
public void PreviewBadge()
{
Assert.AreEqual(SettingsSection.Content.PreviewBadge, @"<div id=""umbracoPreviewBadge"" class=""umbraco-preview-badge""><span class=""umbraco-preview-badge__header"">Preview mode</span><a href=""{0}/preview/end?redir={1}"" class=""umbraco-preview-badge__end""><svg viewBox=""0 0 100 100"" xmlns=""http://www.w3.org/2000/svg""><title>Click to end</title><path d=""M5273.1 2400.1v-2c0-2.8-5-4-9.7-4s-9.7 1.3-9.7 4v2a7 7 0 002 4.9l5 4.9c.3.3.4.6.4 1v6.4c0 .4.2.7.6.8l2.9.9c.5.1 1-.2 1-.8v-7.2c0-.4.2-.7.4-1l5.1-5a7 7 0 002-4.9zm-9.7-.1c-4.8 0-7.4-1.3-7.5-1.8.1-.5 2.7-1.8 7.5-1.8s7.3 1.3 7.5 1.8c-.2.5-2.7 1.8-7.5 1.8z""/><path d=""M5268.4 2410.3c-.6 0-1 .4-1 1s.4 1 1 1h4.3c.6 0 1-.4 1-1s-.4-1-1-1h-4.3zM5272.7 2413.7h-4.3c-.6 0-1 .4-1 1s.4 1 1 1h4.3c.6 0 1-.4 1-1s-.4-1-1-1zM5272.7 2417h-4.3c-.6 0-1 .4-1 1s.4 1 1 1h4.3c.6 0 1-.4 1-1 0-.5-.4-1-1-1z""/><path d=""M78.2 13l-8.7 11.7a32.5 32.5 0 11-51.9 25.8c0-10.3 4.7-19.7 12.9-25.8L21.8 13a47 47 0 1056.4 0z""/><path d=""M42.7 2.5h14.6v49.4H42.7z""/></svg></a></div><style type=""text/css"">.umbraco-preview-badge {{position: absolute;top: 1em;right: 1em;display: inline-flex;background: #1b264f;color: #fff;padding: 1em;font-size: 12px;z-index: 99999999;justify-content: center;align-items: center;box-shadow: 0 10px 50px rgba(0, 0, 0, .1), 0 6px 20px rgba(0, 0, 0, .16);line-height: 1;}}.umbraco-preview-badge__header {{font-weight: bold;}}.umbraco-preview-badge__end {{width: 3em;padding: 1em;margin: -1em -1em -1em 2em;display: flex;flex-shrink: 0;align-items: center;align-self: stretch;}}.umbraco-preview-badge__end:hover,.umbraco-preview-badge__end:focus {{background: #f5c1bc;}}.umbraco-preview-badge__end svg {{fill: #fff;width:1em;}}</style>");
}
[Test]
public void ResolveUrlsFromTextString()
{
Assert.IsFalse(SettingsSection.Content.ResolveUrlsFromTextString);
}
[Test]
public void MacroErrors()
{
Assert.AreEqual(SettingsSection.Content.MacroErrorBehaviour, MacroErrorBehaviour.Inline);
}
[Test]
public void DisallowedUploadFiles()
{
Assert.IsTrue(SettingsSection.Content.DisallowedUploadFiles.All(x => "ashx,aspx,ascx,config,cshtml,vbhtml,asmx,air,axd,xamlx".Split(',').Contains(x)));
}
[Test]
public void AllowedUploadFiles()
{
Assert.IsTrue(SettingsSection.Content.AllowedUploadFiles.All(x => "jpg,gif,png".Split(',').Contains(x)));
}
[Test]
[TestCase("png", true)]
[TestCase("jpg", true)]
[TestCase("gif", true)]
// TODO: Why does it flip to TestingDefaults=true for these two tests on AppVeyor. WHY?
//[TestCase("bmp", false)]
//[TestCase("php", false)]
[TestCase("ashx", false)]
[TestCase("config", false)]
public void IsFileAllowedForUpload_WithWhitelist(string extension, bool expected)
{
// Make really sure that defaults are NOT used
TestingDefaults = false;
Debug.WriteLine("Extension being tested", extension);
Debug.WriteLine("AllowedUploadFiles: {0}", SettingsSection.Content.AllowedUploadFiles);
Debug.WriteLine("DisallowedUploadFiles: {0}", SettingsSection.Content.DisallowedUploadFiles);
var allowedContainsExtension = SettingsSection.Content.AllowedUploadFiles.Any(x => x.InvariantEquals(extension));
var disallowedContainsExtension = SettingsSection.Content.DisallowedUploadFiles.Any(x => x.InvariantEquals(extension));
Debug.WriteLine("AllowedContainsExtension: {0}", allowedContainsExtension);
Debug.WriteLine("DisallowedContainsExtension: {0}", disallowedContainsExtension);
Assert.AreEqual(expected, SettingsSection.Content.IsFileAllowedForUpload(extension));
}
}
}
| 62.699187 | 1,715 | 0.688537 | [
"MIT"
] | AaronSadlerUK/Umbraco-CMS | src/Umbraco.Tests/Configurations/UmbracoSettings/ContentElementTests.cs | 7,714 | C# |
namespace twot
{
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.Extensions.Configuration;
using Tweetinvi;
using Tweetinvi.Events;
using static System.ConsoleColor;
using static ConsoleHelper;
internal class Config
{
private Config()
{
// no-op
}
[ConfigInfo(DisplayName = "API Key", ConfigProperty = "apikey")]
public string APIKey { get; private set; } = string.Empty;
[ConfigInfo(DisplayName = "API Secret", ConfigProperty = "apisecret")]
public string APISecret { get; private set; } = string.Empty;
[ConfigInfo(DisplayName = "Access Token", ConfigProperty = "accesstoken")]
public string AccessToken { get; private set; } = string.Empty;
[ConfigInfo(DisplayName = "Access Secret", ConfigProperty = "accesssecret")]
public string AccessSecret { get; private set; } = string.Empty;
public static (bool Success, Config Config) Load()
{
var configuration = new ConfigurationBuilder()
.AddUserSecrets(typeof(Program).Assembly)
.AddJsonFile("./secrets.json", true, false)
.Build();
var section = configuration.GetSection("twot");
var result = new Config();
var propertiesToSet = result.GetType().GetProperties()
.Select(propertyInfo =>
(PropertyInfo: propertyInfo, Config: propertyInfo.GetCustomAttribute<ConfigInfoAttribute>()))
.Where(property => property.Config != null);
foreach (var propInfo in propertiesToSet)
{
var configValue = section.GetValue<string>(propInfo.Config!.ConfigProperty);
if (string.IsNullOrWhiteSpace(configValue))
{
Writeln(Red, $"🚨 {propInfo.Config.DisplayName} not set");
return (false, new Config());
}
propInfo.PropertyInfo.SetValue(result, configValue);
}
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackOnly;
TweetinviEvents.QueryBeforeExecute += RateLimitCheck;
Auth.SetUserCredentials(result.APIKey, result.APISecret, result.AccessToken, result.AccessSecret);
return (true, result);
}
public override string ToString()
{
return string.Join(Environment.NewLine, this.GetType().GetProperties()
.Select(propertyInfo =>
(PropertyInfo: propertyInfo, Config: propertyInfo.GetCustomAttribute<ConfigInfoAttribute>()))
.Where(property => property.Config != null)
.Select(property => $"{property.Config!.DisplayName} = {property.PropertyInfo.GetValue(this)}"));
}
private static void RateLimitCheck(object? sender, QueryBeforeExecuteEventArgs args)
{
var queryRateLimits = RateLimit.GetQueryRateLimit(args.QueryURL);
if (queryRateLimits != null)
{
if (queryRateLimits.Remaining > 0)
{
return;
}
using (var spinner = new Spinner("You have been rate limited by Twitter until " +
$"{queryRateLimits.ResetDateTime.ToLongTimeString()}. Please wait or Ctrl+C to quit"))
{
Thread.Sleep((int)queryRateLimits.ResetDateTimeInMilliseconds);
spinner.Done();
}
}
}
}
[System.AttributeUsage(System.AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
internal sealed class ConfigInfoAttribute : System.Attribute
{
public string DisplayName { get; set; } = string.Empty;
public string ConfigProperty { get; set; } = string.Empty;
}
}
| 38.776699 | 113 | 0.58638 | [
"Unlicense"
] | rmaclean/twot | Config.cs | 3,997 | C# |
// Copyright (c) 2015 - 2019 Doozy Entertainment. All Rights Reserved.
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using Doozy.Engine.Extensions;
using UnityEditor;
using UnityEngine;
namespace Doozy.Editor
{
public static partial class DGUI
{
public static class WindowUtils
{
public static void DrawIconTitle(Styles.StyleName iconStyleName, string mainTitle, string subTitle, ColorName colorName)
{
GUILayout.BeginHorizontal();
{
Icon.Draw(Styles.GetStyle(iconStyleName), Bar.Height(Size.XL), Bar.Height(Size.XL), colorName);
GUILayout.Space(Properties.Space(4));
GUILayout.BeginVertical(GUILayout.Height(Bar.Height(Size.XL)));
{
GUILayout.Space(-Properties.Space(2));
Label.Draw(mainTitle, Size.XL, colorName, Bar.Height(Size.M));
GUILayout.Space(Properties.Space());
Divider.Draw(Divider.Type.One, colorName);
GUI.color = GUI.color.WithAlpha(0.8f);
Label.Draw(subTitle, Size.S, colorName, Bar.Height(Size.M));
GUI.color = GUI.color.WithAlpha(1f);
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
}
public static void DrawSettingLabel(string label, ColorName colorName, float rowHeight) { DGUI.Label.Draw(label, Size.M, colorName, rowHeight); }
public static void DrawSettingDescription(string description)
{
GUI.color = GUI.color.WithAlpha(Utility.IsProSkin ? 0.6f : 0.8f);
var textStyle = new GUIStyle(Label.Style(Size.S, TextAlign.Left, Colors.DisabledTextColorName));Label.Style(Size.S, TextAlign.Left, Colors.DisabledTextColorName);
textStyle.wordWrap = true;
textStyle.padding = new RectOffset(0, 0, 0, 8);
EditorGUILayout.LabelField(description, textStyle);
Colors.SetNormalGUIColorAlpha();
}
}
}
} | 48.489796 | 179 | 0.579125 | [
"MIT"
] | MikaelStenstrand/drivingo | Assets/Doozy/Editor/GUI/Scripts/DGUI/WindowUtils.cs | 2,376 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Odd_Lines
{
class Program
{
static void Main(string[] args)
{
}
}
}
| 14.5 | 39 | 0.642241 | [
"MIT"
] | StefanRomanov/Programing-Fundamentals-February-2017 | Files And Exceptions/Odd_Lines/Program.cs | 234 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenuAttribute(menuName = "Dialogue", fileName = "DLG_")]
public class DialogueData : ScriptableObject
{
/*
[Multiline]
[SerializeField] string _dialogue = "...";
[SerializeField] string _characterName = "...";
[SerializeField] Sprite _portrait = null;
*/
//public GameObject prefab;
public string diaName;
public string dialogue;
public string characterName;
public Sprite portrait;
public float textDelay;
public string DiaName => diaName;
public string Dialogue => dialogue;
public float TextDelay => textDelay;
public string CharacterName => characterName;
public Sprite Portrait => portrait;
}
| 25.741935 | 69 | 0.674185 | [
"MIT"
] | crs170030/StetsonCloyce_P02 | Assets/Scripts/DialogueData.cs | 800 | C# |
namespace UnitTests.UseCaseTests.Withdraw
{
using System.Linq;
using System.Threading.Tasks;
using Application.Boundaries.Withdraw;
using Application.UseCases;
using Domain.Accounts.ValueObjects;
using Infrastructure.InMemoryDataAccess;
using Infrastructure.InMemoryDataAccess.Presenters;
using TestFixtures;
using Xunit;
public sealed class WithdrawTests : IClassFixture<StandardFixture>
{
private readonly StandardFixture _fixture;
public WithdrawTests(StandardFixture fixture)
{
this._fixture = fixture;
}
[Theory]
[ClassData(typeof(PositiveDataSetup))]
public async Task Withdraw_Valid_Amount(
decimal amount,
decimal expectedBalance)
{
var presenter = new WithdrawPresenter();
var sut = new WithdrawUseCase(
this._fixture.AccountService,
presenter,
this._fixture.AccountRepository,
this._fixture.UnitOfWork);
await sut.Execute(new WithdrawInput(
MangaContext.DefaultAccountId,
new PositiveMoney(amount)));
var actual = presenter.Withdrawals.Last();
Assert.Equal(expectedBalance, actual.UpdatedBalance.ToDecimal());
}
}
}
| 30.522727 | 77 | 0.63589 | [
"Apache-2.0"
] | RaphsVenas/clean-architecture-manga | test/UnitTests/UseCaseTests/Withdraw/WithdrawTests.cs | 1,343 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Dayu.V20180709.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeCCAlarmThresholdResponse : AbstractModel
{
/// <summary>
/// CC告警阈值
/// </summary>
[JsonProperty("CCAlarmThreshold")]
public CCAlarmThreshold CCAlarmThreshold{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamObj(map, prefix + "CCAlarmThreshold.", this.CCAlarmThreshold);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 31.392157 | 87 | 0.654591 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Dayu/V20180709/Models/DescribeCCAlarmThresholdResponse.cs | 1,667 | C# |
using System;
class TrickyStrings
{
static void Main(string[] args)
{
var delimiter = Console.ReadLine();
var numberOfStrings = int.Parse(Console.ReadLine());
var result = string.Empty;
var currentString = string.Empty;
for (int i = 0; i < numberOfStrings; i++)
{
currentString += Console.ReadLine();
result += currentString + delimiter;
Console.Write(result);
}
Console.WriteLine(result);
}
} | 28.5 | 67 | 0.563353 | [
"MIT"
] | viktornikolov038/Programming-Fundamentals-C-Sharp-2018 | 05.Debugging and Troubleshooting Code - Lab/01.TrickyStrings/01.TrickyStrings/Program.cs | 515 | 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.AzureNative.Peering.V20201001.Outputs
{
[OutputType]
public sealed class ContactDetailResponse
{
/// <summary>
/// The e-mail address of the contact.
/// </summary>
public readonly string? Email;
/// <summary>
/// The phone number of the contact.
/// </summary>
public readonly string? Phone;
/// <summary>
/// The role of the contact.
/// </summary>
public readonly string? Role;
[OutputConstructor]
private ContactDetailResponse(
string? email,
string? phone,
string? role)
{
Email = email;
Phone = phone;
Role = role;
}
}
}
| 24.72093 | 81 | 0.578551 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Peering/V20201001/Outputs/ContactDetailResponse.cs | 1,063 | C# |
#region copyright
// Copyright (C) 2018 "Daniel Bramblett" <bram4@pdx.edu>, "Daniel Dupriest" <kououken@gmail.com>, "Brandon Goldbeck" <bpg@pdx.edu>
// This software is licensed under the MIT License. See LICENSE file for the full text.
#endregion
using System;
namespace Game.Components.EnemyTypes
{
class Zombie : Enemy
{
public Zombie(Random rand, int level, bool isShiny)
: base(
"Zombie", //Enemy's name
"Just a normal undead", //Enemy's description
level, //Level of the enemy
7 * level, //Equation for the enemy's health.
(level > 1) ? level - 1 : 0, //Equation for the enemy's armor.
2 * level, //Equation for the enemy's attack.
10 * level, //xp given by beating this enemy.
isShiny,
rand
)
{
}
public override void Start()
{
base.Start();
mapTile.character = 'z'; //enemy's model
if (isShiny) //Color
{
mapTile.color.Set(255, 215, 0);
}
else
{
mapTile.color.Set(0, 120, 120);
}
ai.SetRate(3.0f / ((isShiny) ? 2 : 1)); //Time between each move.
healthRegen.SetHealthRegen(2.0f / ((isShiny) ? 2 : 1)); //Health regen (seconds for 1 health regen).
aggro.SetAggroPatience(5.0f); //Seconds before it gives up.
aggro.SetAggroRange(16); //Distance it can see the player at.
}
}
}
| 40.543478 | 130 | 0.445576 | [
"MIT"
] | bgoldbeck/TEAr | src/Game/Components/EnemyTypes/Normal/Zombie.cs | 1,867 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace ProxyUnsetter.Helpers
{
internal class HostsFileManager
{
public static IEnumerable<HostsFileEntry> Get(string filepath = null)
{
filepath = filepath ?? GetHostsPath();
var lines = File.ReadAllLines(filepath);
return lines
.Where(HostsFileHelper.IsLineAHostFilesEntry)
.Select(HostsFileHelper.GetHostsFileEntry);
}
public static void Set(string hostname, string address, string filepath = null)
{
Set(new[] { new HostsFileEntry(hostname, address), }, filepath);
}
public static void Set(IEnumerable<HostsFileEntry> entries, string filepath = null)
{
filepath = filepath ?? GetHostsPath();
List<Func<IEnumerable<string>, IEnumerable<string>>> transforms =
new List<Func<IEnumerable<string>, IEnumerable<string>>>();
foreach (var entry in entries.Reverse())
{
string hostName = entry.Hostname;
string address = entry.Address;
transforms.Add(HostsFileHelper.GetRemoveTransformForHost(hostName));
transforms.Add(lines => GetSetHostTransform(lines.ToArray(), hostName, address));
}
HostsFileHelper.TransformFile(filepath, transforms.ToArray());
}
public static void Remove(string hostName)
{
var hostsPath = GetHostsPath();
HostsFileHelper.RemoveFromFile(hostName, hostsPath);
}
public static void Remove(Regex pattern)
{
var hostsPath = GetHostsPath();
HostsFileHelper.RemoveFromFile(pattern, hostsPath);
}
public static string GetHostsPath()
{
var systemPath = Environment.GetEnvironmentVariable("SystemRoot");
var hostsPath = Path.Combine(systemPath, "system32\\drivers\\etc\\hosts");
if (!File.Exists(hostsPath))
throw new FileNotFoundException("Hosts file not found at expected location.");
return hostsPath;
}
public static IEnumerable<string> GetSetHostTransform(IEnumerable<string> contents, string hostName,
string address)
{
List<string> result = new List<string>();
var needsInsert = true;
foreach (var line in contents)
{
if (!HostsFileHelper.IsLineAHostFilesEntry(line))
{
result.Add(line);
continue;
}
if (needsInsert)
{
result.Add(GetHostLine(hostName, address));
needsInsert = false;
}
result.Add(line);
}
if (needsInsert)
{
result.Add(GetHostLine(hostName, address));
needsInsert = false;
}
return result;
}
public static string GetHostLine(string hostName, string address)
{
return address + "\t\t" + hostName;
}
}
} | 30.728972 | 108 | 0.562348 | [
"MIT"
] | tjeerdhans/proxyunsetter | ProxyUnsetter/Helpers/HostsFileManager.cs | 3,290 | C# |
using System.ComponentModel.DataAnnotations;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.MultiTenancy;
namespace PetVision.MultiTenancy.Dto
{
[AutoMapTo(typeof(Tenant))]
public class CreateTenantDto
{
[Required]
[StringLength(AbpTenantBase.MaxTenancyNameLength)]
[RegularExpression(Tenant.TenancyNameRegex)]
public string TenancyName { get; set; }
[Required]
[StringLength(Tenant.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string AdminEmailAddress { get; set; }
[MaxLength(AbpTenantBase.MaxConnectionStringLength)]
public string ConnectionString { get; set; }
public bool IsActive { get; set; }
}
} | 28.172414 | 60 | 0.682987 | [
"MIT"
] | JesusCSUF/PetsWhoCode | src/PetVision.Application/MultiTenancy/Dto/CreateTenantDto.cs | 819 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
//[System.Serializable]
//public struct CustomKnowledge
//{
// public Type type;
// public object value;
// public CustomKnowledge(Type _type)
// {
// type = _type;
// value = null;
// }
//}
[CreateAssetMenu(fileName = "Knowledge", menuName = "ScriptableObjects/Knowledge", order = 1)]
public class Knowledge : KnowledgeBase, ISerializationCallbackReceiver
{
[SerializeField]
private Dictionary<string, object> customKnowledge = new Dictionary<string, object>();
public bool HasKnowledge(string _key)
{
return customKnowledge.ContainsKey(_key);
}
public object GetKnowledge(string _key)
{
if (customKnowledge.ContainsKey(_key))
{
return customKnowledge[_key];
}
else
{
Debug.LogError("Tried to access non-existing custom knowledge");
}
return null;
}
//public Type GetKnowledgeType(string _key)
//{
// if (customKnowledge.ContainsKey(_key))
// {
// return customKnowledge[_key].type;
// }
// else
// {
// Debug.LogError("Tried to access non-existing custom knowledge");
// }
// return null;
//}
public void SetKnowledge<T>(string _key, T _value)
{
if (customKnowledge.ContainsKey(_key))
{
if (customKnowledge[_key] != null)
{
if ((T)customKnowledge[_key] != null)
{
customKnowledge[_key] = _value;
}
else
{
Debug.LogError("Retrieved custom knowledge has wrong type.");
}
}
}
else
{
Debug.LogError("Tried to access non-existing custom knowledge");
}
}
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
public List<string> entries;
// Dictionary to List to Inspector
public void OnBeforeSerialize()
{
entries.Clear();
foreach (string key in customKnowledge.Keys)
{
entries.Add(key);
}
}
// List to Dictionary from Inspector
public void OnAfterDeserialize()
{
customKnowledge.Clear();
foreach (string entry in entries)
{
customKnowledge.Add(entry, null);
}
}
//[System.Serializable]
//public struct KnowledgeKey
//{
// public string key;
// public Type type;
// public KnowledgeKey(string _key, Type _type)
// {
// key = _key;
// type = _type;
// }
//}
#endif
}
| 23.465517 | 94 | 0.545555 | [
"MIT"
] | DebuissyVincent/PolyAI | Assets/PolyAI/Knowledge.cs | 2,724 | C# |
/*
Copyright (c) 2018-present, Walmart Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code++. Version 4.4.0.7
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Walmart.Sdk.Marketplace.V2.Payload.LagTime
{
using System.Xml.Serialization;
using System.Xml;
using System.Collections.Generic;
using Walmart.Sdk.Base.Primitive;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.4.0.7")]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlTypeAttribute(Namespace="http://walmart.com/")]
[XmlRootAttribute("lagTime", Namespace="http://walmart.com/", IsNullable=false)]
public class LagTime : BasePayload
{
[XmlElement("sku")]
public string Sku { get; set; }
[XmlElement("fulfillmentLagTime")]
public int FulfillmentLagTime { get; set; }
[XmlElement("additionalAttributes", ElementName="additionalAttributes")]
public List<LagTimeAdditionalAttributes> AdditionalAttributes { get; set; }
/// <summary>
/// LagTime class constructor
/// </summary>
public LagTime()
{
AdditionalAttributes = new List<LagTimeAdditionalAttributes>();
}
}
}
| 37.901961 | 85 | 0.622349 | [
"Apache-2.0"
] | GaryWayneSmith/partnerapi_sdk_dotnet | Source/Walmart.Sdk.Marketplace/V2/Payload/LagTime/LagTime.cs | 1,933 | C# |
namespace Boyer_MooreBondarenko
{
partial class Form1
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.buttonOchistit = new System.Windows.Forms.Button();
this.buttonZagruzka = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.buttonPoisk = new System.Windows.Forms.Button();
this.txtText = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txtPatterns = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox2.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox2
//
this.groupBox2.Controls.Add(this.label9);
this.groupBox2.Controls.Add(this.label10);
this.groupBox2.Controls.Add(this.label8);
this.groupBox2.Controls.Add(this.label7);
this.groupBox2.Controls.Add(this.label6);
this.groupBox2.Controls.Add(this.label5);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Location = new System.Drawing.Point(150, 202);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(301, 231);
this.groupBox2.TabIndex = 14;
this.groupBox2.TabStop = false;
this.groupBox2.Enter += new System.EventHandler(this.groupBox2_Enter);
//
// label9
//
this.label9.AutoSize = true;
this.label9.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label9.Location = new System.Drawing.Point(13, 190);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(160, 16);
this.label9.TabIndex = 15;
this.label9.Text = "Potrachennoye vremya";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label10.Location = new System.Drawing.Point(12, 165);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(171, 16);
this.label10.TabIndex = 14;
this.label10.Text = "Sovpadeniy(Vhozhdeniy)";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label8.Location = new System.Drawing.Point(12, 104);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(160, 16);
this.label8.TabIndex = 13;
this.label8.Text = "Potrachennoye vremya";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label7.Location = new System.Drawing.Point(11, 79);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(171, 16);
this.label7.TabIndex = 12;
this.label7.Text = "Sovpadeniy(Vhozhdeniy)";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label6.Location = new System.Drawing.Point(93, 139);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(102, 16);
this.label6.TabIndex = 11;
this.label6.Text = "Naivniy posk";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label5.Location = new System.Drawing.Point(64, 47);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(191, 16);
this.label5.TabIndex = 10;
this.label5.Text = "Algoritmom Boyer-Moore";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("MS Reference Sans Serif", 11.25F);
this.label4.Location = new System.Drawing.Point(124, 16);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(62, 19);
this.label4.TabIndex = 3;
this.label4.Text = "Results";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.buttonOchistit);
this.groupBox1.Controls.Add(this.buttonZagruzka);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.buttonPoisk);
this.groupBox1.Location = new System.Drawing.Point(11, 202);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(132, 231);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
//
// buttonOchistit
//
this.buttonOchistit.Font = new System.Drawing.Font("Microsoft YaHei", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.buttonOchistit.Location = new System.Drawing.Point(17, 161);
this.buttonOchistit.Name = "buttonOchistit";
this.buttonOchistit.Size = new System.Drawing.Size(98, 51);
this.buttonOchistit.TabIndex = 6;
this.buttonOchistit.Text = "Clear";
this.buttonOchistit.UseVisualStyleBackColor = true;
this.buttonOchistit.Click += new System.EventHandler(this.buttonOchistit_Click);
//
// buttonZagruzka
//
this.buttonZagruzka.Font = new System.Drawing.Font("Microsoft YaHei", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.buttonZagruzka.Location = new System.Drawing.Point(17, 47);
this.buttonZagruzka.Name = "buttonZagruzka";
this.buttonZagruzka.Size = new System.Drawing.Size(98, 51);
this.buttonZagruzka.TabIndex = 5;
this.buttonZagruzka.Text = "Zagruzka faila";
this.buttonZagruzka.UseVisualStyleBackColor = true;
this.buttonZagruzka.Click += new System.EventHandler(this.buttonZagruzka_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("MS Reference Sans Serif", 11.25F);
this.label3.Location = new System.Drawing.Point(24, 16);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(82, 19);
this.label3.TabIndex = 3;
this.label3.Text = "Use to do";
//
// buttonPoisk
//
this.buttonPoisk.Font = new System.Drawing.Font("Microsoft YaHei", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.buttonPoisk.Location = new System.Drawing.Point(17, 104);
this.buttonPoisk.Name = "buttonPoisk";
this.buttonPoisk.Size = new System.Drawing.Size(98, 51);
this.buttonPoisk.TabIndex = 4;
this.buttonPoisk.Text = "Poisk";
this.buttonPoisk.UseVisualStyleBackColor = true;
this.buttonPoisk.Click += new System.EventHandler(this.buttonPoisk_Click);
//
// txtText
//
this.txtText.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.txtText.Location = new System.Drawing.Point(11, 90);
this.txtText.Multiline = true;
this.txtText.Name = "txtText";
this.txtText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtText.Size = new System.Drawing.Size(440, 106);
this.txtText.TabIndex = 12;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("MS Reference Sans Serif", 11.25F);
this.label2.Location = new System.Drawing.Point(191, 68);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(78, 19);
this.label2.TabIndex = 11;
this.label2.Text = "Sam text";
//
// txtPatterns
//
this.txtPatterns.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.txtPatterns.Location = new System.Drawing.Point(150, 31);
this.txtPatterns.Name = "txtPatterns";
this.txtPatterns.Size = new System.Drawing.Size(153, 22);
this.txtPatterns.TabIndex = 10;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("MS Reference Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(76, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(284, 19);
this.label1.TabIndex = 9;
this.label1.Text = "Vvedite patterni dlya poiska cherez *";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.ClientSize = new System.Drawing.Size(459, 434);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.txtText);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtPatterns);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button buttonOchistit;
private System.Windows.Forms.Button buttonZagruzka;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button buttonPoisk;
private System.Windows.Forms.TextBox txtText;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtPatterns;
private System.Windows.Forms.Label label1;
}
}
| 49.373188 | 175 | 0.59184 | [
"Unlicense"
] | foorzy/labs | Boyer-Moore/Boyer-MooreBondarenko/Form1.Designer.cs | 13,884 | 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 AliyunDDNSWindowsApp.Alicore;
using AliyunDDNSWindowsApp.Alicore.Transform;
using AliyunDDNSWindowsApp.Alicore.Utils;
using AliyunDDNSWindowsApp.Alidns.Transform.V20150109;
namespace AliyunDDNSWindowsApp.Alidns.Model.V20150109
{
public class DescribeDnsProductInstancesRequest : RpcAcsRequest<DescribeDnsProductInstancesResponse>
{
public DescribeDnsProductInstancesRequest()
: base("Alidns", "2015-01-09", "DescribeDnsProductInstances")
{
}
private string lang;
private string userClientIp;
private long? pageNumber;
private long? pageSize;
private string versionCode;
public string Lang
{
get
{
return lang;
}
set
{
lang = value;
DictionaryUtil.Add(QueryParameters, "Lang", value);
}
}
public string UserClientIp
{
get
{
return userClientIp;
}
set
{
userClientIp = value;
DictionaryUtil.Add(QueryParameters, "UserClientIp", value);
}
}
public long? PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString());
}
}
public long? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString());
}
}
public string VersionCode
{
get
{
return versionCode;
}
set
{
versionCode = value;
DictionaryUtil.Add(QueryParameters, "VersionCode", value);
}
}
public override DescribeDnsProductInstancesResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DescribeDnsProductInstancesResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
} | 22.701754 | 112 | 0.695904 | [
"MIT"
] | HMBSbige/AliyunDDNS | AliyunDDNSWindowsApp/Alidns/Model/V20150109/DescribeDnsProductInstancesRequest.cs | 2,588 | C# |
/*
Copyright 2011 - 2016 Adrian Popescu.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Redmine.Net.Api.Extensions;
using Redmine.Net.Api.Internals;
using Redmine.Net.Api.Types;
namespace Redmine.Net.Api.Async
{
/// <summary>
/// </summary>
public static class RedmineManagerAsync
{
/// <summary>
/// Gets the current user asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public static async Task<User> GetCurrentUserAsync(this RedmineManager redmineManager, NameValueCollection parameters = null)
{
var uri = UrlHelper.GetCurrentUserUrl(redmineManager);
return await WebApiAsyncHelper.ExecuteDownload<User>(redmineManager, uri, "GetCurrentUserAsync", parameters);
}
/// <summary>
/// Creates the or update wiki page asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="projectId">The project identifier.</param>
/// <param name="pageName">Name of the page.</param>
/// <param name="wikiPage">The wiki page.</param>
/// <returns></returns>
public static async Task<WikiPage> CreateOrUpdateWikiPageAsync(this RedmineManager redmineManager, string projectId, string pageName, WikiPage wikiPage)
{
var uri = UrlHelper.GetWikiCreateOrUpdaterUrl(redmineManager, projectId, pageName);
var data = RedmineSerializer.Serialize(wikiPage, redmineManager.MimeFormat);
return await WebApiAsyncHelper.ExecuteUpload<WikiPage>(redmineManager, uri, HttpVerbs.PUT, data, "CreateOrUpdateWikiPageAsync");
}
/// <summary>
/// Deletes the wiki page asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="projectId">The project identifier.</param>
/// <param name="pageName">Name of the page.</param>
/// <returns></returns>
public static async Task DeleteWikiPageAsync(this RedmineManager redmineManager, string projectId,
string pageName)
{
var uri = UrlHelper.GetDeleteWikirUrl(redmineManager, projectId, pageName);
await WebApiAsyncHelper.ExecuteUpload(redmineManager, uri, HttpVerbs.DELETE, string.Empty, "DeleteWikiPageAsync");
}
/// <summary>
/// Support for adding attachments through the REST API is added in Redmine 1.4.0.
/// Upload a file to server. This method does not block the calling thread.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="data">The content of the file that will be uploaded on server.</param>
/// <returns>
/// .
/// </returns>
public static async Task<Upload> UploadFileAsync(this RedmineManager redmineManager, byte[] data)
{
var uri = UrlHelper.GetUploadFileUrl(redmineManager);
return await WebApiAsyncHelper.ExecuteUploadFile(redmineManager, uri, data, "UploadFileAsync");
}
/// <summary>
/// Downloads the file asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="address">The address.</param>
/// <returns></returns>
public static async Task<byte[]> DownloadFileAsync(this RedmineManager redmineManager, string address)
{
return await WebApiAsyncHelper.ExecuteDownloadFile(redmineManager, address, "DownloadFileAsync");
}
/// <summary>
/// Gets the wiki page asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="projectId">The project identifier.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="pageName">Name of the page.</param>
/// <param name="version">The version.</param>
/// <returns></returns>
public static async Task<WikiPage> GetWikiPageAsync(this RedmineManager redmineManager, string projectId,
NameValueCollection parameters, string pageName, uint version = 0)
{
var uri = UrlHelper.GetWikiPageUrl(redmineManager, projectId, parameters, pageName, version);
return await WebApiAsyncHelper.ExecuteDownload<WikiPage>(redmineManager, uri, "GetWikiPageAsync", parameters);
}
/// <summary>
/// Gets all wiki pages asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="projectId">The project identifier.</param>
/// <returns></returns>
public static async Task<List<WikiPage>> GetAllWikiPagesAsync(this RedmineManager redmineManager, NameValueCollection parameters, string projectId)
{
var uri = UrlHelper.GetWikisUrl(redmineManager, projectId);
return await WebApiAsyncHelper.ExecuteDownloadList<WikiPage>(redmineManager, uri, "GetAllWikiPagesAsync", parameters);
}
/// <summary>
/// Adds an existing user to a group. This method does not block the calling thread.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="groupId">The group id.</param>
/// <param name="userId">The user id.</param>
/// <returns>
/// Returns the Guid associated with the async request.
/// </returns>
public static async Task AddUserToGroupAsync(this RedmineManager redmineManager, int groupId, int userId)
{
var data = DataHelper.UserData(userId, redmineManager.MimeFormat);
var uri = UrlHelper.GetAddUserToGroupUrl(redmineManager, groupId);
await WebApiAsyncHelper.ExecuteUpload(redmineManager, uri, HttpVerbs.POST, data, "AddUserToGroupAsync");
}
/// <summary>
/// Removes an user from a group. This method does not block the calling thread.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="groupId">The group id.</param>
/// <param name="userId">The user id.</param>
/// <returns></returns>
public static async Task DeleteUserFromGroupAsync(this RedmineManager redmineManager, int groupId, int userId)
{
var uri = UrlHelper.GetRemoveUserFromGroupUrl(redmineManager, groupId, userId);
await WebApiAsyncHelper.ExecuteUpload(redmineManager, uri, HttpVerbs.DELETE, string.Empty, "DeleteUserFromGroupAsync");
}
/// <summary>
/// Adds the watcher asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="issueId">The issue identifier.</param>
/// <param name="userId">The user identifier.</param>
/// <returns></returns>
public static async Task AddWatcherAsync(this RedmineManager redmineManager, int issueId, int userId)
{
var data = DataHelper.UserData(userId, redmineManager.MimeFormat);
var uri = UrlHelper.GetAddWatcherUrl(redmineManager, issueId, userId);
await WebApiAsyncHelper.ExecuteUpload(redmineManager, uri, HttpVerbs.POST, data, "AddWatcherAsync");
}
/// <summary>
/// Removes the watcher asynchronous.
/// </summary>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="issueId">The issue identifier.</param>
/// <param name="userId">The user identifier.</param>
/// <returns></returns>
public static async Task RemoveWatcherAsync(this RedmineManager redmineManager, int issueId, int userId)
{
var uri = UrlHelper.GetRemoveWatcherUrl(redmineManager, issueId, userId);
await WebApiAsyncHelper.ExecuteUpload(redmineManager, uri, HttpVerbs.DELETE, string.Empty, "RemoveWatcherAsync");
}
/// <summary>
/// Gets the paginated objects asynchronous.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public static async Task<PaginatedObjects<T>> GetPaginatedObjectsAsync<T>(this RedmineManager redmineManager,
NameValueCollection parameters)
where T : class, new()
{
var uri = UrlHelper.GetListUrl<T>(redmineManager, parameters);
return await WebApiAsyncHelper.ExecuteDownloadPaginatedList<T>(redmineManager, uri, "GetPaginatedObjectsAsync", parameters);
}
/// <summary>
/// Gets the objects asynchronous.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public static async Task<List<T>> GetObjectsAsync<T>(this RedmineManager redmineManager, NameValueCollection parameters)
where T : class, new()
{
int totalCount = 0, pageSize, offset;
List<T> resultList = null;
if (parameters == null) parameters = new NameValueCollection();
int.TryParse(parameters[RedmineKeys.LIMIT], out pageSize);
int.TryParse(parameters[RedmineKeys.OFFSET], out offset);
if (pageSize == default(int))
{
pageSize = redmineManager.PageSize > 0
? redmineManager.PageSize
: RedmineManager.DEFAULT_PAGE_SIZE_VALUE;
parameters.Set(RedmineKeys.LIMIT, pageSize.ToString(CultureInfo.InvariantCulture));
}
try
{
do
{
parameters.Set(RedmineKeys.OFFSET, offset.ToString(CultureInfo.InvariantCulture));
var tempResult = await redmineManager.GetPaginatedObjectsAsync<T>(parameters);
if (tempResult != null)
{
if (resultList == null)
{
resultList = tempResult.Objects;
totalCount = tempResult.TotalCount;
}
else
{
resultList.AddRange(tempResult.Objects);
}
}
offset += pageSize;
} while (offset < totalCount);
}
catch (WebException wex)
{
wex.HandleWebException("GetObjectsAsync", redmineManager.MimeFormat);
}
return resultList;
}
/// <summary>
/// Gets a Redmine object. This method does not block the calling thread.
/// </summary>
/// <typeparam name="T">The type of objects to retrieve.</typeparam>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="id">The id of the object.</param>
/// <param name="parameters">Optional filters and/or optional fetched data.</param>
/// <returns></returns>
public static async Task<T> GetObjectAsync<T>(this RedmineManager redmineManager, string id, NameValueCollection parameters)
where T : class, new()
{
var uri = UrlHelper.GetGetUrl<T>(redmineManager, id);
return await WebApiAsyncHelper.ExecuteDownload<T>(redmineManager, uri, "GetobjectAsync", parameters);
}
/// <summary>
/// Creates a new Redmine object. This method does not block the calling thread.
/// </summary>
/// <typeparam name="T">The type of object to create.</typeparam>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="obj">The object to create.</param>
/// <returns></returns>
public static async Task<T> CreateObjectAsync<T>(this RedmineManager redmineManager, T obj)
where T : class, new()
{
return await CreateObjectAsync(redmineManager, obj, null);
}
/// <summary>
/// Creates a new Redmine object. This method does not block the calling thread.
/// </summary>
/// <typeparam name="T">The type of object to create.</typeparam>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="obj">The object to create.</param>
/// <param name="ownerId">The owner identifier.</param>
/// <returns></returns>
public static async Task<T> CreateObjectAsync<T>(this RedmineManager redmineManager, T obj, string ownerId)
where T : class, new()
{
var uri = UrlHelper.GetCreateUrl<T>(redmineManager, ownerId);
var data = RedmineSerializer.Serialize(obj, redmineManager.MimeFormat);
return await WebApiAsyncHelper.ExecuteUpload<T>(redmineManager, uri, HttpVerbs.POST, data, "CreateObjectAsync");
}
/// <summary>
/// Updates the object asynchronous.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="id">The identifier.</param>
/// <param name="obj">The object.</param>
/// <param name="projectId">The project identifier.</param>
/// <returns></returns>
public static async Task UpdateObjectAsync<T>(this RedmineManager redmineManager, string id, T obj, string projectId = null)
where T : class, new()
{
var uri = UrlHelper.GetUploadUrl(redmineManager, id, obj, projectId);
var data = RedmineSerializer.Serialize(obj, redmineManager.MimeFormat);
data = Regex.Replace(data, @"\r\n|\r|\n", "\r\n");
await WebApiAsyncHelper.ExecuteUpload<T>(redmineManager, uri, HttpVerbs.PUT, data, "UpdateObjectAsync");
}
/// <summary>
/// Deletes the Redmine object. This method does not block the calling thread.
/// </summary>
/// <typeparam name="T">The type of objects to delete.</typeparam>
/// <param name="redmineManager">The redmine manager.</param>
/// <param name="id">The id of the object to delete</param>
/// <param name="parameters">Optional filters and/or optional fetched data.</param>
/// <returns></returns>
public static async Task DeleteObjectAsync<T>(this RedmineManager redmineManager, string id, NameValueCollection parameters)
where T : class, new()
{
var uri = UrlHelper.GetDeleteUrl<T>(redmineManager, id);
await WebApiAsyncHelper.ExecuteUpload<T>(redmineManager, uri, HttpVerbs.DELETE, string.Empty, "DeleteObjectAsync");
}
}
} | 47.892216 | 160 | 0.619655 | [
"Apache-2.0"
] | Enhakiel/redmine-net-api | redmine-net45-api/Async/RedmineManagerAsync.cs | 15,998 | C# |
namespace Labo.Youtube.Model
{
using System;
using System.Collections.Generic;
[Serializable]
public sealed class VideoContentInfoModel
{
private List<string> m_Tags;
private List<string> m_Categories;
public string Keywords { get; set; }
public bool Private { get; set; }
public int Duration { get; set; }
public string Uploader { get; set; }
public string Author { get; set; }
public string BigPicture { get; set; }
public string SmallPicture { get; set; }
public List<string> Tags
{
get
{
return m_Tags ?? (m_Tags = new List<string>());
}
set
{
m_Tags = value;
}
}
public string Description { get; set; }
public double Rating { get; set; }
public int VoteCount { get; set; }
public int ViewCount { get; set; }
public string Title { get; set; }
public Uri VideoUrl { get; set; }
public string VideoId { get; set; }
public string Summary { get; set; }
public List<string> Categories
{
get
{
return m_Categories ?? (m_Categories = new List<string>());
}
set
{
m_Categories = value;
}
}
public DateTime LastUpdateDate { get; set; }
}
} | 21.128571 | 75 | 0.498986 | [
"MIT"
] | LaboFoundation/Labo.Video | Labo.Youtube/Model/VideoContentInfoModel.cs | 1,479 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Enables the user to enumerate the list of CIM Classes under a specific
/// Namespace. If no list of classes is given, the Cmdlet returns all
/// classes in the given namespace.
/// </para>
/// <para>
/// NOTES: The class instance contains the Namespace properties
/// Should the class remember what Session it came from? No.
/// </para>
/// </summary>
[Alias("gcls")]
[Cmdlet(VerbsCommon.Get, GetCimClassCommand.Noun, DefaultParameterSetName = ComputerSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227959")]
[OutputType(typeof(CimClass))]
public class GetCimClassCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// Constructor.
/// </summary>
public GetCimClassCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ClassName".
/// </para>
/// <para>
/// Wildcard expansion should be allowed.
/// </para>
/// </summary>
[Parameter(
Position = 0,
ValueFromPipelineByPropertyName = true)]
public string ClassName
{
get { return className; }
set { className = value; }
}
private string className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Namespace".
/// Specifies the Namespace under which to look for the specified class name.
/// If no class name is specified, the cmdlet should return all classes under
/// the specified Namespace.
/// </para>
/// <para>
/// Default namespace is root\cimv2
/// </para>
/// </summary>
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true)]
public string Namespace
{
get { return nameSpace; }
set { nameSpace = value; }
}
private string nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Enables the user to specify the operation timeout in Seconds. This value
/// overwrites the value specified by the CimSession Operation timeout.
/// </summary>
[Alias(AliasOT)]
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// The following is the definition of the input parameter "Session".
/// Uses a CimSession context.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = SessionSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Provides the name of the computer from which to retrieve the <see cref="CimClass"/>
/// </para>
/// <para>
/// If no ComputerName is specified the default value is "localhost"
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = ComputerSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName
{
get { return computerName; }
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private string[] computerName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "MethodName",
/// Which may contains wildchar.
/// Then Filter the <see cref="CimClass"/> by given methodname
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public string MethodName
{
get { return methodName; }
set { methodName = value; }
}
private string methodName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "PropertyName",
/// Which may contains wildchar.
/// Filter the <see cref="CimClass"/> by given property name.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public string PropertyName
{
get { return propertyName; }
set { propertyName = value; }
}
private string propertyName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "QualifierName",
/// Which may contains wildchar.
/// Filter the <see cref="CimClass"/> by given methodname
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public string QualifierName
{
get { return qualifierName; }
set { qualifierName = value; }
}
private string qualifierName;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
CimGetCimClass cimGetCimClass = this.GetOperationAgent() ?? CreateOperationAgent();
cimGetCimClass.GetCimClass(this);
cimGetCimClass.ProcessActions(this.CmdletOperation);
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimGetCimClass cimGetCimClass = this.GetOperationAgent();
if (cimGetCimClass != null)
{
cimGetCimClass.ProcessRemainActions(this.CmdletOperation);
}
}
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimNewCimInstance"/> object, which is
/// used to delegate all New-CimInstance operations.
/// </para>
/// </summary>
private CimGetCimClass GetOperationAgent()
{
return (this.AsyncOperation as CimGetCimClass);
}
/// <summary>
/// <para>
/// Create <see cref="CimGetCimClass"/> object, which is
/// used to delegate all Get-CimClass operations.
/// </para>
/// </summary>
/// <returns></returns>
private CimGetCimClass CreateOperationAgent()
{
CimGetCimClass cimGetCimClass = new CimGetCimClass();
this.AsyncOperation = cimGetCimClass;
return cimGetCimClass;
}
#endregion
#region internal const strings
/// <summary>
/// Noun of current cmdlet.
/// </summary>
internal const string Noun = @"CimClass";
#endregion
#region private members
#region const string of parameter names
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
#endregion
/// <summary>
/// Static parameter definition entries.
/// </summary>
private static readonly Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false),
}
},
};
/// <summary>
/// Static parameter set entries.
/// </summary>
private static readonly Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.SessionSetName, new ParameterSetEntry(1) },
{ CimBaseCommand.ComputerSetName, new ParameterSetEntry(0, true) },
};
#endregion
}
}
| 30.807571 | 157 | 0.563076 | [
"MIT"
] | AWESOME-S-MINDSET/PowerShell | src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs | 9,766 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace HelloSpa
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API の設定およびサービス
// Web API ルート
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| 22.56 | 62 | 0.567376 | [
"MIT"
] | surviveplus/SPA-Sample | vs2015ja/HelloSpa-1/HelloSpa/App_Start/WebApiConfig.cs | 592 | C# |
using System;
using NuGet.Versioning;
namespace Lykke.NuGetReferencesScanner.Domain.Models
{
public sealed class PackageReference
{
public string Name { get; }
public IComparable Version { get; }
public static PackageReference Parse(string name, string version)
{
version = version.Replace("*", "9999.9999");
if (SemanticVersion.TryParse(version, out var ver))
{
return new PackageReference(name, ver);
}
if (System.Version.TryParse(version, out var ver2))
{
return new PackageReference(name, new SemanticVersion(ver2.Major, ver2.Minor, ver2.Build, ver2.Revision.ToString(), "NotSemVer!"));
}
return new PackageReference(name, new SemanticVersion(0, 0, 0, "UnableToParse"));
}
private PackageReference(string name, IComparable version)
{
Name = name;
Version = version;
}
private bool Equals(PackageReference other)
{
return string.Equals(Name, other.Name) && Equals(Version, other.Version);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((PackageReference)obj);
}
public override int GetHashCode()
{
unchecked
{
return (Name != null ? Name.GetHashCode() : 0) * 397 ^ (Version != null ? Version.GetHashCode() : 0);
}
}
public override string ToString()
{
return $"{Name} {Version}";
}
}
}
| 29.442623 | 147 | 0.555122 | [
"MIT"
] | LykkeBusinessPlatform/Lykke.Job.NugetReferencesScanner | src/Lykke.NuGetReferencesScanner/Domain/Models/PackageReference.cs | 1,798 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace TurnerSoftware.RobotsExclusionTools.Tests.RobotsFile
{
[TestClass]
public class RFCSpecificTests : TestBase
{
[TestMethod]
public void RobotsFileAlwaysAllowed()
{
var robotsFile = GetRfcRobotsFile();
var requestUri = new Uri("http://www.example.org/robots.txt");
Assert.IsTrue(robotsFile.IsAllowedAccess(requestUri, "Unhipbot/2.5"));
Assert.IsTrue(robotsFile.IsAllowedAccess(requestUri, "Excite/1.0"));
Assert.IsTrue(robotsFile.IsAllowedAccess(requestUri, "webcrawler"));
Assert.IsTrue(robotsFile.IsAllowedAccess(requestUri, "SuperSpecialCrawler"));
}
[TestMethod]
public void DefaultAllUserAgentsWhenNoneExplicitlySet()
{
var robotsFile = GetRobotsFile("NoUserAgentRules-Example.txt");
var userAgent = "RandomUserAgent";
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/about.html"), userAgent));
}
[TestMethod]
public void UnhipbotCrawlerDisallowed()
{
var robotsFile = GetRfcRobotsFile();
var userAgent = "Unhipbot/1.0";
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/index.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/server.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/fast.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/slow.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/orgo.gif"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/about.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/plans.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Ejim/jim.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Emak/mak.html"), userAgent));
}
[TestMethod]
public void ExciteCrawlerAllowed()
{
var robotsFile = GetRfcRobotsFile();
var userAgent = "Excite/1.0";
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/index.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/server.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/fast.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/slow.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/orgo.gif"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/about.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/plans.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Ejim/jim.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Emak/mak.html"), userAgent));
}
[TestMethod]
public void WebcrawlerAllowed()
{
var robotsFile = GetRfcRobotsFile();
var userAgent = "Webcrawler/1.0";
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/index.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/server.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/fast.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/slow.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/orgo.gif"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/about.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/plans.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Ejim/jim.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Emak/mak.html"), userAgent));
}
[TestMethod]
public void OtherPartiallyAllowed()
{
var robotsFile = GetRfcRobotsFile();
var userAgent = "SuperSpecialCrawler/1.0";
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/index.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/server.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/fast.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/services/slow.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/orgo.gif"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/about.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/org/plans.html"), userAgent));
Assert.IsFalse(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Ejim/jim.html"), userAgent));
Assert.IsTrue(robotsFile.IsAllowedAccess(new Uri("http://www.example.org/%7Emak/mak.html"), userAgent));
}
}
}
| 55.632075 | 111 | 0.750212 | [
"MIT"
] | AlexRadch/RobotsExclusionTools | tests/TurnerSoftware.RobotsExclusionTools.Tests/RobotsFile/RFCSpecificTests.cs | 5,899 | C# |
//Copyright (c) 2018 Yardi Technology Limited. Http://www.kooboo.com
//All rights reserved.
using System;
using System.Collections.Generic;
using Kooboo.Dom;
using System.Text;
using System.Linq;
using Newtonsoft.Json;
using Kooboo.Sites.Models;
namespace Kooboo.Sites.Service
{
public static class DomService
{
public static string ApplyKoobooId(string html)
{
if (string.IsNullOrEmpty(html))
{
return html;
}
var doc = DomParser.CreateDom(html);
var currentIndex = 0;
var totallen = html.Length;
var iterator = doc.createNodeIterator(doc.documentElement, enumWhatToShow.ELEMENT, null);
var newHtml = new StringBuilder();
var nextNode = iterator.nextNode();
while (nextNode != null)
{
string koobooid = GetKoobooId(nextNode);
var element = nextNode as Element;
if (element != null && element.location.openTokenEndIndex > 0)
{
int openTokenEndIndex = nextNode.location.openTokenEndIndex;
if (IsSelfCloseTag(element.tagName) && element.ownerDocument.HtmlSource[openTokenEndIndex - 1] == '/')
{
openTokenEndIndex = openTokenEndIndex - 1;
}
newHtml.Append(doc.HtmlSource.Substring(currentIndex, openTokenEndIndex - currentIndex));
newHtml.Append(" ").Append(Kooboo.Sites.SiteConstants.KoobooIdAttributeName).AppendFormat("=\"{0}\"", koobooid);
currentIndex = openTokenEndIndex;
}
nextNode = iterator.nextNode();
}
if (currentIndex < totallen)
{
newHtml.Append(doc.HtmlSource.Substring(currentIndex));
}
return newHtml.ToString();
}
public static string EnsureDocType(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return input;
}
int len = input.Length-10;
if (len >500)
{
len = 500;
}
// <!DOCTYPE html>
var sub = input.Substring(0, len);
if (!sub.ToLower().Contains("<!DOCTYPE"))
{
input = "<!DOCTYPE html>\r\n" + input;
}
return input;
}
public static string GetKoobooId(Node node)
{
List<int> indexlist = new List<int>();
indexlist.Add(node.siblingIndex);
Node parentNode = node.parentNode;
while (parentNode != null && parentNode.depth != 0)
{
indexlist.Add(parentNode.siblingIndex);
parentNode = parentNode.parentNode;
}
indexlist.Reverse();
return ConvertIntListToString(indexlist);
}
public static Node GetElementByKoobooId(Document doc, string KoobooId)
{
Node node = doc.documentElement;
List<int> intlist = ConvertStringToIntList(KoobooId);
foreach (int item in intlist)
{
if (item > node.childNodes.length - 1)
{
return null;
}
node = node.childNodes.item[item];
}
return node;
}
public static List<int> ConvertStringToIntList(string IntListString)
{
List<int> intlist = new List<int>();
string[] stringlist = IntListString.Split('-');
foreach (var item in stringlist)
{
intlist.Add(Convert.ToInt32(item));
}
return intlist;
}
public static string ConvertIntListToString(List<int> IntList)
{
return string.Join("-", IntList);
}
public static string GetElementDisplayName(Element element)
{
string name = element.tagName;
if (!string.IsNullOrEmpty(element.id))
{
name = name + " id=" + element.id;
}
if (!string.IsNullOrEmpty(element.className))
{
name = name + " class=" + element.className;
}
return name;
}
/// <summary>
/// after chanage of element attributes, reserialize the element.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static string ReSerializeElement(Element element)
{
string ehtml = string.Empty;
ehtml = "<" + element.tagName;
foreach (var item in element.attributes)
{
ehtml += " " + item.name;
if (!string.IsNullOrEmpty(item.value))
{
ehtml += "=\"" + item.value + "\"";
}
}
if (IsSelfCloseTag(element.tagName))
{
ehtml += " />";
}
else
{
ehtml += ">";
ehtml += element.InnerHtml;
ehtml += "</" + element.tagName + ">";
}
return ehtml;
}
public static string ReSerializeOpenTag(Element element)
{
string ehtml = string.Empty;
ehtml = "<" + element.tagName;
foreach (var item in element.attributes)
{
ehtml += " " + item.name;
if (!string.IsNullOrEmpty(item.value))
{
ehtml += "=\"" + item.value + "\"";
}
}
if (IsSelfCloseTag(element.tagName))
{
ehtml += " />";
}
else
{
ehtml += ">";
}
return ehtml;
}
public static string GenerateOpenTag(Dictionary<string, string> attributes, string tagName)
{
string ehtml = string.Empty;
ehtml = "<" + tagName;
if (attributes !=null)
{
foreach (var item in attributes)
{
ehtml += " " + item.Key;
if (!string.IsNullOrEmpty(item.Value))
{
ehtml += "=\"" + item.Value + "\"";
}
}
}
ehtml += ">";
return ehtml;
}
/// <summary>
/// get the open tag part of this element without reserialize the element.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static string GetOpenTag(Element element)
{
if (element.location.openTokenStartIndex >= element.location.endTokenEndIndex)
{
return string.Empty;
}
else
{
if (element.location.openTokenEndIndex != -1 && element.location.openTokenStartIndex != -1)
{
return element.ownerDocument.HtmlSource.Substring(element.location.openTokenStartIndex, element.location.openTokenEndIndex - element.location.openTokenStartIndex + 1);
}
else
{
if (element.attributes ==null)
{
return GenerateOpenTag(null, element.tagName);
}
else
{
Dictionary<string, string> attr = new Dictionary<string, string>();
foreach (var item in element.attributes)
{
if (item != null && item.name != null)
{
attr.Add(item.name, item.value);
}
}
return GenerateOpenTag(attr, element.tagName);
}
}
}
}
public static bool HasHeadTag(Dom.Document doc)
{
var head = doc.head;
return !IsFakeElement(head);
}
/// <summary>
/// Is Fake and generated element, like Head.. without the <head> tag.
/// </summary>
/// <param name="doc"></param>
/// <returns></returns>
public static bool IsFakeElement(Element el)
{
if (el.location.openTokenStartIndex >= el.location.endTokenEndIndex)
{
return true;
}
if (el.location.endTokenEndIndex <= 0 || el.location.endTokenStartIndex <= 0 || el.location.openTokenEndIndex <= 0)
{
return true;
}
string outhtml = el.OuterHtml;
if (outhtml.Length < 7)
{
return true;
}
if (el.location.endTokenEndIndex > 1)
{
return false;
}
return true;
}
public static string ReSerializeElement(Element element, string innerHtml)
{
string ehtml = string.Empty;
ehtml = "<" + element.tagName;
foreach (var item in element.attributes)
{
ehtml += " " + item.name;
if (!string.IsNullOrEmpty(item.value))
{
ehtml += "=\"" + item.value + "\"";
}
}
if (IsSelfCloseTag(element.tagName))
{
ehtml += " />";
}
else
{
ehtml += ">";
ehtml += innerHtml;
ehtml += "</" + element.tagName + ">";
}
return ehtml;
}
/// <summary>
/// Parse the string into Dom Element. This method is only true when there is only one Element inside the Html String, the TAL element.
/// If there are more element, only the first element will be returned.
/// </summary>
/// <param name="Html"></param>
/// <returns></returns>
public static Element ConvertToElement(string Html)
{
var doc = Dom.DomParser.CreateDom(Html);
foreach (var item in doc.body.childNodes.item)
{
if (item.nodeType == enumNodeType.ELEMENT)
{
return item as Element;
}
}
foreach (var item in doc.documentElement.childNodes.item)
{
if (item.nodeType == enumNodeType.ELEMENT)
{
var el = item as Element;
if (el.tagName != "head" && el.tagName != "body")
{
return el;
}
}
}
return null;
}
/// <summary>
/// Update a html source based on koobooid and new values.
/// </summary>
/// <param name="Source"></param>
/// <param name="Updates">Now use prefix kooboo_attribute to indicate that it is a change of attributes. </param>
/// <returns></returns>
public static string UpdateSource(string Source, Dictionary<string, string> Updates)
{
Document doc = Kooboo.Dom.DomParser.CreateDom(Source);
return UpdateSource(doc, Updates);
}
public static string UpdateSource(Document doc, Dictionary<string, string> Updates)
{
List<SourceUpdate> sourceupdates = new List<SourceUpdate>();
foreach (var item in Updates)
{
string koobooid = CleanKoobooId(item.Key);
if (!string.IsNullOrEmpty(koobooid))
{
var element = GetElementByKoobooId(doc, koobooid);
if (element != null)
{
if (item.Value.StartsWith(SiteConstants.UpdateDomAttributePrefix))
{
/// this is to change the element attribute.
Element currentitem = element as Element;
string AttributeJson = item.Value.Substring(SiteConstants.UpdateDomAttributePrefix.Length);
Dictionary<string, string> attrs = Lib.Helper.JsonHelper.Deserialize<Dictionary<string, string>>(AttributeJson);
foreach (var att in attrs)
{
// for safety reason. convert all duouble quote to single quote within the attribute value.
string value = att.Value;
if (!string.IsNullOrEmpty(value))
{
value = value.Replace("\"\"", "\"");
value = value.Replace("\"", "'");
}
currentitem.setAttribute(att.Key, value);
}
SourceUpdate update = new SourceUpdate();
update.StartIndex = currentitem.location.openTokenStartIndex;
update.EndIndex = currentitem.location.openTokenEndIndex;
update.NewValue = Kooboo.Sites.Service.DomService.ReSerializeOpenTag(currentitem);
sourceupdates.Add(update);
}
else
{
int start = element.location.openTokenEndIndex + 1;
int end = element.location.endTokenStartIndex - 1;
if (end < start)
{
end = -1;
}
sourceupdates.Add(new SourceUpdate()
{
StartIndex = start,
EndIndex = end,
NewValue = item.Value
});
}
}
}
}
return UpdateSource(doc.HtmlSource, sourceupdates);
}
/// <summary>
/// Update the source html based on the index location.
/// TODO: add insertation, can be like endindex = -1;
/// </summary>
/// <param name="htmlsource"></param>
/// <param name="sourceupdates"></param>
/// <returns></returns>
public static string UpdateSource(string htmlsource, List<SourceUpdate> sourceupdates)
{
int currentindex = 0;
int totallen = htmlsource.Length;
StringBuilder sb = new StringBuilder();
int laststart = -1;
int lastend = -1;
// update to real html source.
foreach (var item in sourceupdates.OrderBy(o => o.StartIndex))
{
if (item.StartIndex <= laststart || item.StartIndex < currentindex)
{
// this is an insertation...
sb.Append(item.NewValue);
if (item.EndIndex > currentindex)
{
string currentString = htmlsource.Substring(currentindex, item.EndIndex - currentindex);
if (!string.IsNullOrEmpty(currentString))
{
sb.Append(currentString);
}
currentindex = item.EndIndex + 1;
}
}
else
{
if (item.EndIndex > 0)
{
string currentString = htmlsource.Substring(currentindex, item.StartIndex - currentindex);
if (!string.IsNullOrEmpty(currentString))
{
sb.Append(currentString);
}
sb.Append(item.NewValue);
currentindex = item.EndIndex + 1;
}
else
{
// this should be treated as insertation.
if (item.StartIndex > currentindex)
{
string currentString = htmlsource.Substring(currentindex, item.StartIndex - currentindex);
sb.Append(currentString);
}
sb.Append(item.NewValue);
currentindex = item.StartIndex;
}
}
if (laststart < item.StartIndex)
{ laststart = item.StartIndex; }
if (lastend < item.EndIndex)
{
lastend = item.EndIndex;
}
}
if (currentindex < totallen - 1)
{
sb.Append(htmlsource.Substring(currentindex, totallen - currentindex));
}
return sb.ToString();
}
public static string UpdateInlineStyle(string HtmlSource, List<Kooboo.Sites.Models.InlineStyleChange> changes)
{
int currentindex = 0;
int totallen = HtmlSource.Length;
StringBuilder sb = new StringBuilder();
Document doc = Kooboo.Dom.DomParser.CreateDom(HtmlSource);
List<SourceUpdate> sourceupdates = new List<SourceUpdate>();
foreach (var item in changes)
{
if (string.IsNullOrEmpty(item.KoobooId))
{ continue; }
var node = GetElementByKoobooId(doc, item.KoobooId);
if (node == null)
{ continue; }
var element = node as Element;
if (element == null)
{ continue; }
var declarationtext = element.getAttribute("style");
Kooboo.Dom.CSS.CSSDeclarationBlock declaration;
if (string.IsNullOrEmpty(declarationtext))
{ declaration = new Dom.CSS.CSSDeclarationBlock(); }
else
{
declaration = Kooboo.Dom.CSS.CSSSerializer.deserializeDeclarationBlock(declarationtext);
}
foreach (var propertychange in item.PropertyValues)
{
if (string.IsNullOrEmpty(propertychange.Value))
{
declaration.removeProperty(propertychange.Key);
}
else
{
declaration.setPropertyValue(propertychange.Key, propertychange.Value);
}
}
var newtext = declaration.GenerateCssText();
if (string.IsNullOrEmpty(newtext))
{ element.removeAttribute("style"); }
else
{ element.setAttribute("style", newtext); }
string elementstring = ReSerializeOpenTag(element);
SourceUpdate update = new SourceUpdate();
update.StartIndex = element.location.openTokenStartIndex;
update.EndIndex = element.location.openTokenEndIndex + 1;
update.NewValue = Kooboo.Sites.Service.DomService.ReSerializeOpenTag(element);
sourceupdates.Add(update);
}
// update to real html source.
foreach (var item in sourceupdates.OrderBy(o => o.StartIndex))
{
string currentString = doc.HtmlSource.Substring(currentindex, item.StartIndex - currentindex);
if (!string.IsNullOrEmpty(currentString))
{
sb.Append(currentString);
}
sb.Append(item.NewValue);
currentindex = item.EndIndex;
}
if (currentindex < totallen - 1)
{
sb.Append(doc.HtmlSource.Substring(currentindex, totallen - currentindex));
}
return sb.ToString();
}
public static string CleanKoobooId(string originalKoobooId)
{
int commaindex = originalKoobooId.IndexOf(":");
if (commaindex > -1)
{
return originalKoobooId.Substring(commaindex + 1);
}
else
{
return originalKoobooId;
}
}
public static bool IsSelfCloseTag(string tagName)
{
string lower = tagName.ToLower();
if (lower == "img" || lower == "input" || lower == "link" || lower == "br" || lower == "area" || lower == "base" || lower == "col" || lower == "command" || lower == "embed" || lower == "hr" || lower == "keygen" || lower == "meta" || lower == "param" || lower == "source" || lower == "track" || lower == "wbr")
{
return true;
}
return false;
}
/// <summary>
/// Find the same element in the body container.
/// </summary>
/// <param name="targetElement"></param>
/// <param name="BodyContainer"></param>
/// <returns></returns>
public static Element getSameElement(Element targetElement, Element BodyContainer)
{
var parent = targetElement;
while (parent.tagName != "body")
{
parent = parent.parentElement;
}
var element = _getSameElement(targetElement, parent, BodyContainer);
return element;
}
public static Element getSameElement(Element targetElement, Document destinationDom)
{
return getSameElement(targetElement, destinationDom.body);
}
private static Element _getSameElement(Element target, Element targetParent, Element ContainerElement)
{
if (isSameElement(target, ContainerElement))
{
return ContainerElement;
}
if (ContainerElement.depth >= target.depth)
{
return null;
}
foreach (var item in ContainerElement.childNodes.item)
{
if (item is Element)
{
foreach (var subParent in targetParent.childNodes.item)
{
if (subParent is Element)
{
Element subParentElement = subParent as Element;
Element itemElement = item as Element;
//TODO: check same element.
Element returnelement = _getSameElement(target, subParent as Element, item as Element);
if (returnelement != null)
{
return returnelement;
}
}
}
}
}
return null;
}
private static bool isSameElement(Element x, Element y)
{
if (x.depth != y.depth)
{
return false;
}
if (x.tagName != y.tagName)
{
return false;
}
/// check inner html.
if (x.InnerHtml != y.InnerHtml)
{
return false;
}
foreach (var item in x.attributes)
{
/// class can be like class = "active", we skip the class attribute for now...
if (item.name != "class")
{
var yitem = y.attributes.Find(o => o.name == item.name);
if (yitem == null)
{
return false;
}
else
{
if (yitem.value != item.value)
{
return false;
}
}
}
}
return true;
}
/// <summary>
/// Find the common parents of two elements.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static Element FindParent(Element x, Element y)
{
if (x.depth == y.depth)
{
return _FindParent(x, y);
}
else
{
if (x.depth > y.depth)
{
x = x.parentElement;
return FindParent(x, y);
}
else
{
y = y.parentElement;
return FindParent(x, y);
}
}
}
private static Element _FindParent(Element x, Element y)
{
if (x.isEqualNode(y))
{
return x;
}
else
{
x = x.parentElement;
y = y.parentElement;
return _FindParent(x, y);
}
}
public static Element FindParent(List<Element> elements)
{
Element parent = null;
foreach (var item in elements)
{
if (parent == null)
{
parent = item;
}
else
{
parent = FindParent(parent, item);
}
}
return parent;
}
/// <summary>
/// Find the distince between two elements based on the node tree distince...
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static int GetTreeDistance(Element x, Element y)
{
var parent = FindParent(x, y);
if (parent == null)
{
return int.MaxValue;
}
List<Element> xchain = new List<Element>();
List<Element> ychain = new List<Element>();
var xparent = x.parentElement;
while (xparent != null && xparent.depth != parent.depth)
{
xchain.Add(xparent);
xparent = xparent.parentElement;
}
xchain.Reverse();
var yparent = y.parentElement;
while (yparent != null && yparent.depth != parent.depth)
{
ychain.Add(yparent);
yparent = yparent.parentElement;
}
ychain.Reverse();
int xcount = xchain.Count();
int ycount = ychain.Count();
int count = xcount;
if (count < ycount)
{
count = ycount;
}
int xvalue = x.siblingIndex;
int yvalue = y.siblingIndex;
for (int i = 0; i < xcount; i++)
{
int addvalue = (xchain[i].siblingIndex + 1) * Convert.ToInt32(Math.Pow(10, (count - i)));
xvalue = xvalue + addvalue;
}
for (int i = 0; i < ycount; i++)
{
int addvalue = (ychain[i].siblingIndex + 1) * Convert.ToInt32(Math.Pow(10, (count - i)));
yvalue = yvalue + addvalue;
}
return Math.Abs(xvalue - yvalue);
}
/// <summary>
/// Get the parent path of this element.
/// Example: /body/div/div/p. p is the current element tag...
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static string getParentPath(Element element)
{
if (element == null)
{
return string.Empty;
}
var parent = element.parentElement;
string path = "/" + element.tagName;
while (parent != null && parent.tagName != "html")
{
path = "/" + parent.tagName + path;
parent = parent.parentElement;
}
return path;
}
public static HTMLCollection GetElementsByTagName(List<Node> nodelist, string tagName)
{
HTMLCollection cols = new HTMLCollection();
foreach (var item in nodelist)
{
if (item is Element)
{
Element e = item as Element;
var col = e.getElementsByTagName(tagName).item;
if (col != null && col.Count > 0)
{
cols.item.AddRange(col);
}
}
}
return cols;
}
/// <summary>
/// test whether the sub element is contained with the parent or not..
/// </summary>
/// <param name="Parent"></param>
/// <param name="Sub"></param>
/// <returns></returns>
public static bool ContainsOrEqualElement(Element Parent, Element Sub)
{
if (Sub.depth < Parent.depth)
{ return false; }
var element = Sub;
while (element.depth > Parent.depth)
{
element = element.parentElement;
if (element == null)
{
return false;
}
}
return element.isEqualNode(Parent);
}
/// <summary>
/// get all node sitting between x & y.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static List<Node> GetNodesInBetween(Document doc, Element x, Element y)
{
List<Node> col = new List<Node>();
if (ContainsOrEqualElement(x, y) || ContainsOrEqualElement(y, x))
{
return col;
}
if (x.location.openTokenStartIndex < y.location.openTokenStartIndex)
{
if (x.location.endTokenEndIndex > y.location.openTokenStartIndex)
{
return col;
}
else
{
_GetNodesInBetween(doc.body, col, x.location.endTokenEndIndex, y.location.openTokenStartIndex);
return col;
}
}
else
{
if (y.location.endTokenEndIndex > x.location.openTokenStartIndex)
{ return col; }
else
{
_GetNodesInBetween(doc.body, col, y.location.endTokenEndIndex, x.location.openTokenStartIndex);
return col;
}
}
}
private static void _GetNodesInBetween(Node topElement, List<Node> collection, int startindex, int endindex)
{
if (topElement.location.openTokenStartIndex > startindex && topElement.location.endTokenEndIndex < endindex)
{
collection.Add(topElement);
}
else
{
foreach (var item in topElement.childNodes.item)
{
_GetNodesInBetween(item, collection, startindex, endindex);
}
}
}
public static string ReplaceLink(Element linkElement, string href, string linktext)
{
linkElement.removeAttribute("href");
linkElement.attributes.Add(new Attr() { name = "href", value = href });
return ReSerializeElement(linkElement, linktext);
}
public static Element GetTitleElement(Dom.Document doc)
{
if (doc == null)
{
return null;
}
var head = doc.head;
foreach (var item in head.childNodes.item)
{
if (item.nodeType == enumNodeType.ELEMENT)
{
var el = item as Element;
if (el.tagName.ToLower() == "title")
{
return el;
}
}
}
return null;
}
public static List<SingleMeta> GetMetaValues(Dom.Document doc)
{
List<SingleMeta> metas = new List<SingleMeta>();
var head = doc.head;
foreach (var item in head.childNodes.item)
{
if (item.nodeType == enumNodeType.ELEMENT)
{
var el = item as Element;
if (el.tagName.ToLower() == "meta")
{
SingleMeta meta = new SingleMeta();
meta.name = el.getAttribute("name");
meta.httpequiv = el.getAttribute("http-equiv");
meta.charset = el.getAttribute("charset");
meta.content = el.getAttribute("content");
metas.Add(meta);
}
}
}
return metas;
}
public static string DetectKoobooId(Document dom, List<string> SubLinks)
{
var allinks = dom.getElementsByTagName("a").item;
var GroupbyLinks = MenuService.SimpleGroupBy(allinks);
bool match = true;
bool onetimedismatch = false;
foreach (var item in GroupbyLinks)
{
var allgrouplinks = item.Select(o => o.getAttribute("href"));
match = false;
foreach (var link in SubLinks)
{
if (allgrouplinks.Any(o => IsSameUrl(o, link)))
{
match = true;
}
else
{
if (!onetimedismatch)
{
onetimedismatch = true;
}
else
{
match = false;
break;
}
}
}
if (match)
{
var commoneparent = DomService.FindParent(item);
if (commoneparent != null)
{
return DomService.GetKoobooId(commoneparent);
}
}
}
return null;
}
private static bool IsSameUrl(string x, string y)
{
if (Kooboo.Lib.Helper.StringHelper.IsSameValue(x, y))
{
return true;
}
x = x.Trim();
y = y.Trim();
x = x.Replace("\r", "");
x = x.Replace("\n", "");
y = y.Replace("\r", "");
y = y.Replace("\n", "");
if (Kooboo.Lib.Helper.StringHelper.IsSameValue(x, y))
{
return true;
}
return false;
}
public static string UpdateUrl(string Source, string OldUrl, string NewUrl)
{
if (string.IsNullOrEmpty(OldUrl))
{
return Source;
}
OldUrl = OldUrl.ToLower().Trim();
List<SourceUpdate> updates = new List<SourceUpdate>();
var doc = Kooboo.Dom.DomParser.CreateDom(Source);
var els = GetElementsByUrl(doc, OldUrl);
foreach (var item in els)
{
foreach (var att in item.attributes)
{
if (!string.IsNullOrEmpty(att.value) && att.value.ToLower().Trim() == OldUrl)
{
att.value = NewUrl;
string newhtml = ReSerializeOpenTag(item);
updates.Add(new SourceUpdate() { StartIndex = item.location.openTokenStartIndex, EndIndex = item.location.openTokenEndIndex, NewValue = newhtml });
}
}
}
// this maybe a text with url directly in the field. in the case of text content media file.
els = Helper.ContentHelper.GetByTextContentMedia(doc, OldUrl);
foreach (var item in els)
{
string value = item.InnerHtml;
string newvalue = string.Empty;
if (!string.IsNullOrEmpty(value) && value.ToLower().Trim() == OldUrl)
{
newvalue = NewUrl;
}
else if (value.IndexOf(OldUrl, StringComparison.OrdinalIgnoreCase) > -1)
{
newvalue = Lib.Helper.StringHelper.ReplaceIgnoreCase(value, OldUrl, NewUrl);
}
updates.Add(new SourceUpdate() { StartIndex = item.location.openTokenEndIndex + 1, EndIndex = item.location.endTokenStartIndex - 1, NewValue = newvalue });
}
if (updates.Count() > 0)
{
return UpdateSource(Source, updates);
}
return Source;
}
public static string DeleteUrl(string Source, string OldUrl)
{
if (string.IsNullOrEmpty(OldUrl))
{
return Source;
}
OldUrl = OldUrl.ToLower().Trim();
List<SourceUpdate> updates = new List<SourceUpdate>();
var doc = Kooboo.Dom.DomParser.CreateDom(Source);
var els = GetElementsByUrl(doc, OldUrl);
foreach (var item in els)
{
foreach (var att in item.attributes)
{
if (!string.IsNullOrEmpty(att.value) && att.value.ToLower().Trim() == OldUrl)
{
//item.removeAttribute(att.name);
//string newhtml = ReSerializeOpenTag(item);
updates.Add(new SourceUpdate() { StartIndex = item.location.openTokenStartIndex, EndIndex = item.location.endTokenEndIndex, NewValue = "" });
break;
}
}
}
// this maybe a text with url directly in the field. in the case of text content media file.
els = Helper.ContentHelper.GetByTextContentMedia(doc, OldUrl);
foreach (var item in els)
{
string value = item.InnerHtml;
if (string.IsNullOrEmpty(value) || value.Length <= 1)
{
continue;
}
value = value.Trim();
string newvalue = string.Empty;
if (!string.IsNullOrEmpty(value) && value.ToLower() == OldUrl)
{
newvalue = "";
updates.Add(new SourceUpdate() { StartIndex = item.location.openTokenEndIndex + 1, EndIndex = item.location.endTokenStartIndex - 1, NewValue = newvalue });
}
else if (value.IndexOf(OldUrl, StringComparison.OrdinalIgnoreCase) > -1)
{
// this is only the text content multile values.
if (value.StartsWith("[") && value.EndsWith("]"))
{
try
{
List<string> files = Lib.Helper.JsonHelper.Deserialize<List<string>>(value);
if (files != null && files.Count() > 0)
{
List<int> removeindex = new List<int>();
int count = files.Count();
for (int i = 0; i < count; i++)
{
var file = files[i];
if (!string.IsNullOrWhiteSpace(file) && file.ToLower().Trim() == OldUrl)
{
removeindex.Add(i);
}
}
if (removeindex.Count() > 0)
{
foreach (var remove in removeindex.OrderByDescending(o => o))
{
files.RemoveAt(remove);
}
newvalue = Lib.Helper.JsonHelper.Serialize(files);
updates.Add(new SourceUpdate() { StartIndex = item.location.openTokenEndIndex + 1, EndIndex = item.location.endTokenStartIndex - 1, NewValue = newvalue });
}
}
}
catch (Exception)
{
}
}
}
}
if (updates.Count() > 0)
{
return UpdateSource(Source, updates);
}
return Source;
}
public static List<Element> GetElementsByUrl(Document doc, string url)
{
List<Element> result = new List<Element>();
if (string.IsNullOrWhiteSpace(url))
{
return result;
}
_getElementByUrl(doc.documentElement, url.ToLower().Trim(), ref result);
return result;
}
private static void _getElementByUrl(Element el, string Url, ref List<Element> result)
{
var link = DomUrlService.GetLinkOrSrc(el);
if (!string.IsNullOrWhiteSpace(link) && link.Trim().ToLower() == Url)
{
result.Add(el);
}
foreach (var item in el.childNodes.item)
{
if (item.nodeType == enumNodeType.ELEMENT)
{
var subel = item as Element;
_getElementByUrl(subel, Url, ref result);
}
}
}
public static List<string> GetElementPath(Element element)
{
if (element == null)
{
return new List<string>();
}
List<string> paths = new List<string>();
while (element != null && element.tagName != "html")
{
var key = _GetElementKey(element);
paths.Add(key);
element = element.parentElement;
}
paths.Reverse();
return paths;
}
private static string _GetElementKey(Element el)
{
if (el == null)
{
return null;
}
string key = el.tagName;
if (!string.IsNullOrEmpty(el.id))
{
key += "||" + el.id;
}
var parent = el.parentElement;
if (parent != null)
{
int count = 0;
foreach (var item in parent.childNodes.item)
{
var itemel = item as Element;
if (itemel != null)
{
if (itemel.isEqualNode(el))
{
break;
}
else
{
count += 1;
}
}
}
key = key + count.ToString();
}
return key.ToLower();
}
public static Element GetElementByPath(Document doc, List<string> Paths)
{
var el = doc.body;
int index = 0;
int pathcount = Paths.Count();
if (pathcount == 0)
{
return null;
}
var bodykey = _GetElementKey(el);
if (bodykey != Paths[0])
{
return null;
}
while (index <= pathcount - 1)
{
if (index == pathcount - 1)
{
return el;
}
else
{
Element sub = null;
var deeperkey = Paths[index + 1];
foreach (var item in el.childNodes.item)
{
var itemel = item as Element;
if (itemel !=null)
{
var itemkey = _GetElementKey(itemel);
if (itemkey == deeperkey)
{
sub = itemel;
}
}
}
if (sub !=null )
{
el = sub;
index += 1;
}
else
{
return null;
}
}
}
return null;
}
// el.tagName =='form' should have been checked before.
public static bool IsAspNetWebForm(Element el)
{
foreach (var item in el.childNodes.item)
{
if (item.nodeType == enumNodeType.ELEMENT)
{
var childel = item as Element;
if (childel.tagName == "input" && childel.id !=null && childel.id == "__VIEWSTATE")
{
return true;
}
if (IsAspNetWebForm(childel))
{
return true;
}
}
}
return false;
}
}
}
| 32.213941 | 321 | 0.435023 | [
"MIT"
] | Kooboo/Kooboo | Kooboo.Sites/Service/DomService.cs | 46,678 | C# |
// Author:
// Brian Faust <brian@ark.io>
//
// Copyright (c) 2018 Ark Ecosystem <info@ark.io>
//
// 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace ArkEcosystem.Crypto.Tests.Deserializers
{
[TestClass]
public class TransferTest
{
[TestMethod]
public void Should_Deserialize_The_Transaction()
{
var fixture = File.ReadAllText("../../../fixtures/transfer.json");
var transaction = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(fixture);
var actual = new Deserializer(transaction["serialized"]).Deserialize();
Assert.AreEqual((UInt64)transaction["amount"], actual.Amount);
Assert.AreEqual((UInt64)transaction["fee"], actual.Fee);
Assert.AreEqual(transaction["expiration"], actual.Expiration);
Assert.AreEqual(transaction["id"], actual.Id);
Assert.AreEqual(transaction["network"], actual.Network);
Assert.AreEqual(transaction["recipientId"], actual.RecipientId);
Assert.AreEqual(transaction["senderPublicKey"], actual.SenderPublicKey);
Assert.AreEqual(transaction["signature"], actual.Signature);
Assert.AreEqual(transaction["timestamp"], actual.Timestamp);
Assert.AreEqual(transaction["type"], actual.Type);
Assert.AreEqual(transaction["version"], actual.Version);
Assert.AreEqual(transaction["serialized"], Encoders.Hex.EncodeData(new Serializer(actual).Serialize()));
}
}
}
| 46.948276 | 116 | 0.711348 | [
"MIT"
] | supaiku0/dotnet-crypto | ArkEcosystem.Crypto/ArkEcosystem.Crypto.Tests/ArkEcosystem.Crypto.Tests/Deserializers/TransferTest.cs | 2,723 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace ITACO_MVC.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
| 18.969697 | 67 | 0.58147 | [
"Apache-2.0"
] | jacgandres/ITACO | ITACO_MVC/ITACO_MVC/Controllers/HomeController.cs | 628 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
namespace QuickDir
{
public class QDCommands
{
public static event EventHandler QDCommandFinished;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
protected delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
protected static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_CLOSE = 0xF060;
public static void Execute(string commandText)
{
if(commandsList.Find(command => command.Text.Equals(commandText))
.Action(commandText))
{
QDCommandFinished(commandText, new EventArgs());
}
}
public static List<string> FindCommands(string text)
{
List<string> commandsTextsList = commandsList
.ConvertAll(command => command.Text);
List<string> result = commandsTextsList
.FindAll(command => command.ToLower().StartsWith(text.ToLower()));
result.AddRange(commandsTextsList
.FindAll(command => command.ToLower().Contains(text.ToLower())
&& !result.Contains(command)));
string findTextPattern = SmartSearch.GetRegexSmartSearchPattern(text.Split(':')[0]);
result.AddRange(commandsTextsList
.FindAll(command => Regex.IsMatch(command.ToLower(), findTextPattern.ToLower())
&& !result.Contains(command)));
return result;
}
private class QDCommand
{
internal string Text
{
get;
set;
}
internal Func<string, bool> Action
{
get;
set;
}
internal QDCommand(string text, Func<string, bool> action)
{
this.Text = text;
this.Action = action;
}
}
private static string GetClassName(IntPtr hwnd)
{
int nRet;
// Pre-allocate 256 characters, since this is the maximum class name length.
StringBuilder className = new StringBuilder(100);
//Get the window class name
nRet = GetClassName(hwnd, className, className.Capacity);
if (nRet != 0)
{
return className.ToString();
}
else
{
return "";
}
}
private static void CloseAllWindowsWithClassName(string className)
{
EnumWindows(delegate (IntPtr hwnd, IntPtr lParam) {
if (GetClassName(hwnd).Equals(className))
{
SendMessage(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0);
}
return true;
}
, IntPtr.Zero);
}
private static bool GetBoolFromString(string stringValue)
{
string sResult = stringValue.Trim(' ', '\t');
bool result = sResult.Equals("1")
|| sResult.ToLower().Equals("yes")
|| sResult.ToLower().Equals("on")
|| sResult.ToLower().Equals("true") ? true :
(sResult.Equals("0")
|| sResult.ToLower().Equals("no")
|| sResult.ToLower().Equals("off")
|| sResult.ToLower().Equals("false") ? false : bool.Parse(sResult));
return result;
}
private static void SetBoolConfig(string configName, bool value)
{
Config.Instance.GetType().GetProperty(configName)
.SetValue(Config.Instance, value);
}
private static bool GetBoolConfig(string configName)
{
return (bool)Config.Instance.GetType().GetProperty(configName)
.GetValue(Config.Instance);
}
private static bool SetBoolCommand(string name, string configName)
{
TextBox txtField = MainWindow.Instance.txtDirRequest;
string[] commandsArgsArray = MainWindow.Instance.txtDirRequest.Text.Split(':');
if(commandsArgsArray.Length > 1)
{
try
{
SetBoolConfig(configName, GetBoolFromString(commandsArgsArray[1]));
}
catch(Exception ex)
{
MessageBox.Show("Impossible to attribute the " + name + " value. " + ex.Message);
}
return true;
}
else
{
string current = GetBoolConfig(configName).ToString();
txtField.Text = "> " + name + ":" + current;
txtField.Select(txtField.Text.Length - current.Length, current.Length);
return false;
}
}
private static void SetIntConfig(string configName, int value)
{
Config.Instance.GetType().GetProperty(configName)
.SetValue(Config.Instance, value);
}
private static int GetIntConfig(string configName)
{
return (int)Config.Instance.GetType().GetProperty(configName)
.GetValue(Config.Instance);
}
private static bool SetIntCommand(string name, string configName)
{
TextBox txtField = MainWindow.Instance.txtDirRequest;
string[] commandsArgsArray = MainWindow.Instance.txtDirRequest.Text.Split(':');
if (commandsArgsArray.Length > 1)
{
try
{
int width = int.Parse(commandsArgsArray[1].Trim(' ', '\t'));
SetIntConfig(configName, width);
}
catch (Exception ex)
{
MessageBox.Show("Impossible to set the width. " + ex.Message);
}
return true;
}
else
{
string currentWidth = GetIntConfig(configName).ToString();
txtField.Text = "> " + name + ":" + currentWidth;
txtField.Select(txtField.Text.Length - currentWidth.Length, currentWidth.Length);
return false;
}
}
private static List<QDCommand> commandsList = (new QDCommand[]
{
new QDCommand("Set Close on Escape key press" , delegate(string name)
{
Config.Instance.CloseOnEscape = true;
MessageBox.Show("A press on [Escape] when the field is empty will now close the application.");
return true;
}),
new QDCommand("Set Minimize on Escape key press" , delegate(string name)
{
Config.Instance.CloseOnEscape = false;
MessageBox.Show("A press on [Escape] when the field is empty will now minimize the application.");
return true;
}),
new QDCommand("Close all explorer windows", delegate(string name)
{
CloseAllWindowsWithClassName("CabinetWClass");
return true;
}),
new QDCommand("Close all cmd terminal windows", delegate(string name)
{
CloseAllWindowsWithClassName("ConsoleWindowClass");
return true;
}),
new QDCommand("Set Field Width", delegate(string name)
{
return SetIntCommand(name, "Width");
}),
new QDCommand("Set Max Height", delegate(string name)
{
return SetIntCommand(name, "MaxHeight");
}),
new QDCommand("Activate Search Favs by Keys", delegate(string name)
{
return SetBoolCommand(name, "SearchFavByKeys");
}),
new QDCommand("Activate SmartSearch on Favs", delegate(string name)
{
return SetBoolCommand(name, "SmartSearchOnFavs");
}),
new QDCommand("Activate Smart History", delegate(string name)
{
return SetBoolCommand(name, "SmartHistory");
}),
new QDCommand("Clear Smart History", delegate(string name)
{
if(MessageBox.Show("It will empty the history. Do you validate ?", "Clear", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
Config.Instance.ClearHistory();
return true;
}),
new QDCommand("Activate SmartSearch on Directories", delegate(string name)
{
return SetBoolCommand(name, "SmartSearchOnDirectories");
}),
new QDCommand("Minimize On Validation", delegate(string name)
{
return SetBoolCommand(name, "MinimizeOnValidate");
}),
new QDCommand("Empty Field On Validation", delegate(string name)
{
return SetBoolCommand(name, "EmptyOnValidate");
}),
new QDCommand("Exit", delegate(string name){
MainWindow.Instance.Close();
return true;
}),
})
.OrderBy(command => command.Text)
.ToList();
private static void GetSubDir(string current, List<string> index)
{
if (Config.Instance.IsManaged(current))
{
try
{
if (Directory.GetDirectories(current).Length > 0)
{
Directory.GetDirectories(current).ToList()
.ForEach(delegate(string dir)
{
GetSubDir(dir, index);
});
}
else
{
index.Add(current);
}
}
catch
{
index.Add(current);
}
}
}
}
}
| 36.094463 | 167 | 0.499955 | [
"MIT"
] | codingseb/QuickDirWpf | QuickDir/QDCommands.cs | 11,083 | C# |
namespace Functional.CQS.AOP.IoC.SimpleInjector.MetricsCapturing.Configuration
{
/// <summary>
/// Encapsulates configuration parameters used by Functional.CQS.AOP.IoC.SimpleInjector.MetricsCapturing components.
/// </summary>
public class MetricsCapturingModuleConfigurationParameters
{
/// <summary>
/// Initializes a new instance of the <see cref="MetricsCapturingModuleConfigurationParameters"/> class.
/// </summary>
/// <param name="universalMetricsCapturingDecoratorEnabled">Indicates if the universal metrics-capturing decorator is enabled.</param>
/// <param name="commandSpecificMetricsCapturingDecoratorEnabled">Indicates if the metrics-capturing decorator for <see cref="ICommandHandler{TCommand, TError}"/> and <see cref="IAsyncCommandHandler{TCommand, TError}"/> is enabled.</param>
/// <param name="querySpecificMetricsCapturingDecoratorEnabled">Indicates if the metrics-capturing decorator for <see cref="IQueryHandler{TQuery, TResult}"/> and <see cref="IAsyncQueryHandler{TQuery, TResult}"/> is enabled.</param>
public MetricsCapturingModuleConfigurationParameters(
bool universalMetricsCapturingDecoratorEnabled,
bool commandSpecificMetricsCapturingDecoratorEnabled,
bool querySpecificMetricsCapturingDecoratorEnabled)
{
UniversalMetricsCapturingDecoratorEnabled = universalMetricsCapturingDecoratorEnabled;
CommandSpecificMetricsCapturingDecoratorEnabled = commandSpecificMetricsCapturingDecoratorEnabled;
QuerySpecificMetricsCapturingDecoratorEnabled = querySpecificMetricsCapturingDecoratorEnabled;
}
/// <summary>
/// Indicates if the universal metrics-capturing decorator is enabled.
/// </summary>
public bool UniversalMetricsCapturingDecoratorEnabled { get; }
/// <summary>
/// Indicates if the metrics-capturing decorator for <see cref="ICommandHandler{TCommand, TError}"/> and <see cref="IAsyncCommandHandler{TCommand, TError}"/> is enabled.
/// </summary>
public bool CommandSpecificMetricsCapturingDecoratorEnabled { get; }
/// <summary>
/// Indicates if the metrics-capturing decorator for <see cref="IQueryHandler{TQuery, TResult}"/> and <see cref="IAsyncQueryHandler{TQuery, TResult}"/> is enabled.
/// </summary>
public bool QuerySpecificMetricsCapturingDecoratorEnabled { get; }
}
}
| 57.175 | 241 | 0.794491 | [
"MIT"
] | RyanMarcotte/Functional.CQS | src/Functional.CQS.AOP.IoC.SimpleInjector.MetricsCapturing/Configuration/MetricsCapturingModuleConfigurationParameters.cs | 2,289 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Syroot.BinaryData;
namespace GTAdhocToolchain.Core.Instructions
{
/// <summary>
/// Pops 2 pointers off the stack, and copies the second item to the first item
/// </summary>
public class InsAssign : InstructionBase
{
public readonly static InsAssign Default = new();
public override AdhocInstructionType InstructionType => AdhocInstructionType.ASSIGN;
public override string InstructionName => "ASSIGN";
public override void Deserialize(AdhocStream strema)
{
}
public override string ToString()
=> $"{InstructionType}";
}
}
| 24.096774 | 92 | 0.682731 | [
"MIT"
] | Nenkai/GTAdhocCompiler | GTAdhocToolchain.Core/Instructions/InsAssign.cs | 749 | C# |
using System;
using System.Collections.Generic;
using System.Text.Json;
using Sentry.Internal.Extensions;
namespace Sentry
{
// https://develop.sentry.dev/sdk/event-payloads/span
/// <summary>
/// Transaction span.
/// </summary>
public class Span : ISpanData, IJsonSerializable
{
/// <inheritdoc />
public SpanId SpanId { get; private set; }
/// <inheritdoc />
public SpanId? ParentSpanId { get; private set; }
/// <inheritdoc />
public SentryId TraceId { get; private set; }
/// <inheritdoc />
public DateTimeOffset StartTimestamp { get; private set; } = DateTimeOffset.UtcNow;
/// <inheritdoc />
public DateTimeOffset? EndTimestamp { get; private set; }
/// <inheritdoc />
public bool IsFinished => EndTimestamp is not null;
/// <inheritdoc />
public string Operation { get; set; }
/// <inheritdoc />
public string? Description { get; set; }
/// <inheritdoc />
public SpanStatus? Status { get; set; }
/// <inheritdoc />
public bool? IsSampled { get; internal set; }
private Dictionary<string, string>? _tags;
/// <inheritdoc />
public IReadOnlyDictionary<string, string> Tags => _tags ??= new Dictionary<string, string>();
/// <inheritdoc />
public void SetTag(string key, string value) =>
(_tags ??= new Dictionary<string, string>())[key] = value;
/// <inheritdoc />
public void UnsetTag(string key) =>
(_tags ??= new Dictionary<string, string>()).Remove(key);
// Aka 'data'
private Dictionary<string, object?>? _extra;
/// <inheritdoc />
public IReadOnlyDictionary<string, object?> Extra => _extra ??= new Dictionary<string, object?>();
/// <inheritdoc />
public void SetExtra(string key, object? value) =>
(_extra ??= new Dictionary<string, object?>())[key] = value;
/// <summary>
/// Initializes an instance of <see cref="SpanTracer"/>.
/// </summary>
public Span(SpanId? parentSpanId, string operation)
{
SpanId = SpanId.Create();
ParentSpanId = parentSpanId;
TraceId = SentryId.Create();
Operation = operation;
}
/// <summary>
/// Initializes an instance of <see cref="SpanTracer"/>.
/// </summary>
public Span(ISpan tracer)
: this(tracer.ParentSpanId, tracer.Operation)
{
SpanId = tracer.SpanId;
TraceId = tracer.TraceId;
StartTimestamp = tracer.StartTimestamp;
EndTimestamp = tracer.EndTimestamp;
Description = tracer.Description;
Status = tracer.Status;
IsSampled = tracer.IsSampled;
_extra = tracer.Extra.ToDictionary();
_tags = tracer.Tags.ToDictionary();
}
/// <inheritdoc />
public SentryTraceHeader GetTraceHeader() => new(
TraceId,
SpanId,
IsSampled);
/// <inheritdoc />
public void WriteTo(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WriteSerializable("span_id", SpanId);
writer.WriteSerializableIfNotNull("parent_span_id", ParentSpanId);
writer.WriteSerializable("trace_id", TraceId);
writer.WriteStringIfNotWhiteSpace("op", Operation);
writer.WriteStringIfNotWhiteSpace("description", Description);
writer.WriteStringIfNotWhiteSpace("status", Status?.ToString().ToSnakeCase());
writer.WriteString("start_timestamp", StartTimestamp);
writer.WriteStringIfNotNull("timestamp", EndTimestamp);
writer.WriteStringDictionaryIfNotEmpty("tags", _tags!);
writer.WriteDictionaryIfNotEmpty("data", _extra!);
writer.WriteEndObject();
}
/// <summary>
/// Parses a span from JSON.
/// </summary>
public static Span FromJson(JsonElement json)
{
var spanId = json.GetPropertyOrNull("span_id")?.Pipe(SpanId.FromJson) ?? SpanId.Empty;
var parentSpanId = json.GetPropertyOrNull("parent_span_id")?.Pipe(SpanId.FromJson);
var traceId = json.GetPropertyOrNull("trace_id")?.Pipe(SentryId.FromJson) ?? SentryId.Empty;
var startTimestamp = json.GetProperty("start_timestamp").GetDateTimeOffset();
var endTimestamp = json.GetProperty("timestamp").GetDateTimeOffset();
var operation = json.GetPropertyOrNull("op")?.GetString() ?? "unknown";
var description = json.GetPropertyOrNull("description")?.GetString();
var status = json.GetPropertyOrNull("status")?.GetString()?.Replace("_", "").ParseEnum<SpanStatus>();
var isSampled = json.GetPropertyOrNull("sampled")?.GetBoolean();
var tags = json.GetPropertyOrNull("tags")?.GetStringDictionaryOrNull()?.ToDictionary();
var data = json.GetPropertyOrNull("data")?.GetDictionaryOrNull()?.ToDictionary();
return new Span(parentSpanId, operation)
{
SpanId = spanId,
TraceId = traceId,
StartTimestamp = startTimestamp,
EndTimestamp = endTimestamp,
Description = description,
Status = status,
IsSampled = isSampled,
_tags = tags!,
_extra = data!
};
}
}
}
| 36.894737 | 113 | 0.582204 | [
"MIT"
] | kanadaj/sentry-dotnet | src/Sentry/Span.cs | 5,608 | C# |
using Endpoint.Core.Models;
using Endpoint.Core.Services;
using Endpoint.Core.Strategies.Application;
using Endpoint.Core.Strategies.Infrastructure;
using System.Collections.Generic;
using System.IO;
namespace Endpoint.Core.Strategies.Api.FileGeneration
{
public interface IMinimalApiProgramGenerationStratey
{
void Create(MinimalApiProgramModel model, string directory);
}
public class MinimalApiProgramGenerationStratey : IMinimalApiProgramGenerationStratey
{
private readonly IFileSystem _fileSystem;
private readonly IWebApplicationBuilderGenerationStrategy _webApplicationBuilderGenerationStrategy;
private readonly IWebApplicationGenerationStrategy _webApplicationGenerationStrategy;
public MinimalApiProgramGenerationStratey(IFileSystem fileSystem, ITemplateProcessor templateProcessor, ITemplateLocator templateLocator)
{
_fileSystem = fileSystem;
_webApplicationBuilderGenerationStrategy = new WebApplicationBuilderGenerationStrategy(templateProcessor, templateLocator);
_webApplicationGenerationStrategy = new WebApplicationGenerationStrategy(templateProcessor, templateLocator);
}
public void Create(MinimalApiProgramModel model, string directory)
{
var content = new List<string>();
foreach(var @using in model.Usings)
{
content.Add($"using {@using};");
}
content.Add("");
content.AddRange(_webApplicationBuilderGenerationStrategy.Create(model));
content.Add("");
content.AddRange(_webApplicationGenerationStrategy.Create(model));
content.Add("");
foreach (var aggregateRoot in model.AggregateRoots)
{
content.AddRange(new AggregateRootGenerationStrategy().Create(aggregateRoot));
content.Add("");
}
content.AddRange(new DbContextGenerationStrategy().Create(new DbContextModel(model.DbContextName, model.AggregateRoots)));
_fileSystem.WriteAllLines($"{directory}{Path.DirectorySeparatorChar}Program.cs", content.ToArray());
}
}
}
| 37.083333 | 145 | 0.70427 | [
"MIT"
] | PeterKneale/Endpoint | src/Endpoint.Core/Strategies/Api/FileGeneration/MinimalApiProgramGenerationStratey.cs | 2,227 | C# |
using System;
using OpenQA.Selenium;
namespace JDI.Light.Attributes
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class XPathAttribute : Attribute
{
public XPathAttribute(string locator)
{
Value = By.XPath(locator);
}
public By Value { get; }
}
} | 22.666667 | 72 | 0.641176 | [
"MIT"
] | Igor-Ratsuk/jdi-light-csharp | JDI.Light/JDI.Light/Attributes/XPathAttribute.cs | 342 | C# |
/*
* Copyright (c) Contributors, http://whitecore-sim.org/, http://aurora-sim.org
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WhiteCore-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using WhiteCore.Framework.Servers.HttpServer.Implementation;
namespace WhiteCore.Modules.Web
{
public class WelcomeScreenMain : IWebInterfacePage
{
public string[] FilePath
{
get
{
return new[]
{
"html/welcomescreen/index.html"
};
}
}
public bool RequiresAuthentication
{
get { return false; }
}
public bool RequiresAdminAuthentication
{
get { return false; }
}
public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
ITranslator translator, out string response)
{
response = null;
var vars = new Dictionary<string, object>();
// Style Switcher
vars.Add("styles1", translator.GetTranslatedString("styles1"));
vars.Add("styles2", translator.GetTranslatedString("styles2"));
vars.Add("styles3", translator.GetTranslatedString("styles3"));
vars.Add("styles4", translator.GetTranslatedString("styles4"));
vars.Add("styles5", translator.GetTranslatedString("styles5"));
vars.Add("StyleSwitcherStylesText", translator.GetTranslatedString("StyleSwitcherStylesText"));
vars.Add("StyleSwitcherLanguagesText", translator.GetTranslatedString("StyleSwitcherLanguagesText"));
vars.Add("StyleSwitcherChoiceText", translator.GetTranslatedString("StyleSwitcherChoiceText"));
// Language Switcher
vars.Add("en", translator.GetTranslatedString("en"));
vars.Add("fr", translator.GetTranslatedString("fr"));
vars.Add("de", translator.GetTranslatedString("de"));
vars.Add("it", translator.GetTranslatedString("it"));
vars.Add("es", translator.GetTranslatedString("es"));
vars.Add("nl", translator.GetTranslatedString("nl"));
return vars;
}
public bool AttemptFindPage(string filename, ref OSHttpResponse httpResponse, out string text)
{
text = "";
return false;
}
}
} | 46.043956 | 122 | 0.636516 | [
"BSD-3-Clause"
] | WhiteCoreSim/WhiteCore-Dev | WhiteCore/Modules/Web/html/welcomescreen/index.cs | 4,192 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebProject.Master {
public partial class Register {
/// <summary>
/// HeadRegister control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadRegister;
/// <summary>
/// FormRegisterBody control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder FormRegisterBody;
}
}
| 33.117647 | 88 | 0.508881 | [
"Apache-2.0"
] | NumericTechnology/SkeletonApp.Net | WebSolution/WebProject/Master/Register.master.designer.cs | 1,128 | C# |
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace DevExpress.Mvvm {
public interface IDelegateCommand : ICommand {
void RaiseCanExecuteChanged();
}
public interface IAsyncCommand : IDelegateCommand {
bool IsExecuting { get; }
[EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use the IsCancellationRequested property instead.")]
bool ShouldCancel { get; }
CancellationTokenSource CancellationTokenSource { get; }
bool IsCancellationRequested { get; }
ICommand CancelCommand { get; }
#if DEBUG
[Obsolete("Use 'await ExecuteAsync' instead.")]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
void Wait(TimeSpan timeout);
Task ExecuteAsync(object parameter);
}
}
namespace DevExpress.Mvvm {
[EditorBrowsable(EditorBrowsableState.Never)]
public static class IAsyncCommandExtensions {
#if DEBUG
[Obsolete("Use 'await ExecuteAsync' instead.")]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Wait(this IAsyncCommand service) {
VerifyService(service);
service.Wait(TimeSpan.FromMilliseconds(-1));
}
static void VerifyService(IAsyncCommand service) {
if(service == null) throw new ArgumentNullException("service");
}
}
} | 34.926829 | 116 | 0.692039 | [
"MIT"
] | Tdue21/DevExpress.Mvvm.Free | DevExpress.Mvvm/Commands/ICommand.cs | 1,432 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using VideoOS.ConfigurationAPI;
namespace ConfigAPIClient.Panels
{
public partial class SimpleUserControl : UserControl
{
private ConfigurationItem _item;
private ConfigurationItem _privacyMaskItem;
private string _originalName = "";
private ConfigApiClient _configApiClient;
private bool _showChildren;
private UI.PrivacyMaskUserControl _privacyMaskUserControl;
private UI.MotionDetectUserControl _motionDetectMaskUserControl;
public SimpleUserControl(ConfigurationItem item, bool showChildren, ConfigApiClient configApiClient)
{
InitializeComponent();
_configApiClient = configApiClient;
_showChildren = showChildren;
_item = item;
_privacyMaskItem = null;
InitalizeUI();
}
public SimpleUserControl(ConfigurationItem item, bool showChildren, ConfigApiClient configApiClient, ConfigurationItem privacyMaskItem)
{
InitializeComponent();
_configApiClient = configApiClient;
_showChildren = showChildren;
_item = item;
_privacyMaskItem = privacyMaskItem;
InitalizeUI();
}
private void InitalizeUI(string propertyToFocus = null)
{
buttonSave.Enabled = (_item.ItemCategory == ItemCategories.Item);
scrollPanel1.Clear();
_originalName = _item.DisplayName;
textBoxName.Text = _item.DisplayName;
textBoxName.ReadOnly = true;
if (_item.EnableProperty != null)
{
EnabledCheckBox.Text = _item.EnableProperty.DisplayName;
EnabledCheckBox.Checked = _item.EnableProperty.Enabled;
scrollPanel1.EnableContent = _item.EnableProperty.Enabled || !_item.EnableProperty.UIToFollowEnabled;
}
else
{
EnabledCheckBox.Visible = false;
}
pictureBox1.Image = UI.Icons.IconListBlack.Images[UI.Icons.GetImageIndex(_item.ItemType)];
if (!_item.ChildrenFilled)
{
try
{
_item.Children = _configApiClient.GetChildItems(_item.Path);
}
catch (Exception)
{
_item.Children = new ConfigurationItem[0];
}
_item.ChildrenFilled = true;
}
int top = 10; // panelId.Height;
if (_item.Properties != null)
{
top = ConfigAPIClient.Panels.PanelUtils.BuildPropertiesUI(_item, top, 0, scrollPanel1, ValueChangedHandler, _configApiClient, propertyToFocus);
if (_item.ItemType == ItemTypes.PrivacyMask)
{
_privacyMaskUserControl = new UI.PrivacyMaskUserControl(_item, _configApiClient);
_privacyMaskUserControl.Location = new Point(80, top);
top += _privacyMaskUserControl.Height + 10;
scrollPanel1.Add(_privacyMaskUserControl);
}
else if (_item.ItemType == ItemTypes.MotionDetection)
{
_motionDetectMaskUserControl = new UI.MotionDetectUserControl(_item, _privacyMaskItem, _configApiClient);
_motionDetectMaskUserControl.Location = new Point(80, top);
top += _motionDetectMaskUserControl.Height + 10;
scrollPanel1.Add(_motionDetectMaskUserControl);
}
else
{
_privacyMaskUserControl = null;
_motionDetectMaskUserControl = null;
}
}
// Show command buttons
if (_item.MethodIds != null && _item.MethodIds.Length > 0)
{
foreach (String id in _item.MethodIds)
{
if (_configApiClient.AllMethodInfos.ContainsKey(id))
{
MethodInfo mi = _configApiClient.AllMethodInfos[id];
Button b = new Button() { Text = mi.DisplayName, Tag = mi, UseVisualStyleBackColor = true };
ToolTip toolTip = new ToolTip();
toolTip.SetToolTip(b, mi.MethodId);
int width = mi.DisplayName.Length < 20 ? 150 : 300;
b.Size = new System.Drawing.Size(width, 24);
b.Location = new Point(10, top);
top += b.Height + 10;
b.Click += PerformAction;
scrollPanel1.Add(b);
}
}
}
if (_showChildren && _item.Children != null && _item.Children.Any())
{
int leftOffset = Constants.LeftIndentChildControl;
if (ShowAsDropDown())
{
ShowDropDown(leftOffset, top);
} else
{
ShowAllChildren(leftOffset, top);
}
}
if (propertyToFocus == null)
scrollPanel1.ScrollToTop();
}
private bool ShowAsDropDown()
{
// Check all of same itemType
string itemType = _item.Children[0].ItemType;
foreach (var c in _item.Children)
{
if (c.ItemType != itemType)
return false;
if (c.ItemCategory != ItemCategories.Item)
return false;
}
return true;
}
private GroupBox groupBox = null;
private void ShowDropDown(int leftOffset, int top)
{
ComboBox c = new ComboBox()
{
Left = leftOffset + 8,
Top = top,
Width = 500,
DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList,
};
c.SelectedIndexChanged += new EventHandler(this.OnItemSelected);
scrollPanel1.Add(c);
foreach (var child in _item.Children)
{
c.Items.Add(new TagItem(child));
}
top += 24;
groupBox = new GroupBox()
{
Left = leftOffset + 20,
Top = top + 20,
Width = this.Width - 80,
Height = 800,
Text = "",
Anchor = ((AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right))),
};
scrollPanel1.Add(groupBox);
}
private void OnItemSelected(object sender, EventArgs e)
{
groupBox.Controls.Clear();
ConfigurationItem item = ((sender as ComboBox).SelectedItem as TagItem)?.Item;
if (item != null)
{
groupBox.Text = item.DisplayName;
var uc = new SimpleUserControl(item, true, _configApiClient);
uc.Top = 16;
uc.Left = 16;
uc.Height = 780;
uc.Margin = new Padding(20);
uc.Dock = DockStyle.Fill;
uc.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
groupBox.Controls.Add(uc);
}
}
private void ShowAllChildren(int leftOffset, int top)
{
foreach (ConfigurationItem child in _item.Children)
{
if (MainForm._navItemTypes.Contains(child.ItemType)) // Do not repeat what is on the navigation tree
continue;
if ((child.Children == null || child.Children.Length == 0) && child.EnableProperty != null)
{
UserControl uc = new PropertyEnableUserControl(child, ValueChangedHandler, leftOffset, _configApiClient, null);
uc.Width = scrollPanel1.Width;
uc.Location = new Point(leftOffset, top);
uc.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
top += uc.Height;
scrollPanel1.Add(uc);
}
else
{
UserControl uc = new PropertyListUserControl(child, ValueChangedHandler, leftOffset, _configApiClient, null);
uc.Width = scrollPanel1.Width;
uc.Location = new Point(leftOffset, top);
uc.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
top += uc.Height;
scrollPanel1.Add(uc);
}
if (_item.ItemCategory == ItemCategories.Group)
{
// Add save button on individual items as group can not be saved
Button b = new Button() { Text = "Save", Tag = child, UseVisualStyleBackColor = true };
b.Size = new System.Drawing.Size(75, 24);
b.Location = new Point(10, top);
top += b.Height + 10;
b.Click += PerformItemSave;
scrollPanel1.Add(b);
}
}
}
void ValueChangedHandler(object sender, EventArgs e)
{
if (_item.ItemCategory == ItemCategories.Item)
buttonSave.Enabled = true;
if (_privacyMaskUserControl != null)
_privacyMaskUserControl.Refresh();
if (_motionDetectMaskUserControl != null)
_motionDetectMaskUserControl.Refresh();
PropertyUserControl c = sender as PropertyUserControl;
if (c != null)
{
if (c.Property.ServerValidation)
{
PerformItemValidation(sender);
}
}
// TODO: Enable/disable save button on child items?
}
private string _sessionDataId = "0";
private void PerformAction(object sender, EventArgs e)
{
MethodInfo mi = ((Control)sender).Tag as MethodInfo;
if (mi != null)
{
try
{
ConfigurationItem result = _configApiClient.InvokeMethod(_item, mi.MethodId);
if (result != null)
{
Property sessionDataProperty = result.Properties.FirstOrDefault<Property>(p => p.Key == "SessionDataId");
if (sessionDataProperty != null)
{
sessionDataProperty.Value = _sessionDataId;
_sessionDataId = "0";
}
MethodInvokeForm form = new MethodInvokeForm(result, _configApiClient);
form.ShowDialog();
_sessionDataId = form.SessionDataId;
//if (_item.ItemCategory != ItemCategories.ChildItem)
// _item = _configApiClient.GetItem(_item.Path);
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to perform action:" + ex.Message);
}
}
_item = _configApiClient.GetItem(_item.Path);
InitalizeUI();
MainForm.UpdateTree();
}
private void PerformItemSave(object sender, EventArgs e)
{
ConfigurationItem childItem = ((Control)sender).Tag as ConfigurationItem;
if (childItem == null)
return;
try
{
ValidateResult result = _configApiClient.ValidateItem(childItem);
if (result.ValidatedOk)
{
_configApiClient.SetItem(childItem);
// Reload parent item
_item = _configApiClient.GetItem(_item.Path);
}
else
{
if (result.ErrorResults.Any())
{
MessageBox.Show(result.ErrorResults[0].ErrorText, "Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to Save:" + ex.Message);
}
InitalizeUI();
}
private void PerformItemValidation(object sender)
{
string nextToFocusOn = null;
try
{
ValidateResult result = _configApiClient.ValidateItem(_item);
_item = result.ResultItem;
if (!result.ValidatedOk)
{
if (result.ErrorResults.Any())
{
//MessageBox.Show(result.ErrorResults[0].ErrorText, "Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
nextToFocusOn = result.ErrorResults[0].ErrorProperty;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to Validate on server:" + ex.Message);
}
InitalizeUI(nextToFocusOn);
}
private void OnSave(object sender, EventArgs e)
{
try
{
ValidateResult result = _configApiClient.ValidateItem(_item);
if (result.ValidatedOk)
{
string path = _item.Path;
_item = _configApiClient.SetItem(_item).ResultItem;
if (_item == null)
_item = _configApiClient.GetItem(path);
buttonSave.Enabled = false;
}
else
{
if (result.ErrorResults.Any())
{
MessageBox.Show(result.ErrorResults[0].ErrorText, "Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
if (result.ResultItem != null)
_item = result.ResultItem; // new From 2018, March
}
} catch (Exception ex)
{
MessageBox.Show("Unable to Save:" + ex.Message);
}
buttonSave.Enabled = false;
if (_originalName != _item.DisplayName)
{
MainForm.UpdateTree();
if (this.Parent is TabPage)
{
this.Parent.Text = _item.DisplayName;
}
}
InitalizeUI();
}
private void OnEnabledChanged(object sender, EventArgs e)
{
if (EnabledCheckBox.Visible && _item!=null && _item.EnableProperty!=null)
{
_item.EnableProperty.Enabled = EnabledCheckBox.Checked;
if (_item.EnableProperty.UIToFollowEnabled)
{
scrollPanel1.EnableContent = _item.EnableProperty.Enabled || !_item.EnableProperty.UIToFollowEnabled;
}
}
}
}
internal class TagItem
{
internal ConfigurationItem Item { get; set; }
internal TagItem(ConfigurationItem item)
{
Item = item;
}
public override string ToString()
{
return Item.DisplayName;
}
}
}
| 36.667453 | 159 | 0.514504 | [
"MIT"
] | hakimo-ai/mipsdk-samples-component | ConfigApiClient/Panels/SimpleUserControl.cs | 15,549 | C# |
// -----------------------------------------------------------------------
// <copyright file="ScoreboardPacketCommandBase.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------
namespace Starboard.Sockets.Commands
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// TODO: Update summary.
/// </summary>
public abstract class ScoreboardPacketCommandBase : IScoreboardPacketCommand
{
public abstract PacketCommandType PacketType { get; }
public CommandType Command { get; set; }
public byte Player { get; set; }
public abstract byte[] ToBytes();
}
}
| 27.642857 | 80 | 0.536176 | [
"MIT"
] | williamjhagen/TwitchVotingTool | starboard-sc2/Sockets/Commands/ScoreboardPacketCommandBase.cs | 776 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
// [START dialogflow_v3_generated_SessionEntityTypes_GetSessionEntityType_sync]
using Google.Cloud.Dialogflow.Cx.V3;
public sealed partial class GeneratedSessionEntityTypesClientSnippets
{
/// <summary>Snippet for GetSessionEntityType</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetSessionEntityTypeRequestObject()
{
// Create client
SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create();
// Initialize request argument(s)
GetSessionEntityTypeRequest request = new GetSessionEntityTypeRequest
{
SessionEntityTypeName = SessionEntityTypeName.FromProjectLocationAgentSessionEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[SESSION]", "[ENTITY_TYPE]"),
};
// Make the request
SessionEntityType response = sessionEntityTypesClient.GetSessionEntityType(request);
}
}
// [END dialogflow_v3_generated_SessionEntityTypes_GetSessionEntityType_sync]
}
| 43.204545 | 172 | 0.709627 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Dialogflow.Cx.V3/Google.Cloud.Dialogflow.Cx.V3.GeneratedSnippets/SessionEntityTypesClient.GetSessionEntityTypeRequestObjectSnippet.g.cs | 1,901 | C# |
// <copyright file="GlobalSuppressions.cs" company="Okta, Inc">
// Copyright (c) 2018-present Okta, Inc. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
// </copyright>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Reviewed")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA0001XmlCommentAnalysisDisabled", Justification = "Reviewed")]
| 73.125 | 165 | 0.793162 | [
"Apache-2.0"
] | JABIL/okta-aspnet | Okta.AspNet.Abstractions/GlobalSuppressions.cs | 587 | C# |
namespace SimpleSence.Administration.Pages
{
using Serenity.Web;
using System.Web.Mvc;
[RoutePrefix("Administration/Language"), Route("{action=index}")]
[PageAuthorize(typeof(Entities.LanguageRow))]
public class LanguageController : Controller
{
public ActionResult Index()
{
return View(MVC.Views.Administration.Language.LanguageIndex);
}
}
} | 25.625 | 73 | 0.668293 | [
"MIT"
] | davidzhang9990/SimpleProject | SimpleSence.Web/Modules/Administration/Language/LanguagePage.cs | 412 | C# |
using System.Web.Mvc;
using Newtonsoft.Json;
using VAdvantage.Utility;
using VIS.Filters;
namespace VIS.Controllers
{
public class InfoGeneralController : Controller
{
public ActionResult Index()
{
return View();
}
[AjaxAuthorizeAttribute]
[AjaxSessionFilterAttribute]
public JsonResult GetSearchColumns(string tableName)
{
VIS.Models.InfoGeneralModel model = new Models.InfoGeneralModel();
return Json(new { result = model.GetSchema(tableName)}, JsonRequestBehavior.AllowGet);
//return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}
[AjaxAuthorizeAttribute]
[AjaxSessionFilterAttribute]
public JsonResult GetDispalyColumns(int AD_Table_ID)
{
VIS.Models.InfoGeneralModel model = new Models.InfoGeneralModel();
return Json(new { result = model.GetDisplayCol(AD_Table_ID) }, JsonRequestBehavior.AllowGet);
//return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}
[AjaxAuthorizeAttribute]
[AjaxSessionFilterAttribute]
[HttpPost]
[ValidateInput(false)]
public JsonResult GetData(string sql,string tableName)
{
VIS.Models.InfoGeneralModel model = new Models.InfoGeneralModel();
//model.GetSchema(Ad_InfoWindow_ID);
return Json(JsonConvert.SerializeObject(model.GetData(sql, tableName, Session["ctx"] as Ctx)), JsonRequestBehavior.AllowGet);
}
}
} | 35.840909 | 137 | 0.646164 | [
"Apache-2.0"
] | AsimKhan2019/ERP-CMR-DMS | ViennaAdvantageWeb/VIS/Areas/VIS/Controllers/InfoGeneralController.cs | 1,579 | C# |
using UnityEngine;
public class EnumFlagsAttribute : PropertyAttribute { } | 25.333333 | 55 | 0.815789 | [
"MIT"
] | nottvlike/EGP | ECS/UI/Script/EnumFlagsAttribute.cs | 78 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.