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 |
|---|---|---|---|---|---|---|---|---|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DesktopVirtualization.V20201110Preview.Outputs
{
[OutputType]
public sealed class ScalingScheduleResponse
{
/// <summary>
/// Set of days of the week on which this schedule is active.
/// </summary>
public readonly ImmutableArray<string> DaysOfWeek;
/// <summary>
/// Name of the scaling schedule.
/// </summary>
public readonly string? Name;
/// <summary>
/// Load balancing algorithm for off-peak period.
/// </summary>
public readonly string? OffPeakLoadBalancingAlgorithm;
/// <summary>
/// Starting time for off-peak period.
/// </summary>
public readonly string? OffPeakStartTime;
/// <summary>
/// Load balancing algorithm for peak period.
/// </summary>
public readonly string? PeakLoadBalancingAlgorithm;
/// <summary>
/// Starting time for peak period.
/// </summary>
public readonly string? PeakStartTime;
/// <summary>
/// Capacity threshold for ramp down period.
/// </summary>
public readonly int? RampDownCapacityThresholdPct;
/// <summary>
/// Should users be logged off forcefully from hosts.
/// </summary>
public readonly bool? RampDownForceLogoffUsers;
/// <summary>
/// Load balancing algorithm for ramp down period.
/// </summary>
public readonly string? RampDownLoadBalancingAlgorithm;
/// <summary>
/// Minimum host percentage for ramp down period.
/// </summary>
public readonly int? RampDownMinimumHostsPct;
/// <summary>
/// Notification message for users during ramp down period.
/// </summary>
public readonly string? RampDownNotificationMessage;
/// <summary>
/// Starting time for ramp down period.
/// </summary>
public readonly string? RampDownStartTime;
/// <summary>
/// Specifies when to stop hosts during ramp down period.
/// </summary>
public readonly string? RampDownStopHostsWhen;
/// <summary>
/// Number of minutes to wait to stop hosts during ramp down period.
/// </summary>
public readonly int? RampDownWaitTimeMinutes;
/// <summary>
/// Capacity threshold for ramp up period.
/// </summary>
public readonly int? RampUpCapacityThresholdPct;
/// <summary>
/// Load balancing algorithm for ramp up period.
/// </summary>
public readonly string? RampUpLoadBalancingAlgorithm;
/// <summary>
/// Minimum host percentage for ramp up period.
/// </summary>
public readonly int? RampUpMinimumHostsPct;
/// <summary>
/// Starting time for ramp up period.
/// </summary>
public readonly string? RampUpStartTime;
[OutputConstructor]
private ScalingScheduleResponse(
ImmutableArray<string> daysOfWeek,
string? name,
string? offPeakLoadBalancingAlgorithm,
string? offPeakStartTime,
string? peakLoadBalancingAlgorithm,
string? peakStartTime,
int? rampDownCapacityThresholdPct,
bool? rampDownForceLogoffUsers,
string? rampDownLoadBalancingAlgorithm,
int? rampDownMinimumHostsPct,
string? rampDownNotificationMessage,
string? rampDownStartTime,
string? rampDownStopHostsWhen,
int? rampDownWaitTimeMinutes,
int? rampUpCapacityThresholdPct,
string? rampUpLoadBalancingAlgorithm,
int? rampUpMinimumHostsPct,
string? rampUpStartTime)
{
DaysOfWeek = daysOfWeek;
Name = name;
OffPeakLoadBalancingAlgorithm = offPeakLoadBalancingAlgorithm;
OffPeakStartTime = offPeakStartTime;
PeakLoadBalancingAlgorithm = peakLoadBalancingAlgorithm;
PeakStartTime = peakStartTime;
RampDownCapacityThresholdPct = rampDownCapacityThresholdPct;
RampDownForceLogoffUsers = rampDownForceLogoffUsers;
RampDownLoadBalancingAlgorithm = rampDownLoadBalancingAlgorithm;
RampDownMinimumHostsPct = rampDownMinimumHostsPct;
RampDownNotificationMessage = rampDownNotificationMessage;
RampDownStartTime = rampDownStartTime;
RampDownStopHostsWhen = rampDownStopHostsWhen;
RampDownWaitTimeMinutes = rampDownWaitTimeMinutes;
RampUpCapacityThresholdPct = rampUpCapacityThresholdPct;
RampUpLoadBalancingAlgorithm = rampUpLoadBalancingAlgorithm;
RampUpMinimumHostsPct = rampUpMinimumHostsPct;
RampUpStartTime = rampUpStartTime;
}
}
}
| 35.297297
| 81
| 0.628254
|
[
"Apache-2.0"
] |
pulumi/pulumi-azure-nextgen
|
sdk/dotnet/DesktopVirtualization/V20201110Preview/Outputs/ScalingScheduleResponse.cs
| 5,224
|
C#
|
namespace DynamicPowerShellApi.Logging
{
/// <summary>
/// Crash logging.
/// </summary>
public interface ICrashLogger
{
/// <summary>
/// Saves the log entry to a file
/// </summary>
/// <param name="entry">The error entry.</param>
/// <returns>The file name that the error entry became.</returns>
string SaveLog(CrashLogEntry entry);
}
}
| 23.933333
| 67
| 0.660167
|
[
"MIT"
] |
DimensionDataCBUSydney/PowerShell.REST.API
|
Logging/ICrashLogger.cs
| 361
|
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementOrStatementStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchUriPath
{
[OutputConstructor]
private WebAclRuleStatementOrStatementStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchUriPath()
{
}
}
}
| 33.727273
| 157
| 0.787062
|
[
"ECL-2.0",
"Apache-2.0"
] |
Otanikotani/pulumi-aws
|
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementOrStatementStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchUriPath.cs
| 742
|
C#
|
using Application.Mapping;
using Domain.Entities;
using AutoMapper;
using Application.Mapping.Portofilo;
using Application;
namespace Application.Profiles
{
class ApplicationProfile : Profile
{
public ApplicationProfile()
{
//user entity
CreateMap<AllUserDTO, User>();
CreateMap<User, UserByIdDTO>();
CreateMap<UserByIdDTO, User>();
CreateMap<User, AllUserDTO>();
CreateMap<User, LoginUserDTO>();
CreateMap<LoginUserDTO, User>();
CreateMap<UploadImageUserDTO, UserProfile>();
CreateMap<UserProfile, UploadImageUserDTO>();
CreateMap<UserProfileCreateDTO, UserProfile>();
CreateMap<UserProfile, UserProfileCreateDTO>();
CreateMap<UpdateProfileDTO, UserProfile>();
CreateMap<UserProfile, UpdateProfileDTO>();
CreateMap<User, RegisterUserDTO>();
CreateMap<RegisterUserDTO, User>();
CreateMap<UserNameDTO, User>();
CreateMap<User, UserNameDTO>();
//skill entity
CreateMap<Skill,CreateSkillDTo>();
CreateMap<CreateSkillDTo, Skill>();
CreateMap<UpdateSkillDTO,Skill>();
CreateMap<Skill,UpdateSkillDTO >();
//portofilo
CreateMap<PortoFilo,CreatePortoDTO>();
CreateMap<CreatePortoDTO,PortoFilo>();
CreateMap<PortoFilo,UpdatePortofiloDTO>();
CreateMap<UpdatePortofiloDTO, PortoFilo>();
//Blog
CreateMap<User, UserBlogViewModel>();
CreateMap<UserBlogViewModel,User >();
CreateMap<Blog,UpdateBlogDTO>();
CreateMap<UpdateBlogDTO, Blog>();
CreateMap<Blog, CreateBlogDTO>();
CreateMap<CreateBlogDTO,Blog>();
//BlogComment
CreateMap<BlogComment,CreateCommentDTO>();
CreateMap<CreateCommentDTO, BlogComment>();
CreateMap<Blog,BlogGetAllComment>();
CreateMap<BlogGetAllComment, Blog>();
CreateMap<BlogComment,BlogCommentDTO>();
CreateMap<BlogCommentDTO, BlogComment>();
}
}
}
| 35
| 59
| 0.598639
|
[
"Apache-2.0"
] |
DesertFoox/YourPortofilo
|
src/YourPortofilo/Profile/ApplicationProfile.cs
| 2,207
|
C#
|
/*
Copyright (c) 2021 Robert Bosch Manufacturing Solutions GmbH
Author: Monisha Macharla Vasu
This source code is licensed under the Apache License 2.0 (see LICENSE.txt).
This source code may use other Open Source software components (see LICENSE.txt).
*/
// ReSharper disable StringLastIndexOfIsCultureSpecific.1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AasxBammRdfImExport.RDFentities;
using AdminShellNS;
using VDS.RDF;
using VDS.RDF.Parsing;
using VDS.RDF.Writing;
using static AdminShellNS.AdminShellV20;
namespace AasxBammRdfImExport
{
public static class BAMMRDFimport
{
public static AdminShellNS.AdminShellPackageEnv thePackageEnv;
public static void ImportInto(string rdffn, AdminShell.AdministrationShellEnv env, AdminShell.Submodel sm,
AdminShell.SubmodelRef smref)
{
thePackageEnv = new AdminShellNS.AdminShellPackageEnv();
List<string> entity_subject = new List<string>();
List<string> autos_list = new List<string>();
List<string> set_list = new List<string>();
List<string> entity_idshort_prop = new List<string>();
List<string> entity_property_char = new List<string>();
List<string> object_extract = new List<string>();
//parser graphs
IGraph g = new Graph();
TurtleParser ttlparser = new TurtleParser();
ttlparser.Load(g, rdffn);
//initializing aspect
Aspect obj_aspect = new Aspect();
//Lists generated
List<string> properties_list = new List<string>();
List<string> properties_true_list = new List<string>();
List<string> property_set_list = new List<string>();
Entity entity = new Entity();
SubmodelElementCollection set_property = new SubmodelElementCollection();
SubmodelElementCollection et = new SubmodelElementCollection();
SubmodelElementCollection entity_set = new SubmodelElementCollection();
// begin new (temporary) objects
string semantic = "";
string smc_semantic = "";
foreach (Triple t in g.Triples)
{ // Read the aspect name
entity.idShort = (t.Subject.ToString());
if ((t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1)) == "Aspect")
{
obj_aspect.Name = (t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1));
sm.idShort = obj_aspect.Name;
var msemanticID = AdminShell.Key.CreateNew("GlobalReference", false, "IRI", t.Subject.ToString());
AdminShellNS.AdminShellV20.SemanticId smid =
new AdminShellNS.AdminShellV20.SemanticId(msemanticID);
sm.semanticId = smid;
thePackageEnv.AasEnv.Submodels.Add(sm);
}
}
//checks for BAMM entity, and creates a list of subject of entities
foreach (Triple t in g.Triples)
{
if ((t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1)) == "Entity")
{
entity_subject.Add((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1)));
foreach (var month in entity_subject)
{
Console.WriteLine(month);
}
}
}
foreach (string prop in entity_subject)
{
foreach (Triple t in g.Triples)
{
if (((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1)) == prop)
&& ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "properties"))
{
string value = (t.Object.ToString()); //autos7
Console.WriteLine(value); //autos7
autos_list.Add(value);
}
}
}
//algorithm for the child properties to find the SubmodelCollection
foreach (string a in autos_list)
{
string after_rmov = "";
int number = 0;
int b = 0;
foreach (Triple t in g.Triples)
{
string subjectstring = "";
subjectstring = ((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1)));
if ((subjectstring == a) &&
((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1)) == "first"))
{
string object_extract_method = (t.Object.ToString().Substring(
t.Object.ToString().LastIndexOf("#") + 1));
Console.WriteLine(object_extract_method);
object_extract.Add(object_extract_method);
b = 1;
var modified_value = a.Substring(a.Length - 1);
number = int.Parse(modified_value);
after_rmov = (a.Remove(a.LastIndexOf("s") + 1) + (number + b).ToString());
Console.WriteLine(after_rmov);
}
if (((subjectstring) == after_rmov)
&& ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "first"))
{
string object_extract_method = (t.Object.ToString().Substring(
t.Object.ToString().LastIndexOf("#") + 1));
Console.WriteLine(object_extract_method);
object_extract.Add(object_extract_method);
number = number + b;
after_rmov = (a.Remove(a.LastIndexOf("s") + 1) + (number + b).ToString());
Console.WriteLine(after_rmov);
foreach (var month in object_extract)
{
Console.WriteLine(month);
}
}
}
}
//set
// find set from the g.triples and add a list of subject. Then check from the property_list whether
// it contains set object, then assign it to another
//list.
foreach (Triple t in g.Triples)
{
// Read the set name list
if ((t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1)) == "Set")
{
set_list.Add(t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1));
}
}
foreach (string set_accept in properties_list)
{
foreach (Triple t in g.Triples)
{
// Read the properties name list
if ((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1) == set_accept)
&& set_list.Contains((t.Object.ToString().Substring(
t.Object.ToString().LastIndexOf("#") + 1))))
{
//positions
property_set_list.Add(
t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1));
}
}
}
// create a submodelelement for the set subject. list of set smc = set_property
foreach (string prop_set in property_set_list)
{
string property_Name = "";
foreach (Triple t in g.Triples)
{
if ((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1)) == prop_set)
{
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1)) == "name")
{
property_Name = (t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1));
Console.WriteLine(property_Name);
}
AdminShell.Key msemanticID = AdminShell.Key.CreateNew(
"GlobalReference", false, "IRI", semantic);
set_property = AdminShell.SubmodelElementCollection.CreateNew(
property_Name, null, msemanticID);
sm.Add(set_property);
}
}
}
//Identify the entity[n] for the SubmodelCollection (SET)
foreach (string prop in entity_subject)
{
foreach (Triple t in g.Triples)
{
if (((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1)) == prop))
{
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1)) == "name")
{
string entity_set_idshort =
(t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1));
AdminShell.Key msemanticID = AdminShell.Key.CreateNew(
"GlobalReference", false, "IRI", semantic);
entity_set = AdminShell.SubmodelElementCollection.CreateNew(
entity_set_idshort, null, msemanticID);
set_property.Add(entity_set);
}
}
}
}
foreach (var entity_scope in entity_subject) // entity_subject -- t.object --> "entity"
{
foreach (Triple t in g.Triples)
{
// if object == entity_subject and predicate == dataType
//Characteristic_name = subject
if ((t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1) == entity_scope)
&& (t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1)
== "dataType"))
{
//list which datatype of the entity
entity_idshort_prop.Add(
t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1));
}
}
}
//entity_idshort_prop -- spatialpositioncharacteristic
foreach (var characteristic_prop in entity_idshort_prop)
{
foreach (Triple t in g.Triples)
{
if ((t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1)
== characteristic_prop)
&& (t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1)
== "characteristic"))
{
entity_property_char.Add(
t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1));
smc_semantic = t.Subject.ToString();
}
}
}
//Identifying the true properties -- avoiding the SMC from the aspect properties
foreach (Triple t in g.Triples)
{
// Read the properties name list
if ((t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1)) == "Property")
{
properties_list.Add(
t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1));
properties_true_list = properties_list.Except(object_extract).ToList();
properties_true_list = properties_true_list.Except(entity_property_char).ToList();
}
}
foreach (string prop in properties_true_list)
{
string property_Name = "";
string property_ExampleValue = "";
string property_PreferredName = "";
string property_Description = "";
string unit_name = "";
// ReSharper disable once NotAccessedVariable
string characteristic = "";
foreach (Triple t in g.Triples)
{
if ((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1)) == prop)
{
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "name")
{
property_Name =
(t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1));
}
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "preferredName")
{
property_PreferredName =
(t.Object.ToString().Substring((t.Object.ToString().LastIndexOf("#") + 1),
t.Object.ToString().Length - 3));
}
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "description")
{
property_Description =
(t.Object.ToString().Substring((t.Object.ToString().LastIndexOf("#") + 1),
t.Object.ToString().Length - 3));
}
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "exampleValue")
{
property_ExampleValue =
(t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1));
}
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "characteristic")
{
characteristic = (t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1));
}
semantic = (t.Subject.ToString());
}
}
using (var cd = AdminShell.ConceptDescription.CreateNew(
"" + property_Name, AdminShell.Identification.IRI, semantic))
{
env.ConceptDescriptions.Add(cd);
cd.SetIEC61360Spec(
preferredNames: new[] { "EN", property_PreferredName },
shortName: null,
unit: null,
AdminShell.UnitId.CreateNew("GlobalReference", false, "IRI", unit_name),
valueFormat: null,
dataType: "BOOLEAN",
definition: new[] { "EN", property_Description }
);
AdminShell.Key msemanticID = AdminShell.Key.CreateNew("ConceptDescription", true, "IRI", semantic);
var mp = AdminShell.Property.CreateNew(property_Name, null, msemanticID);
mp.valueType = "string";
mp.value = property_ExampleValue;
sm.Add(mp);
}
}
//SMC appended to the Submodel to the AAS
foreach (var charc_prop in entity_property_char)
{
AdminShell.Key msemanticID = AdminShell.Key.CreateNew("ConceptDescription", true, "IRI", smc_semantic);
et = AdminShell.SubmodelElementCollection.CreateNew(charc_prop, null, msemanticID);
sm.Add(et);
}
//SMC elements
foreach (string b in object_extract)
{
string name = "";
string preferred_name = "";
string description = "";
string unit_name = "";
foreach (Triple t in g.Triples)
{
if ((t.Subject.ToString().Substring(t.Subject.ToString().LastIndexOf("#") + 1)) == b)
{
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1)) == "name")
{
name = (t.Object.ToString().Substring(t.Object.ToString().LastIndexOf("#") + 1));
}
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "preferredName")
{
preferred_name = (t.Object.ToString().Substring((t.Object.ToString().LastIndexOf("#") + 1),
t.Object.ToString().Length - 3));
}
if ((t.Predicate.ToString().Substring(t.Predicate.ToString().LastIndexOf("#") + 1))
== "description")
{
description = (t.Object.ToString().Substring((t.Object.ToString().LastIndexOf("#") + 1),
t.Object.ToString().Length - 3));
}
semantic = (t.Subject.ToString());
}
}
using (var cd = AdminShell.ConceptDescription.CreateNew(
"" + name, AdminShell.Identification.IRI, semantic))
{
env.ConceptDescriptions.Add(cd);
cd.SetIEC61360Spec(
preferredNames: new[] { "EN", preferred_name },
shortName: null,
unit: null,
AdminShell.UnitId.CreateNew("GlobalReference", false, "IRI", unit_name),
valueFormat: null,
dataType: "BOOLEAN",
definition: new[] { "EN", description }
);
AdminShell.Key msemanticID = AdminShell.Key.CreateNew("ConceptDescription", true, "IRI", semantic);
var mp = AdminShell.Property.CreateNew(name, null, msemanticID);
mp.valueType = "string";
mp.value = description;
et.Add(mp);
}
}
}
}
}
| 39.530738
| 119
| 0.470219
|
[
"Apache-2.0"
] |
SAidta/aasx-package-explorer
|
src/AasxBammRdfImExport/RDFimport.cs
| 19,291
|
C#
|
using Basket.API.Entities;
using Basket.API.Repositories;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Net;
using System.Threading.Tasks;
namespace Basket.API.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class BasketController : ControllerBase
{
private readonly IBasketRepository _repository;
public BasketController(IBasketRepository repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
[HttpGet("{userName}", Name = "GetBasket")]
[ProducesResponseType(typeof(ShoppingCart), (int)HttpStatusCode.OK)]
public async Task<ActionResult<ShoppingCart>> GetBasket(string userName)
{
var basket = await _repository.GetBasket(userName);
return Ok(basket ?? new ShoppingCart(userName));
}
[HttpPut]
[ProducesResponseType(typeof(ShoppingCart), (int)HttpStatusCode.OK)]
public async Task<ActionResult<ShoppingCart>> UpdateBasket([FromBody] ShoppingCart basket)
{
return Ok(await _repository.UpdateBasket(basket));
}
[HttpDelete("{userName}", Name = "DeleteBasket")]
[ProducesResponseType(typeof(ShoppingCart), (int)HttpStatusCode.OK)]
public async Task<IActionResult> DeleteBasket(string userName)
{
await _repository.DeleteBasket(userName);
return Ok();
}
}
}
| 31.553191
| 98
| 0.66352
|
[
"MIT"
] |
durnasaban/aspnet-microservices
|
src/Services/Basket/Basket.API/Controllers/BasketController.cs
| 1,485
|
C#
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* 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.
*/
// C# Port by Atsushi Eno
// Copyright (C) 2012 Xamarin, Inc. (Apache License, Version 2.0 too)
using System;
using Android.App;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Text;
using Android.Text.Style;
using Android.Views;
using Android.Views.Animations;
using Android.Widget;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
namespace GooglePlayServicesTest
{
[Activity (Label = "Mono GoogleMapV2 MarkerDemo")]
public class MarkerDemoActivity : Android.Support.V4.App.FragmentActivity,
GoogleMap.IOnMarkerClickListener, GoogleMap.IOnInfoWindowClickListener, GoogleMap.IOnMarkerDragListener
{
static readonly LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
static readonly LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
static readonly LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
static readonly LatLng ADELAIDE = new LatLng(-34.92873, 138.59995);
static readonly LatLng PERTH = new LatLng(-31.952854, 115.857342);
/** Demonstrates customizing the info window and/or its contents. */
class CustomInfoWindowAdapter : Java.Lang.Object, GoogleMap.IInfoWindowAdapter {
MarkerDemoActivity parent;
private readonly RadioGroup mOptions;
// These a both viewgroups containing an ImageView with id "badge" and two TextViews with id
// "title" and "snippet".
private readonly View mWindow;
private readonly View mContents;
internal CustomInfoWindowAdapter (MarkerDemoActivity parent)
{
this.parent = parent;
mWindow = parent.LayoutInflater.Inflate (Resource.Layout.custom_info_window, null);
mContents = parent.LayoutInflater.Inflate (Resource.Layout.custom_info_contents, null);
mOptions = (RadioGroup) parent.FindViewById (Resource.Id.custom_info_window_options);
}
public View GetInfoWindow (Marker marker) {
if (mOptions.CheckedRadioButtonId != Resource.Id.custom_info_window) {
// This means that getInfoContents will be called.
return null;
}
Render(marker, mWindow);
return mWindow;
}
public View GetInfoContents (Marker marker) {
if (mOptions.CheckedRadioButtonId != Resource.Id.custom_info_contents) {
// This means that the default info contents will be used.
return null;
}
Render (marker, mContents);
return mContents;
}
private void Render (Marker marker, View view) {
int badge;
// Use the equals() method on a Marker to check for equals. Do not use ==.
if (marker.Equals(parent.mBrisbane)) {
badge = Resource.Drawable.badge_qld;
} else if (marker.Equals(parent.mAdelaide)) {
badge = Resource.Drawable.badge_sa;
} else if (marker.Equals(parent.mSydney)) {
badge = Resource.Drawable.badge_nsw;
} else if (marker.Equals(parent.mMelbourne)) {
badge = Resource.Drawable.badge_victoria;
} else if (marker.Equals(parent.mPerth)) {
badge = Resource.Drawable.badge_wa;
} else {
// Passing 0 to setImageResource will clear the image view.
badge = 0;
}
((ImageView) view.FindViewById (Resource.Id.badge)).SetImageResource (badge);
String title = marker.Title;
TextView titleUi = ((TextView) view.FindViewById (Resource.Id.title));
if (title != null) {
// Spannable string allows us to edit the formatting of the text.
SpannableString titleText = new SpannableString (title);
SpanTypes st = (SpanTypes) 0;
// FIXME: this somehow rejects to compile
//titleText.SetSpan (new ForegroundColorSpan(Color.Red), 0, titleText.Length, st);
titleUi.TextFormatted = (titleText);
} else {
titleUi.Text = ("");
}
String snippet = marker.Snippet;
TextView snippetUi = ((TextView) view.FindViewById(Resource.Id.snippet));
if (snippet != null) {
SpannableString snippetText = new SpannableString(snippet);
snippetText.SetSpan(new ForegroundColorSpan(Color.Magenta), 0, 10, 0);
snippetText.SetSpan(new ForegroundColorSpan(Color.Blue), 12, 21, 0);
snippetUi.TextFormatted = (snippetText);
} else {
snippetUi.Text = ("");
}
}
}
private GoogleMap mMap;
private Marker mPerth;
private Marker mSydney;
private Marker mBrisbane;
private Marker mAdelaide;
private Marker mMelbourne;
private TextView mTopText;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.marker_demo);
mTopText = (TextView) FindViewById (Resource.Id.top_text);
SetUpMapIfNeeded ();
}
protected override void OnResume ()
{
base.OnResume ();
SetUpMapIfNeeded ();
}
private void SetUpMapIfNeeded ()
{
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) SupportFragmentManager.FindFragmentById(Resource.Id.map)).Map;
// Check if we were successful in obtaining the map.
if (mMap != null) {
SetUpMap ();
}
}
}
class GlobalLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
{
Action on_global_layout;
public GlobalLayoutListener (Action onGlobalLayout)
{
on_global_layout = onGlobalLayout;
}
public void OnGlobalLayout ()
{
on_global_layout ();
}
}
private void SetUpMap ()
{
// Hide the zoom controls as the button panel will cover it.
mMap.UiSettings.ZoomControlsEnabled = false;
// Add lots of markers to the map.
AddMarkersToMap();
// Setting an info window adapter allows us to change the both the contents and look of the
// info window.
mMap.SetInfoWindowAdapter (new CustomInfoWindowAdapter (this));
// Set listeners for marker events. See the bottom of this class for their behavior.
mMap.SetOnMarkerClickListener(this);
mMap.SetOnInfoWindowClickListener(this);
mMap.SetOnMarkerDragListener(this);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
View mapView = SupportFragmentManager.FindFragmentById (Resource.Id.map).View;
if (mapView.ViewTreeObserver.IsAlive) {
GlobalLayoutListener gll = null;
gll = new GlobalLayoutListener (
delegate {
LatLngBounds bounds = new LatLngBounds.Builder()
.Include(PERTH)
.Include(SYDNEY)
.Include(ADELAIDE)
.Include(BRISBANE)
.Include(MELBOURNE)
.Build ();
/*if (Build.VERSION.SdkInt < Build.VERSION_CODES.JellyBean)*/ {
mapView.ViewTreeObserver.RemoveGlobalOnLayoutListener (gll);
} /* else {
mapView.ViewTreeObserver.RemoveOnGlobalLayoutListener (this);
}*/
mMap.MoveCamera (CameraUpdateFactory.NewLatLngBounds (bounds, 50));
});
mapView.ViewTreeObserver.AddOnGlobalLayoutListener (gll);
}
}
private void AddMarkersToMap ()
{
// Uses a colored icon.
mBrisbane = mMap.AddMarker(new MarkerOptions()
.SetPosition(BRISBANE)
.SetTitle("Brisbane")
.SetSnippet("Population: 2,074,200")
.InvokeIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueAzure)));
// Uses a custom icon.
mSydney = mMap.AddMarker(new MarkerOptions()
.SetPosition(SYDNEY)
.SetTitle("Sydney")
.SetSnippet("Population: 4,627,300")
.InvokeIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.arrow)));
// Creates a draggable marker. Long press to drag.
mMelbourne = mMap.AddMarker(new MarkerOptions()
.SetPosition(MELBOURNE)
.SetTitle("Melbourne")
.SetSnippet("Population: 4,137,400")
.Draggable(true));
// A few more markers for good measure.
mPerth = mMap.AddMarker(new MarkerOptions()
.SetPosition(PERTH)
.SetTitle("Perth")
.SetSnippet("Population: 1,738,800"));
mAdelaide = mMap.AddMarker(new MarkerOptions()
.SetPosition(ADELAIDE)
.SetTitle("Adelaide")
.SetSnippet("Population: 1,213,000"));
// Creates a marker rainbow demonstrating how to create default marker icons of different
// hues (colors).
int numMarkersInRainbow = 12;
for (int i = 0; i < numMarkersInRainbow; i++) {
mMap.AddMarker(new MarkerOptions()
.SetPosition(new LatLng(
-30 + 10 * Math.Sin(i * Math.PI / (numMarkersInRainbow - 1)),
135 - 10 * Math.Cos(i * Math.PI / (numMarkersInRainbow - 1))))
.SetTitle("Marker " + i)
.InvokeIcon(BitmapDescriptorFactory.DefaultMarker(i * 360 / numMarkersInRainbow)));
}
}
private bool CheckReady ()
{
if (mMap == null) {
Toast.MakeText(this, Resource.String.map_not_ready, ToastLength.Short).Show();
return false;
}
return true;
}
/** Called when the Clear button is clicked. */
[Java.Interop.Export ("onClearMap")]
public void OnClearMap (View view)
{
if (!CheckReady()) {
return;
}
mMap.Clear();
}
/** Called when the Reset button is clicked. */
[Java.Interop.Export ("onResetMap")]
public void OnResetMap(View view)
{
if (!CheckReady()) {
return;
}
// Clear the map because we don't want duplicates of the markers.
mMap.Clear();
AddMarkersToMap();
}
class Runnable : Java.Lang.Object, Java.Lang.IRunnable
{
Action run;
public Runnable (Action run)
{
this.run = run;
}
public void Run ()
{
run ();
}
}
//
// Marker related listeners.
//
public bool OnMarkerClick (Marker marker)
{
// This causes the marker at Perth to bounce into position when it is clicked.
if (marker.Equals(mPerth)) {
Handler handler = new Handler ();
long start = SystemClock.UptimeMillis ();
Projection proj = mMap.Projection;
Point startPoint = proj.ToScreenLocation(PERTH);
startPoint.Offset(0, -100);
LatLng startLatLng = proj.FromScreenLocation(startPoint);
long duration = 1500;
IInterpolator interpolator = new BounceInterpolator();
Runnable run = null;
run = new Runnable (delegate {
long elapsed = SystemClock.UptimeMillis () - start;
float t = interpolator.GetInterpolation ((float) elapsed / duration);
double lng = t * PERTH.Longitude + (1 - t) * startLatLng.Longitude;
double lat = t * PERTH.Latitude + (1 - t) * startLatLng.Latitude;
marker.Position = (new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.PostDelayed(run, 16);
}
});
handler.Post(run);
}
// We return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
public void OnInfoWindowClick (Marker marker) {
Toast.MakeText(BaseContext, "Click Info Window", ToastLength.Short).Show();
}
public void OnMarkerDragStart (Marker marker) {
mTopText.Text = ("onMarkerDragStart");
}
public void OnMarkerDragEnd (Marker marker) {
mTopText.Text = ("onMarkerDragEnd");
}
public void OnMarkerDrag(Marker marker) {
mTopText.Text = ("onMarkerDrag. Current Position: " + marker.Position);
}
}
}
| 33.495935
| 116
| 0.659951
|
[
"Apache-2.0"
] |
aevangelistispot/monodroid-samples
|
GooglePlayServices/GooglePlayServicesTest/Source/MarkerDemoActivity.cs
| 12,360
|
C#
|
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Snippets;
using ICSharpCode.SharpDevelop.Dom.Refactoring;
using ICSharpCode.SharpDevelop.Editor;
using ICSharpCode.SharpDevelop.Editor.AvalonEdit;
using ICSharpCode.SharpDevelop.Refactoring;
using SharpRefactoring.Gui;
namespace SharpRefactoring
{
public class CreatePropertiesCommand : AbstractRefactoringCommand
{
protected override void Run(ITextEditor textEditor, RefactoringProvider provider)
{
new Snippet {
Elements = {
new InlineRefactorSnippetElement(context => CreateProperties.CreateDialog(context), "")
}
}.Insert((TextArea)textEditor.GetService(typeof(TextArea)));
}
}
}
| 43.619048
| 93
| 0.782751
|
[
"MIT"
] |
galich/SharpDevelop
|
src/AddIns/Misc/SharpRefactoring/Project/Src/CreatePropertiesCommand.cs
| 1,834
|
C#
|
using System;
public class Car
{
private const double maxFuel = 160;
private double fuelAmount;
public Car(int hp, double fuelAmount, Tyre tyre)
{
this.Hp = hp;
this.FuelAmount = fuelAmount;
this.Tyre = tyre;
}
public int Hp { get; }
public double FuelAmount
{
get => this.fuelAmount;
private set
{
if (value < 0)
{
throw new ArgumentException(OutputMesseges.OutOfFuel);
}
this.fuelAmount = Math.Min(value, maxFuel);
}
}
public Tyre Tyre { get; private set; }
public void Refuel(double fuelAmount)
{
this.FuelAmount += fuelAmount;
}
public void ChangeTyres(Tyre tyre)
{
this.Tyre = tyre;
}
public void CompleteLap(double trackLenght, double fuelConsumption)
{
this.FuelAmount -= trackLenght * fuelConsumption;
this.Tyre.CompleteLab();
}
}
| 19.196078
| 71
| 0.563841
|
[
"MIT"
] |
ignatovg/Software-University
|
C#-Fundamentals/02_OOP_Basics/Bojo_GrdanPrix/Models/Car.cs
| 981
|
C#
|
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using TwitchDonateToChatroom.Service;
using TwitchDonateToChatroom.Service.Interface;
using TwitchDonateToChatroom.Views;
namespace TwitchDonateToChatroom
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public static ServiceProvider ServiceProvider { get; private set; }
public App()
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
ServiceProvider = serviceCollection.BuildServiceProvider();
}
private void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(typeof(MainWindow));
services.AddSingleton<IOpayCheckService, OpayCheckService>();
services.AddSingleton<IConfigService, ConfigService>();
}
}
}
| 29.051282
| 76
| 0.681377
|
[
"MIT"
] |
TzuHsuan/TwitchDonateToChatroom
|
TwitchDonateToChatroom/App.xaml.cs
| 1,135
|
C#
|
using System.Runtime.Serialization;
namespace AbstractGameLogic {
/// <summary>
/// Направление паралакса.
/// </summary>
[DataContract]
public enum ParallaxDirection {
/// <summary>
/// Слева направо.
/// </summary>
[EnumMember]
LeftToRight ,
/// <summary>
/// Справо налево.
/// </summary>
[EnumMember]
RightToLeft ,
/// <summary>
/// Сверху вниз.
/// </summary>
[EnumMember]
UpToDown ,
/// <summary>
/// Снизу вверх.
/// </summary>
[EnumMember]
DownToUp
}
}
| 14.710526
| 37
| 0.550984
|
[
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] |
trueromanus/ShineGame
|
src/AbstractGameObject/ParallaxDirection.cs
| 625
|
C#
|
using System;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using Nethereum.Hex.HexTypes;
using Nethereum.RPC.Eth;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.RPC.Fee1559Suggestions;
using Nethereum.Util;
namespace Nethereum.RPC.TransactionManagers
{
#if !DOTNET35
public class EtherTransferService : IEtherTransferService
{
private readonly ITransactionManager _transactionManager;
public EtherTransferService(ITransactionManager transactionManager)
{
_transactionManager = transactionManager ?? throw new ArgumentNullException(nameof(transactionManager));
}
public Task<string> TransferEtherAsync(string toAddress, decimal etherAmount, decimal? gasPriceGwei = null, BigInteger? gas = null, BigInteger? nonce = null)
{
var fromAddress = _transactionManager?.Account?.Address;
var transactionInput = EtherTransferTransactionInputBuilder.CreateTransactionInput(fromAddress, toAddress, etherAmount, gasPriceGwei, gas, nonce);
return _transactionManager.SendTransactionAsync(transactionInput);
}
public Task<TransactionReceipt> TransferEtherAndWaitForReceiptAsync(string toAddress, decimal etherAmount, decimal? gasPriceGwei = null, BigInteger? gas = null, BigInteger? nonce = null, CancellationTokenSource tokenSource = null)
{
var fromAddress = _transactionManager?.Account?.Address;
var transactionInput = EtherTransferTransactionInputBuilder.CreateTransactionInput(fromAddress, toAddress, etherAmount, gasPriceGwei, gas, nonce);
return _transactionManager.SendTransactionAndWaitForReceiptAsync(transactionInput, tokenSource);
}
public async Task<decimal> CalculateTotalAmountToTransferWholeBalanceInEtherAsync(string address, decimal gasPriceGwei, BigInteger? gas = null)
{
var ethGetBalance = new EthGetBalance(_transactionManager.Client);
var currentBalance = await ethGetBalance.SendRequestAsync(address).ConfigureAwait(false);
var gasPrice = UnitConversion.Convert.ToWei(gasPriceGwei, UnitConversion.EthUnit.Gwei);
var gasAmount = gas ?? _transactionManager.DefaultGas;
var totalAmount = currentBalance.Value - (gasAmount * gasPrice);
if (totalAmount <= 0) throw new Exception("Insufficient balance to make a transfer");
return UnitConversion.Convert.FromWei(totalAmount);
}
public Task<TransactionReceipt> TransferEtherAndWaitForReceiptAsync(string toAddress, decimal etherAmount, BigInteger maxPriorityFeePerGas, BigInteger maxFeePerGas, BigInteger? gas = null, BigInteger? nonce = null, CancellationTokenSource tokenSource = null)
{
var fromAddress = _transactionManager?.Account?.Address;
var transactionInput = EtherTransferTransactionInputBuilder.CreateTransactionInput(fromAddress, toAddress, etherAmount, maxPriorityFeePerGas, maxFeePerGas, gas, nonce);
return _transactionManager.SendTransactionAndWaitForReceiptAsync(transactionInput, tokenSource);
}
public Task<string> TransferEtherAsync(string toAddress, decimal etherAmount, BigInteger maxPriorityFeePerGas, BigInteger maxFeePerGas, BigInteger? gas = null, BigInteger? nonce = null)
{
//Make the the maxPriorityFee and maxFeePerGas
var fromAddress = _transactionManager?.Account?.Address;
var transactionInput = EtherTransferTransactionInputBuilder.CreateTransactionInput(fromAddress, toAddress, etherAmount, maxPriorityFeePerGas, maxFeePerGas, gas, nonce);
return _transactionManager.SendTransactionAsync(transactionInput);
}
public async Task<Fee1559> SuggestFeeToTransferWholeBalanceInEtherAsync(
BigInteger? maxPriorityFeePerGas = null)
{
var fee1559 = await _transactionManager.Fee1559SuggestionStrategy.SuggestFeeAsync(maxPriorityFeePerGas).ConfigureAwait(false);
//Match it so there are not crumbs
fee1559.MaxPriorityFeePerGas = fee1559.MaxFeePerGas;
return fee1559;
}
public async Task<decimal> CalculateTotalAmountToTransferWholeBalanceInEtherAsync(string address, BigInteger maxFeePerGas, BigInteger? gas = null)
{
var ethGetBalance = new EthGetBalance(_transactionManager.Client);
var currentBalance = await ethGetBalance.SendRequestAsync(address).ConfigureAwait(false);
var gasAmount = gas ?? _transactionManager.DefaultGas;
var totalAmount = currentBalance.Value - (gasAmount * maxFeePerGas);
if (totalAmount <= 0) throw new Exception("Insufficient balance to make a transfer");
return UnitConversion.Convert.FromWei(totalAmount);
}
public async Task<BigInteger> EstimateGasAsync(string toAddress, decimal etherAmount)
{
var fromAddress = _transactionManager?.Account?.Address;
var callInput = (CallInput)EtherTransferTransactionInputBuilder.CreateTransactionInput(fromAddress, toAddress, etherAmount);
var hexEstimate = await _transactionManager.EstimateGasAsync(callInput).ConfigureAwait(false);
return hexEstimate.Value;
}
}
#endif
}
| 54.161616
| 266
| 0.732003
|
[
"MIT"
] |
6ara6aka/Nethereum
|
src/Nethereum.RPC/TransactionManagers/EtherTransferService.cs
| 5,364
|
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 Microsoft.AspNetCore.Mvc.ModelBinding;
using Xunit;
namespace Microsoft.AspNetCore.Mvc
{
public class SerializableErrorTests
{
[Fact]
public void ConvertsModelState_To_Dictionary()
{
// Arrange
var modelState = new ModelStateDictionary();
modelState.AddModelError("key1", "Test Error 1");
modelState.AddModelError("key1", "Test Error 2");
modelState.AddModelError("key2", "Test Error 3");
// Act
var serializableError = new SerializableError(modelState);
// Assert
var arr = Assert.IsType<string[]>(serializableError["key1"]);
Assert.Equal("Test Error 1", arr[0]);
Assert.Equal("Test Error 2", arr[1]);
Assert.Equal("Test Error 3", (serializableError["key2"] as string[])[0]);
}
[Fact]
public void LookupIsCaseInsensitive()
{
// Arrange
var modelState = new ModelStateDictionary();
modelState.AddModelError("key1", "x");
// Act
var serializableError = new SerializableError(modelState);
// Assert
var arr = Assert.IsType<string[]>(serializableError["KEY1"]);
Assert.Equal("x", arr[0]);
}
[Fact]
public void ConvertsModelState_To_Dictionary_AddsDefaultValuesWhenErrorsAreAbsent()
{
// Arrange
var modelState = new ModelStateDictionary();
modelState.AddModelError("key1", "");
// Act
var serializableError = new SerializableError(modelState);
// Assert
var arr = Assert.IsType<string[]>(serializableError["key1"]);
Assert.Equal("The input was not valid.", arr[0]);
}
[Fact]
public void DoesNotThrowOnValidModelState()
{
// Arrange, Act & Assert (does not throw)
new SerializableError(new ModelStateDictionary());
}
[Fact]
public void DoesNotAddEntries_IfNoErrorsArePresent()
{
// Arrange
var modelState = new ModelStateDictionary();
modelState.SetModelValue("key1", "value1", "value1");
modelState.SetModelValue("key2", "value2", "value2");
// Act
var serializableError = new SerializableError(modelState);
// Assert
Assert.Empty(serializableError);
}
}
}
| 32.156627
| 111
| 0.57662
|
[
"Apache-2.0"
] |
belav/aspnetcore
|
src/Mvc/Mvc.Core/test/SerializableErrorTests.cs
| 2,669
|
C#
|
// ================================================================================================================================
// File: ConstraintLineExtractor.cs
// Description:
// ================================================================================================================================
using System;
using BepuUtilities.Collections;
using BepuUtilities.Memory;
using BepuPhysics;
using BepuPhysics.Constraints;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Diagnostics;
using BepuUtilities;
using System.Numerics;
using BepuPhysics.CollisionDetection;
using BepuPhysics.Constraints.Contact;
namespace ContentRenderer.Constraints
{
unsafe interface IConstraintLineExtractor<TPrestep>
{
int LinesPerConstraint { get; }
void ExtractLines(ref TPrestep prestepBundle, int setIndex, int* bodyLocations, Bodies bodies, ref Vector3 tint, ref QuickList<LineInstance> lines);
}
abstract class TypeLineExtractor
{
public abstract int LinesPerConstraint { get; }
public abstract void ExtractLines(Bodies bodies, int setIndex, ref TypeBatch typeBatch, int constraintStart, int constraintCount, ref QuickList<LineInstance> lines);
}
class TypeLineExtractor<T, TBodyReferences, TPrestep, TProjection, TAccumulatedImpulses> : TypeLineExtractor
where TPrestep : struct
where T : struct, IConstraintLineExtractor<TPrestep>
{
public override int LinesPerConstraint => default(T).LinesPerConstraint;
public unsafe override void ExtractLines(Bodies bodies, int setIndex, ref TypeBatch typeBatch, int constraintStart, int constraintCount,
ref QuickList<LineInstance> lines)
{
ref var prestepStart = ref Buffer<TPrestep>.Get(ref typeBatch.PrestepData, 0);
ref var referencesStart = ref Buffer<TBodyReferences>.Get(ref typeBatch.BodyReferences, 0);
//For now, we assume that TBodyReferences is always a series of contiguous Vector<int> values.
//We can extract each body by abusing the memory layout.
var bodyCount = Unsafe.SizeOf<TBodyReferences>() / Unsafe.SizeOf<Vector<int>>();
Debug.Assert(bodyCount * Unsafe.SizeOf<Vector<int>>() == Unsafe.SizeOf<TBodyReferences>());
var bodyIndices = stackalloc int[bodyCount];
var extractor = default(T);
var constraintEnd = constraintStart + constraintCount;
if (setIndex == 0)
{
var tint = new Vector3(1, 1, 1);
for (int i = constraintStart; i < constraintEnd; ++i)
{
BundleIndexing.GetBundleIndices(i, out var bundleIndex, out var innerIndex);
ref var prestepBundle = ref Unsafe.Add(ref prestepStart, bundleIndex);
ref var referencesBundle = ref Unsafe.Add(ref referencesStart, bundleIndex);
ref var firstReference = ref Unsafe.As<TBodyReferences, Vector<int>>(ref referencesBundle);
for (int j = 0; j < bodyCount; ++j)
{
//Active set constraint body references refer directly to the body index.
bodyIndices[j] = GatherScatter.Get(ref Unsafe.Add(ref firstReference, j), innerIndex);
}
extractor.ExtractLines(ref GatherScatter.GetOffsetInstance(ref prestepBundle, innerIndex), setIndex, bodyIndices, bodies, ref tint, ref lines);
}
}
else
{
var tint = new Vector3(0.4f, 0.4f, 0.8f);
for (int i = constraintStart; i < constraintEnd; ++i)
{
BundleIndexing.GetBundleIndices(i, out var bundleIndex, out var innerIndex);
ref var prestepBundle = ref Unsafe.Add(ref prestepStart, bundleIndex);
ref var referencesBundle = ref Unsafe.Add(ref referencesStart, bundleIndex);
ref var firstReference = ref Unsafe.As<TBodyReferences, Vector<int>>(ref referencesBundle);
for (int j = 0; j < bodyCount; ++j)
{
//Inactive constraints store body references in the form of handles, so we have to follow the indirection.
var bodyHandle = GatherScatter.Get(ref Unsafe.Add(ref firstReference, j), innerIndex);
Debug.Assert(bodies.HandleToLocation[bodyHandle].SetIndex == setIndex);
bodyIndices[j] = bodies.HandleToLocation[bodyHandle].Index;
}
extractor.ExtractLines(ref GatherScatter.GetOffsetInstance(ref prestepBundle, innerIndex), setIndex, bodyIndices, bodies, ref tint, ref lines);
}
}
}
}
internal class ConstraintLineExtractor : IDisposable
{
TypeLineExtractor[] lineExtractors;
const int jobsPerThread = 4;
QuickList<ThreadJob> jobs;
BufferPool pool;
struct ThreadJob
{
public int SetIndex;
public int BatchIndex;
public int TypeBatchIndex;
public int ConstraintStart;
public int ConstraintCount;
public int LineStart;
public int LinesPerConstraint;
public QuickList<LineInstance> jobLines;
}
public bool Enabled { get; set; } = true;
Action<int> executeJobDelegate;
ref TypeLineExtractor AllocateSlot(int typeId)
{
if (typeId >= lineExtractors.Length)
Array.Resize(ref lineExtractors, typeId + 1);
return ref lineExtractors[typeId];
}
public ConstraintLineExtractor(BufferPool pool)
{
this.pool = pool;
lineExtractors = new TypeLineExtractor[32];
AllocateSlot(BallSocketTypeProcessor.BatchTypeId) = new TypeLineExtractor<BallSocketLineExtractor, TwoBodyReferences, BallSocketPrestepData, BallSocketProjection, Vector3Wide>();
AllocateSlot(WeldTypeProcessor.BatchTypeId) = new TypeLineExtractor<WeldLineExtractor, TwoBodyReferences, WeldPrestepData, WeldProjection, WeldAccumulatedImpulses>();
AllocateSlot(DistanceServoTypeProcessor.BatchTypeId) = new TypeLineExtractor<DistanceServoLineExtractor, TwoBodyReferences, DistanceServoPrestepData, DistanceServoProjection, Vector<float>>();
AllocateSlot(DistanceLimitTypeProcessor.BatchTypeId) = new TypeLineExtractor<DistanceLimitLineExtractor, TwoBodyReferences, DistanceLimitPrestepData, DistanceLimitProjection, Vector<float>>();
AllocateSlot(CenterDistanceTypeProcessor.BatchTypeId) = new TypeLineExtractor<CenterDistanceLineExtractor, TwoBodyReferences, CenterDistancePrestepData, CenterDistanceProjection, Vector<float>>();
AllocateSlot(PointOnLineServoTypeProcessor.BatchTypeId) = new TypeLineExtractor<PointOnLineLineExtractor, TwoBodyReferences, PointOnLineServoPrestepData, PointOnLineServoProjection, Vector2Wide>();
AllocateSlot(LinearAxisServoTypeProcessor.BatchTypeId) = new TypeLineExtractor<LinearAxisServoLineExtractor, TwoBodyReferences, LinearAxisServoPrestepData, LinearAxisServoProjection, Vector<float>>();
AllocateSlot(AngularSwivelHingeTypeProcessor.BatchTypeId) = new TypeLineExtractor<AngularSwivelHingeLineExtractor, TwoBodyReferences, AngularSwivelHingePrestepData, AngularSwivelHingeProjection, Vector<float>>();
AllocateSlot(SwivelHingeTypeProcessor.BatchTypeId) = new TypeLineExtractor<SwivelHingeLineExtractor, TwoBodyReferences, SwivelHingePrestepData, SwivelHingeProjection, Vector4Wide>();
AllocateSlot(HingeTypeProcessor.BatchTypeId) = new TypeLineExtractor<HingeLineExtractor, TwoBodyReferences, HingePrestepData, HingeProjection, HingeAccumulatedImpulses>();
AllocateSlot(OneBodyLinearServoTypeProcessor.BatchTypeId) = new TypeLineExtractor<OneBodyLinearServoLineExtractor, Vector<int>, OneBodyLinearServoPrestepData, OneBodyLinearServoProjection, Vector<float>>();
AllocateSlot(Contact1OneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact1OneBodyLineExtractor, Vector<int>, Contact1OneBodyPrestepData, Contact1OneBodyProjection, Contact1AccumulatedImpulses>();
AllocateSlot(Contact2OneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact2OneBodyLineExtractor, Vector<int>, Contact2OneBodyPrestepData, Contact2OneBodyProjection, Contact2AccumulatedImpulses>();
AllocateSlot(Contact3OneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact3OneBodyLineExtractor, Vector<int>, Contact3OneBodyPrestepData, Contact3OneBodyProjection, Contact3AccumulatedImpulses>();
AllocateSlot(Contact4OneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact4OneBodyLineExtractor, Vector<int>, Contact4OneBodyPrestepData, Contact4OneBodyProjection, Contact4AccumulatedImpulses>();
AllocateSlot(Contact1TypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact1LineExtractor, TwoBodyReferences, Contact1PrestepData, Contact1Projection, Contact1AccumulatedImpulses>();
AllocateSlot(Contact2TypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact2LineExtractor, TwoBodyReferences, Contact2PrestepData, Contact2Projection, Contact2AccumulatedImpulses>();
AllocateSlot(Contact3TypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact3LineExtractor, TwoBodyReferences, Contact3PrestepData, Contact3Projection, Contact3AccumulatedImpulses>();
AllocateSlot(Contact4TypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact4LineExtractor, TwoBodyReferences, Contact4PrestepData, Contact4Projection, Contact4AccumulatedImpulses>();
AllocateSlot(Contact2NonconvexOneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact2NonconvexOneBodyLineExtractor, Vector<int>, Contact2NonconvexOneBodyPrestepData, Contact2NonconvexOneBodyProjection, Contact2NonconvexAccumulatedImpulses>();
AllocateSlot(Contact3NonconvexOneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact3NonconvexOneBodyLineExtractor, Vector<int>, Contact3NonconvexOneBodyPrestepData, Contact3NonconvexOneBodyProjection, Contact3NonconvexAccumulatedImpulses>();
AllocateSlot(Contact4NonconvexOneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact4NonconvexOneBodyLineExtractor, Vector<int>, Contact4NonconvexOneBodyPrestepData, Contact4NonconvexOneBodyProjection, Contact4NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact5NonconvexOneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact5NonconvexOneBodyLineExtractor, Vector<int>, Contact5NonconvexOneBodyPrestepData, Contact5NonconvexOneBodyProjection, Contact5NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact6NonconvexOneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact6NonconvexOneBodyLineExtractor, Vector<int>, Contact6NonconvexOneBodyPrestepData, Contact6NonconvexOneBodyProjection, Contact6NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact7NonconvexOneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact7NonconvexOneBodyLineExtractor, Vector<int>, Contact7NonconvexOneBodyPrestepData, Contact7NonconvexOneBodyProjection, Contact7NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact8NonconvexOneBodyTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact8NonconvexOneBodyLineExtractor, Vector<int>, Contact8NonconvexOneBodyPrestepData, Contact8NonconvexOneBodyProjection, Contact8NonconvexAccumulatedImpulses>();
AllocateSlot(Contact2NonconvexTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact2NonconvexLineExtractor, TwoBodyReferences, Contact2NonconvexPrestepData, Contact2NonconvexProjection, Contact2NonconvexAccumulatedImpulses>();
AllocateSlot(Contact3NonconvexTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact3NonconvexLineExtractor, TwoBodyReferences, Contact3NonconvexPrestepData, Contact3NonconvexProjection, Contact3NonconvexAccumulatedImpulses>();
AllocateSlot(Contact4NonconvexTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact4NonconvexLineExtractor, TwoBodyReferences, Contact4NonconvexPrestepData, Contact4NonconvexProjection, Contact4NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact5NonconvexTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact5NonconvexLineExtractor, TwoBodyReferences, Contact5NonconvexPrestepData, Contact5NonconvexProjection, Contact5NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact6NonconvexTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact6NonconvexLineExtractor, TwoBodyReferences, Contact6NonconvexPrestepData, Contact6NonconvexProjection, Contact6NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact7NonconvexTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact7NonconvexLineExtractor, TwoBodyReferences, Contact7NonconvexPrestepData, Contact7NonconvexProjection, Contact7NonconvexAccumulatedImpulses>();
//AllocateSlot(Contact8NonconvexTypeProcessor.BatchTypeId) = new TypeLineExtractor<Contact8NonconvexLineExtractor, TwoBodyReferences, Contact8NonconvexPrestepData, Contact8NonconvexProjection, Contact8NonconvexAccumulatedImpulses>();
jobs = new QuickList<ThreadJob>(Environment.ProcessorCount * (jobsPerThread + 1), pool);
executeJobDelegate = ExecuteJob;
}
Bodies bodies;
Solver solver;
private void ExecuteJob(int jobIndex)
{
ref var job = ref jobs[jobIndex];
ref var typeBatch = ref solver.Sets[job.SetIndex].Batches[job.BatchIndex].TypeBatches[job.TypeBatchIndex];
Debug.Assert(lineExtractors[typeBatch.TypeId] != null, "Jobs should only be created for types which are registered and used.");
lineExtractors[typeBatch.TypeId].ExtractLines(bodies, job.SetIndex, ref typeBatch, job.ConstraintStart, job.ConstraintCount, ref job.jobLines);
}
internal void AddInstances(Bodies bodies, Solver solver, bool showConstraints, bool showContacts, ref QuickList<LineInstance> lines, ParallelLooper looper)
{
int neededLineCapacity = lines.Count;
jobs.Count = 0;
for (int setIndex = 0; setIndex < solver.Sets.Length; ++setIndex)
{
ref var set = ref solver.Sets[setIndex];
if (set.Allocated)
{
for (int batchIndex = 0; batchIndex < set.Batches.Count; ++batchIndex)
{
ref var batch = ref set.Batches[batchIndex];
for (int typeBatchIndex = 0; typeBatchIndex < batch.TypeBatches.Count; ++typeBatchIndex)
{
ref var typeBatch = ref batch.TypeBatches[typeBatchIndex];
if (typeBatch.TypeId >= lineExtractors.Length)
continue; //No registered extractor for this type, clearly.
var extractor = lineExtractors[typeBatch.TypeId];
var isContactBatch = NarrowPhase.IsContactConstraintType(typeBatch.TypeId);
if (extractor != null && ((isContactBatch && showContacts) || (!isContactBatch && showConstraints)))
{
jobs.Add(new ThreadJob
{
SetIndex = setIndex,
BatchIndex = batchIndex,
TypeBatchIndex = typeBatchIndex,
ConstraintStart = 0,
ConstraintCount = typeBatch.ConstraintCount,
LineStart = neededLineCapacity,
LinesPerConstraint = extractor.LinesPerConstraint
}, pool);
neededLineCapacity += extractor.LinesPerConstraint * typeBatch.ConstraintCount;
}
}
}
}
}
var maximumJobSize = Math.Max(1, neededLineCapacity / (jobsPerThread * Environment.ProcessorCount));
var originalJobCount = jobs.Count;
//Split jobs if they're larger than desired to help load balancing a little bit. This isn't terribly important, but it's pretty easy.
for (int i = 0; i < originalJobCount; ++i)
{
ref var job = ref jobs[i];
if (job.ConstraintCount > maximumJobSize)
{
var subjobCount = (int)Math.Round(0.5 + job.ConstraintCount / (double)maximumJobSize);
var constraintsPerSubjob = job.ConstraintCount / subjobCount;
var remainder = job.ConstraintCount - constraintsPerSubjob * subjobCount;
//Modify the first job in place.
job.ConstraintCount = constraintsPerSubjob;
if (remainder > 0)
++job.ConstraintCount;
//Append the remaining jobs.
var previousJob = job;
for (int j = 1; j < subjobCount; ++j)
{
var newJob = previousJob;
newJob.LineStart += previousJob.ConstraintCount * newJob.LinesPerConstraint;
newJob.ConstraintStart += previousJob.ConstraintCount;
newJob.ConstraintCount = constraintsPerSubjob;
if (remainder > j)
++newJob.ConstraintCount;
jobs.Add(newJob, pool);
previousJob = newJob;
}
}
}
lines.EnsureCapacity(neededLineCapacity, pool);
lines.Count = neededLineCapacity; //Line additions will be performed on suballocated lists. This count will be used by the renderer when reading line data.
for (int i = 0; i < jobs.Count; ++i)
{
//Creating a local copy of the list reference and count allows additions to proceed in parallel.
jobs[i].jobLines = new QuickList<LineInstance>(lines.Span);
//By setting the count, we work around the fact that Array<T> doesn't support slicing.
jobs[i].jobLines.Count = jobs[i].LineStart;
}
this.bodies = bodies;
this.solver = solver;
looper.For(0, jobs.Count, executeJobDelegate);
this.bodies = null;
this.solver = solver;
}
public void Dispose()
{
jobs.Dispose(pool);
}
}
}
| 71.469925
| 267
| 0.673715
|
[
"MIT"
] |
Swaelo/mmo-server-2.0
|
ContentRenderer/Constraints/ConstraintLineExtractor.cs
| 19,013
|
C#
|
//*********************************************************
//
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System.Linq;
using Windows.UI.Input.Inking;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
namespace XAMLShapesAdvancedManipulations
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
// Initialize the InkCanvas
inkCanvas.InkPresenter.InputDeviceTypes =
Windows.UI.Core.CoreInputDeviceTypes.Mouse |
Windows.UI.Core.CoreInputDeviceTypes.Pen |
Windows.UI.Core.CoreInputDeviceTypes.Touch;
// When the user finished to draw something on the InkCanvas
inkCanvas.InkPresenter.StrokesCollected += InkPresenter_StrokesCollected;
}
private void InkPresenter_StrokesCollected(
Windows.UI.Input.Inking.InkPresenter sender,
Windows.UI.Input.Inking.InkStrokesCollectedEventArgs args)
{
InkStroke stroke = inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Last();
// Action 1 = We use a function that we will implement just after to create the XAML Line
Line line = ConvertStrokeToXAMLLine(stroke);
// Action 2 = We add the Line in the second Canvas
ShapesCanvas.Children.Add(line);
// We delete the InkStroke from the InkCanvas
stroke.Selected = true;
inkCanvas.InkPresenter.StrokeContainer.DeleteSelected();
}
private Line ConvertStrokeToXAMLLine(InkStroke stroke)
{
var line = new Line();
line.Stroke = new SolidColorBrush(Windows.UI.Colors.Green);
line.StrokeThickness = 6;
// The origin = (X1, Y1)
line.X1 = stroke.GetInkPoints().First().Position.X;
line.Y1 = stroke.GetInkPoints().First().Position.Y;
// The end = (X2, Y2)
line.X2 = stroke.GetInkPoints().Last().Position.X;
line.Y2 = stroke.GetInkPoints().Last().Position.Y;
// Draw the anchors and initiate the advanced drag & drop functionalities
line.Tapped += Line_Tapped;
return line;
}
// XAML Shapes manipulations
private TranslateTransform dragTranslation;
private void Line_Tapped(object sender, TappedRoutedEventArgs e)
{
// Remove the anchor from the selected line
UnselectActiveLine();
Line line = (Line)sender;
line.Stroke = new SolidColorBrush(Windows.UI.Colors.DarkRed);
line.StrokeThickness = 10;
int size_EndLines = 25;
// Create 2 circles for the ends of the line
Ellipse anchorOrigin = new Ellipse
{
Fill = new SolidColorBrush(Windows.UI.Colors.OrangeRed),
Height = size_EndLines,
Width = size_EndLines
};
ShapesCanvas.Children.Add(anchorOrigin);
Ellipse anchorEnd = new Ellipse
{
Fill = new SolidColorBrush(Windows.UI.Colors.OrangeRed),
Height = size_EndLines,
Width = size_EndLines
};
ShapesCanvas.Children.Add(anchorEnd);
// Put the anchors at the origin and at the end of the line
Canvas.SetLeft(anchorOrigin, line.X1 - size_EndLines / 2);
Canvas.SetLeft(anchorEnd, line.X2 - size_EndLines / 2);
Canvas.SetTop(anchorOrigin, line.Y1 - size_EndLines / 2);
Canvas.SetTop(anchorEnd, line.Y2 - size_EndLines / 2);
// Enable manipulations on the anchors
anchorOrigin.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY;
anchorOrigin.ManipulationStarted += Anchor_ManipulationStarted;
anchorOrigin.ManipulationDelta += Anchor_Origin_ManipulationDelta;
anchorOrigin.ManipulationCompleted += Anchor_Origin_ManipulationCompleted;
anchorEnd.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY;
anchorEnd.ManipulationStarted += Anchor_ManipulationStarted;
anchorEnd.ManipulationDelta += Anchor_End_ManipulationDelta;
anchorEnd.ManipulationCompleted += Anchor_End_ManipulationCompleted;
InitializeActiveLine(line, anchorOrigin, anchorEnd);
}
private void Anchor_ManipulationStarted(object sender,
ManipulationStartedRoutedEventArgs e)
{
Ellipse anchor = (Ellipse)sender;
// Initialize the transforms that will be used to manipulate the shape
dragTranslation = new TranslateTransform();
anchor.RenderTransform = dragTranslation;
anchor.Fill = new SolidColorBrush(Windows.UI.Colors.Orange);
}
private void Anchor_Origin_ManipulationDelta(object sender,
ManipulationDeltaRoutedEventArgs e)
{
AnchorManipulationDelta(sender, e, true);
}
private void Anchor_End_ManipulationDelta(object sender,
ManipulationDeltaRoutedEventArgs e)
{
AnchorManipulationDelta(sender, e, false);
}
private void AnchorManipulationDelta(object sender,
ManipulationDeltaRoutedEventArgs e,
bool OriginofLine)
{
double x = e.Delta.Translation.X;
double y = e.Delta.Translation.Y;
dragTranslation.X += x;
dragTranslation.Y += y;
if (OriginofLine)
{
activeLine.line.X1 += x;
activeLine.line.Y1 += y;
}
else
{
activeLine.line.X2 += x;
activeLine.line.Y2 += y;
}
}
private void Anchor_Origin_ManipulationCompleted(object sender,
ManipulationCompletedRoutedEventArgs e)
{
AnchorManipulationCompleted(sender, e, true);
}
private void Anchor_End_ManipulationCompleted(object sender,
ManipulationCompletedRoutedEventArgs e)
{
AnchorManipulationCompleted(sender, e, false);
}
private void AnchorManipulationCompleted(object sender,
ManipulationCompletedRoutedEventArgs e,
bool OriginofLine)
{
Ellipse anchor = (Ellipse)sender;
anchor.RenderTransform = null;
double x = e.Cumulative.Translation.X;
double y = e.Cumulative.Translation.Y;
Canvas.SetLeft(anchor, Canvas.GetLeft(anchor) + x);
Canvas.SetTop(anchor, Canvas.GetTop(anchor) + y);
anchor.Fill = new SolidColorBrush(Windows.UI.Colors.Black);
if (OriginofLine)
{
activeLine.line.X1 = activeLine.initialX1 + x;
activeLine.line.Y1 = activeLine.initialY1 + y;
activeLine.initialX1 = activeLine.line.X1;
activeLine.initialY1 = activeLine.line.Y1;
}
else
{
activeLine.line.X2 = activeLine.initialX2 + x;
activeLine.line.Y2 = activeLine.initialY2 + y;
activeLine.initialX2 = activeLine.line.X2;
activeLine.initialY2 = activeLine.line.Y2;
}
}
/// <summary>
/// Take this line as the one to be modified with the anchors
/// Selecting the line is:
/// - get the line object
/// - keep track of its coordinates
/// - get the 2 anchors objects
/// </summary>
private void InitializeActiveLine(Line line, Ellipse origin, Ellipse end)
{
activeLine.line = line;
activeLine.initialX1 = line.X1;
activeLine.initialY1 = line.Y1;
activeLine.initialX2 = line.X2;
activeLine.initialY2 = line.Y2;
activeLine.AnchorOrigin = origin;
activeLine.AnchorEnd = end;
}
/// <summary>
/// Before doing manipulations on the newly selected line, we put back the origina color
/// of the previous line and we remove its the anchors from the screen
/// </summary>
public void UnselectActiveLine()
{
if (activeLine.line != null
&& activeLine.AnchorOrigin != null
&& activeLine.AnchorEnd != null)
{
activeLine.line.Stroke = new SolidColorBrush(Windows.UI.Colors.Green);
activeLine.line.StrokeThickness = 6;
ShapesCanvas.Children.Remove(activeLine.AnchorOrigin);
ShapesCanvas.Children.Remove(activeLine.AnchorEnd);
}
}
/// <summary>
/// We doing manipulations on the anchors of a line, we move the line position
/// in real time, so we have to keep track about the line's original position
/// in order to do the definitive move when the manipulation is completed.
/// We also move the anchors during the manipulation.
/// </summary>
private struct ActiveLine
{
public Line line;
public double initialX1;
public double initialY1;
public double initialX2;
public double initialY2;
public Ellipse AnchorOrigin;
public Ellipse AnchorEnd;
}
private ActiveLine activeLine;
}
}
| 30.924528
| 95
| 0.721049
|
[
"MIT"
] |
jonthysell/Windows-AppConsult-Samples-UWP
|
UWP-Advanced-Inking/XAMLShapesAdvancedManipulations/XAMLShapesAdvancedManipulations/MainPage.xaml.cs
| 8,197
|
C#
|
using UnityEngine;
public class RoadPreview : MonoBehaviour, IBigridTransform, IValidatable {
public Transform head;
public Transform body;
public Transform tail;
public Renderer headRenderer;
public Renderer bodyRenderer;
public Renderer tailRenderer;
public Material validBodyMaterial;
public Material validEndMaterial;
public Material invalidBodyMaterial;
public Material invalidEndMaterial;
private Grid startGrid;
private Grid endGrid;
private float roadLength;
private bool valid;
private string invalidStatus;
public Grid StartGrid {
get {
return startGrid;
}
set {
startGrid = value;
if (startGrid != null && endGrid != null) {
Vector3 roadVector = endGrid.Coordinates - startGrid.Coordinates;
Vector3 forwardDirection = (roadVector == Vector3.zero) ? Vector3.forward : roadVector.normalized;
transform.rotation = Quaternion.LookRotation(forwardDirection, Vector3.up);
roadLength = roadVector.magnitude;
head.position = tail.position - forwardDirection * roadLength;
body.localScale = new Vector3(
(roadLength == 0.0f) ? 0.0f : 1.0f,
(roadLength == 0.0f) ? 0.0f : 1.0f,
roadLength);
bodyRenderer.material.mainTextureScale = new Vector2(bodyRenderer.material.mainTextureScale.x, roadLength);
}
Validate();
}
}
public Grid EndGrid {
get {
return endGrid;
}
set {
endGrid = value;
if (startGrid != null && endGrid != null) {
Vector3 roadVector = endGrid.Coordinates - startGrid.Coordinates;
Vector3 forwardDirection = (roadVector == Vector3.zero) ? Vector3.forward : roadVector.normalized;
transform.rotation = Quaternion.LookRotation(forwardDirection, Vector3.up);
roadLength = roadVector.magnitude;
body.localScale = new Vector3(
(roadLength == 0.0f) ? 0.0f : 1.0f,
(roadLength == 0.0f) ? 0.0f : 1.0f,
roadLength);
bodyRenderer.material.mainTextureScale = new Vector2(bodyRenderer.material.mainTextureScale.x, roadLength);
tail.position = head.position + forwardDirection * roadLength;
}
Validate();
}
}
public void Split(Grid intermediateGrid, out IBigridTransform head, out IBigridTransform tail) {
head = null;
tail = null;
return;
}
public float RoadLength {
get {
return roadLength;
}
}
public bool IsValid {
get {
return valid;
}
set {
valid = value;
invalidStatus = valid ? "" : invalidStatus;
bodyRenderer.material = valid ? validBodyMaterial : invalidBodyMaterial;
bodyRenderer.material.mainTextureScale = new Vector2(bodyRenderer.material.mainTextureScale.x, roadLength);
headRenderer.material = tailRenderer.material = valid ? validEndMaterial : invalidEndMaterial;
}
}
public string InvalidStatus {
get {
return invalidStatus;
}
}
public void Validate() {
if (startGrid == null || endGrid == null) {
IsValid = false;
invalidStatus = "No end grid selected";
return;
}
if (startGrid == endGrid) {
IsValid = false;
invalidStatus = "Same start and end grids";
return;
}
if (CalculateSqrSlope() > 0.041f) {
IsValid = false;
invalidStatus = "Road too steep!";
return;
}
// Check for intersection with occupied grids
Vector3 rayVector = endGrid.transform.position - startGrid.transform.position;
RaycastHit hitInfo;
if (Physics.SphereCast(
startGrid.transform.position + Vector3.up * startGrid.transform.localScale.y * 0.5f,
startGrid.transform.localScale.y * 0.392f, // The min sphere radius to disallow < 20% slope
rayVector.normalized,
out hitInfo,
rayVector.magnitude,
LayerUtils.Mask.OCCUPIED_GRID)) {
IsValid = false;
invalidStatus = "Road obstructed";
return;
}
IsValid = true;
}
private float CalculateSqrSlope() {
Vector2 flattenedRoadVector = new Vector2(
endGrid.Coordinates.x - startGrid.Coordinates.x,
endGrid.Coordinates.z - startGrid.Coordinates.z);
float sqrLength = Vector2.SqrMagnitude(flattenedRoadVector);
float sqrHeight = Mathf.Pow(endGrid.Coordinates.y - startGrid.Coordinates.y, 2);
return sqrHeight / sqrLength;
}
}
| 26.679739
| 111
| 0.712641
|
[
"Unlicense",
"MIT"
] |
AlvianPrasetya/TrafficPlanner
|
Assets/Scripts/Game/Previews/RoadPreview.cs
| 4,084
|
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.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.FileSystemGlobbing.Util;
namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PathSegments
{
public class LiteralPathSegment : IPathSegment
{
private readonly StringComparison _comparisonType;
public bool CanProduceStem => false;
public LiteralPathSegment(string value!!, StringComparison comparisonType)
{
Value = value;
_comparisonType = comparisonType;
}
public string Value { get; }
public bool Match(string value)
{
return string.Equals(Value, value, _comparisonType);
}
public override bool Equals([NotNullWhen(true)] object? obj)
{
return obj is LiteralPathSegment other &&
_comparisonType == other._comparisonType &&
string.Equals(other.Value, Value, _comparisonType);
}
public override int GetHashCode()
{
return StringComparisonHelper.GetStringComparer(_comparisonType).GetHashCode(Value);
}
}
}
| 30.02381
| 96
| 0.66138
|
[
"MIT"
] |
AUTOMATE-2001/runtime
|
src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs
| 1,261
|
C#
|
namespace Vendstor.Backend.Constants
{
public static class Constants
{
/// <summary>
/// This is the url to access the remote REST API.
/// </summary>
public static readonly string ApiUrl = "http://rigle.co/vendstor/api";
/// <summary>
/// This is the token used to authenticate with the remote REST API
/// </summary>
public static readonly string ApiAuthToken = "9d8a22dcff084215cd7e6187427c9b1d";
/// <summary>
/// This is the unique ID which indicates which software in the database is installed
/// This is used to determine if the software is outdated or not
/// </summary>
public static readonly string SoftwareId = "a0e6d48c2ba4db74e55ca4f6565aad4d";
}
}
| 39
| 93
| 0.638462
|
[
"MIT"
] |
franznkemaka/Vendstor
|
Vendstor/Backend/Constants/Constants.cs
| 782
|
C#
|
using ClosedXML.Excel;
using SimpleInventory.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace SimpleInventory.Helpers
{
class StockInfoExcelGenerator
{
public void ExportStockInfo(List<DetailedStockReportInfo> items, DateTime startDate, DateTime endDate, string path)
{
items.Sort((a, b) => (a.Item.Name + a.Item.Description).ToLower().CompareTo((b.Item.Name + b.Item.Description).ToLower()));
var startDateString = startDate.ToString(Utilities.DateTimeToFriendlyFullDateTimeStringFormat());
var endDateString = endDate.ToString(Utilities.DateTimeToFriendlyFullDateTimeStringFormat());
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Stock Info");
worksheet.Cell("A1").Value = "SimpleInventory -- Stock Info Report for Sold Items";
worksheet.Cell("A1").Style.Font.Bold = true;
worksheet.Cell("A2").Value = startDateString + " - " + endDateString;
// table headers
worksheet.Cell("A4").SetValue("Name").Style.Font.SetBold(true);
worksheet.Cell("B4").SetValue("Description").Style.Font.SetBold(true);
worksheet.Cell("C4").SetValue("Beginning Stock (Computer)").Style.Font.SetBold(true);
worksheet.Cell("D4").SetValue("Ending Stock (Computer)").Style.Font.SetBold(true);
worksheet.Cell("E4").SetValue("Ending Stock (Manual Entry)").Style.Font.SetBold(true);
worksheet.Cell("F4").SetValue("Computer Difference").Style.Font.SetBold(true);
worksheet.Cell("G4").SetValue("Manual Difference").Style.Font.SetBold(true);
worksheet.Cell("H4").SetValue("Stock Difference").Style.Font.SetBold(true);
worksheet.Cell("I4").SetValue("Item Cost").Style.Font.SetBold(true);
worksheet.Cell("J4").SetValue("Cost Difference (Missing Items)").Style.Font.SetBold(true);
worksheet.Cell("K4").SetValue("Cost Difference (Extra Items)").Style.Font.SetBold(true);
// start exporting data
var currentCell = worksheet.Cell("A5");
var lastRow = currentCell.WorksheetRow();
IXLCell firstCellWithData = null;
// TODO: adjust formulas with string.Format() rather than string concat
foreach (DetailedStockReportInfo item in items)
{
lastRow = currentCell.WorksheetRow();
if (firstCellWithData == null)
{
firstCellWithData = currentCell;
}
currentCell.Value = item.Item.Name;
currentCell.CellRight(1).Value = item.Item.Description;
currentCell.CellRight(2).Value = item.StartStockWithPurchaseStockIncrease;
currentCell.CellRight(3).Value = item.EndStock; // computer
currentCell.CellRight(4).Value = ""; // manual entry
currentCell.CellRight(4).AddConditionalFormat()
.WhenEquals("\"\"")
.Fill.SetBackgroundColor(XLColor.Yellow); // if data not entered, highlight that work needs to happen!!
currentCell.CellRight(5).FormulaA1 = "=SUM(-" + currentCell.CellRight(2).Address.ToStringFixed() + ","
+ currentCell.CellRight(3).Address.ToStringFixed() + ")"; // computer diff
currentCell.CellRight(6).FormulaA1 = "=IF(" + currentCell.CellRight(3).Address.ToStringFixed() + "=\"\", \"-\", "
+ "SUM(-" + currentCell.CellRight(2).Address.ToStringFixed() + ","
+ currentCell.CellRight(4).Address.ToStringFixed() + "))"; // manual diff
currentCell.CellRight(5).AddConditionalFormat()
.WhenNotEquals("=" + currentCell.CellRight(6).Address.ToStringFixed())
.Fill.SetBackgroundColor(XLColor.LightPink);
currentCell.CellRight(6).AddConditionalFormat()
.WhenNotEquals("=" + currentCell.CellRight(5).Address.ToStringFixed())
.Fill.SetBackgroundColor(XLColor.LightPink);
currentCell.CellRight(7).SetFormulaA1("=ABS(SUM(" + currentCell.CellRight(5).Address.ToStringFixed() + ", -"
+ currentCell.CellRight(6).Address.ToStringFixed() + "))").AddConditionalFormat()
.WhenNotEquals("0")
.Fill.SetBackgroundColor(XLColor.LightPink); // stock difference
currentCell.CellRight(8).Value = item.Item.Cost; // item cost
// first sum column is items that have less in real life than in the computer
string formula = string.Format("=IF({0}<>\"\", IF({1}>{2},{3}*{4},\"\"), \"\")",
currentCell.CellRight(4).Address.ToStringFixed(), // ending stock manual entry
currentCell.CellRight(3).Address.ToStringFixed(), // ending stock computer
currentCell.CellRight(4).Address.ToStringFixed(), // ending stock manual entry
currentCell.CellRight(7).Address.ToStringFixed(), // stock diff
currentCell.CellRight(8).Address.ToStringFixed() // item cost
);
currentCell.CellRight(9).SetFormulaA1(formula); // cost difference for missing items
// second sum column is items that have more in real life than in the computer
formula = string.Format("=IF({0}<>\"\", IF({1}<{2},{3}*{4},\"\"), \"\")",
currentCell.CellRight(4).Address.ToStringFixed(), // ending stock manual entry
currentCell.CellRight(3).Address.ToStringFixed(), // ending stock computer
currentCell.CellRight(4).Address.ToStringFixed(), // ending stock manual entry
currentCell.CellRight(7).Address.ToStringFixed(), // stock diff
currentCell.CellRight(8).Address.ToStringFixed() // item cost
);
currentCell.CellRight(10).SetFormulaA1(formula); // cost difference for extra items
// if item count is equal, doesn't add to either column
if (currentCell.WorksheetRow().RowNumber() % 2 == 0)
{
currentCell.WorksheetRow().Style.Fill.BackgroundColor = XLColor.LightGray;
}
// if you add more data columns make sure to adjust print area!!!
// go to next row
currentCell = currentCell.CellBelow();
}
// add cost discrepency
if (items.Count > 0)
{
currentCell.CellRight(8).SetValue("Cost Discrepency").Style.Font.SetBold(true);
currentCell.CellRight(9).SetFormulaA1("=SUM(" + firstCellWithData.CellRight(9).Address.ToStringFixed()
+ ":" + currentCell.CellAbove(1).CellRight(9).Address.ToStringFixed() + ")").Style.Font.SetBold(true);
currentCell.CellRight(10).SetFormulaA1("=SUM(" + firstCellWithData.CellRight(10).Address.ToStringFixed()
+ ":" + currentCell.CellAbove(1).CellRight(10).Address.ToStringFixed() + ")").Style.Font.SetBold(true);
}
//// auto fit width
worksheet.Columns().AdjustToContents(4, 4, 10, 25);
// set print area
worksheet.PageSetup.PrintAreas.Clear();
var firstCellForPrinting = worksheet.Cell("A1");
var lastCellForPrinting = items.Count > 0 ? currentCell.CellRight(10) : worksheet.Cell("J4");
worksheet.PageSetup.PrintAreas.Add(firstCellForPrinting.Address.ToStringRelative() + ":" + lastCellForPrinting.Address.ToStringRelative());
worksheet.PageSetup.SetRowsToRepeatAtTop("4:4");
worksheet.PageSetup.PagesWide = 1;
worksheet.PageSetup.PageOrientation = XLPageOrientation.Landscape;
workbook.SaveAs(path);
Process.Start(path);
}
}
}
}
| 65.546154
| 155
| 0.570356
|
[
"MIT"
] |
Deadpikle/SimpleInventory
|
SimpleInventory/Helpers/StockInfoExcelGenerator.cs
| 8,523
|
C#
|
namespace TerritoryTools.Entities.AddressParsers
{
public class AddressPartResult
{
public string Value { get; set; }
public int Index { get; set; }
public override string ToString()
{
return Index + ": " + Value ?? "Null";
}
}
}
| 19.8
| 50
| 0.552189
|
[
"MIT"
] |
territorytools/territory-tools
|
Common/AddressParser/AddressPartResult.cs
| 299
|
C#
|
using UnityEngine;
using UnityEngine.UI;
public class HeroPanel : BattlePanel {
public Text Hp, MaxHp;
public Action LastUsedAction;
public override void Setup() {
base.Setup();
Image.sprite = Unit.Sprite;
Hp.text = Unit.CurHp.ToString();
MaxHp.text = $"/{ Unit.MaxHp }";
}
}
| 20.2
| 38
| 0.666667
|
[
"MIT"
] |
ashriot/Legend-RPG
|
Assets/Scripts/UI/HeroPanel.cs
| 305
|
C#
|
using System;
using System.Linq;
using Demo.LearnByDoing.Core;
using Xunit;
using Xunit.Abstractions;
namespace Demo.LearnByDoing.Tests.RandomStuff
{
public class RecursionTest : BaseTest
{
public RecursionTest(ITestOutputHelper output) : base(output)
{
}
[Theory]
[InlineData(new []{1,2,3}, 6)]
[InlineData(new []{2, 4, 8}, 14)]
[InlineData(new []{-1, 0, 1}, 0)]
public void TestSumming(int[] input, int expected)
{
var sut = new RecursionStuff();
int actual = sut.GetSum(input);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(new object[]{new []{1,2,3}, 4, new []{5}}, 15)]
[InlineData(new object[]{-1, new[] {0, 1}, new []{5}, 10}, 15)]
public void TestNestedArraySum(object[] input, int expected)
{
var sut = new RecursionStuff();
int actual = sut.GetNestedArraySum(input);
Assert.Equal(expected, actual);
}
}
public class RecursionStuff
{
public int GetNestedArraySum(object[] input)
{
return GetNestedArraySumRecursively(input, input.Length - 1);
}
private int GetNestedArraySumRecursively(object[] input, int i)
{
if (i < 0) return 0;
var arr = input[i] as int[];
int current = arr == null ? Convert.ToInt32(input[i]) : 0;
if (arr != null)
{
current += GetNestedArraySumRecursively(arr.Select(x => (object)x).ToArray(), arr.Length - 1);
}
return current + GetNestedArraySumRecursively(input, i - 1);
}
public int GetSum(int[] input)
{
return GetSumRecursively(input, input.Length - 1);
}
private int GetSumRecursively(int[] input, int i)
{
if (i == 0) return input[i];
return input[i] + GetSumRecursively(input, i - 1);
}
}
}
| 23.507042
| 98
| 0.654284
|
[
"MIT"
] |
dance2die/Demo.LearnByDoing
|
Demo.LearnByDoing.Tests/RandomStuff/RecursionTest.cs
| 1,671
|
C#
|
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
namespace DotSpatial.Symbology
{
/// <summary>
/// PatternTypes
/// </summary>
public enum PatternType
{
/// <summary>
/// A pattern that gradually changes from one color to another
/// </summary>
Gradient,
/// <summary>
/// A pattern comprised of evenly spaced lines
/// </summary>
Line,
/// <summary>
/// A pattern comprised of point symbolizers
/// </summary>
Marker,
/// <summary>
/// A pattern comprised of a tiled texture
/// </summary>
Picture,
/// <summary>
/// A pattern comprised strictly of a fill color.
/// </summary>
Simple
}
}
| 25.722222
| 106
| 0.529158
|
[
"MIT"
] |
AlexanderSemenyak/DotSpatial
|
Source/DotSpatial.Symbology/PatternType.cs
| 926
|
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 lambda-2015-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Lambda.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lambda.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetProvisionedConcurrencyConfig operation
/// </summary>
public class GetProvisionedConcurrencyConfigResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetProvisionedConcurrencyConfigResponse response = new GetProvisionedConcurrencyConfigResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("AllocatedProvisionedConcurrentExecutions", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
response.AllocatedProvisionedConcurrentExecutions = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("AvailableProvisionedConcurrentExecutions", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
response.AvailableProvisionedConcurrentExecutions = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("LastModified", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.LastModified = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("RequestedProvisionedConcurrentExecutions", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
response.RequestedProvisionedConcurrentExecutions = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Status = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StatusReason", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.StatusReason = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException"))
{
return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ProvisionedConcurrencyConfigNotFoundException"))
{
return ProvisionedConcurrencyConfigNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException"))
{
return ServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonLambdaException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetProvisionedConcurrencyConfigResponseUnmarshaller _instance = new GetProvisionedConcurrencyConfigResponseUnmarshaller();
internal static GetProvisionedConcurrencyConfigResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetProvisionedConcurrencyConfigResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 44.435897
| 190
| 0.615407
|
[
"Apache-2.0"
] |
philasmar/aws-sdk-net
|
sdk/src/Services/Lambda/Generated/Model/Internal/MarshallTransformations/GetProvisionedConcurrencyConfigResponseUnmarshaller.cs
| 6,932
|
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\EntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type SharePointSiteUsagePagesRequestBuilder.
/// </summary>
public partial class SharePointSiteUsagePagesRequestBuilder : EntityRequestBuilder, ISharePointSiteUsagePagesRequestBuilder
{
/// <summary>
/// Constructs a new SharePointSiteUsagePagesRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public SharePointSiteUsagePagesRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public new ISharePointSiteUsagePagesRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public new ISharePointSiteUsagePagesRequest Request(IEnumerable<Option> options)
{
return new SharePointSiteUsagePagesRequest(this.RequestUrl, this.Client, options);
}
}
}
| 35.927273
| 153
| 0.589069
|
[
"MIT"
] |
OfficeGlobal/msgraph-beta-sdk-dotnet
|
src/Microsoft.Graph/Requests/Generated/SharePointSiteUsagePagesRequestBuilder.cs
| 1,976
|
C#
|
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
public interface IDuplexSessionChannel : IDuplexChannel, ISessionChannel<IDuplexSession>
{
}
}
| 32.25
| 92
| 0.444444
|
[
"Apache-2.0"
] |
295007712/295007712.github.io
|
sourceCode/dotNet4.6/ndp/cdf/src/WCF/ServiceModel/System/ServiceModel/Channels/IDuplexSessionChannel.cs
| 387
|
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>
//------------------------------------------------------------------------------
[assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("YourDrink.CreateDrinkPage.xaml", "CreateDrinkPage.xaml", typeof(global::YourDrink.CreateDrinkPage))]
namespace YourDrink {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("CreateDrinkPage.xaml")]
public partial class CreateDrinkPage : global::Xamarin.Forms.ContentPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Entry DrinkName;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Image DrinkImage;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.ImageButton SelectImageButton;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.ListView ReceptList;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Button AddIngredient;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Editor MakingLabel;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(CreateDrinkPage));
DrinkName = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Entry>(this, "DrinkName");
DrinkImage = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Image>(this, "DrinkImage");
SelectImageButton = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.ImageButton>(this, "SelectImageButton");
ReceptList = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.ListView>(this, "ReceptList");
AddIngredient = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Button>(this, "AddIngredient");
MakingLabel = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Editor>(this, "MakingLabel");
}
}
}
| 59.306122
| 163
| 0.670681
|
[
"Apache-2.0"
] |
yassin1530/your-drink
|
YourDrink/YourDrink/obj/Debug/netstandard2.0/CreateDrinkPage.xaml.g.cs
| 2,906
|
C#
|
using Joy.Core.Encode;
using System;
namespace Portal.Testing.Crypto
{
public partial class TestCrypto : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Form["s"];
string p = Request.Form["p"];
string a = Request.Form["a"];
if (!string.IsNullOrEmpty(a))
{
s = "Success!";
s = OpenSSL.OpenSSLEncrypt(s, p);
Response.Clear();
Response.Write(s);
Response.End();
}
else if (!string.IsNullOrEmpty(s))
{
Response.Clear();
string t = OpenSSL.OpenSSLDecrypt(s, p);
Response.Write(t);
Response.End();
}
}
}
}
| 27
| 60
| 0.462366
|
[
"MIT"
] |
mind0n/hive
|
Product/Website/Portal/Portal/Testing/Crypto/TestCrypto.aspx.cs
| 839
|
C#
|
using System;
namespace Application
{
public class fizzbuzz
{
public fizzbuzz ()
{
for(int a = 1; a < 100; a++){
Console.WriteLine(fizz_or_buzz(a));
}
}
public string fizz_or_buzz (int number)
{
string fizz_or_buzz_string;
if ( (number_modulo(number, 3)) && (number_modulo(number, 5)) ) {
fizz_or_buzz_string = "FizzBuzz";
} else if (number_modulo(number, 3)) {
fizz_or_buzz_string = "Fizz";
} else if (number_modulo(number, 5)) {
fizz_or_buzz_string = "Buzz";
} else {
fizz_or_buzz_string = number.ToString();
}
return fizz_or_buzz_string+"\n";
}
public Boolean number_modulo (int number, int dividend){
if ((number % dividend) == 0) {
return true;
} else {
return false;
}
}
}
public class test {
public static void Main(){
fizzbuzz f = new fizzbuzz();
}
}
}
| 18.104167
| 68
| 0.617952
|
[
"Apache-2.0"
] |
ruanpienaar/c_sharp
|
fizzbuzz.cs
| 869
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MoogleEngine
{
//Clase para Parsear la query y obtener la informacion sobre los operadores
public class Parsing
{
//Palabras que deben existir
public HashSet<string> MustExistWords = new HashSet<string>();
//Palabras que no deben existir
public HashSet<string> MustNotExistWords = new HashSet<string>();
//Pares de palabras que cercanas aumentan el score
public HashSet<Tuple<string,string>> PairWords = new HashSet<Tuple<string,string>>();
//Para cada palabra su multiplicador de importancia
public Dictionary<string,double> ImportanceWords = new Dictionary<string,double>();
//Limite a la hora de obligar a palabras a existir entre las similares
static int MustExistWordsLimit = 0;
//Limite a la hora de obligar a palabras a no existir entre las similares
static int MustNotExistWordsLimit = 1;
//Limite a la hora de chequear cercania de palabras similares
static int PairWordsLimit = 2;
//Comparar dos palabras lexicograficamente
public bool CompareWords(string s1, string s2)
{
//Comparar por caracter a caracter
for(int i = 0 ; i < Math.Min(s1.Length, s2.Length) ; i++)
{
if(s1[i] < s2[i])return true;
if(s1[i] > s2[i])return false;
}
//Si una es prefijo de otra comparar por tamanno
if(s1.Length < s2.Length)return true;
return false;
}
//Obtener la lista de posiciones en donde un caracter se encuentra en un string
public List<int> GetCharPositions(string cad, char c)
{
//Lista de posiciones
List<int> Pos = new List<int>();
//Iterando sobre el string
for(int i = 0 ; i < cad.Length ; i++)
{
//Chequeando igualdad
if(cad[i] == c)
{
//Annadiendo posicion
Pos.Add(i);
}
}
//Retornando lista de posiciones
return Pos;
}
//Dado una lista de palabras y sus posiciones retornar el menor indice de la palabra con
//posicion mayor que la dada
public int FindFistRight(List<Tuple<string,int>> vect, int pos)
{
//Iterando de menor a mayor
for(int i = 0 ; i < vect.Count ; i++)
{
//Chequeando
if(pos < vect[i].Item2)
{
return i;
}
}
//No se encontro palabra
return -1;
}
//Dado una lista de palabras y sus posiciones retornar el mayor indice de la palabra con
//posicion menor que la dada
public int FindFistLeft(List<Tuple<string,int>> vect, int pos)
{
//Iterando de mayor a menor
for(int i = vect.Count-1 ; i >= 0 ; i--)
{
//Chequeando
if(pos > vect[i].Item2)
{
return i;
}
}
//No se encontro palabra
return -1;
}
//Parseando query
//Primer parametro la cadena a parsear
//Segundo parametro la lista de string similares
//Tercer parametro un objeto de la clase SelectBestQuery para obtener informacion de los similares
public Parsing(string cad, List<string> list, SelectBestQuery bestQ)
{
//Obteniendo palabras y sus posiciones de un string
List<Tuple<string,int>> vect = TextPreprocessing.GetWordsAndPositionsFromString(cad);
//Buscando palabras que deberian estar obligado
foreach(int pos in GetCharPositions(cad,'^'))
{
//Buscando primera palabra a la derecha
int R = FindFistRight(vect, pos);
//Si R = -1 no existe
if(R != -1)
{
//Agregarla al conjunto si no esta
if(!MustExistWords.Contains(list[R]))
{
MustExistWords.Add(list[R]);
}
//Iterando sobre similares para volverlas obligadas a pertenecer en el documento
for(int i = 0 ; i < Math.Min(MustExistWordsLimit, bestQ.arr[R].Count) ; i++)
{
//Agregarla al conjunto si no esta
if(!MustExistWords.Contains(bestQ.arr[R][i].Item1))
{
MustExistWords.Add(bestQ.arr[R][i].Item1);
}
}
}
}
//Buscando palabras que no deben estar en el documento
foreach(int pos in GetCharPositions(cad,'!'))
{
//Buscando primera palabra a la derecha
int R = FindFistRight(vect, pos);
//Si R = -1 no existe
if(R != -1)
{
//Agregarla al conjunto si no esta
if(!MustNotExistWords.Contains(list[R]))
{
MustNotExistWords.Add(list[R]);
}
//Iterando sobre similares para volverlas obligadas a no pertenecer en el documento
for(int i = 0 ; i < Math.Min(MustNotExistWordsLimit, bestQ.arr[R].Count) ; i++)
{
//Agregarla al conjunto si no esta
if(!MustNotExistWords.Contains(bestQ.arr[R][i].Item1))
{
MustNotExistWords.Add(bestQ.arr[R][i].Item1);
}
}
}
}
//Inicializando importancia de palabras
foreach(string word in list)
{
if(!ImportanceWords.ContainsKey(word))
{
//Inicializando con valor neutro 1
ImportanceWords.Add(word, 1);
}
}
//Buscando palabras operadores de importancia
foreach(int pos in GetCharPositions(cad,'*'))
{
//Buscando primera palabra a la derecha
int R = FindFistRight(vect, pos);
//Si R = -1 no existe
if(R != -1)
{
//Duplicando la importancia de la palabra
ImportanceWords[list[R]] *= 2;
}
}
//Buscando pares de palabras que cercanas aumentan el score
foreach(int pos in GetCharPositions(cad,'~'))
{
//Buscando primera palabra a la izquierda
int L = FindFistLeft(vect, pos);
//Buscando primera palabra a la derecha
int R = FindFistRight(vect, pos);
//Si L = -1 o R = -1 entonces no podemos usar el operador
if(L != -1 && R != -1)
{
string s1 = list[L];
string s2 = list[R];
//Comparando palabras para volverlas una tupla ordenada
if(CompareWords(s2,s1))
{
(s1,s2) = (s2,s1);
}
//Insertando al set de pares palabras
if(!PairWords.Contains(new Tuple<string, string>(s1,s2)))
{
PairWords.Add(new Tuple<string, string>(s1,s2));
}
//Iterando por palabras similares a la primera
for(int i = 0 ; i < Math.Min(PairWordsLimit, bestQ.arr[L].Count) ; i++)
{
//Iterando por palabras similares a la segunda
for(int j = 0 ; j < Math.Min(PairWordsLimit, bestQ.arr[R].Count) ; j++)
{
s1 = bestQ.arr[L][i].Item1;
s2 = bestQ.arr[R][i].Item1;
//Comparando palabras para volverlas una tupla ordenada
if(CompareWords(s2,s1))
{
(s1,s2) = (s2,s1);
}
//Insertando al set de pares palabras
if(!PairWords.Contains(new Tuple<string, string>(s1,s2)))
{
PairWords.Add(new Tuple<string, string>(s1,s2));
}
}
}
}
}
}
}
}
| 37.902128
| 106
| 0.471315
|
[
"MIT"
] |
brayandm/moogle-2021
|
MoogleEngine/Libraries/Parsing.cs
| 8,907
|
C#
|
using ControlledForms.IntegrationTests;
using SilveR.StatsModels;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace SilveR.IntegrationTests
{
public class EquivalenceTOSTTestTests : IClassFixture<SilveRTestWebApplicationFactory<Startup>>
{
private readonly SilveRTestWebApplicationFactory<Startup> _factory;
public EquivalenceTOSTTestTests(SilveRTestWebApplicationFactory<Startup> factory)
{
_factory = factory;
}
[Fact]
public async Task ETT1()
{
string testName = "ETT1";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Resp 1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("Response (Resp 1) has been selected in more than one input category, please change your input options.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT2()
{
string testName = "ETT2";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp6";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("There are no observations recorded on the levels of the Treatment factor (Treat1). Please amend the dataset prior to running the analysis.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT3()
{
string testName = "ETT3";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat7" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("There are no observations recorded on the levels of the Treatment factor (Treat7). Please amend the dataset prior to running the analysis.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT4()
{
string testName = "ETT4";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Tre at4" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("The Treatment factor (Tre at4) contains missing data where there are observations present in the Response. Please check the input data and make sure the data was entered correctly.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT5()
{
string testName = "ETT5";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp4";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("The Response (Resp4) contains non-numerical data which cannot be processed. Please check the input data and make sure the data was entered correctly.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT6()
{
string testName = "ETT6";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.Covariates = new string[] { "Cov4" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("The Covariate (Cov4) contains non-numerical data which cannot be processed. Please check the input data and make sure the data was entered correctly.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT7()
{
string testName = "ETT7";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp5";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("The Response (Resp5) contains missing data.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT8()
{
string testName = "ETT8";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.Covariates = new string[] { "Cov5" };
model.PrimaryFactor = "Treat1";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("The Covariate (Cov5) contains missing data. Any response that does not have a corresponding covariate will be excluded from the analysis.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT9()
{
string testName = "ETT9";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "T reat5" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("One or more of the factors (T reat5) has only one level present in the dataset. Please select another factor.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT10()
{
string testName = "ETT10";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat6" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("There is no replication in one or more of the levels of the Treatment factor (Treat6). Please select another factor.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT11()
{
string testName = "ETT11";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 2";
model.ResponseTransformation = "Log10";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have Log10 transformed the Resp 2 variable. Unfortunately some of the Resp 2 values are zero and/or negative. These values have been ignored in the analysis as it is not possible to transform them.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT12()
{
string testName = "ETT12";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp3";
model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10;
model.UpperBoundPercentageChange = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have Loge transformed the Resp3 variable. Unfortunately some of the Resp3 values are zero and/or negative. These values have been ignored in the analysis as it is not possible to transform them.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT13()
{
string testName = "ETT13";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 2";
model.ResponseTransformation = "Square Root";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have Square Root transformed the Resp 2 variable. Unfortunately some of the Resp 2 values are negative. These values have been ignored in the analysis as it is not possible to transform them.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT14()
{
string testName = "ETT14";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.Covariates = new string[] { "Cov2" };
model.CovariateTransformation = "Log10";
model.PrimaryFactor = "Treat1";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have Log10 transformed the Cov2 variable. Unfortunately some of the Cov2 values are zero and/or negative. These values have been ignored in the analysis as it is not possible to transform them. Any response where the covariate has been removed will also be excluded from the analysis.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT15()
{
string testName = "ETT15";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.Covariates = new string[] { "Cov3" };
model.CovariateTransformation = "Loge";
model.PrimaryFactor = "Treat1";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have Loge transformed the Cov3 variable. Unfortunately some of the Cov3 values are zero and/or negative. These values have been ignored in the analysis as it is not possible to transform them. Any response where the covariate has been removed will also be excluded from the analysis.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT16()
{
string testName = "ETT16";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.Covariates = new string[] { "Cov2" };
model.CovariateTransformation = "Square Root";
model.PrimaryFactor = "Treat1";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have Square Root transformed the Cov2 variable. Unfortunately some of the Cov2 values are negative. These values have been ignored in the analysis as it is not possible to transform them. Any response where the covariate has been removed will also be excluded from the analysis.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT17()
{
string testName = "ETT17";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp9";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have ArcSine transformed the Resp9 variable. Unfortunately some of the Resp9 values are <0 or >1. These values have been ignored in the analysis as it is not possible to transform them.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT18()
{
string testName = "ETT18";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp8";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have ArcSine transformed the Resp8 variable. Unfortunately some of the Resp8 values are <0 or >1. These values have been ignored in the analysis as it is not possible to transform them.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT19()
{
string testName = "ETT19";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp7";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.Covariates = new string[] { "Cov2" };
model.CovariateTransformation = "ArcSine";
model.PrimaryFactor = "Treat1";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have ArcSine transformed the Cov2 variable. Unfortunately some of the Cov2 values are <0 or >1. These values have been ignored in the analysis as it is not possible to transform them. Any response where the covariate has been removed will also be excluded from the analysis.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT20()
{
string testName = "ETT20";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp7";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.Covariates = new string[] { "Resp8" };
model.CovariateTransformation = "ArcSine";
model.PrimaryFactor = "Treat1";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("You have ArcSine transformed the Resp8 variable. Unfortunately some of the Resp8 values are <0 or >1. These values have been ignored in the analysis as it is not possible to transform them. Any response where the covariate has been removed will also be excluded from the analysis.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT21()
{
string testName = "ETT21";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp8";
model.Treatments = new string[] { "Treat12", "Treat13" };
model.SelectedEffect = "Treat12";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT22()
{
string testName = "ETT22";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp11";
model.Treatments = new string[] { "Treat14" };
model.SelectedEffect = "Treat14";
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 10;
model.UpperBoundAbsolute = 20;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT23()
{
string testName = "ETT23";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 0.5m;
model.UpperBoundAbsolute = 0.1m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("The lower bound selected is higher than the upper bound, please check the bounds as the lower bound should be less than the upper bound.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT25()
{
string testName = "ETT25";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = -1m;
model.UpperBoundPercentageChange = 0.1m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("User cannot select a negative Percentage change.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT26()
{
string testName = "ETT26";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = -2m;
model.UpperBoundPercentageChange = -1m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> errors = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("User cannot select a negative Percentage change.", errors);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, errors);
}
[Fact]
public async Task ETT27()
{
string testName = "ETT27";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Log10";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 1m;
model.UpperBoundAbsolute = 2m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("As you have chosen to log transformed the response, the comparisons between the predicted means will be in the form of ratios. This implies that the difference between the means will be a % change and hence you should select % boundaries rather than absolute boundaries.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT28()
{
string testName = "ETT28";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = 1m;
model.UpperBoundAbsolute = 2m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("As you have chosen to log transformed the response, the comparisons between the predicted means will be in the form of ratios. This implies that the difference between the means will be a % change and hence you should select % boundaries rather than absolute boundaries.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT29()
{
string testName = "ETT29";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Square Root";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 1m;
model.UpperBoundPercentageChange = 2m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("As you have selected to [sqrt, arcsine, rank] transform the responses you should choose absolute boundaries rather than % boundaries. The absolute boundaries should be defined on the transformed scale rather than the original scale.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT30()
{
string testName = "ETT30";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 1m;
model.UpperBoundPercentageChange = 2m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("As you have selected to [sqrt, arcsine, rank] transform the responses you should choose absolute boundaries rather than % boundaries. The absolute boundaries should be defined on the transformed scale rather than the original scale.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT31()
{
string testName = "ETT31";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Rank";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 1m;
model.UpperBoundPercentageChange = 2m;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractErrors(response);
//Assert
Assert.Contains("As you have selected to [sqrt, arcsine, rank] transform the responses you should choose absolute boundaries rather than % boundaries. The absolute boundaries should be defined on the transformed scale rather than the original scale.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
}
[Fact]
public async Task ETT32()
{
string testName = "ETT32";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.2m;
model.UpperBoundAbsolute = 0.2m;
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT33()
{
string testName = "ETT33";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.2m;
model.UpperBoundAbsolute = 0.2m;
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT34()
{
string testName = "ETT34";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Square Root";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.15m;
model.UpperBoundAbsolute = 0.15m;
model.Significance = "0.001";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT35()
{
string testName = "ETT35";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Square Root";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.15m;
model.UpperBoundAbsolute = 0.15m;
model.Significance = "0.001";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT36()
{
string testName = "ETT36";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp7";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.3m;
model.UpperBoundAbsolute = 0.3m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT37()
{
string testName = "ETT37";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp7";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.3m;
model.UpperBoundAbsolute = 0.3m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT38()
{
string testName = "ETT38";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("As you have chosen the % equivalence bounds, the actual boundaries has been calculated as a % of the overall mean of the response.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
//Act - ignore warnings
var modelIgnoreWarnings = model.ToKeyValue();
modelIgnoreWarnings.Add("ignoreWarnings", "true");
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(modelIgnoreWarnings));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT39()
{
string testName = "ETT39";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("As you have chosen the % equivalence bounds, the actual boundaries has been calculated as a % of the selected control group.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
//Act - ignore warnings
var modelIgnoreWarnings = model.ToKeyValue();
modelIgnoreWarnings.Add("ignoreWarnings", "true");
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(modelIgnoreWarnings));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT40()
{
string testName = "ETT40";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Log10";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT41()
{
string testName = "ETT41";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Log10";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT42()
{
string testName = "ETT42";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT43()
{
string testName = "ETT43";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT44()
{
string testName = "ETT44";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.2m;
//model.UpperBoundAbsolute = 0m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT45()
{
string testName = "ETT45";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.2m;
//model.UpperBoundAbsolute = 0m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT46()
{
string testName = "ETT46";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Square Root";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.15m;
//model.UpperBoundAbsolute = 0m;
model.Significance = "0.001";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT47()
{
string testName = "ETT47";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp7";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
model.LowerBoundAbsolute = -0.3m;
//model.UpperBoundAbsolute = 0m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT48()
{
string testName = "ETT48";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
//model.UpperBoundAbsolute = 0m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("As you have chosen the % equivalence bounds, the actual boundaries has been calculated as a % of the overall mean of the response.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
//Act - ignore warnings
var modelIgnoreWarnings = model.ToKeyValue();
modelIgnoreWarnings.Add("ignoreWarnings", "true");
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(modelIgnoreWarnings));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT49()
{
string testName = "ETT49";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Log10";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
//model.UpperBoundAbsolute = 0m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT50()
{
string testName = "ETT50";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
model.LowerBoundPercentageChange = 10m;
//model.UpperBoundAbsolute = 0m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT51()
{
string testName = "ETT51";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
//model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundAbsolute = 0.2m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT52()
{
string testName = "ETT52";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
//model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundAbsolute = 0.2m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT53()
{
string testName = "ETT53";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Square Root";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundAbsolute = 0.15m;
model.Significance = "0.001";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT54()
{
string testName = "ETT54";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp7";
model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Absolute;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundAbsolute = 0.3m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT55()
{
string testName = "ETT55";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
//model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("As you have chosen the % equivalence bounds, the actual boundaries has been calculated as a % of the overall mean of the response.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
//Act - ignore warnings
var modelIgnoreWarnings = model.ToKeyValue();
modelIgnoreWarnings.Add("ignoreWarnings", "true");
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(modelIgnoreWarnings));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT56()
{
string testName = "ETT56";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
//model.ResponseTransformation = "ArcSine";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
HttpResponseMessage response = await client.PostAsync("Analyses/EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
IEnumerable<string> warnings = await Helpers.ExtractWarnings(response);
//Assert
Assert.Contains("As you have chosen the % equivalence bounds, the actual boundaries has been calculated as a % of the selected control group.", warnings);
Helpers.SaveOutput("EquivalenceTOSTTest", testName, warnings);
//Act - ignore warnings
var modelIgnoreWarnings = model.ToKeyValue();
modelIgnoreWarnings.Add("ignoreWarnings", "true");
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(modelIgnoreWarnings));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT57()
{
string testName = "ETT57";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Log10";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.ComparisonsToControl;
model.ControlGroup = "D1";
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
[Fact]
public async Task ETT58()
{
string testName = "ETT58";
//Arrange
HttpClient client = _factory.CreateClient();
EquivalenceTOSTTestModel model = new EquivalenceTOSTTestModel();
model.DatasetID = _factory.SheetNames.Single(x => x.Value == "Equivalence TOST").Key;
model.Response = "Resp 1";
model.ResponseTransformation = "Loge";
model.Treatments = new string[] { "Treat1" };
model.EquivalenceBoundsType = EquivalenceTOSTTestModel.EquivalenceBoundsOption.Percentage;
//model.LowerBoundAbsolute = 0.2m;
model.UpperBoundPercentageChange = 10m;
model.Significance = "0.05";
model.PRPlotSelected = true;
model.SelectedEffect = "Treat1";
model.LSMeansSelected = true;
model.ComparisonType = EquivalenceTOSTTestModel.ComparisonOption.AllPairwise;
//Act
StatsOutput statsOutput = await Helpers.SubmitAnalysis(client, "EquivalenceTOSTTest", new FormUrlEncodedContent(model.ToKeyValue()));
Helpers.SaveTestOutput("EquivalenceTOSTTest", model, testName, statsOutput);
//Assert
string expectedHtml = File.ReadAllText(Path.Combine("ExpectedResults", "EquivalenceTOSTTest", testName + ".html"));
Assert.Equal(Helpers.RemoveAllImageNodes(expectedHtml), Helpers.RemoveAllImageNodes(statsOutput.HtmlResults));
}
}
}
| 48.675899
| 330
| 0.647495
|
[
"MIT"
] |
robalexclark/SilveR
|
SilveR.IntegrationTests/StatsTests/EquivalenceTOSTTestTests.cs
| 82,603
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.Administration.Commands;
using Content.Server.GameObjects.Components.Items.Clothing;
using Content.Server.GameObjects.Components.Items.Storage;
using Content.Server.GameObjects.EntitySystems.Click;
using Content.Server.Interfaces.GameObjects;
using Content.Shared.GameObjects.Components.Inventory;
using Content.Shared.GameObjects.Components.Movement;
using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.GameObjects.EntitySystems.ActionBlocker;
using Content.Shared.GameObjects.EntitySystems.EffectBlocker;
using Content.Shared.GameObjects.Verbs;
using Content.Shared.Interfaces;
using Robust.Server.Console;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Players;
using Robust.Shared.ViewVariables;
using static Content.Shared.GameObjects.Components.Inventory.EquipmentSlotDefines;
using static Content.Shared.GameObjects.Components.Inventory.SharedInventoryComponent.ClientInventoryMessage;
namespace Content.Server.GameObjects.Components.GUI
{
[RegisterComponent]
[ComponentReference(typeof(SharedInventoryComponent))]
public class InventoryComponent : SharedInventoryComponent, IExAct, IEffectBlocker, IPressureProtection
{
[Dependency] private readonly IEntitySystemManager _entitySystemManager = default!;
[ViewVariables] private readonly Dictionary<Slots, ContainerSlot> _slotContainers = new();
private KeyValuePair<Slots, (EntityUid entity, bool fits)>? _hoverEntity;
public IEnumerable<Slots> Slots => _slotContainers.Keys;
public event Action OnItemChanged;
public override void Initialize()
{
base.Initialize();
foreach (var slotName in InventoryInstance.SlotMasks)
{
if (slotName != EquipmentSlotDefines.Slots.NONE)
{
AddSlot(slotName);
}
}
}
// Optimization: Cache this
[ViewVariables]
public float HighPressureMultiplier
{
get
{
var multiplier = 1f;
foreach (var (slot, containerSlot) in _slotContainers)
{
foreach (var entity in containerSlot.ContainedEntities)
{
foreach (var protection in entity.GetAllComponents<IPressureProtection>())
{
multiplier *= protection.HighPressureMultiplier;
}
}
}
return multiplier;
}
}
// Optimization: Cache this
[ViewVariables]
public float LowPressureMultiplier
{
get
{
var multiplier = 1f;
foreach (var (slot, containerSlot) in _slotContainers)
{
foreach (var entity in containerSlot.ContainedEntities)
{
foreach (var protection in entity.GetAllComponents<IPressureProtection>())
{
multiplier *= protection.LowPressureMultiplier;
}
}
}
return multiplier;
}
}
public override float WalkSpeedModifier
{
get
{
var mod = 1f;
foreach (var slot in _slotContainers.Values)
{
if (slot.ContainedEntity != null)
{
foreach (var modifier in slot.ContainedEntity.GetAllComponents<IMoveSpeedModifier>())
{
mod *= modifier.WalkSpeedModifier;
}
}
}
return mod;
}
}
public override float SprintSpeedModifier
{
get
{
var mod = 1f;
foreach (var slot in _slotContainers.Values)
{
if (slot.ContainedEntity != null)
{
foreach (var modifier in slot.ContainedEntity.GetAllComponents<IMoveSpeedModifier>())
{
mod *= modifier.SprintSpeedModifier;
}
}
}
return mod;
}
}
bool IEffectBlocker.CanSlip()
{
if (Owner.TryGetComponent(out InventoryComponent inventoryComponent) &&
inventoryComponent.TryGetSlotItem(EquipmentSlotDefines.Slots.SHOES, out ItemComponent shoes)
)
{
return EffectBlockerSystem.CanSlip(shoes.Owner);
}
return true;
}
public override void OnRemove()
{
var slots = _slotContainers.Keys.ToList();
foreach (var slot in slots)
{
if (TryGetSlotItem(slot, out ItemComponent item))
{
item.Owner.Delete();
}
RemoveSlot(slot);
}
base.OnRemove();
}
public IEnumerable<IEntity> GetAllHeldItems()
{
foreach (var (_, container) in _slotContainers)
{
foreach (var entity in container.ContainedEntities)
{
yield return entity;
}
}
}
/// <summary>
/// Helper to get container name for specified slot on this component
/// </summary>
/// <param name="slot"></param>
/// <returns></returns>
private string GetSlotString(Slots slot)
{
return Name + "_" + Enum.GetName(typeof(Slots), slot);
}
/// <summary>
/// Gets the clothing equipped to the specified slot.
/// </summary>
/// <param name="slot">The slot to get the item for.</param>
/// <returns>Null if the slot is empty, otherwise the item.</returns>
public ItemComponent GetSlotItem(Slots slot)
{
return GetSlotItem<ItemComponent>(slot);
}
public IEnumerable<T> LookupItems<T>() where T : Component
{
return _slotContainers.Values.SelectMany(x => x.ContainedEntities.Select(e => e.GetComponentOrNull<T>()))
.Where(x => x != null);
}
public T GetSlotItem<T>(Slots slot) where T : ItemComponent
{
if (!_slotContainers.ContainsKey(slot))
{
return null;
}
var containedEntity = _slotContainers[slot].ContainedEntity;
if (containedEntity?.Deleted == true)
{
_slotContainers[slot] = null;
containedEntity = null;
Dirty();
}
return containedEntity?.GetComponent<T>();
}
public bool TryGetSlotItem<T>(Slots slot, out T itemComponent) where T : ItemComponent
{
itemComponent = GetSlotItem<T>(slot);
return itemComponent != null;
}
/// <summary>
/// Equips slothing to the specified slot.
/// </summary>
/// <remarks>
/// This will fail if there is already an item in the specified slot.
/// </remarks>
/// <param name="slot">The slot to put the item in.</param>
/// <param name="item">The item to insert into the slot.</param>
/// <param name="mobCheck">Whether to perform an ActionBlocker check to the entity.</param>
/// <param name="reason">The translated reason why the item cannot be equipped, if this function returns false. Can be null.</param>
/// <returns>True if the item was successfully inserted, false otherwise.</returns>
public bool Equip(Slots slot, ItemComponent item, bool mobCheck, out string reason)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item),
"Clothing must be passed here. To remove some clothing from a slot, use Unequip()");
}
if (!CanEquip(slot, item, mobCheck, out reason))
{
return false;
}
var inventorySlot = _slotContainers[slot];
if (!inventorySlot.Insert(item.Owner))
{
return false;
}
_entitySystemManager.GetEntitySystem<InteractionSystem>().EquippedInteraction(Owner, item.Owner, slot);
OnItemChanged?.Invoke();
Dirty();
UpdateMovementSpeed();
return true;
}
public bool Equip(Slots slot, ItemComponent item, bool mobCheck = true) =>
Equip(slot, item, mobCheck, out var _);
public bool Equip(Slots slot, IEntity entity, bool mobCheck = true) =>
Equip(slot, entity.GetComponent<ItemComponent>(), mobCheck);
/// <summary>
/// Checks whether an item can be put in the specified slot.
/// </summary>
/// <param name="slot">The slot to check for.</param>
/// <param name="item">The item to check for.</param>
/// <param name="reason">The translated reason why the item cannot be equiped, if this function returns false. Can be null.</param>
/// <returns>True if the item can be inserted into the specified slot.</returns>
public bool CanEquip(Slots slot, ItemComponent item, bool mobCheck, out string reason)
{
var pass = false;
reason = null;
if (mobCheck && !ActionBlockerSystem.CanEquip(Owner))
return false;
if (item is ClothingComponent clothing)
{
if (clothing.SlotFlags != SlotFlags.PREVENTEQUIP && (clothing.SlotFlags & SlotMasks[slot]) != 0)
{
pass = true;
}
else
{
reason = Loc.GetString("This doesn't fit.");
}
}
if (Owner.TryGetComponent(out IInventoryController controller))
{
pass = controller.CanEquip(slot, item.Owner, pass, out var controllerReason);
reason = controllerReason ?? reason;
}
if (!pass && reason == null)
{
reason = Loc.GetString("You can't equip this!");
}
return pass && _slotContainers[slot].CanInsert(item.Owner);
}
public bool CanEquip(Slots slot, ItemComponent item, bool mobCheck = true) =>
CanEquip(slot, item, mobCheck, out var _);
public bool CanEquip(Slots slot, IEntity entity, bool mobCheck = true) =>
CanEquip(slot, entity.GetComponent<ItemComponent>(), mobCheck);
/// <summary>
/// Drops the item in a slot.
/// </summary>
/// <param name="slot">The slot to drop the item from.</param>
/// <returns>True if an item was dropped, false otherwise.</returns>
/// <param name="mobCheck">Whether to perform an ActionBlocker check to the entity.</param>
public bool Unequip(Slots slot, bool mobCheck = true)
{
if (!CanUnequip(slot, mobCheck))
{
return false;
}
var inventorySlot = _slotContainers[slot];
var entity = inventorySlot.ContainedEntity;
var item = entity.GetComponent<ItemComponent>();
if (!inventorySlot.Remove(entity))
{
return false;
}
// TODO: The item should be dropped to the container our owner is in, if any.
entity.Transform.AttachParentToContainerOrGrid();
_entitySystemManager.GetEntitySystem<InteractionSystem>().UnequippedInteraction(Owner, entity, slot);
OnItemChanged?.Invoke();
Dirty();
UpdateMovementSpeed();
return true;
}
private void UpdateMovementSpeed()
{
if (Owner.TryGetComponent(out MovementSpeedModifierComponent mod))
{
mod.RefreshMovementSpeedModifiers();
}
}
public void ForceUnequip(Slots slot)
{
var inventorySlot = _slotContainers[slot];
var entity = inventorySlot.ContainedEntity;
if (entity == null)
{
return;
}
var item = entity.GetComponent<ItemComponent>();
inventorySlot.ForceRemove(entity);
var itemTransform = entity.Transform;
itemTransform.AttachParentToContainerOrGrid();
_entitySystemManager.GetEntitySystem<InteractionSystem>().UnequippedInteraction(Owner, item.Owner, slot);
OnItemChanged?.Invoke();
Dirty();
}
/// <summary>
/// Checks whether an item can be dropped from the specified slot.
/// </summary>
/// <param name="slot">The slot to check for.</param>
/// <param name="mobCheck">Whether to perform an ActionBlocker check to the entity.</param>
/// <returns>
/// True if there is an item in the slot and it can be dropped, false otherwise.
/// </returns>
public bool CanUnequip(Slots slot, bool mobCheck = true)
{
if (mobCheck && !ActionBlockerSystem.CanUnequip(Owner))
return false;
var inventorySlot = _slotContainers[slot];
return inventorySlot.ContainedEntity != null && inventorySlot.CanRemove(inventorySlot.ContainedEntity);
}
/// <summary>
/// Adds a new slot to this inventory component.
/// </summary>
/// <param name="slot">The name of the slot to add.</param>
/// <exception cref="InvalidOperationException">
/// Thrown if the slot with specified name already exists.
/// </exception>
public ContainerSlot AddSlot(Slots slot)
{
if (HasSlot(slot))
{
throw new InvalidOperationException($"Slot '{slot}' already exists.");
}
Dirty();
_slotContainers[slot] = ContainerHelpers.CreateContainer<ContainerSlot>(Owner, GetSlotString(slot));
OnItemChanged?.Invoke();
return _slotContainers[slot];
}
/// <summary>
/// Removes a slot from this inventory component.
/// </summary>
/// <remarks>
/// If the slot contains an item, the item is dropped.
/// </remarks>
/// <param name="slot">The name of the slot to remove.</param>
public void RemoveSlot(Slots slot)
{
if (!HasSlot(slot))
{
throw new InvalidOperationException($"Slow '{slot}' does not exist.");
}
ForceUnequip(slot);
var container = _slotContainers[slot];
container.Shutdown();
_slotContainers.Remove(slot);
OnItemChanged?.Invoke();
Dirty();
}
/// <summary>
/// Checks whether a slot with the specified name exists.
/// </summary>
/// <param name="slot">The slot name to check.</param>
/// <returns>True if the slot exists, false otherwise.</returns>
public bool HasSlot(Slots slot)
{
return _slotContainers.ContainsKey(slot);
}
/// <summary>
/// The underlying Container System just notified us that an entity was removed from it.
/// We need to make sure we process that removed entity as being unequipped from the slot.
/// </summary>
private void ForceUnequip(IContainer container, IEntity entity)
{
// make sure this is one of our containers.
// Technically the correct way would be to enumerate the possible slot names
// comparing with this container, but I might as well put the dictionary to good use.
if (container is not ContainerSlot slot || !_slotContainers.ContainsValue(slot))
return;
if (entity.TryGetComponent(out ItemComponent itemComp))
{
itemComp.RemovedFromSlot();
}
OnItemChanged?.Invoke();
Dirty();
}
/// <summary>
/// Message that tells us to equip or unequip items from the inventory slots
/// </summary>
/// <param name="msg"></param>
private async void HandleInventoryMessage(ClientInventoryMessage msg)
{
switch (msg.Updatetype)
{
case ClientInventoryUpdate.Equip:
{
var hands = Owner.GetComponent<HandsComponent>();
var activeHand = hands.GetActiveHand;
if (activeHand != null && activeHand.Owner.TryGetComponent(out ItemComponent clothing))
{
hands.Drop(hands.ActiveHand, doDropInteraction: false);
if (!Equip(msg.Inventoryslot, clothing, true, out var reason))
{
hands.PutInHand(clothing);
if (reason != null)
Owner.PopupMessageCursor(reason);
}
}
break;
}
case ClientInventoryUpdate.Use:
{
var interactionSystem = _entitySystemManager.GetEntitySystem<InteractionSystem>();
var hands = Owner.GetComponent<HandsComponent>();
var activeHand = hands.GetActiveHand;
var itemContainedInSlot = GetSlotItem(msg.Inventoryslot);
if (itemContainedInSlot != null)
{
if (activeHand != null)
{
await interactionSystem.Interaction(Owner, activeHand.Owner, itemContainedInSlot.Owner,
new EntityCoordinates());
}
else if (Unequip(msg.Inventoryslot))
{
hands.PutInHand(itemContainedInSlot);
}
}
break;
}
case ClientInventoryUpdate.Hover:
{
var hands = Owner.GetComponent<HandsComponent>();
var activeHand = hands.GetActiveHand;
if (activeHand != null && GetSlotItem(msg.Inventoryslot) == null)
{
var canEquip = CanEquip(msg.Inventoryslot, activeHand, true, out var reason);
_hoverEntity =
new KeyValuePair<Slots, (EntityUid entity, bool fits)>(msg.Inventoryslot,
(activeHand.Owner.Uid, canEquip));
Dirty();
}
break;
}
}
}
/// <inheritdoc />
public override void HandleMessage(ComponentMessage message, IComponent component)
{
base.HandleMessage(message, component);
switch (message)
{
case ContainerContentsModifiedMessage msg:
if (msg.Removed)
ForceUnequip(msg.Container, msg.Entity);
break;
default:
break;
}
}
/// <inheritdoc />
public override void HandleNetworkMessage(ComponentMessage message, INetChannel netChannel,
ICommonSession session = null)
{
base.HandleNetworkMessage(message, netChannel, session);
if (session == null)
{
throw new ArgumentNullException(nameof(session));
}
switch (message)
{
case ClientInventoryMessage msg:
var playerentity = session.AttachedEntity;
if (playerentity == Owner)
HandleInventoryMessage(msg);
break;
case OpenSlotStorageUIMessage msg:
if (!HasSlot(msg.Slot)) // client input sanitization
return;
var item = GetSlotItem(msg.Slot);
if (item != null && item.Owner.TryGetComponent(out ServerStorageComponent storage))
storage.OpenStorageUI(Owner);
break;
}
}
public override ComponentState GetComponentState(ICommonSession player)
{
var list = new List<KeyValuePair<Slots, EntityUid>>();
foreach (var (slot, container) in _slotContainers)
{
if (container != null && container.ContainedEntity != null)
{
list.Add(new KeyValuePair<Slots, EntityUid>(slot, container.ContainedEntity.Uid));
}
}
var hover = _hoverEntity;
_hoverEntity = null;
return new InventoryComponentState(list, hover);
}
void IExAct.OnExplosion(ExplosionEventArgs eventArgs)
{
if (eventArgs.Severity < ExplosionSeverity.Heavy)
{
return;
}
foreach (var slot in _slotContainers.Values.ToList())
{
foreach (var entity in slot.ContainedEntities)
{
var exActs = entity.GetAllComponents<IExAct>().ToList();
foreach (var exAct in exActs)
{
exAct.OnExplosion(eventArgs);
}
}
}
}
public override bool IsEquipped(IEntity item)
{
if (item == null) return false;
foreach (var containerSlot in _slotContainers.Values)
{
// we don't want a recursive check here
if (containerSlot.Contains(item))
{
return true;
}
}
return false;
}
[Verb]
private sealed class SetOutfitVerb : Verb<InventoryComponent>
{
public override bool RequireInteractionRange => false;
public override bool BlockedByContainers => false;
protected override void GetData(IEntity user, InventoryComponent component, VerbData data)
{
data.Visibility = VerbVisibility.Invisible;
if (!CanCommand(user))
return;
data.Visibility = VerbVisibility.Visible;
data.Text = Loc.GetString("Set Outfit");
data.CategoryData = VerbCategories.Debug;
}
protected override void Activate(IEntity user, InventoryComponent component)
{
if (!CanCommand(user))
return;
var target = component.Owner;
var entityId = target.Uid.ToString();
var command = new SetOutfitCommand();
var host = IoCManager.Resolve<IServerConsoleHost>();
var args = new string[] {entityId};
var session = user.PlayerSession();
command.Execute(new ConsoleShell(host, session), $"{command.Command} {entityId}", args);
}
private static bool CanCommand(IEntity user)
{
var groupController = IoCManager.Resolve<IConGroupController>();
return user.TryGetComponent<IActorComponent>(out var player) &&
groupController.CanCommand(player.playerSession, "setoutfit");
}
}
}
}
| 35.007133
| 140
| 0.532478
|
[
"MIT"
] |
Neocraftz1553/space-station-14
|
Content.Server/GameObjects/Components/GUI/InventoryComponent.cs
| 24,540
|
C#
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.RecoveryServices.Properties;
using Microsoft.Azure.Management.RecoveryServices.Models;
using Microsoft.Azure.Portal.RecoveryServices.Models.Common;
namespace Microsoft.Azure.Commands.RecoveryServices
{
/// <summary>
/// Retrieves Azure Recovery Services Vault Settings File.
/// </summary>
[Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "RecoveryServicesVaultSettingsFile")]
[OutputType(typeof(VaultSettingsFilePath))]
public class GetAzureRmRecoveryServicesVaultSettingsFile : RecoveryServicesCmdletBase
{
/// <summary>
/// Expiry in hours for generated certificate.
/// </summary>
private const int VaultCertificateExpiryInHoursForHRM = 120;
/// <summary>
/// Expiry in hours for generated certificate.
/// </summary>
private const int VaultCertificateExpiryInHoursForBackup = 48;
/// <summary>
/// Vault Credential version.
/// </summary>
public const string VaultCredentialVersionAad = "2.0";
/// <summary>
/// Recovery services vault type.
/// </summary>
public const string RecoveryServicesVaultType = "Vaults";
#region Parameters
/// <summary>
/// Gets or sets vault Object.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, Position = 1)]
[ValidateNotNullOrEmpty]
public ARSVault Vault { get; set; }
/// <summary>
/// Gets or sets Site Identifier.
/// </summary>
[Parameter(ParameterSetName = ARSParameterSets.ForSite, Mandatory = true)]
[ValidateNotNullOrEmpty]
public String SiteIdentifier { get; set; }
/// <summary>
/// Gets or sets SiteFriendlyName.
/// </summary>
[Parameter(ParameterSetName = ARSParameterSets.ForSite, Mandatory = true)]
[ValidateNotNullOrEmpty]
public String SiteFriendlyName { get; set; }
/// <summary>
/// Gets or sets the path where the credential file is to be generated
/// </summary>
/// <summary>
/// Gets or sets vault Object.
/// </summary>
[Parameter(Position = 2)]
public string Path { get; set; }
/// <summary>
/// Gets or sets the path where the credential file is to be generated
/// </summary>
/// <summary>
/// Gets or sets vault Object.
/// </summary>
[Parameter(ParameterSetName = ARSParameterSets.ByDefault, Mandatory = false)]
[Parameter(ParameterSetName = ARSParameterSets.ForSite, Mandatory = false)]
public SwitchParameter SiteRecovery
{
get { return siteRecovery; }
set { siteRecovery = value; }
}
private bool siteRecovery;
/// <summary>
/// Gets or sets the path where the credential file is to be generated
/// </summary>
/// <summary>
/// Gets or sets vault Object.
/// </summary>
[Parameter(ParameterSetName = ARSParameterSets.ForBackupVaultType, Mandatory = true)]
public SwitchParameter Backup
{
get { return backup; }
set { backup = value; }
}
private bool backup;
#endregion Parameters
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteCmdlet()
{
try
{
if (backup)
{
this.GetAzureRMRecoveryServicesVaultBackupCredentials();
}
else
{
this.GetSiteRecoveryCredentials();
}
}
catch (AggregateException aggregateEx)
{
// if an exception is thrown from a task, it will be wrapped in AggregateException
// and propagated to the main thread. Just throwing the first exception in the list.
Exception exception = aggregateEx.InnerExceptions.First<Exception>();
this.HandleException(exception);
}
}
/// <summary>
/// Method to execute the command
/// </summary>
private void GetSiteRecoveryCredentials()
{
IAzureSubscription subscription = DefaultProfile.DefaultContext.Subscription;
// Generate certificate
X509Certificate2 cert = CertUtils.CreateSelfSignedCertificate(
VaultCertificateExpiryInHoursForHRM,
subscription.Id.ToString(),
this.Vault.Name);
ASRSite site = new ASRSite();
if (!string.IsNullOrEmpty(this.SiteIdentifier)
&& !string.IsNullOrEmpty(this.SiteFriendlyName))
{
site.ID = this.SiteIdentifier;
site.Name = this.SiteFriendlyName;
}
string fileName = this.GenerateFileName();
string filePath = string.IsNullOrEmpty(this.Path) ? Utilities.GetDefaultPath() : this.Path;
filePath = ResolveUserPath(filePath);
// Generate file.
if (RecoveryServicesClient.getVaultAuthType(this.Vault.ResourceGroupName, this.Vault.Name) == 0)
{
ASRVaultCreds vaultCreds = RecoveryServicesClient.GenerateVaultCredential(
cert,
this.Vault,
site,
AuthType.ACS);
// write the content to a file.
VaultSettingsFilePath output = new VaultSettingsFilePath()
{
FilePath = Utilities.WriteToFile<ASRVaultCreds>(vaultCreds, filePath, fileName)
};
// print the path to the user.
this.WriteObject(output, true);
}
else
{
string fullFilePath = System.IO.Path.Combine(filePath, fileName);
WriteDebug(
string.Format(
CultureInfo.InvariantCulture,
Resources.ExecutingGetVaultCredCmdlet,
subscription.Id,
this.Vault.ResourceGroupName,
this.Vault.Name,
fullFilePath));
VaultCertificateResponse vaultCertificateResponse = null;
try
{
// Upload cert into ID Mgmt
WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadingCertToIdmgmt));
vaultCertificateResponse = UploadCert(cert);
WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadedCertToIdmgmt));
// generate vault credentials
string vaultCredsFileContent = GenerateVaultCredsForSiteRecovery(
cert,
subscription.Id,
vaultCertificateResponse,
site);
WriteDebug(string.Format(Resources.SavingVaultCred, fullFilePath));
AzureSession.Instance.DataStore.WriteFile(fullFilePath, Encoding.UTF8.GetBytes(vaultCredsFileContent));
VaultSettingsFilePath output = new VaultSettingsFilePath()
{
FilePath = fullFilePath,
};
// Output filename back to user
WriteObject(output, true);
}
catch (Exception exception)
{
throw exception;
}
}
}
/// <summary>
/// Method to generate the file name
/// </summary>
/// <returns>file name as string.</returns>
private string GenerateFileName()
{
string fileName;
string format = "yyyy-MM-ddTHH-mm-ss";
if (string.IsNullOrEmpty(this.SiteIdentifier) || string.IsNullOrEmpty(this.SiteFriendlyName))
{
fileName = string.Format("{0}_{1}.VaultCredentials", this.Vault.Name, DateTime.UtcNow.ToString(format));
}
else
{
fileName = string.Format("{0}_{1}_{2}.VaultCredentials", this.SiteFriendlyName, this.Vault.Name, DateTime.UtcNow.ToString(format));
}
return fileName;
}
#region Backup Vault Credentials
/// <summary>
/// Get vault credentials for backup vault type.
/// </summary>
public void GetAzureRMRecoveryServicesVaultBackupCredentials()
{
string targetLocation = string.IsNullOrEmpty(this.Path) ? Utilities.GetDefaultPath() : this.Path;
targetLocation = ResolveUserPath(targetLocation);
if (!Directory.Exists(targetLocation))
{
throw new ArgumentException(Resources.VaultCredPathException);
}
string subscriptionId = DefaultContext.Subscription.Id.ToString();
string displayName = this.Vault.Name;
WriteDebug(string.Format(CultureInfo.InvariantCulture,
Resources.ExecutingGetVaultCredCmdlet,
subscriptionId, this.Vault.ResourceGroupName, this.Vault.Name, targetLocation));
// Generate certificate
X509Certificate2 cert = CertUtils.CreateSelfSignedCertificate(
VaultCertificateExpiryInHoursForBackup, subscriptionId.ToString(), this.Vault.Name);
VaultCertificateResponse vaultCertificateResponse = null;
string channelIntegrityKey = string.Empty;
try
{
// Upload cert into ID Mgmt
WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadingCertToIdmgmt));
vaultCertificateResponse = UploadCert(cert);
WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadedCertToIdmgmt));
}
catch (Exception exception)
{
throw exception;
}
// generate vault credentials
string vaultCredsFileContent = GenerateVaultCreds(cert, subscriptionId, vaultCertificateResponse);
// NOTE: One of the scenarios for this cmdlet is to generate a file which will be an input
// to DPM servers.
// We found a bug in the DPM UI which is looking for a particular namespace in the input file.
// The below is a hack to circumvent this issue and this would be removed once the bug can be fixed.
vaultCredsFileContent = vaultCredsFileContent.Replace("Microsoft.Azure.Commands.AzureBackup.Models",
"Microsoft.Azure.Portal.RecoveryServices.Models.Common");
// prepare for download
string fileName = string.Format("{0}_{1:ddd MMM dd yyyy}.VaultCredentials", displayName, DateTime.UtcNow);
string filePath = System.IO.Path.Combine(targetLocation, fileName);
WriteDebug(string.Format(Resources.SavingVaultCred, filePath));
AzureSession.Instance.DataStore.WriteFile(filePath, Encoding.UTF8.GetBytes(vaultCredsFileContent));
VaultSettingsFilePath output = new VaultSettingsFilePath()
{
FilePath = filePath,
};
// Output filename back to user
WriteObject(output);
}
/// <summary>
/// Upload certificate
/// </summary>
/// <param name="cert">management certificate</param>
/// <returns>acs namespace of the uploaded cert</returns>
private VaultCertificateResponse UploadCert(X509Certificate2 cert)
{
return RecoveryServicesClient.UploadCertificate(cert, this.Vault);
}
/// <summary>
/// Generates vault creds file
/// </summary>
/// <param name="cert">management certificate</param>
/// <param name="subscriptionId">subscription Id</param>
/// <param name="acsNamespace">acs namespace</param>
/// <returns>xml file in string format</returns>
private string GenerateVaultCreds(X509Certificate2 cert, string subscriptionId, VaultCertificateResponse vaultCertificateResponse)
{
try
{
return GenerateVaultCredsForBackup(cert, subscriptionId, vaultCertificateResponse);
}
catch (Exception exception)
{
throw exception;
}
}
/// <summary>
/// Generates vault creds file content for backup Vault
/// </summary>
/// <param name="cert">management certificate</param>
/// <param name="subscriptionId">subscription Id</param>
/// <param name="acsNamespace">acs namespace</param>
/// <returns>xml file in string format</returns>
private string GenerateVaultCredsForBackup(X509Certificate2 cert, string subscriptionId,
VaultCertificateResponse vaultCertificateResponse)
{
using (var output = new MemoryStream())
{
using (var writer = XmlWriter.Create(output, GetXmlWriterSettings()))
{
ResourceCertificateAndAadDetails aadDetails = vaultCertificateResponse.Properties as ResourceCertificateAndAadDetails;
RSBackupVaultAADCreds vaultCreds = new RSBackupVaultAADCreds()
{
SubscriptionId = subscriptionId,
ResourceName = Vault.Name,
ManagementCert = CertUtils.SerializeCert(cert, X509ContentType.Pfx),
ResourceId = aadDetails.ResourceId.Value,
AadAuthority = aadDetails.AadAuthority,
AadTenantId = aadDetails.AadTenantId,
ServicePrincipalClientId = aadDetails.ServicePrincipalClientId,
IdMgmtRestEndpoint = aadDetails.AzureManagementEndpointAudience,
ProviderNamespace = PSRecoveryServicesClient.ProductionRpNamespace,
ResourceGroup = Vault.ResourceGroupName,
Location = Vault.Location,
Version = VaultCredentialVersionAad,
ResourceType = RecoveryServicesVaultType,
AgentLinks = GetAgentLinks()
};
DataContractSerializer serializer = new DataContractSerializer(typeof(RSBackupVaultAADCreds));
serializer.WriteObject(writer, vaultCreds);
WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.BackupVaultSerialized));
}
return Encoding.UTF8.GetString(output.ToArray());
}
}
/// <summary>
/// Generates vault creds file content for Site Recovery Vault
/// </summary>
/// <param name="cert">management certificate</param>
/// <param name="subscriptionId">subscription Id</param>
/// <param name="vaultCertificateResponse">vaultCertificate Response</param>
/// <param name="asrSite">asrSite Info</param>
/// <returns>xml file in string format</returns>
private string GenerateVaultCredsForSiteRecovery(X509Certificate2 cert, string subscriptionId,
VaultCertificateResponse vaultCertificateResponse, ASRSite asrSite)
{
using (var output = new MemoryStream())
{
using (var writer = XmlWriter.Create(output, GetXmlWriterSettings()))
{
ResourceCertificateAndAadDetails aadDetails = vaultCertificateResponse.Properties as ResourceCertificateAndAadDetails;
string resourceProviderNamespace = string.Empty;
string resourceType = string.Empty;
Utilities.GetResourceProviderNamespaceAndType(this.Vault.ID, out resourceProviderNamespace, out resourceType);
Logger.Instance.WriteDebug(string.Format(
"GenerateVaultCredential resourceProviderNamespace = {0}, resourceType = {1}",
resourceProviderNamespace,
resourceType));
// Update vault settings with the working vault to generate file
Utilities.UpdateCurrentVaultContext(new ASRVaultCreds()
{
ResourceGroupName = this.Vault.ResourceGroupName,
ResourceName = this.Vault.Name,
ResourceNamespace = resourceProviderNamespace,
ARMResourceType = resourceType
});
//Code taken from Ibiza code
string aadAudience = string.Format(CultureInfo.InvariantCulture,
@"https://RecoveryServiceVault/{0}/{1}/{2}",
Vault.Location,
Vault.Name,
aadDetails.ResourceId);
RSVaultAsrCreds vaultCreds = new RSVaultAsrCreds()
{
VaultDetails = new ASRVaultDetails
{
SubscriptionId = subscriptionId,
ResourceGroup = this.Vault.ResourceGroupName,
ResourceName = this.Vault.Name,
ResourceId = aadDetails.ResourceId.Value,
Location = Vault.Location,
ResourceType = RecoveryServicesVaultType,
ProviderNamespace = PSRecoveryServicesClient.ProductionRpNamespace
},
ManagementCert = CertUtils.SerializeCert(cert, X509ContentType.Pfx),
Version = VaultCredentialVersionAad,
AadDetails = new ASRVaultAadDetails
{
AadAuthority = aadDetails.AadAuthority,
AadTenantId = aadDetails.AadTenantId,
ServicePrincipalClientId = aadDetails.ServicePrincipalClientId,
AadVaultAudience = aadAudience,
ArmManagementEndpoint = aadDetails.AzureManagementEndpointAudience
},
ChannelIntegrityKey = this.RecoveryServicesClient.GetCurrentVaultChannelIntegrityKey(),
SiteId = asrSite.ID == null ? String.Empty : asrSite.ID,
SiteName = asrSite.Name == null ? String.Empty : asrSite.Name
};
DataContractSerializer serializer = new DataContractSerializer(typeof(RSVaultAsrCreds));
serializer.WriteObject(writer, vaultCreds);
}
return Encoding.UTF8.GetString(output.ToArray());
}
}
/// <summary>
/// Get Agent Links
/// </summary>
/// <returns>Agent links in string format</returns>
private static string GetAgentLinks()
{
return "WABUpdateKBLink,http://go.microsoft.com/fwlink/p/?LinkId=229525;" +
"StorageQuotaPurchaseLink,http://go.microsoft.com/fwlink/?LinkId=205490;" +
"WebPortalLink,http://go.microsoft.com/fwlink/?LinkId=817353;" +
"WABprivacyStatement,http://go.microsoft.com/fwlink/?LinkId=221308";
}
/// <summary>
/// A set of XmlWriterSettings to use for the publishing profile
/// </summary>
/// <returns>The XmlWriterSettings set</returns>
private XmlWriterSettings GetXmlWriterSettings()
{
return new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
Indent = true,
NewLineOnAttributes = true
};
}
#endregion
}
}
| 43.659363
| 148
| 0.561756
|
[
"MIT"
] |
FonsecaSergio/azure-powershell
|
src/ResourceManager/RecoveryServices/Commands.RecoveryServices/Vault/GetAzureRMRecoveryServicesVaultSettingsFile.cs
| 21,418
|
C#
|
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
// Several test methods in this file use the same member data, but in some cases the test does not use all of the
// supported parameters. See https://github.com/xunit/xunit/issues/1556.
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters
namespace StyleCop.Analyzers.Test.ReadabilityRules
{
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using TestHelper;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopDiagnosticVerifier<StyleCop.Analyzers.ReadabilityRules.SA1117ParametersMustBeOnSameLineOrSeparateLines>;
public class SA1117UnitTests
{
public static IEnumerable<object[]> GetTestDeclarations(string delimiter)
{
yield return new object[] { $"public Foo(int a, int b,{delimiter} string s) {{ }}" };
yield return new object[] { $"public object Bar(int a, int b,{delimiter} string s) => null;" };
yield return new object[] { $"public object this[int a, int b,{delimiter} string s] => null;" };
yield return new object[] { $"public delegate void Bar(int a, int b,{delimiter} string s);" };
}
public static IEnumerable<object[]> GetTestConstructorInitializers(string delimiter)
{
yield return new object[] { $"this(42, 43, {delimiter} \"hello\")" };
yield return new object[] { $"base(42, 43, {delimiter} \"hello\")" };
}
public static IEnumerable<object[]> GetTestExpressions(string delimiter)
{
yield return new object[] { $"Bar(1, 2, {delimiter} 2)", 13 };
yield return new object[] { $"System.Action<int, int, int> func = (int x, int y, {delimiter} int z) => Bar(x, y, z)", 41 };
yield return new object[] { $"System.Action<int, int, int> func = delegate(int x, int y, {delimiter} int z) {{ Bar(x, y, z); }}", 49 };
yield return new object[] { $"new System.DateTime(2015, 9, {delimiter} 14)", 20 };
yield return new object[] { $"var arr = new string[2, 2, {delimiter} 2];", 30 };
yield return new object[] { $"char cc = (new char[3, 3, 3])[2, 2,{delimiter} 2];", 36 };
yield return new object[] { $"char? c = (new char[3, 3, 3])?[2, 2,{delimiter} 2];", 37 };
yield return new object[] { $"long ll = this[2, 2,{delimiter} 2];", 24 };
}
public static IEnumerable<object[]> ValidTestExpressions()
{
yield return new object[] { $"System.Action func = () => Bar(0, 2, 3)", 0 };
yield return new object[] { $"System.Action<int> func = x => Bar(x, 2, 3)", 0 };
yield return new object[] { $"System.Action func = delegate {{ Bar(0, 0, 0); }}", 0 };
yield return new object[] { "var weird = new int[10][,,,];", 0 };
}
public static IEnumerable<object[]> ValidTestDeclarations()
{
yield return new object[]
{
$@"public Foo(
int a, int b, string s) {{ }}",
};
yield return new object[]
{
$@"public Foo(
int a,
int b,
string s) {{ }}",
};
}
[Theory]
[MemberData(nameof(GetTestDeclarations), "")]
[MemberData(nameof(ValidTestDeclarations))]
public async Task TestValidDeclarationAsync(string declaration)
{
var testCode = $@"
class Foo
{{
{declaration}
}}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(GetTestDeclarations), "\r\n")]
public async Task TestInvalidDeclarationAsync(string declaration)
{
var testCode = $@"
class Foo
{{
{declaration}
}}";
DiagnosticResult expected = Diagnostic().WithLocation(5, 2);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(GetTestConstructorInitializers), "")]
public async Task TestValidConstructorInitializerAsync(string initializer)
{
var testCode = $@"
class Base
{{
public Base(int a, int b, string s)
{{
}}
}}
class Derived : Base
{{
public Derived()
: {initializer}
{{
}}
public Derived(int i, int j, string z)
: base(i, j, z)
{{
}}
}}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(GetTestConstructorInitializers), "\r\n")]
public async Task TestInvalidConstructorInitializerAsync(string initializer)
{
var testCode = $@"
class Base
{{
public Base(int a, int b, string s)
{{
}}
}}
class Derived : Base
{{
public Derived()
: {initializer}
{{
}}
public Derived(int i, int j, string z)
: base(i, j, z)
{{
}}
}}";
DiagnosticResult expected = Diagnostic().WithLocation(13, 2);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(GetTestExpressions), "")]
[MemberData(nameof(ValidTestExpressions))]
public async Task TestValidExpressionAsync(string expression, int column)
{
var testCode = $@"
class Foo
{{
public void Bar(int i, int j, int k)
{{
}}
public void Baz()
{{
{expression};
}}
public long this[int a, int b, int s] => a + b + s;
}}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Theory]
[MemberData(nameof(GetTestExpressions), "\r\n")]
public async Task TestInvalidExpressionAsync(string expression, int column)
{
var testCode = $@"
class Foo
{{
public void Bar(int i, int j, int k)
{{
}}
public void Baz()
{{
{expression};
}}
public long this[int a, int b, int s] => a + b + s;
}}";
DiagnosticResult expected = Diagnostic().WithLocation(11, 2);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestValidAttributeAsync()
{
var testCode = @"
[System.AttributeUsage(System.AttributeTargets.Class)]
public class MyAttribute : System.Attribute
{
public MyAttribute(int a, int b, int c)
{
}
}
[MyAttribute(1, 2, 3)]
class Foo
{
}
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1211
[System.Obsolete]
class ObsoleteType
{
}";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
public async Task TestInvalidAttributeAsync()
{
var testCode = @"
[System.AttributeUsage(System.AttributeTargets.Class)]
public class MyAttribute : System.Attribute
{
public MyAttribute(int a, int b, int c)
{
}
}
[MyAttribute(
1,
2, 3)]
class Foo
{
}";
DiagnosticResult expected = Diagnostic().WithLocation(12, 8);
await VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
}
}
}
| 31.424
| 163
| 0.60667
|
[
"Apache-2.0"
] |
Andreyul/StyleCopAnalyzers
|
StyleCop.Analyzers/StyleCop.Analyzers.Test/ReadabilityRules/SA1117UnitTests.cs
| 7,858
|
C#
|
using System.Collections.Generic;
using OrchardCore.Security.Permissions;
namespace OrchardCore.Tenants
{
public class Permissions : IPermissionProvider
{
public static readonly Permission ManageTenants = new Permission("ManageTenants", "Manage tenants");
public IEnumerable<Permission> GetPermissions()
{
return new[] { ManageTenants };
}
public IEnumerable<PermissionStereotype> GetDefaultStereotypes()
{
return new[]
{
new PermissionStereotype
{
Name = "Administrator",
Permissions = new[] { ManageTenants }
}
};
}
}
}
| 27
| 108
| 0.563786
|
[
"BSD-3-Clause"
] |
1426463237/OrchardCore
|
src/OrchardCore.Modules/OrchardCore.Tenants/Permissions.cs
| 731
|
C#
|
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
namespace WC.Cryptography
{
public class AESEncodeMessage
{
public string data;
public string hmac;
public string iv;
}
public class WalletConnectCryptography
{
static async public Task<string> AESEncode(string _key, string _message)
{
byte[] key = HexToByteArray(_key);
byte[] msg = Encoding.UTF8.GetBytes(_message);
byte[] encryptedContent, iv, hmac;
using (MemoryStream ms = new MemoryStream())
{
using (AesManaged aes = new AesManaged())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 256;
iv = aes.IV;
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
await cs.WriteAsync(msg, 0, msg.Length);
}
encryptedContent = ms.ToArray();
}
}
using (HMACSHA256 hmac256 = new HMACSHA256(key))
{
hmac256.Initialize();
byte[] toSign = new byte[iv.Length + encryptedContent.Length];
//copy our 2 array into one
Buffer.BlockCopy(encryptedContent, 0, toSign, 0, encryptedContent.Length);
Buffer.BlockCopy(iv, 0, toSign, encryptedContent.Length, iv.Length);
hmac = hmac256.ComputeHash(toSign);
}
AESEncodeMessage aesEncodeMessage = new AESEncodeMessage()
{
data = BitConverter.ToString(encryptedContent).Replace("-", ""),
hmac = BitConverter.ToString(hmac).Replace("-", ""),
iv = BitConverter.ToString(iv).Replace("-", "")
};
return Newtonsoft.Json.JsonConvert.SerializeObject(aesEncodeMessage);
}
static async public Task<string> AESDecode(string _key, string _encryptedContent, string _iv)
{
byte[] encrypted = HexToByteArray(_encryptedContent);
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 256;
aes.Key = HexToByteArray(_key);
aes.IV = HexToByteArray(_iv);
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(encrypted))
{
using (MemoryStream sink = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
await cs.CopyToAsync(sink);
string decrypted = Encoding.UTF8.GetString(sink.ToArray());
return decrypted;
}
}
}
}
}
static private byte[] HexToByteArray(string hex)
{
// https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
}
| 26.290909
| 105
| 0.682918
|
[
"MIT"
] |
leon-do/wc-unity
|
WalletConnectCryptography.cs
| 2,892
|
C#
|
namespace Sistema_de_Salon_de_belleza.Todos_los_formularios
{
partial class FormProductos
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.Label activoLabel;
System.Windows.Forms.Label descripcionLabel;
System.Windows.Forms.Label existenciaLabel;
System.Windows.Forms.Label idLabel;
System.Windows.Forms.Label marcaLabel;
System.Windows.Forms.Label precioLabel;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormProductos));
this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator();
this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox();
this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel();
this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton();
this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton();
this.seguridadBlBindingNavigatorSaveItem = new System.Windows.Forms.ToolStripButton();
this.seguridadBlBindingNavigator = new System.Windows.Forms.BindingNavigator(this.components);
this.ListaProductosBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.activoCheckBox = new System.Windows.Forms.CheckBox();
this.descripcionTextBox = new System.Windows.Forms.TextBox();
this.existenciaTextBox = new System.Windows.Forms.TextBox();
this.idTextBox = new System.Windows.Forms.TextBox();
this.marcaTextBox = new System.Windows.Forms.TextBox();
this.precioTextBox = new System.Windows.Forms.TextBox();
this.listaProductosDataGridView = new System.Windows.Forms.DataGridView();
this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewCheckBoxColumn1 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
activoLabel = new System.Windows.Forms.Label();
descripcionLabel = new System.Windows.Forms.Label();
existenciaLabel = new System.Windows.Forms.Label();
idLabel = new System.Windows.Forms.Label();
marcaLabel = new System.Windows.Forms.Label();
precioLabel = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.seguridadBlBindingNavigator)).BeginInit();
this.seguridadBlBindingNavigator.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ListaProductosBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.listaProductosDataGridView)).BeginInit();
this.SuspendLayout();
//
// activoLabel
//
activoLabel.AutoSize = true;
activoLabel.BackColor = System.Drawing.Color.Transparent;
activoLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
activoLabel.Location = new System.Drawing.Point(11, 70);
activoLabel.Name = "activoLabel";
activoLabel.Size = new System.Drawing.Size(56, 20);
activoLabel.TabIndex = 2;
activoLabel.Text = "Activo:";
//
// descripcionLabel
//
descripcionLabel.AutoSize = true;
descripcionLabel.BackColor = System.Drawing.Color.Transparent;
descripcionLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
descripcionLabel.Location = new System.Drawing.Point(10, 98);
descripcionLabel.Name = "descripcionLabel";
descripcionLabel.Size = new System.Drawing.Size(96, 20);
descripcionLabel.TabIndex = 4;
descripcionLabel.Text = "Descripcion:";
//
// existenciaLabel
//
existenciaLabel.AutoSize = true;
existenciaLabel.BackColor = System.Drawing.Color.Transparent;
existenciaLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
existenciaLabel.Location = new System.Drawing.Point(11, 124);
existenciaLabel.Name = "existenciaLabel";
existenciaLabel.Size = new System.Drawing.Size(85, 20);
existenciaLabel.TabIndex = 6;
existenciaLabel.Text = "Existencia:";
//
// idLabel
//
idLabel.AutoSize = true;
idLabel.BackColor = System.Drawing.Color.Transparent;
idLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
idLabel.Location = new System.Drawing.Point(11, 150);
idLabel.Name = "idLabel";
idLabel.Size = new System.Drawing.Size(27, 20);
idLabel.TabIndex = 8;
idLabel.Text = "Id:";
//
// marcaLabel
//
marcaLabel.AutoSize = true;
marcaLabel.BackColor = System.Drawing.Color.Transparent;
marcaLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
marcaLabel.Location = new System.Drawing.Point(11, 176);
marcaLabel.Name = "marcaLabel";
marcaLabel.Size = new System.Drawing.Size(57, 20);
marcaLabel.TabIndex = 10;
marcaLabel.Text = "Marca:";
//
// precioLabel
//
precioLabel.AutoSize = true;
precioLabel.BackColor = System.Drawing.Color.Transparent;
precioLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
precioLabel.Location = new System.Drawing.Point(11, 202);
precioLabel.Name = "precioLabel";
precioLabel.Size = new System.Drawing.Size(57, 20);
precioLabel.TabIndex = 12;
precioLabel.Text = "Precio:";
//
// bindingNavigatorMoveFirstItem
//
this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image")));
this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem";
this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMoveFirstItem.Text = "Mover primero";
//
// bindingNavigatorMovePreviousItem
//
this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image")));
this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem";
this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMovePreviousItem.Text = "Mover anterior";
//
// bindingNavigatorSeparator
//
this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator";
this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25);
//
// bindingNavigatorPositionItem
//
this.bindingNavigatorPositionItem.AccessibleName = "Posición";
this.bindingNavigatorPositionItem.AutoSize = false;
this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem";
this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 23);
this.bindingNavigatorPositionItem.Text = "0";
this.bindingNavigatorPositionItem.ToolTipText = "Posición actual";
//
// bindingNavigatorCountItem
//
this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem";
this.bindingNavigatorCountItem.Size = new System.Drawing.Size(37, 22);
this.bindingNavigatorCountItem.Text = "de {0}";
this.bindingNavigatorCountItem.ToolTipText = "Número total de elementos";
//
// bindingNavigatorSeparator1
//
this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1";
this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25);
//
// bindingNavigatorMoveNextItem
//
this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image")));
this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem";
this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMoveNextItem.Text = "Mover siguiente";
//
// bindingNavigatorMoveLastItem
//
this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image")));
this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem";
this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorMoveLastItem.Text = "Mover último";
//
// bindingNavigatorSeparator2
//
this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2";
this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25);
//
// bindingNavigatorAddNewItem
//
this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image")));
this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem";
this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorAddNewItem.Text = "Agregar nuevo";
//
// bindingNavigatorDeleteItem
//
this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image")));
this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem";
this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true;
this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22);
this.bindingNavigatorDeleteItem.Text = "Eliminar";
//
// seguridadBlBindingNavigatorSaveItem
//
this.seguridadBlBindingNavigatorSaveItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.seguridadBlBindingNavigatorSaveItem.Enabled = false;
this.seguridadBlBindingNavigatorSaveItem.Image = ((System.Drawing.Image)(resources.GetObject("seguridadBlBindingNavigatorSaveItem.Image")));
this.seguridadBlBindingNavigatorSaveItem.Name = "seguridadBlBindingNavigatorSaveItem";
this.seguridadBlBindingNavigatorSaveItem.Size = new System.Drawing.Size(23, 22);
this.seguridadBlBindingNavigatorSaveItem.Text = "Guardar datos";
//
// seguridadBlBindingNavigator
//
this.seguridadBlBindingNavigator.AddNewItem = this.bindingNavigatorAddNewItem;
this.seguridadBlBindingNavigator.CountItem = this.bindingNavigatorCountItem;
this.seguridadBlBindingNavigator.DeleteItem = this.bindingNavigatorDeleteItem;
this.seguridadBlBindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.bindingNavigatorMoveFirstItem,
this.bindingNavigatorMovePreviousItem,
this.bindingNavigatorSeparator,
this.bindingNavigatorPositionItem,
this.bindingNavigatorCountItem,
this.bindingNavigatorSeparator1,
this.bindingNavigatorMoveNextItem,
this.bindingNavigatorMoveLastItem,
this.bindingNavigatorSeparator2,
this.bindingNavigatorAddNewItem,
this.bindingNavigatorDeleteItem,
this.seguridadBlBindingNavigatorSaveItem});
this.seguridadBlBindingNavigator.Location = new System.Drawing.Point(0, 0);
this.seguridadBlBindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem;
this.seguridadBlBindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem;
this.seguridadBlBindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem;
this.seguridadBlBindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem;
this.seguridadBlBindingNavigator.Name = "seguridadBlBindingNavigator";
this.seguridadBlBindingNavigator.PositionItem = this.bindingNavigatorPositionItem;
this.seguridadBlBindingNavigator.Size = new System.Drawing.Size(1073, 25);
this.seguridadBlBindingNavigator.TabIndex = 0;
this.seguridadBlBindingNavigator.Text = "bindingNavigator1";
//
// ListaProductosBindingSource
//
this.ListaProductosBindingSource.DataSource = typeof(BL.Rentas.Producto);
this.ListaProductosBindingSource.CurrentChanged += new System.EventHandler(this.productoBindingSource_CurrentChanged);
//
// activoCheckBox
//
this.activoCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.ListaProductosBindingSource, "Activo", true));
this.activoCheckBox.Location = new System.Drawing.Point(105, 69);
this.activoCheckBox.Name = "activoCheckBox";
this.activoCheckBox.Size = new System.Drawing.Size(104, 24);
this.activoCheckBox.TabIndex = 3;
this.activoCheckBox.Text = "checkBox1";
this.activoCheckBox.UseVisualStyleBackColor = true;
//
// descripcionTextBox
//
this.descripcionTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ListaProductosBindingSource, "Descripcion", true));
this.descripcionTextBox.Location = new System.Drawing.Point(105, 99);
this.descripcionTextBox.Name = "descripcionTextBox";
this.descripcionTextBox.Size = new System.Drawing.Size(104, 20);
this.descripcionTextBox.TabIndex = 5;
//
// existenciaTextBox
//
this.existenciaTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ListaProductosBindingSource, "Existencia", true));
this.existenciaTextBox.Location = new System.Drawing.Point(105, 125);
this.existenciaTextBox.Name = "existenciaTextBox";
this.existenciaTextBox.Size = new System.Drawing.Size(104, 20);
this.existenciaTextBox.TabIndex = 7;
//
// idTextBox
//
this.idTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ListaProductosBindingSource, "Id", true));
this.idTextBox.Location = new System.Drawing.Point(105, 151);
this.idTextBox.Name = "idTextBox";
this.idTextBox.Size = new System.Drawing.Size(104, 20);
this.idTextBox.TabIndex = 9;
//
// marcaTextBox
//
this.marcaTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ListaProductosBindingSource, "Marca", true));
this.marcaTextBox.Location = new System.Drawing.Point(105, 177);
this.marcaTextBox.Name = "marcaTextBox";
this.marcaTextBox.Size = new System.Drawing.Size(104, 20);
this.marcaTextBox.TabIndex = 11;
//
// precioTextBox
//
this.precioTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ListaProductosBindingSource, "Precio", true));
this.precioTextBox.Location = new System.Drawing.Point(105, 203);
this.precioTextBox.Name = "precioTextBox";
this.precioTextBox.Size = new System.Drawing.Size(104, 20);
this.precioTextBox.TabIndex = 13;
//
// listaProductosDataGridView
//
this.listaProductosDataGridView.AutoGenerateColumns = false;
this.listaProductosDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.listaProductosDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.dataGridViewTextBoxColumn1,
this.dataGridViewTextBoxColumn2,
this.dataGridViewTextBoxColumn3,
this.dataGridViewTextBoxColumn4,
this.dataGridViewTextBoxColumn5,
this.dataGridViewCheckBoxColumn1});
this.listaProductosDataGridView.DataSource = this.ListaProductosBindingSource;
this.listaProductosDataGridView.Location = new System.Drawing.Point(243, 46);
this.listaProductosDataGridView.Name = "listaProductosDataGridView";
this.listaProductosDataGridView.Size = new System.Drawing.Size(650, 526);
this.listaProductosDataGridView.TabIndex = 13;
//
// dataGridViewTextBoxColumn1
//
this.dataGridViewTextBoxColumn1.DataPropertyName = "Id";
this.dataGridViewTextBoxColumn1.HeaderText = "Id";
this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
//
// dataGridViewTextBoxColumn2
//
this.dataGridViewTextBoxColumn2.DataPropertyName = "Descripcion";
this.dataGridViewTextBoxColumn2.HeaderText = "Descripcion";
this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
//
// dataGridViewTextBoxColumn3
//
this.dataGridViewTextBoxColumn3.DataPropertyName = "Marca";
this.dataGridViewTextBoxColumn3.HeaderText = "Marca";
this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
//
// dataGridViewTextBoxColumn4
//
this.dataGridViewTextBoxColumn4.DataPropertyName = "Precio";
this.dataGridViewTextBoxColumn4.HeaderText = "Precio";
this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
//
// dataGridViewTextBoxColumn5
//
this.dataGridViewTextBoxColumn5.DataPropertyName = "Existencia";
this.dataGridViewTextBoxColumn5.HeaderText = "Existencia";
this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5";
//
// dataGridViewCheckBoxColumn1
//
this.dataGridViewCheckBoxColumn1.DataPropertyName = "Activo";
this.dataGridViewCheckBoxColumn1.HeaderText = "Activo";
this.dataGridViewCheckBoxColumn1.Name = "dataGridViewCheckBoxColumn1";
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// FormProductos
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::Sistema_de_Salon_de_belleza.Properties.Resources.fondo_poligono_geometrico_papel_pintado_diamantes_patron_elegante_color_suave_206846_996;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ClientSize = new System.Drawing.Size(1073, 629);
this.Controls.Add(this.listaProductosDataGridView);
this.Controls.Add(activoLabel);
this.Controls.Add(this.activoCheckBox);
this.Controls.Add(descripcionLabel);
this.Controls.Add(this.descripcionTextBox);
this.Controls.Add(existenciaLabel);
this.Controls.Add(this.existenciaTextBox);
this.Controls.Add(idLabel);
this.Controls.Add(this.idTextBox);
this.Controls.Add(marcaLabel);
this.Controls.Add(this.marcaTextBox);
this.Controls.Add(precioLabel);
this.Controls.Add(this.precioTextBox);
this.Controls.Add(this.seguridadBlBindingNavigator);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Location = new System.Drawing.Point(0, 50);
this.Name = "FormProductos";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Productos";
this.Load += new System.EventHandler(this.Productos_Load);
((System.ComponentModel.ISupportInitialize)(this.seguridadBlBindingNavigator)).EndInit();
this.seguridadBlBindingNavigator.ResumeLayout(false);
this.seguridadBlBindingNavigator.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ListaProductosBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.listaProductosDataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem;
private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem;
private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator;
private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem;
private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem;
private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1;
private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem;
private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem;
private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2;
private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem;
private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem;
private System.Windows.Forms.ToolStripButton seguridadBlBindingNavigatorSaveItem;
private System.Windows.Forms.BindingNavigator seguridadBlBindingNavigator;
private System.Windows.Forms.BindingSource ListaProductosBindingSource;
private System.Windows.Forms.CheckBox activoCheckBox;
private System.Windows.Forms.TextBox descripcionTextBox;
private System.Windows.Forms.TextBox existenciaTextBox;
private System.Windows.Forms.TextBox idTextBox;
private System.Windows.Forms.TextBox marcaTextBox;
private System.Windows.Forms.TextBox precioTextBox;
private System.Windows.Forms.DataGridView listaProductosDataGridView;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
private System.Windows.Forms.DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn1;
private System.Windows.Forms.ImageList imageList1;
}
}
| 61.601336
| 182
| 0.663907
|
[
"MIT"
] |
ProyectoL2/Proyecto-L3
|
Sistema de Salon de belleza/Sistema de Salon de belleza/Todos los formularios/Form3.Designer.cs
| 27,665
|
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Gcp.Dataproc.Outputs
{
[OutputType]
public sealed class ClusterClusterConfigEncryptionConfig
{
/// <summary>
/// The Cloud KMS key name to use for PD disk encryption for
/// all instances in the cluster.
/// </summary>
public readonly string KmsKeyName;
[OutputConstructor]
private ClusterClusterConfigEncryptionConfig(string kmsKeyName)
{
KmsKeyName = kmsKeyName;
}
}
}
| 27.758621
| 88
| 0.673292
|
[
"ECL-2.0",
"Apache-2.0"
] |
dimpu47/pulumi-gcp
|
sdk/dotnet/Dataproc/Outputs/ClusterClusterConfigEncryptionConfig.cs
| 805
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Crestron.SimplSharp.CrestronIO
{
public class FileNotFoundException : Exception
{
}
}
| 16.333333
| 50
| 0.755102
|
[
"MIT"
] |
ProfessorAire/Evands.Pellucid-Crestron
|
src/Evands.Pellucid.Fakes/Crestron/SimplSharp/CrestronIO/FileNotFoundException.cs
| 198
|
C#
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190901.Inputs
{
/// <summary>
/// A load balancing rule for a load balancer.
/// </summary>
public sealed class LoadBalancingRuleArgs : Pulumi.ResourceArgs
{
/// <summary>
/// A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs.
/// </summary>
[Input("backendAddressPool")]
public Input<Inputs.SubResourceArgs>? BackendAddressPool { get; set; }
/// <summary>
/// The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables "Any Port".
/// </summary>
[Input("backendPort")]
public Input<int>? BackendPort { get; set; }
/// <summary>
/// Configures SNAT for the VMs in the backend pool to use the publicIP address specified in the frontend of the load balancing rule.
/// </summary>
[Input("disableOutboundSnat")]
public Input<bool>? DisableOutboundSnat { get; set; }
/// <summary>
/// Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint.
/// </summary>
[Input("enableFloatingIP")]
public Input<bool>? EnableFloatingIP { get; set; }
/// <summary>
/// Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP.
/// </summary>
[Input("enableTcpReset")]
public Input<bool>? EnableTcpReset { get; set; }
/// <summary>
/// A reference to frontend IP addresses.
/// </summary>
[Input("frontendIPConfiguration")]
public Input<Inputs.SubResourceArgs>? FrontendIPConfiguration { get; set; }
/// <summary>
/// The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables "Any Port".
/// </summary>
[Input("frontendPort", required: true)]
public Input<int> FrontendPort { get; set; } = null!;
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP.
/// </summary>
[Input("idleTimeoutInMinutes")]
public Input<int>? IdleTimeoutInMinutes { get; set; }
/// <summary>
/// The load distribution policy for this rule.
/// </summary>
[Input("loadDistribution")]
public InputUnion<string, Pulumi.AzureNextGen.Network.V20190901.LoadDistribution>? LoadDistribution { get; set; }
/// <summary>
/// The name of the resource that is unique within the set of load balancing rules used by the load balancer. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The reference of the load balancer probe used by the load balancing rule.
/// </summary>
[Input("probe")]
public Input<Inputs.SubResourceArgs>? Probe { get; set; }
/// <summary>
/// The reference to the transport protocol used by the load balancing rule.
/// </summary>
[Input("protocol", required: true)]
public InputUnion<string, Pulumi.AzureNextGen.Network.V20190901.TransportProtocol> Protocol { get; set; } = null!;
public LoadBalancingRuleArgs()
{
}
}
}
| 42.425743
| 288
| 0.634772
|
[
"Apache-2.0"
] |
pulumi/pulumi-azure-nextgen
|
sdk/dotnet/Network/V20190901/Inputs/LoadBalancingRuleArgs.cs
| 4,285
|
C#
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/WinTrust.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public unsafe partial struct CRYPT_PROVIDER_SGNR
{
[NativeTypeName("DWORD")]
public uint cbStruct;
public FILETIME sftVerifyAsOf;
[NativeTypeName("DWORD")]
public uint csCertChain;
[NativeTypeName("struct _CRYPT_PROVIDER_CERT *")]
public CRYPT_PROVIDER_CERT* pasCertChain;
[NativeTypeName("DWORD")]
public uint dwSignerType;
[NativeTypeName("CMSG_SIGNER_INFO *")]
public CMSG_SIGNER_INFO* psSigner;
[NativeTypeName("DWORD")]
public uint dwError;
[NativeTypeName("DWORD")]
public uint csCounterSigners;
[NativeTypeName("struct _CRYPT_PROVIDER_SGNR *")]
public CRYPT_PROVIDER_SGNR* pasCounterSigners;
[NativeTypeName("PCCERT_CHAIN_CONTEXT")]
public CERT_CHAIN_CONTEXT* pChainContext;
}
}
| 29.35
| 145
| 0.684838
|
[
"MIT"
] |
Ethereal77/terrafx.interop.windows
|
sources/Interop/Windows/um/WinTrust/CRYPT_PROVIDER_SGNR.cs
| 1,176
|
C#
|
using System;
using System.ComponentModel.DataAnnotations;
using NCS.DSS.Transfer.Annotations;
namespace NCS.DSS.Transfer.Models
{
public class Transfer : ITransfer
{
[Display(Description = "Unique identifier of the transfer record.")]
[Example(Description = "b8592ff8-af97-49ad-9fb2-e5c3c717fd85")]
[Newtonsoft.Json.JsonProperty(PropertyName = "id")]
public Guid? TransferId { get; set; }
[Display(Description = "Unique identifier of a customer.")]
[Example(Description = "2730af9c-fc34-4c2b-a905-c4b584b0f379")]
public Guid CustomerId { get; set; }
[Display(Description = "Unique identifier for the related interaction record.")]
[Example(Description = "2730af9c-fc34-4c2b-a905-c4b584b0f379")]
public Guid? InteractionId { get; set; }
[StringLength(10, MinimumLength = 10)]
[Display(Description = "Identifier of the touchpoint who made the last change to the record")]
[Example(Description = "0000000001")]
public string OriginatingTouchpointId { get; set; }
[Required]
[StringLength(10, MinimumLength = 10)]
[Display(Description = "Identifier of the touchpoint who made the last change to the record")]
[Example(Description = "0000000001")]
public string TargetTouchpointId { get; set; }
[Required]
[StringLength(2000)]
[Display(Description = "Context of the transfer.")]
[Example(Description = "this is some text")]
public string Context { get; set; }
[DataType(DataType.DateTime)]
[Display(Description = "Date and time the transfer request was made.")]
[Example(Description = "2018-06-20T13:45:00")]
public DateTime? DateandTimeOfTransfer { get; set; }
[DataType(DataType.DateTime)]
[Display(Description = "Date and time the transfer request was accepted by the target touchpoint.")]
[Example(Description = "2018-06-21T08:45:00")]
public DateTime? DateandTimeofTransferAccepted { get; set; }
[DataType(DataType.DateTime)]
[Display(Description = "Date and time the customer wants to be called back.")]
[Example(Description = "2018-06-27T08:45:00")]
public DateTime? RequestedCallbackTime { get; set; }
[DataType(DataType.DateTime)]
[Display(Description = "Date and time the transfer was acted upon and the customer was contacted.")]
[Example(Description = "2018-06-26T08:45:00")]
public DateTime? ActualCallbackTime { get; set; }
[DataType(DataType.DateTime)]
[Display(Description = "Date and time of the last modification to the record.")]
[Example(Description = "2018-06-28T08:00:00")]
public DateTime? LastModifiedDate { get; set; }
[StringLength(10, MinimumLength = 10)]
[Display(Description = "Identifier of the touchpoint who made the last change to the record")]
[Example(Description = "0000000001")]
public string LastModifiedTouchpointId { get; set; }
public void SetDefaultValues()
{
if (!DateandTimeOfTransfer.HasValue)
DateandTimeOfTransfer = DateTime.UtcNow;
if (!LastModifiedDate.HasValue)
LastModifiedDate = DateTime.UtcNow;
}
public void SetIds(Guid customerId, Guid interactionId, string touchpointId)
{
TransferId = Guid.NewGuid();
CustomerId = customerId;
InteractionId = interactionId;
LastModifiedTouchpointId = touchpointId;
OriginatingTouchpointId = touchpointId;
}
public void Patch(TransferPatch transferPatch)
{
if (transferPatch == null)
return;
if(!string.IsNullOrEmpty(transferPatch.TargetTouchpointId))
TargetTouchpointId = transferPatch.TargetTouchpointId;
if(!string.IsNullOrEmpty(transferPatch.Context))
Context = transferPatch.Context;
if(transferPatch.DateandTimeOfTransfer.HasValue)
DateandTimeOfTransfer = transferPatch.DateandTimeOfTransfer;
if(transferPatch.DateandTimeofTransferAccepted.HasValue)
DateandTimeofTransferAccepted = transferPatch.DateandTimeofTransferAccepted;
if (transferPatch.RequestedCallbackTime.HasValue)
RequestedCallbackTime = transferPatch.RequestedCallbackTime;
if(transferPatch.ActualCallbackTime.HasValue)
ActualCallbackTime = transferPatch.ActualCallbackTime;
if(transferPatch.LastModifiedDate.HasValue)
LastModifiedDate = transferPatch.LastModifiedDate;
if(!string.IsNullOrEmpty(transferPatch.LastModifiedTouchpointId))
LastModifiedTouchpointId = transferPatch.LastModifiedTouchpointId;
}
}
}
| 41.394958
| 108
| 0.655907
|
[
"MIT"
] |
SkillsFundingAgency/dss-transfer
|
NCS.DSS.Transfer/Models/Transfer.cs
| 4,928
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Tips.DependencyInjectionOfInternals.Business.Commands;
using Tips.DependencyInjectionOfInternals.Business.Configuration;
using Tips.DependencyInjectionOfInternals.Business.Models;
namespace Tips.DependencyInjectionOfInternals.Business.Tests.Commands
{
[TestClass]
public class CommandProcessTest
{
private readonly BusinessConfiguration _expectedBusinessConfiguration;
private readonly List<ICommand> _expectedCommands;
public CommandProcessTest()
{
_expectedBusinessConfiguration = new BusinessConfiguration
{
ConnectionString = "ConnectionStringTest",
DocumentPath = "DocumentPathTest",
IocFiles = new List<string>
{
"IocFile1",
"IocFile2",
"IocFile3"
}
};
_expectedCommands = new List<ICommand>
{
new CommandB(),
new CommandA(_expectedBusinessConfiguration),
new CommandC(_expectedBusinessConfiguration)
};
}
[TestMethod]
[DataRow("CommandA", CommandType.CommandA, "CommandA was processed. ConnectionString: {0}")]
[DataRow("CommandB", CommandType.CommandB, "CommandB was processed.")]
[DataRow("CommandC", CommandType.CommandC, "CommandC was processed. DocumentPath: {1}")]
public void CommandWhenProcessThenMessage(string commandTypeName, CommandType expectedCommandType, string expectedMessage)
{
var processRequest = new ProcessRequest
{
CommandType = expectedCommandType
};
var command = _expectedCommands.Single(x => x.GetType().Name == commandTypeName);
var message = command.Process(processRequest);
var expected = string.Format(expectedMessage, _expectedBusinessConfiguration.ConnectionString, _expectedBusinessConfiguration.DocumentPath);
Assert.AreEqual(expected, message);
}
[TestMethod]
[DataRow(CommandType.CommandA, 1, new[] { "CommandA" })]
[DataRow(CommandType.CommandB, 1, new[] { "CommandB" })]
[DataRow(CommandType.CommandC, 1, new[] { "CommandC" })]
[DataRow(CommandType.All, 1, new[] { "CommandB", "CommandA", "CommandC" })]
[DataRow(CommandType.None, 1, new string[] { })]
public void CommandFactoryWhenCreate(CommandType expectedCommandType, int fixForDataRowArray, string[] expectedCommandNames)
{
var services = new ServiceCollection();
services.AddSingleton(typeof(BusinessConfiguration));
services.AddScoped(typeof(ICommand), typeof(CommandB));
services.AddScoped(typeof(ICommand), typeof(CommandA));
services.AddScoped(typeof(ICommand), typeof(CommandC));
var serviceProvider = services.BuildServiceProvider();
var factory = new CommandFactory(serviceProvider);
var actualCommands = factory.Create(expectedCommandType).ToList();
Assert.AreEqual(expectedCommandNames.Length, actualCommands.Count);
for (var i = 0; i < actualCommands.Count; i++)
{
Assert.AreEqual(expectedCommandNames[i], actualCommands[i].GetType().Name);
}
}
}
}
| 41.103448
| 152
| 0.642058
|
[
"MIT"
] |
penblade/Tips
|
Tips.DependencyInjectionOfInternals/src/Tips.DependencyInjectionOfInternals.Business.Tests/Commands/CommandProcessTest.cs
| 3,578
|
C#
|
//----------------------
// <auto-generated>
// This file was automatically generated. Any changes to it will be lost if and when the file is regenerated.
// </auto-generated>
//----------------------
#pragma warning disable
using System;
using SQEX.Luminous.Core.Object;
using System.Collections.Generic;
using CodeDom = System.CodeDom;
namespace Black.Entity.Menu
{
[Serializable, CodeDom.Compiler.GeneratedCode("Luminaire", "0.1")]
public partial class ChocoboFeedMenuEntity : Black.Entity.Menu.SwfEntryEntity
{
new public static ObjectType ObjectType { get; private set; }
private static PropertyContainer fieldProperties;
new public static void SetupObjectType()
{
if (ObjectType != null)
{
return;
}
var dummy = new ChocoboFeedMenuEntity();
var properties = dummy.GetFieldProperties();
ObjectType = new ObjectType("Black.Entity.Menu.ChocoboFeedMenuEntity", 0, Black.Entity.Menu.ChocoboFeedMenuEntity.ObjectType, Construct, properties, 0, 512);
}
public override ObjectType GetObjectType()
{
return ObjectType;
}
protected override PropertyContainer GetFieldProperties()
{
if (fieldProperties != null)
{
return fieldProperties;
}
fieldProperties = new PropertyContainer("Black.Entity.Menu.ChocoboFeedMenuEntity", base.GetFieldProperties(), -1399761743, -394695504);
fieldProperties.AddIndirectlyProperty(new Property("position_", 987254735, "Luminous.Math.VectorA", 80, 16, 1, Property.PrimitiveType.Vector4, 0, (char)0));
fieldProperties.AddIndirectlyProperty(new Property("rotation_", 36328192, "Luminous.Math.VectorA", 96, 16, 1, Property.PrimitiveType.Vector4, 0, (char)0));
fieldProperties.AddIndirectlyProperty(new Property("entitySearchLabelId_", 3840219358, "SQEX.Ebony.Std.Fixid", 112, 4, 1, Property.PrimitiveType.Fixid, 0, (char)0));
fieldProperties.AddIndirectlyProperty(new Property("menuFixID_", 107051205, "SQEX.Ebony.Std.Fixid", 256, 4, 1, Property.PrimitiveType.Fixid, 0, (char)0));
fieldProperties.AddIndirectlyProperty(new Property("swfEntryPackagePath_", 3946372377, "Ebony.Base.String", 272, 16, 1, Property.PrimitiveType.String, 0, (char)0));
return fieldProperties;
}
private static BaseObject Construct()
{
return new ChocoboFeedMenuEntity();
}
}
}
| 37.086957
| 169
| 0.657288
|
[
"MIT"
] |
Gurrimo/Luminaire
|
Assets/Editor/Generated/Black/Entity/Menu/ChocoboFeedMenuEntity.generated.cs
| 2,559
|
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("Bulker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Bulker")]
[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("6fd0ed2f-1156-424e-b35c-1ab71345b726")]
// 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")]
| 37.297297
| 84
| 0.745652
|
[
"MIT"
] |
rlittletht/UpcInv
|
Bulker/Properties/AssemblyInfo.cs
| 1,383
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace QuickSale.Models.BusinessModels
{
public class ItemAmount
{
public int ItemAmountId { get; set; }
[ForeignKey("ItemId")]
public Item Item { get; set; }
public int ItemId { get; set; }
public string ItemAmountDescription { get; set; }
}
}
| 19.826087
| 57
| 0.675439
|
[
"MIT"
] |
Kasunjith-Bimal/QuickSale
|
QuickSale/Models/BusinessModels/ItemAmount.cs
| 458
|
C#
|
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d2d1_3.h(1594,1)
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using D2D1_TAG = System.UInt64;
namespace DirectN
{
[Guid("7836d248-68cc-4df6-b9e8-de991bf62eb7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface ID2D1DeviceContext5 : ID2D1DeviceContext4
{
// ID2D1Resource
[PreserveSig]
new void GetFactory(/* _Outptr_ */ out ID2D1Factory factory);
// ID2D1RenderTarget
[PreserveSig]
new HRESULT CreateBitmap(D2D_SIZE_U size, /* optional(void) */ IntPtr srcData, uint pitch, /* _In_ */ ref D2D1_BITMAP_PROPERTIES bitmapProperties, /* _COM_Outptr_ */ out ID2D1Bitmap bitmap);
[PreserveSig]
new HRESULT CreateBitmapFromWicBitmap(/* _In_ */ IWICBitmapSource wicBitmapSource, /* optional(D2D1_BITMAP_PROPERTIES) */ IntPtr bitmapProperties, /* _COM_Outptr_ */ out ID2D1Bitmap bitmap);
[PreserveSig]
new HRESULT CreateSharedBitmap(/* _In_ */ [MarshalAs(UnmanagedType.LPStruct)] Guid riid, /* _Inout_ */ [MarshalAs(UnmanagedType.IUnknown)] object data, /* optional(D2D1_BITMAP_PROPERTIES) */ IntPtr bitmapProperties, /* _COM_Outptr_ */ out ID2D1Bitmap bitmap);
[PreserveSig]
new HRESULT CreateBitmapBrush(/* _In_opt_ */ ID2D1Bitmap bitmap, /* optional(D2D1_BITMAP_BRUSH_PROPERTIES) */ IntPtr bitmapBrushProperties, /* optional(D2D1_BRUSH_PROPERTIES) */ IntPtr brushProperties, /* _COM_Outptr_ */ out ID2D1BitmapBrush bitmapBrush);
[PreserveSig]
new HRESULT CreateSolidColorBrush(/* _In_ */ ref _D3DCOLORVALUE color, /* optional(D2D1_BRUSH_PROPERTIES) */ IntPtr brushProperties, /* _COM_Outptr_ */ out ID2D1SolidColorBrush solidColorBrush);
[PreserveSig]
new HRESULT CreateGradientStopCollection(/* _In_reads_(gradientStopsCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] D2D1_GRADIENT_STOP[] gradientStops, /* _In_range_(>=,1) */ int gradientStopsCount, D2D1_GAMMA colorInterpolationGamma, D2D1_EXTEND_MODE extendMode, /* _COM_Outptr_ */ out ID2D1GradientStopCollection gradientStopCollection);
[PreserveSig]
new HRESULT CreateLinearGradientBrush(/* _In_ */ ref D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES linearGradientBrushProperties, /* optional(D2D1_BRUSH_PROPERTIES) */ IntPtr brushProperties, /* _In_ */ ID2D1GradientStopCollection gradientStopCollection, /* _COM_Outptr_ */ out ID2D1LinearGradientBrush linearGradientBrush);
[PreserveSig]
new HRESULT CreateRadialGradientBrush(/* _In_ */ ref D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES radialGradientBrushProperties, /* optional(D2D1_BRUSH_PROPERTIES) */ IntPtr brushProperties, /* _In_ */ ID2D1GradientStopCollection gradientStopCollection, /* _COM_Outptr_ */ out ID2D1RadialGradientBrush radialGradientBrush);
[PreserveSig]
new HRESULT CreateCompatibleRenderTarget(/* optional(D2D_SIZE_F) */ IntPtr desiredSize, /* optional(D2D_SIZE_U) */ IntPtr desiredPixelSize, /* optional(D2D1_PIXEL_FORMAT) */ IntPtr desiredFormat, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS options, /* _COM_Outptr_ */ out ID2D1BitmapRenderTarget bitmapRenderTarget);
[PreserveSig]
new HRESULT CreateLayer(/* optional(D2D_SIZE_F) */ IntPtr size, /* _COM_Outptr_ */ out ID2D1Layer layer);
[PreserveSig]
new HRESULT CreateMesh(/* _COM_Outptr_ */ out ID2D1Mesh mesh);
[PreserveSig]
new void DrawLine(D2D_POINT_2F point0, D2D_POINT_2F point1, /* _In_ */ ID2D1Brush brush, float strokeWidth, /* _In_opt_ */ ID2D1StrokeStyle strokeStyle);
[PreserveSig]
new void DrawRectangle(/* _In_ */ ref D2D_RECT_F rect, /* _In_ */ ID2D1Brush brush, float strokeWidth, /* _In_opt_ */ ID2D1StrokeStyle strokeStyle);
[PreserveSig]
new void FillRectangle(/* _In_ */ ref D2D_RECT_F rect, /* _In_ */ ID2D1Brush brush);
[PreserveSig]
new void DrawRoundedRectangle(/* _In_ */ ref D2D1_ROUNDED_RECT roundedRect, /* _In_ */ ID2D1Brush brush, float strokeWidth, /* _In_opt_ */ ID2D1StrokeStyle strokeStyle);
[PreserveSig]
new void FillRoundedRectangle(/* _In_ */ ref D2D1_ROUNDED_RECT roundedRect, /* _In_ */ ID2D1Brush brush);
[PreserveSig]
new void DrawEllipse(/* _In_ */ ref D2D1_ELLIPSE ellipse, /* _In_ */ ID2D1Brush brush, float strokeWidth, /* _In_opt_ */ ID2D1StrokeStyle strokeStyle);
[PreserveSig]
new void FillEllipse(/* _In_ */ ref D2D1_ELLIPSE ellipse, /* _In_ */ ID2D1Brush brush);
[PreserveSig]
new void DrawGeometry(/* _In_ */ ID2D1Geometry geometry, /* _In_ */ ID2D1Brush brush, float strokeWidth, /* _In_opt_ */ ID2D1StrokeStyle strokeStyle);
[PreserveSig]
new void FillGeometry(/* _In_ */ ID2D1Geometry geometry, /* _In_ */ ID2D1Brush brush, /* _In_opt_ */ ID2D1Brush opacityBrush);
[PreserveSig]
new void FillMesh(/* _In_ */ ID2D1Mesh mesh, /* _In_ */ ID2D1Brush brush);
[PreserveSig]
new void FillOpacityMask(/* _In_ */ ID2D1Bitmap opacityMask, /* _In_ */ ID2D1Brush brush, D2D1_OPACITY_MASK_CONTENT content, /* optional(D2D_RECT_F) */ IntPtr destinationRectangle, /* optional(D2D_RECT_F) */ IntPtr sourceRectangle);
[PreserveSig]
new void DrawBitmap(/* _In_ */ ID2D1Bitmap bitmap, /* optional(D2D_RECT_F) */ IntPtr destinationRectangle, float opacity, D2D1_BITMAP_INTERPOLATION_MODE interpolationMode, /* optional(D2D_RECT_F) */ IntPtr sourceRectangle);
[PreserveSig]
new void DrawTextW(/* _In_reads_(stringLength) */ [MarshalAs(UnmanagedType.LPWStr)] string @string, uint stringLength, /* _In_ */ IDWriteTextFormat textFormat, /* _In_ */ ref D2D_RECT_F layoutRect, /* _In_ */ ID2D1Brush defaultFillBrush, D2D1_DRAW_TEXT_OPTIONS options, DWRITE_MEASURING_MODE measuringMode);
[PreserveSig]
new void DrawTextLayout(D2D_POINT_2F origin, /* _In_ */ IDWriteTextLayout textLayout, /* _In_ */ ID2D1Brush defaultFillBrush, D2D1_DRAW_TEXT_OPTIONS options);
[PreserveSig]
new void DrawGlyphRun(D2D_POINT_2F baselineOrigin, /* _In_ */ ref DWRITE_GLYPH_RUN glyphRun, /* _In_ */ ID2D1Brush foregroundBrush, DWRITE_MEASURING_MODE measuringMode);
[PreserveSig]
new void SetTransform(/* _In_ */ ref D2D_MATRIX_3X2_F transform);
[PreserveSig]
new void GetTransform(/* _Out_ */ out D2D_MATRIX_3X2_F transform);
[PreserveSig]
new void SetAntialiasMode(D2D1_ANTIALIAS_MODE antialiasMode);
[PreserveSig]
new D2D1_ANTIALIAS_MODE GetAntialiasMode();
[PreserveSig]
new void SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE textAntialiasMode);
[PreserveSig]
new D2D1_TEXT_ANTIALIAS_MODE GetTextAntialiasMode();
[PreserveSig]
new void SetTextRenderingParams(/* _In_opt_ */ IDWriteRenderingParams textRenderingParams);
[PreserveSig]
new void GetTextRenderingParams(/* _Outptr_result_maybenull_ */ out IDWriteRenderingParams textRenderingParams);
[PreserveSig]
new void SetTags(ulong tag1, ulong tag2);
[PreserveSig]
new void GetTags(/* _Out_opt_ */ out D2D1_TAG tag1, /* _Out_opt_ */ out D2D1_TAG tag2);
[PreserveSig]
new void PushLayer(/* _In_ */ ref D2D1_LAYER_PARAMETERS layerParameters, /* _In_opt_ */ ID2D1Layer layer);
[PreserveSig]
new void PopLayer();
[PreserveSig]
new HRESULT Flush(/* _Out_opt_ */ out D2D1_TAG tag1, /* _Out_opt_ */ out D2D1_TAG tag2);
[PreserveSig]
new void SaveDrawingState(/* _Inout_ */ ID2D1DrawingStateBlock drawingStateBlock);
[PreserveSig]
new void RestoreDrawingState(/* _In_ */ ID2D1DrawingStateBlock drawingStateBlock);
[PreserveSig]
new void PushAxisAlignedClip(/* _In_ */ ref D2D_RECT_F clipRect, D2D1_ANTIALIAS_MODE antialiasMode);
[PreserveSig]
new void PopAxisAlignedClip();
[PreserveSig]
new void Clear(/* optional(_D3DCOLORVALUE) */ IntPtr clearColor);
[PreserveSig]
new void BeginDraw();
[PreserveSig]
new HRESULT EndDraw(/* _Out_opt_ */ out D2D1_TAG tag1, /* _Out_opt_ */ out D2D1_TAG tag2);
[PreserveSig]
new D2D1_PIXEL_FORMAT GetPixelFormat();
[PreserveSig]
new void SetDpi(float dpiX, float dpiY);
[PreserveSig]
new void GetDpi(/* _Out_ */ out float dpiX, /* _Out_ */ out float dpiY);
[PreserveSig]
new D2D_SIZE_F GetSize();
[PreserveSig]
new D2D_SIZE_U GetPixelSize();
[PreserveSig]
new uint GetMaximumBitmapSize();
[PreserveSig]
new bool IsSupported(/* _In_ */ ref D2D1_RENDER_TARGET_PROPERTIES renderTargetProperties);
// ID2D1DeviceContext
[PreserveSig]
new HRESULT CreateBitmap(D2D_SIZE_U size, /* optional(void) */ IntPtr sourceData, uint pitch, /* _In_ */ ref D2D1_BITMAP_PROPERTIES1 bitmapProperties, /* _COM_Outptr_ */ out ID2D1Bitmap1 bitmap);
[PreserveSig]
new HRESULT CreateBitmapFromWicBitmap(/* _In_ */ IWICBitmapSource wicBitmapSource, /* optional(D2D1_BITMAP_PROPERTIES1) */ IntPtr bitmapProperties, /* _COM_Outptr_ */ out ID2D1Bitmap1 bitmap);
[PreserveSig]
new HRESULT CreateColorContext(D2D1_COLOR_SPACE space, /* _In_reads_opt_(profileSize) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] profile, int profileSize, /* _COM_Outptr_ */ out ID2D1ColorContext colorContext);
[PreserveSig]
new HRESULT CreateColorContextFromFilename(/* _In_ */ [MarshalAs(UnmanagedType.LPWStr)] string filename, /* _COM_Outptr_ */ out ID2D1ColorContext colorContext);
[PreserveSig]
new HRESULT CreateColorContextFromWicColorContext(/* _In_ */ IWICColorContext wicColorContext, /* _COM_Outptr_ */ out ID2D1ColorContext colorContext);
[PreserveSig]
new HRESULT CreateBitmapFromDxgiSurface(/* _In_ */ IDXGISurface surface, /* optional(D2D1_BITMAP_PROPERTIES1) */ IntPtr bitmapProperties, /* _COM_Outptr_ */ out ID2D1Bitmap1 bitmap);
[PreserveSig]
new HRESULT CreateEffect(/* _In_ */ [MarshalAs(UnmanagedType.LPStruct)] Guid effectId, /* _COM_Outptr_ */ out ID2D1Effect effect);
[PreserveSig]
new HRESULT CreateGradientStopCollection(/* _In_reads_(straightAlphaGradientStopsCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] D2D1_GRADIENT_STOP[] straightAlphaGradientStops, /* _In_range_(>=,1) */ int straightAlphaGradientStopsCount, D2D1_COLOR_SPACE preInterpolationSpace, D2D1_COLOR_SPACE postInterpolationSpace, D2D1_BUFFER_PRECISION bufferPrecision, D2D1_EXTEND_MODE extendMode, D2D1_COLOR_INTERPOLATION_MODE colorInterpolationMode, /* _COM_Outptr_ */ out ID2D1GradientStopCollection1 gradientStopCollection1);
[PreserveSig]
new HRESULT CreateImageBrush(/* _In_opt_ */ ID2D1Image image, /* _In_ */ ref D2D1_IMAGE_BRUSH_PROPERTIES imageBrushProperties, /* optional(D2D1_BRUSH_PROPERTIES) */ IntPtr brushProperties, /* _COM_Outptr_ */ out ID2D1ImageBrush imageBrush);
[PreserveSig]
new HRESULT CreateBitmapBrush(/* _In_opt_ */ ID2D1Bitmap bitmap, /* optional(D2D1_BITMAP_BRUSH_PROPERTIES1) */ IntPtr bitmapBrushProperties, /* optional(D2D1_BRUSH_PROPERTIES) */ IntPtr brushProperties, /* _COM_Outptr_ */ out ID2D1BitmapBrush1 bitmapBrush);
[PreserveSig]
new HRESULT CreateCommandList(/* _COM_Outptr_ */ out ID2D1CommandList commandList);
[PreserveSig]
new bool IsDxgiFormatSupported(DXGI_FORMAT format);
[PreserveSig]
new bool IsBufferPrecisionSupported(D2D1_BUFFER_PRECISION bufferPrecision);
[PreserveSig]
new HRESULT GetImageLocalBounds(/* _In_ */ ID2D1Image image, /* _Out_ */ out D2D_RECT_F localBounds);
[PreserveSig]
new HRESULT GetImageWorldBounds(/* _In_ */ ID2D1Image image, /* _Out_ */ out D2D_RECT_F worldBounds);
[PreserveSig]
new HRESULT GetGlyphRunWorldBounds(D2D_POINT_2F baselineOrigin, /* _In_ */ ref DWRITE_GLYPH_RUN glyphRun, DWRITE_MEASURING_MODE measuringMode, /* _Out_ */ out D2D_RECT_F bounds);
[PreserveSig]
new void GetDevice(/* _Outptr_ */ out ID2D1Device device);
[PreserveSig]
new void SetTarget(/* _In_opt_ */ ID2D1Image image);
[PreserveSig]
new void GetTarget(/* _Outptr_result_maybenull_ */ out ID2D1Image image);
[PreserveSig]
new void SetRenderingControls(/* _In_ */ ref D2D1_RENDERING_CONTROLS renderingControls);
[PreserveSig]
new void GetRenderingControls(/* _Out_ */ out D2D1_RENDERING_CONTROLS renderingControls);
[PreserveSig]
new void SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND primitiveBlend);
[PreserveSig]
new D2D1_PRIMITIVE_BLEND GetPrimitiveBlend();
[PreserveSig]
new void SetUnitMode(D2D1_UNIT_MODE unitMode);
[PreserveSig]
new D2D1_UNIT_MODE GetUnitMode();
[PreserveSig]
new void DrawGlyphRun(D2D_POINT_2F baselineOrigin, /* _In_ */ ref DWRITE_GLYPH_RUN glyphRun, /* optional(DWRITE_GLYPH_RUN_DESCRIPTION) */ IntPtr glyphRunDescription, /* _In_ */ ID2D1Brush foregroundBrush, DWRITE_MEASURING_MODE measuringMode);
[PreserveSig]
new void DrawImage(/* _In_ */ ID2D1Image image, /* optional(D2D_POINT_2F) */ IntPtr targetOffset, /* optional(D2D_RECT_F) */ IntPtr imageRectangle, D2D1_INTERPOLATION_MODE interpolationMode, D2D1_COMPOSITE_MODE compositeMode);
[PreserveSig]
new void DrawGdiMetafile(/* _In_ */ ID2D1GdiMetafile gdiMetafile, /* optional(D2D_POINT_2F) */ IntPtr targetOffset);
[PreserveSig]
new void DrawBitmap(/* _In_ */ ID2D1Bitmap bitmap, /* optional(D2D_RECT_F) */ IntPtr destinationRectangle, float opacity, D2D1_INTERPOLATION_MODE interpolationMode, /* optional(D2D_RECT_F) */ IntPtr sourceRectangle, /* optional(D2D_MATRIX_4X4_F) */ IntPtr perspectiveTransform);
[PreserveSig]
new void PushLayer(/* _In_ */ ref D2D1_LAYER_PARAMETERS1 layerParameters, /* _In_opt_ */ ID2D1Layer layer);
[PreserveSig]
new HRESULT InvalidateEffectInputRectangle(/* _In_ */ ID2D1Effect effect, uint input, /* _In_ */ ref D2D_RECT_F inputRectangle);
[PreserveSig]
new HRESULT GetEffectInvalidRectangleCount(/* _In_ */ ID2D1Effect effect, /* _Out_ */ out uint rectangleCount);
[PreserveSig]
new HRESULT GetEffectInvalidRectangles(/* _In_ */ ID2D1Effect effect, /* _Out_writes_(rectanglesCount) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] D2D_RECT_F[] rectangles, int rectanglesCount);
[PreserveSig]
new HRESULT GetEffectRequiredInputRectangles(/* _In_ */ ID2D1Effect renderEffect, /* optional(D2D_RECT_F) */ IntPtr renderImageRectangle, /* _In_reads_(inputCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] D2D1_EFFECT_INPUT_DESCRIPTION[] inputDescriptions, /* _Out_writes_(inputCount) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] D2D_RECT_F[] requiredInputRects, int inputCount);
[PreserveSig]
new void FillOpacityMask(/* _In_ */ ID2D1Bitmap opacityMask, /* _In_ */ ID2D1Brush brush, /* optional(D2D_RECT_F) */ IntPtr destinationRectangle, /* optional(D2D_RECT_F) */ IntPtr sourceRectangle);
// ID2D1DeviceContext1
[PreserveSig]
new HRESULT CreateFilledGeometryRealization(/* _In_ */ ID2D1Geometry geometry, float flatteningTolerance, /* _COM_Outptr_ */ out ID2D1GeometryRealization geometryRealization);
[PreserveSig]
new HRESULT CreateStrokedGeometryRealization(/* _In_ */ ID2D1Geometry geometry, float flatteningTolerance, float strokeWidth, /* _In_opt_ */ ID2D1StrokeStyle strokeStyle, /* _COM_Outptr_ */ out ID2D1GeometryRealization geometryRealization);
[PreserveSig]
new void DrawGeometryRealization(/* _In_ */ ID2D1GeometryRealization geometryRealization, /* _In_ */ ID2D1Brush brush);
// ID2D1DeviceContext2
[PreserveSig]
new HRESULT CreateInk(/* _In_ */ ref D2D1_INK_POINT startPoint, /* _COM_Outptr_ */ out ID2D1Ink ink);
[PreserveSig]
new HRESULT CreateInkStyle(/* optional(D2D1_INK_STYLE_PROPERTIES) */ IntPtr inkStyleProperties, /* _COM_Outptr_ */ out ID2D1InkStyle inkStyle);
[PreserveSig]
new HRESULT CreateGradientMesh(/* _In_reads_(patchesCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] D2D1_GRADIENT_MESH_PATCH[] patches, int patchesCount, /* _COM_Outptr_ */ out ID2D1GradientMesh gradientMesh);
[PreserveSig]
new HRESULT CreateImageSourceFromWic(/* _In_ */ IWICBitmapSource wicBitmapSource, D2D1_IMAGE_SOURCE_LOADING_OPTIONS loadingOptions, D2D1_ALPHA_MODE alphaMode, /* _COM_Outptr_ */ out ID2D1ImageSourceFromWic imageSource);
[PreserveSig]
new HRESULT CreateLookupTable3D(D2D1_BUFFER_PRECISION precision, /* _In_reads_(3) */ [MarshalAs(UnmanagedType.LPArray, SizeConst = 3)] uint[] extents, /* _In_reads_(dataCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] data, int dataCount, /* _In_reads_(2) */ [MarshalAs(UnmanagedType.LPArray, SizeConst = 2)] uint[] strides, /* _COM_Outptr_ */ out ID2D1LookupTable3D lookupTable);
[PreserveSig]
new HRESULT CreateImageSourceFromDxgi(/* _In_reads_(surfaceCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] IDXGISurface[] surfaces, int surfaceCount, DXGI_COLOR_SPACE_TYPE colorSpace, D2D1_IMAGE_SOURCE_FROM_DXGI_OPTIONS options, /* _COM_Outptr_ */ out ID2D1ImageSource imageSource);
[PreserveSig]
new HRESULT GetGradientMeshWorldBounds(/* _In_ */ ID2D1GradientMesh gradientMesh, /* _Out_ */ out D2D_RECT_F pBounds);
[PreserveSig]
new void DrawInk(/* _In_ */ ID2D1Ink ink, /* _In_ */ ID2D1Brush brush, /* _In_opt_ */ ID2D1InkStyle inkStyle);
[PreserveSig]
new void DrawGradientMesh(/* _In_ */ ID2D1GradientMesh gradientMesh);
[PreserveSig]
new void DrawGdiMetafile(/* _In_ */ ID2D1GdiMetafile gdiMetafile, /* optional(D2D_RECT_F) */ IntPtr destinationRectangle, /* optional(D2D_RECT_F) */ IntPtr sourceRectangle);
[PreserveSig]
new HRESULT CreateTransformedImageSource(/* _In_ */ ID2D1ImageSource imageSource, /* _In_ */ ref D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES properties, /* _COM_Outptr_ */ out ID2D1TransformedImageSource transformedImageSource);
// ID2D1DeviceContext3
[PreserveSig]
new HRESULT CreateSpriteBatch(/* _COM_Outptr_ */ out ID2D1SpriteBatch spriteBatch);
[PreserveSig]
new void DrawSpriteBatch(/* _In_ */ ID2D1SpriteBatch spriteBatch, uint startIndex, uint spriteCount, /* _In_ */ ID2D1Bitmap bitmap, D2D1_BITMAP_INTERPOLATION_MODE interpolationMode, D2D1_SPRITE_OPTIONS spriteOptions);
// ID2D1DeviceContext4
[PreserveSig]
new HRESULT CreateSvgGlyphStyle(/* _COM_Outptr_ */ out ID2D1SvgGlyphStyle svgGlyphStyle);
[PreserveSig]
new void DrawTextW(/* _In_reads_(stringLength) */ [MarshalAs(UnmanagedType.LPWStr)] string @string, uint stringLength, /* _In_ */ IDWriteTextFormat textFormat, /* _In_ */ ref D2D_RECT_F layoutRect, /* _In_opt_ */ ID2D1Brush defaultFillBrush, /* _In_opt_ */ ID2D1SvgGlyphStyle svgGlyphStyle, uint colorPaletteIndex, D2D1_DRAW_TEXT_OPTIONS options, DWRITE_MEASURING_MODE measuringMode);
[PreserveSig]
new void DrawTextLayout(D2D_POINT_2F origin, /* _In_ */ IDWriteTextLayout textLayout, /* _In_opt_ */ ID2D1Brush defaultFillBrush, /* _In_opt_ */ ID2D1SvgGlyphStyle svgGlyphStyle, uint colorPaletteIndex, D2D1_DRAW_TEXT_OPTIONS options);
[PreserveSig]
new void DrawColorBitmapGlyphRun(DWRITE_GLYPH_IMAGE_FORMATS glyphImageFormat, D2D_POINT_2F baselineOrigin, /* _In_ */ ref DWRITE_GLYPH_RUN glyphRun, DWRITE_MEASURING_MODE measuringMode, D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION bitmapSnapOption);
[PreserveSig]
new void DrawSvgGlyphRun(D2D_POINT_2F baselineOrigin, /* _In_ */ ref DWRITE_GLYPH_RUN glyphRun, /* _In_opt_ */ ID2D1Brush defaultFillBrush, /* _In_opt_ */ ID2D1SvgGlyphStyle svgGlyphStyle, uint colorPaletteIndex, DWRITE_MEASURING_MODE measuringMode);
[PreserveSig]
new HRESULT GetColorBitmapGlyphImage(DWRITE_GLYPH_IMAGE_FORMATS glyphImageFormat, D2D_POINT_2F glyphOrigin, /* _In_ */ IDWriteFontFace fontFace, float fontEmSize, ushort glyphIndex, bool isSideways, /* optional(D2D_MATRIX_3X2_F) */ IntPtr worldTransform, float dpiX, float dpiY, /* _Out_ */ out D2D_MATRIX_3X2_F glyphTransform, /* _COM_Outptr_ */ out ID2D1Image glyphImage);
[PreserveSig]
new HRESULT GetSvgGlyphImage(D2D_POINT_2F glyphOrigin, /* _In_ */ IDWriteFontFace fontFace, float fontEmSize, ushort glyphIndex, bool isSideways, /* optional(D2D_MATRIX_3X2_F) */ IntPtr worldTransform, /* _In_opt_ */ ID2D1Brush defaultFillBrush, /* _In_opt_ */ ID2D1SvgGlyphStyle svgGlyphStyle, uint colorPaletteIndex, /* _Out_ */ out D2D_MATRIX_3X2_F glyphTransform, /* _COM_Outptr_ */ out ID2D1CommandList glyphImage);
// ID2D1DeviceContext5
[PreserveSig]
HRESULT CreateSvgDocument(/* _In_opt_ */ IStream inputXmlStream, D2D_SIZE_F viewportSize, /* _COM_Outptr_ */ out ID2D1SvgDocument svgDocument);
[PreserveSig]
void DrawSvgDocument(/* _In_ */ ID2D1SvgDocument svgDocument);
[PreserveSig]
HRESULT CreateColorContextFromDxgiColorSpace(DXGI_COLOR_SPACE_TYPE colorSpace, /* _COM_Outptr_ */ out ID2D1ColorContext1 colorContext);
[PreserveSig]
HRESULT CreateColorContextFromSimpleColorProfile(/* _In_ */ ref D2D1_SIMPLE_COLOR_PROFILE simpleProfile, /* _COM_Outptr_ */ out ID2D1ColorContext1 colorContext);
}
}
| 61.794038
| 543
| 0.698886
|
[
"MIT"
] |
bbday/DirectN
|
DirectN/DirectN/Generated/ID2D1DeviceContext5.cs
| 22,804
|
C#
|
//GENERATED: CS Code
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine{
public partial class URichTextBlockDecorator:UObject
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern new IntPtr StaticClass();
}
}
| 25.833333
| 55
| 0.8
|
[
"MIT"
] |
RobertAcksel/UnrealCS
|
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile/URichTextBlockDecorator.cs
| 310
|
C#
|
namespace GermanWhistBlazor;
public partial class GamePage
{
private static int TargetHeight => 15;
[CascadingParameter]
public TestOptions? TestData { get; set; }
[CascadingParameter]
public IGameInfo? GameData { get; set; }
[CascadingParameter]
public BasicData? BasicData { get; set; }
[CascadingParameter]
public MultiplayerBasicParentShell? Shell { get; set; }
}
| 31
| 59
| 0.71464
|
[
"MIT"
] |
musictopia2/GamingPackXV3
|
Blazor/Games/GermanWhistBlazor/GamePage.razor.cs
| 403
|
C#
|
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace MLBot.Mvc
{
/// <summary>
/// Swagger 文件上传参数
/// </summary>
[Author("Linyee", "2019-07-05")]//从bot搬过来的
public class SwaggerFileUploadOperation : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.OperationId == "Import")
{
operation.Parameters.Clear();
operation.Parameters.Add(new NonBodyParameter
{
Name = "uploadedFile",
In = "formData",
Description = "Upload Zip File, meta.json is the extra data for customized function.",
Required = true,
Type = "file"
});
operation.Consumes.Add("multipart/form-data");
}
}
}
}
| 30.096774
| 106
| 0.534834
|
[
"MIT"
] |
jiaguoxinzhi/MLBot
|
MLBot/LinyeeWechat/SwaggerFileUploadOperation.cs
| 959
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace implicit_winform
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
webBrowser1.BringToFront();
webBrowser1.Visible = true;
//Redirect the browser to the login window.
webBrowser1.Url = new Uri( "https://login.mypurecloud.com/oauth/authorize?" +
"response_type=token" +
"&client_id=bfadf7a0-3364-4f65-9fda-00d37877113f" +
"&redirect_uri=http://localhost:8085/oauth2/callback");
}
private void LoadUserInformation(string bearerToken)
{
webBrowser1.Visible = false;
//Make a request to /api/v2/users/me
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.mypurecloud.com/api/v2/users/me");
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + bearerToken);
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
txtInfo.Text = response;
}
}
}
}
private void OnWebBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
//When the web browser control navigates, check if the url is the callback and contains the access_token
var url = e.Url.ToString();
if (url.Contains("access_token"))
{
var queryString = url.Substring(url.LastIndexOf("#")+1);
var props = queryString.Split('&');
var authCode = props[0].Split('=')[1];
LoadUserInformation(authCode);
}
}
}
}
| 35.130435
| 118
| 0.549917
|
[
"MIT"
] |
Genesys-Heinan/developercenter-tutorials
|
oauth-implicit/csharp/MainForm.cs
| 2,426
|
C#
|
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using DataLinq.Metadata;
namespace DataLinq.Instances
{
public class ForeignKey
{
public ForeignKey(Column column, object data)
{
Column = column;
Data = data;
}
public Column Column { get; set; }
public object Data { get; }
public bool Equals(ForeignKey other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Column == other.Column && Data == other.Data;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(ForeignKey))
return false;
return Column == (obj as ForeignKey).Column && Data == (obj as ForeignKey).Data;
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 31 + Column.GetHashCode();
hash = hash * 31 + Data.GetHashCode();
return hash;
}
}
}
}
| 24.981481
| 92
| 0.503336
|
[
"MIT"
] |
bazer/DataLinq
|
src/DataLinq/Instances/ForeignKey.cs
| 1,351
|
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.Tcss.V20201101.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class SoftQuotaDayInfo : AbstractModel
{
/// <summary>
/// 扣费时间
/// </summary>
[JsonProperty("PayTime")]
public string PayTime{ get; set; }
/// <summary>
/// 计费核数
/// </summary>
[JsonProperty("CoresCnt")]
public ulong? CoresCnt{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "PayTime", this.PayTime);
this.SetParamSimple(map, prefix + "CoresCnt", this.CoresCnt);
}
}
}
| 29.313725
| 81
| 0.633445
|
[
"Apache-2.0"
] |
TencentCloud/tencentcloud-sdk-dotnet
|
TencentCloud/Tcss/V20201101/Models/SoftQuotaDayInfo.cs
| 1,511
|
C#
|
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace NSG.Identity.Models
{
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
public class FactorViewModel
{
public string Purpose { get; set; }
}
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string Number { get; set; }
}
public class VerifyPhoneNumberViewModel
{
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
}
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
}
}
| 30.204545
| 110
| 0.625282
|
[
"Apache-2.0"
] |
PHuhn/net-incident
|
WebSrv/Identity/Models/ManageViewModels.cs
| 2,660
|
C#
|
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace RackManager.Areas.Identity.Pages.Account.Manage
{
public class SetPasswordModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public SetPasswordModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToPage("./ChangePassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var addPasswordResult = await _userManager.AddPasswordAsync(user, Input.NewPassword);
if (!addPasswordResult.Succeeded)
{
foreach (var error in addPasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your password has been set.";
return RedirectToPage();
}
}
}
| 25.763441
| 120
| 0.714107
|
[
"MIT"
] |
AnthonyRyck/RackManager
|
src/BlazorRackManager/RackManager/Areas/Identity/Pages/Account/Manage/SetPassword.cshtml.cs
| 2,398
|
C#
|
using System.Windows.Forms;
using System;
namespace SystemConfig.Editor.Search
{
public class SearchDataGrid : DataGridView
{
public event Action SearchDone;
public SearchDataGrid()
{
this.ReadOnly = true;
this.AllowUserToAddRows = false;
this.AutoGenerateColumns = false;
this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.MultiSelect = false;
this.KeyDown += new KeyEventHandler(OnKeyDown);
this.CellDoubleClick += new DataGridViewCellEventHandler(SearchDataGrid_CellDoubleClick);
}
void SearchDataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (this.SearchDone != null)
this.SearchDone();
((SearchPanel)this.Parent).ClosePanel(true);
}
internal void OnKeyDown(object sender, KeyEventArgs e)
{
var index = -1;
if (this.CurrentCell != null)
index = this.CurrentCell.RowIndex;
if (e.KeyCode == Keys.Up)
index--;
else if (e.KeyCode == Keys.Down)
index++;
else if (e.KeyCode == Keys.Enter)
{
if (this.SearchDone != null)
this.SearchDone();
((SearchPanel)this.Parent).ClosePanel(true);
}
else if (e.KeyCode == Keys.Escape)
((SearchPanel)this.Parent).ClosePanel(false);
if (index < 0 || index > this.Rows.Count - 1)
return;
this.CurrentCell = this.Rows[index].Cells[0];
}
}
}
| 33.019608
| 101
| 0.550475
|
[
"MIT"
] |
xasealand-org2/QueueSystem
|
SystemConfig/SystemConfig/Editor/Search/SearchDataGrid.cs
| 1,686
|
C#
|
using System.Linq;
using RimWorld;
using Verse;
namespace Rumor_Code
{
public class IncidentWorker_MadWithLoneliness : IncidentWorker
{
private void HaveEpisode(Pawn p)
{
var value = Rand.Value;
if (value < 0.15)
{
p.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk);
}
else if (value < 0.45)
{
p.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Wander_Psychotic);
}
else if (p.story.traits.HasTrait(TraitDefOf.DrugDesire))
{
p.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Binging_DrugExtreme);
}
else
{
p.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Wander_Sad);
}
}
protected override bool TryExecuteWorker(IncidentParms parms)
{
var enumerable = from x in ThirdPartyManager.GetAllFreeColonistsAlive
where ThirdPartyManager.DoesEveryoneLocallyHate(x)
select x;
bool result;
if (!enumerable.Any())
{
result = false;
}
else
{
var pawn = enumerable.RandomElement();
if (pawn == null)
{
result = false;
}
else if (!pawn.RaceProps.Humanlike)
{
result = false;
}
else
{
HaveEpisode(pawn);
result = true;
}
}
return result;
}
}
}
| 29.311475
| 105
| 0.489933
|
[
"MIT"
] |
emipa606/RoumorHasIt
|
Source/Rainbeau's Rumor Has It/IncidentWorker_MadWithLoneliness.cs
| 1,790
|
C#
|
using System;
using System.Globalization;
using System.Text;
using System.Windows.Data;
namespace Ais.Internal.Dcm.ModernUIV2.Converter
{
/// <summary>
/// This class converts input size value and presents it in KB/MB/GB.
/// For example if the value is passed as 1024, it converts and returns 1 KB.
/// </summary>
public class SizeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || value == System.DBNull.Value)
return string.Empty;
double size = System.Convert.ToDouble(value);
long bytesSize = System.Convert.ToInt64(value);
StringBuilder stringBuilder = new StringBuilder();
string str;
string sizeAsString;
if (size / 1024 < 1)
{
sizeAsString = size.ToString(CultureInfo.CurrentCulture);
stringBuilder.AppendFormat("{0} {1}", sizeAsString, "Bytes");
str = stringBuilder.ToString();
}
else
{
size /= 1024;
if (size / 1024 < 1)
{
sizeAsString = Math.Round(size, 2).ToString(CultureInfo.CurrentCulture);
stringBuilder.AppendFormat("{0} {1}", sizeAsString, "KB");
str = stringBuilder.ToString();
}
else
{
size /= 1024;
if (size / 1024 < 1)
{
sizeAsString = Math.Round(size, 2).ToString(CultureInfo.CurrentCulture);
stringBuilder.AppendFormat("{0} {1}", sizeAsString, "MB");
str = stringBuilder.ToString();
}
else
{
size /= 1024;
sizeAsString = Math.Round(size, 2).ToString(CultureInfo.CurrentCulture);
stringBuilder.AppendFormat("{0} {1}", sizeAsString, "GB");
str = stringBuilder.ToString();
}
}
}
return str;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}
| 36.716418
| 124
| 0.504878
|
[
"Apache-2.0"
] |
AppliedIS/wams-manager
|
Source/Ais.Internal.Dcm/Ais.Internal.Dcm.ModernUIV2/Converter/SizeConverter.cs
| 2,462
|
C#
|
namespace MyDashWallet.Node
{
public class TxInput
{
public TxInput(string tx, int outputIndex, decimal amount)
{
Tx = tx;
OutputIndex = outputIndex;
Amount = amount;
}
public string Tx { get; }
public int OutputIndex { get; }
/// <summary>
/// The amount is not needed as an input for building the raw tx, but we use it to check if
/// the total amount matches (all inputs must equal all outputs+tx fee).
/// </summary>
public decimal Amount { get; }
}
}
| 24.45
| 93
| 0.666667
|
[
"Apache-2.0"
] |
GetAywa/AywaWebWallet
|
Node/TxInput.cs
| 491
|
C#
|
using System;
using Bit.Core.Models;
using Bit.Owin.Contracts;
using Owin;
namespace Bit.Owin.Middlewares
{
public class SignOutPageMiddlewareConfiguration : IOwinMiddlewareConfiguration
{
public virtual AppEnvironment AppEnvironment { get; set; }
public virtual void Configure(IAppBuilder owinApp)
{
if (owinApp == null)
throw new ArgumentNullException(nameof(owinApp));
owinApp.Map("/SignOut",
innerApp =>
{
if (AppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false))
{
innerApp.UseHsts(config => config.IncludeSubdomains().MaxAge(days: 30));
}
innerApp.UseXfo(xFrameOptions => { xFrameOptions.SameOrigin(); });
innerApp.UseXContentTypeOptions();
innerApp.UseXDownloadOptions();
innerApp.UseXXssProtection(xssProtectionOptions => { xssProtectionOptions.EnabledWithBlockMode(); });
innerApp.Use<OwinNoCacheResponseMiddleware>();
innerApp.Use<SignOutPageMiddleware>();
});
}
}
}
| 31
| 121
| 0.574194
|
[
"MIT"
] |
Jaguel/bit-framework
|
src/Server/Bit.Owin/Middlewares/SignOutPageMiddlewareConfiguration.cs
| 1,242
|
C#
|
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslynator.CSharp;
namespace Roslynator.CSharp.Analysis
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class RemoveUnnecessaryCaseLabelAnalyzer : BaseDiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(DiagnosticDescriptors.RemoveUnnecessaryCaseLabel); }
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.RegisterSyntaxNodeAction(f => AnalyzeSwitchSection(f), SyntaxKind.SwitchSection);
}
private static void AnalyzeSwitchSection(SyntaxNodeAnalysisContext context)
{
var switchSection = (SwitchSectionSyntax)context.Node;
if (!switchSection.IsParentKind(SyntaxKind.SwitchStatement))
return;
SyntaxList<SwitchLabelSyntax> labels = switchSection.Labels;
if (labels.Count <= 1)
return;
if (!labels.Any(SyntaxKind.DefaultSwitchLabel))
return;
foreach (SwitchLabelSyntax label in labels)
{
if (!label.IsKind(SyntaxKind.DefaultSwitchLabel)
&& label.Keyword.TrailingTrivia.IsEmptyOrWhitespace()
&& label.ColonToken.LeadingTrivia.IsEmptyOrWhitespace())
{
DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.RemoveUnnecessaryCaseLabel, label);
}
}
}
}
}
| 35.071429
| 160
| 0.670061
|
[
"Apache-2.0"
] |
RickeyEstes/Roslynator
|
src/Analyzers/CSharp/Analysis/RemoveUnnecessaryCaseLabelAnalyzer.cs
| 1,966
|
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 iotsitewise-2019-12-02.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.IoTSiteWise.Model
{
/// <summary>
/// Container for the parameters to the DescribeGateway operation.
/// Retrieves information about a gateway.
/// </summary>
public partial class DescribeGatewayRequest : AmazonIoTSiteWiseRequest
{
private string _gatewayId;
/// <summary>
/// Gets and sets the property GatewayId.
/// <para>
/// The ID of the gateway device.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=36, Max=36)]
public string GatewayId
{
get { return this._gatewayId; }
set { this._gatewayId = value; }
}
// Check to see if GatewayId property is set
internal bool IsSetGatewayId()
{
return this._gatewayId != null;
}
}
}
| 30.305085
| 110
| 0.636465
|
[
"Apache-2.0"
] |
philasmar/aws-sdk-net
|
sdk/src/Services/IoTSiteWise/Generated/Model/DescribeGatewayRequest.cs
| 1,788
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InfoBridge.SuperLinq.Core.Attributes
{
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class ColumnInfo : Attribute
{
public string Name { get; private set; }
public bool UseRaw { get; set; }
public ColumnInfo(string name)
{
Name = name;
}
}
}
| 23.428571
| 88
| 0.664634
|
[
"MIT"
] |
troien/InfoBridge.SuperLinq
|
src/InfoBridge.SuperLinq.Core/Attributes/ColumnInfo.cs
| 494
|
C#
|
using System.Collections.Generic;
using QuickGraph;
using System.Windows;
using GraphX;
using System;
namespace GraphX.GraphSharp.Algorithms.EdgeRouting
{
public abstract class EdgeRoutingAlgorithmBase<TVertex, TEdge, TGraph> : IExternalEdgeRouting<TVertex, TEdge>, IDisposable
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : class, IBidirectionalGraph<TVertex, TEdge>
{
protected IEdgeRoutingParameters _parameters;
protected TGraph _graph;
public IDictionary<TVertex, Rect> VertexSizes { get; set; }
public IDictionary<TVertex, Point> VertexPositions { get; set; }
/// <summary>
/// Gets or sets the resulting routing points of the edges.
/// </summary>
public IDictionary<TEdge, Point[]> EdgeRoutes
{
get;
private set;
}
public EdgeRoutingAlgorithmBase(TGraph graph, IDictionary<TVertex, Point> vertexPositions, IDictionary<TVertex, Rect> vertexSizes, IEdgeRoutingParameters parameters = null)
{
_graph = graph;
_parameters = parameters;
VertexSizes = vertexSizes;
VertexPositions = vertexPositions;
EdgeRoutes = new Dictionary<TEdge, Point[]>();
}
/// <summary>
/// Run algorithm calculation
/// </summary>
public virtual void Compute()
{
}
public virtual Point[] ComputeSingle(TEdge edge)
{
return null;
}
public virtual void UpdateVertexData(TVertex vertex, Point position, Rect size)
{
VertexPositions[vertex] = position;
VertexSizes[vertex] = size;
}
/// <summary>
/// GraphArea rendering size
/// </summary>
public Rect AreaRectangle { get; set; }
public void Dispose()
{
_graph = null;
_parameters = null;
}
}
}
| 28.537313
| 182
| 0.620816
|
[
"Apache-2.0"
] |
wangwshuai/graphic
|
GraphX.Logic/GraphXComponents/EdgeRouting/EdgeRoutingAlgorithmBase.cs
| 1,914
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarBehavior : MonoBehaviour {
public float maxSpeedMagnitude = 30f;
public float maxAccelerationMagnitude = 3f;
public float jerkMagnitude = 0.5f;
public float turnRate = 10f;
private float speed;
private float acceleration;
private float horizontalAxis;
private bool isInTheWeeds;
public Vector3 velocity;
private Rigidbody rb;
// Use this for initialization
void Start () {
speed = 0f;
acceleration = 0f;
horizontalAxis = 0f;
isInTheWeeds = false;
rb = GetComponent<Rigidbody>();
velocity = rb.velocity;
}
// Update is called once per frame
void Update () {
transform.Rotate(new Vector3(0, 1, 0), turnRate * horizontalAxis * Time.deltaTime);
}
private void FixedUpdate()
{
// the mass was originally 100, and we balanced things around that, so
// this will keep things in check if we shift the mass
rb.AddRelativeForce(Vector3.forward * speed * (rb.mass / 100), ForceMode.Impulse);
if (rb.velocity.magnitude > maxSpeedMagnitude)
rb.velocity = rb.velocity.normalized * maxSpeedMagnitude;
velocity = rb.velocity;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.gameObject.CompareTag("Weeds")){
isInTheWeeds = true;
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.collider.gameObject.CompareTag("Weeds"))
{
isInTheWeeds = false;
}
}
public void Accelerate (bool isPedalDown = false, bool isReverse = false) {
float jerk = 0;
float maxAcceleration = maxAccelerationMagnitude;
float maxSpeed = maxSpeedMagnitude;
if (isInTheWeeds) {
maxAcceleration /= 2;
maxSpeed /= 4;
}
if (isPedalDown)
{
jerk = jerkMagnitude;
if (isReverse) jerk *= -1;
if (acceleration + jerk > maxAcceleration)
acceleration = maxAcceleration;
else if (acceleration + jerk < (maxAcceleration * -1))
acceleration = maxAcceleration * -1;
else acceleration += jerk;
}
else {
if (speed < 0)
acceleration = maxAcceleration * 10; // speed up
else
acceleration = maxAcceleration * -1000; // slow down
}
if (speed + acceleration > maxSpeed)
speed = maxSpeed;
else if (speed + acceleration <= 0 && speed >= 0 && !isPedalDown) {
speed = 0;
acceleration = 0;
}
else if (speed + acceleration >= 0 && speed <= 0 && !isPedalDown) {
speed = 0;
acceleration = 0;
}
else if (speed + acceleration < (maxSpeed * -1))
speed = maxSpeed * -1;
else speed += acceleration;
}
public void Turn (float horizontalAxis) {
this.horizontalAxis = horizontalAxis;
}
void OnTriggerEnter(Collider other) {
//Destroy (other.gameObject);
if(other.gameObject.CompareTag("Ball"))
StartCoroutine(GameObject.FindGameObjectWithTag("GameController").GetComponent<GameController>().EndGame());
}
}
| 24.578512
| 114
| 0.672159
|
[
"MIT"
] |
makerslocal/LudumDare41
|
Pins and Needles/Assets/Scripts/CarBehavior.cs
| 2,976
|
C#
|
using System;
namespace ObjCRuntime
{
[Flags]
public enum Platform : ulong
{
None = 0,
iOS_2_0 = 0x0000000000020000,
iOS_2_2 = 0x0000000000020200,
iOS_3_0 = 0x0000000000030000,
iOS_3_1 = 0x0000000000030100,
iOS_3_2 = 0x0000000000030200,
iOS_4_0 = 0x0000000000040000,
iOS_4_1 = 0x0000000000040100,
iOS_4_2 = 0x0000000000040200,
iOS_4_3 = 0x0000000000040300,
iOS_5_0 = 0x0000000000050000,
iOS_5_1 = 0x0000000000050100,
iOS_6_0 = 0x0000000000060000,
iOS_6_1 = 0x0000000000060100,
iOS_7_0 = 0x0000000000070000,
iOS_7_1 = 0x0000000000070100,
iOS_8_0 = 0x0000000000080000,
iOS_8_1 = 0x0000000000080100,
iOS_8_2 = 0x0000000000080200,
iOS_8_3 = 0x0000000000080300,
Mac_10_0 = 0x000A000000000000,
Mac_10_1 = 0x000A010000000000,
Mac_10_2 = 0x000A020000000000,
Mac_10_3 = 0x000A030000000000,
Mac_10_4 = 0x000A040000000000,
Mac_10_5 = 0x000A050000000000,
Mac_10_6 = 0x000A060000000000,
Mac_10_7 = 0x000A070000000000,
Mac_10_8 = 0x000A080000000000,
Mac_10_9 = 0x000A090000000000,
Mac_10_10 = 0x000A0A0000000000,
iOS_Version = 0x0000000000FFFFFF,
Mac_Version = 0x00FFFFFF00000000,
Mac_Arch32 = 0x0100000000000000,
Mac_Arch64 = 0x0200000000000000,
Mac_Arch = 0xFF00000000000000,
iOS_Arch32 = 0x0000000001000000,
iOS_Arch64 = 0x0000000002000000,
iOS_Arch = 0x00000000FF000000
}
}
| 27.571429
| 35
| 0.775722
|
[
"MIT"
] |
JeffABC/api-doc-tools
|
mdoc/mdoc.Test/SampleClasses/ApplePlatformEnum.cs
| 1,353
|
C#
|
// Papercut
//
// Copyright © 2008 - 2012 Ken Robertson
// Copyright © 2013 - 2017 Jaben Cargman
//
// 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 Papercut.Module.WebUI.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using Core.Domain.Message;
using MimeKit;
public class MimeMessageEntry : MessageEntry
{
public string Subject => MailMessage?.Subject;
public DateTime? Created => _created;
public string Id => this.Name;
public MimeMessage MailMessage { get; }
public MimeMessageEntry(MessageEntry entry, MimeMessage message) : base(entry.File)
{
MailMessage = message;
}
public class RefDto
{
public static RefDto CreateFrom(MimeMessageEntry messageEntry)
{
return new RefDto
{
Subject = messageEntry.Subject,
CreatedAt = messageEntry.Created?.ToUniversalTime(),
Id = messageEntry.Id,
Size = messageEntry.FileSize
};
}
public string Size { get; set; }
public string Id { get; set; }
public DateTime? CreatedAt { get; set; }
public string Subject { get; set; }
}
public class DetailDto
{
public static DetailDto CreateFrom(MimeMessageEntry messageEntry)
{
var mail = messageEntry.MailMessage;
return new DetailDto
{
Subject = messageEntry.Subject,
CreatedAt = messageEntry.Created?.ToUniversalTime(),
Id = messageEntry.Id,
From = ToAddressList(mail?.From),
To = ToAddressList(mail?.To),
Cc = ToAddressList(mail?.Cc),
BCc = ToAddressList(mail?.Bcc),
HtmlBody = mail?.HtmlBody,
TextBody = mail?.TextBody,
Headers = (mail?.Headers ?? new HeaderList()).Select(h => new HeaderDto { Name = h.Field, Value = h.Value}).ToList(),
Sections = ToSectionDtos(mail?.BodyParts)
};
}
static List<EmailAttachmentDto> ToSectionDtos(IEnumerable<MimeEntity> bodyParts)
{
if (bodyParts == null) return new List<EmailAttachmentDto>();
return bodyParts
.OfType<MimePart>()
.Select(e => new EmailAttachmentDto
{
Id = e.ContentId,
MediaType = $"{e.ContentType.MediaType}/{e.ContentType.MediaSubtype}",
FileName = e.FileName
}).ToList();
}
static List<EmailAddressDto> ToAddressList(IList<InternetAddress> mailAddresses)
{
if (mailAddresses == null)
{
return new List<EmailAddressDto>();
}
return mailAddresses
.OfType<MailboxAddress>()
.Select(f => new EmailAddressDto {Address = f.Address, Name = f.Name})
.ToList();
}
public string Id { get; set; }
public DateTime? CreatedAt { get; set; }
public string Subject { get; set; }
public List<EmailAddressDto> From { get; set; } = new List<EmailAddressDto>();
public List<EmailAddressDto> To { get; set; } = new List<EmailAddressDto>();
public List<EmailAddressDto> Cc { get; set; } = new List<EmailAddressDto>();
public List<EmailAddressDto> BCc { get; set; } = new List<EmailAddressDto>();
public string HtmlBody { get; set; }
public string TextBody { get; set; }
public List<HeaderDto> Headers { get; set; }
public List<EmailAttachmentDto> Sections { get; set; }
}
public class EmailAddressDto
{
public string Name { get; set; }
public string Address { get; set; }
}
public class HeaderDto
{
public string Name { get; set; }
public string Value { get; set; }
}
public class EmailAttachmentDto
{
public string Id { get; set; }
public string MediaType { get; set; }
public string FileName { get; set; }
}
}
}
| 34.243243
| 137
| 0.539661
|
[
"Apache-2.0"
] |
jijiechen/PapercutCore
|
src/Papercut.Module.WebUI/Models/MimeMessageEntry.cs
| 5,072
|
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 System;
namespace Lucene.Net.Index
{
/// <summary>Extends <c>TermFreqVector</c> to provide additional information about
/// positions in which each of the terms is found. A TermPositionVector not necessarily
/// contains both positions and offsets, but at least one of these arrays exists.
/// </summary>
public interface TermPositionVector:ITermFreqVector
{
/// <summary>Returns an array of positions in which the term is found.
/// Terms are identified by the index at which its number appears in the
/// term String array obtained from the <c>indexOf</c> method.
/// May return null if positions have not been stored.
/// </summary>
int[] GetTermPositions(int index);
/// <summary> Returns an array of TermVectorOffsetInfo in which the term is found.
/// May return null if offsets have not been stored.
///
/// </summary>
/// <seealso cref="Lucene.Net.Analysis.Token">
///
/// </seealso>
/// <param name="index">The position in the array to get the offsets from
/// </param>
/// <returns> An array of TermVectorOffsetInfo objects or the empty list
/// </returns>
TermVectorOffsetInfo[] GetOffsets(int index);
}
}
| 42.44
| 91
| 0.675778
|
[
"Apache-2.0"
] |
BlueCurve-Team/lucenenet
|
src/Lucene.Net.Core/Index/TermPositionVector.cs
| 2,122
|
C#
|
using System;
using System.ComponentModel;
using AsmJit.AssemblerContext;
using AsmJit.Common.Operands;
using AsmJit.CompilerContext;
namespace AsmJit.Common
{
internal sealed class FunctionDeclaration
{
internal const int MaxArgumentCount = 16;
private int[] _passedOrderGp = new int[8].InitializeWith(() => -1);
private int[] _passedOrderXyz = new int[8].InitializeWith(() => -1);
private FunctionInOut[] _arguments;
private FunctionInOut[] _returns;
private ArgumentPassingDirection _argumentPassingDirection;
internal FunctionDeclaration(CallingConvention callingConvention, VariableType[] arguments, VariableType @return)
{
Used = new RegisterMask();
Passed = new RegisterMask();
Preserved = new RegisterMask();
CallingConvention = callingConvention == CallingConvention.Default ? Constants.DefaultCallingConvention : callingConvention;
_returns = new FunctionInOut[2];
_arguments = new FunctionInOut[arguments.Length];
Init(arguments, @return);
}
internal CallingConvention CallingConvention { get; private set; }
internal bool CalleePopsStack { get; private set; }
internal int ArgumentCount
{
get { return _arguments.Length; }
}
internal int ReturnCount { get; private set; }
internal int ArgumentsStackSize { get; private set; }
internal int RedZoneSize { get; private set; }
internal int SpillZoneSize { get; private set; }
public RegisterMask Preserved { get; private set; }
public RegisterMask Passed { get; private set; }
public RegisterMask Used { get; private set; }
internal FunctionInOut GetArgument(int index)
{
if (!(index >= 0 && index < _arguments.Length)) { throw new ArgumentException(); }
return _arguments[index];
}
internal FunctionInOut GetReturn(int index)
{
if (!(index >= 0 && index < _returns.Length)) { throw new ArgumentException(); }
return _returns[index];
}
private void Init(VariableType[] arguments, VariableType @return)
{
if (_arguments.Length > MaxArgumentCount)
{
throw new ArgumentException();
}
InitCallingConvention();
InitFunction(@return, arguments);
}
private void InitCallingConvention()
{
ArgumentsStackSize = 0;
RedZoneSize = 0;
SpillZoneSize = 0;
CalleePopsStack = false;
Passed.Reset();
Preserved.Reset();
if (Constants.X64)
{
switch (CallingConvention)
{
case CallingConvention.X64Win:
SpillZoneSize = 32;
Passed.Set(RegisterClass.Gp, Utils.Mask(RegisterIndex.Cx, RegisterIndex.Dx, 8, 9));
_passedOrderGp[0] = RegisterIndex.Cx;
_passedOrderGp[1] = RegisterIndex.Dx;
_passedOrderGp[2] = 8;
_passedOrderGp[3] = 9;
Passed.Set(RegisterClass.Xyz, Utils.Mask(0, 1, 2, 3));
_passedOrderXyz[0] = 0;
_passedOrderXyz[1] = 1;
_passedOrderXyz[2] = 2;
_passedOrderXyz[3] = 3;
Preserved.Set(RegisterClass.Gp, Utils.Mask(RegisterIndex.Bx, RegisterIndex.Sp, RegisterIndex.Bp, RegisterIndex.Si, RegisterIndex.Di, 12, 13, 14, 15));
Preserved.Set(RegisterClass.Xyz, Utils.Mask(6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
break;
case CallingConvention.X64Unix:
RedZoneSize = 128;
Passed.Set(RegisterClass.Gp, Utils.Mask(7, 6, 2, 1, 8, 9));
_passedOrderGp[0] = 7;
_passedOrderGp[1] = 6;
_passedOrderGp[2] = 2;
_passedOrderGp[3] = 1;
_passedOrderGp[4] = 8;
_passedOrderGp[5] = 9;
Passed.Set(RegisterClass.Xyz, Utils.Mask(0, 1, 2, 3, 4, 5, 6, 7));
_passedOrderXyz[0] = 0;
_passedOrderXyz[1] = 1;
_passedOrderXyz[2] = 2;
_passedOrderXyz[3] = 3;
_passedOrderXyz[4] = 4;
_passedOrderXyz[5] = 5;
_passedOrderXyz[6] = 6;
_passedOrderXyz[7] = 7;
Preserved.Set(RegisterClass.Gp, Utils.Mask(3, 4, 5, 12, 13, 14, 15));
break;
}
}
else
{
_argumentPassingDirection = ArgumentPassingDirection.RightToLeft;
Preserved.Set(RegisterClass.Gp, Utils.Mask(3, 4, 5, 6, 7));
switch (CallingConvention)
{
case CallingConvention.X86CDecl:
break;
case CallingConvention.X86StdCall:
CalleePopsStack = true;
break;
case CallingConvention.X86MsThisCall:
CalleePopsStack = true;
Passed.Set(RegisterClass.Gp, Utils.Mask(1));
_passedOrderGp[0] = 1;
break;
case CallingConvention.X86MsFastCall:
CalleePopsStack = true;
Passed.Set(RegisterClass.Gp, Utils.Mask(1, 1));
_passedOrderGp[0] = 1;
_passedOrderGp[1] = 2;
break;
case CallingConvention.X86BorlandFastCall:
CalleePopsStack = true;
_argumentPassingDirection = ArgumentPassingDirection.LeftToRight;
Passed.Set(RegisterClass.Gp, Utils.Mask(0, 2, 1));
_passedOrderGp[0] = 0;
_passedOrderGp[1] = 2;
_passedOrderGp[2] = 1;
break;
case CallingConvention.X86GccFastCall:
CalleePopsStack = true;
Passed.Set(RegisterClass.Gp, Utils.Mask(1, 2));
_passedOrderGp[0] = 1;
_passedOrderGp[1] = 2;
break;
case CallingConvention.X86GccRegParm1:
Passed.Set(RegisterClass.Gp, Utils.Mask(0));
_passedOrderGp[0] = 0;
break;
case CallingConvention.X86GccRegParm2:
Passed.Set(RegisterClass.Gp, Utils.Mask(0, 2));
_passedOrderGp[0] = 0;
_passedOrderGp[1] = 2;
break;
case CallingConvention.X86GccRegParm3:
Passed.Set(RegisterClass.Gp, Utils.Mask(0, 2, 1));
_passedOrderGp[0] = 0;
_passedOrderGp[1] = 2;
_passedOrderGp[2] = 1;
break;
}
}
}
private void InitFunction(VariableType ret, VariableType[] args)
{
var callConv = CallingConvention;
int i;
var gpPos = 0;
var xmmPos = 0;
var stackOffset = 0;
ReturnCount = 0;
var argumets = new ValueSet<VariableType, int, int>[args.Length];
for (i = 0; i < args.Length; i++)
{
argumets[i] = new ValueSet<VariableType, int, int>
{
Value0 = args[i].GetMappedType(),
Value1 = Constants.InvalidValue,
Value2 = Constants.InvalidValue
};
}
ArgumentsStackSize = 0;
Used.Reset();
if (ret != VariableType.Invalid)
{
switch (ret)
{
case VariableType.Int8:
case VariableType.UInt8:
case VariableType.Int16:
case VariableType.UInt16:
case VariableType.Int32:
case VariableType.UInt32:
ReturnCount = 1;
_returns[0] = new FunctionInOut(ret, 0);
break;
case VariableType.Int64:
if (Constants.X64)
{
ReturnCount = 1;
_returns[0] = new FunctionInOut(ret, 0);
}
else
{
ReturnCount = 2;
_returns[0] = new FunctionInOut(VariableType.UInt32, 0);
_returns[1] = new FunctionInOut(VariableType.Int32, 2);
}
break;
case VariableType.UInt64:
if (Constants.X64)
{
ReturnCount = 1;
_returns[0] = new FunctionInOut(ret, 0);
}
else
{
ReturnCount = 2;
_returns[0] = new FunctionInOut(VariableType.UInt32, 0);
_returns[1] = new FunctionInOut(VariableType.UInt32, 2);
}
break;
case VariableType.Fp32:
ReturnCount = 1;
if (Constants.X64)
{
_returns[0] = new FunctionInOut(VariableType.XmmSs, 0);
}
else
{
_returns[0] = new FunctionInOut(VariableType.Fp32, 0);
}
break;
case VariableType.Fp64:
ReturnCount = 1;
if (Constants.X64)
{
_returns[0] = new FunctionInOut(VariableType.XmmSd, 0);
}
else
{
_returns[0] = new FunctionInOut(VariableType.Fp64, 0);
}
break;
case VariableType.Mm:
case VariableType.Xmm:
case VariableType.XmmSs:
case VariableType.XmmPs:
case VariableType.XmmSd:
case VariableType.XmmPd:
ReturnCount = 1;
_returns[0] = new FunctionInOut(ret, 0);
break;
default:
throw new InvalidEnumArgumentException();
}
}
if (args.Length == 0) return;
VariableType varType;
if (Constants.X64)
{
if (callConv == CallingConvention.X64Win)
{
var argMax = Math.Min(args.Length, 4);
// Register arguments (Gp/Xmm), always left-to-right.
for (i = 0; i != argMax; i++)
{
varType = argumets[i].Value0.GetMappedType();
if (varType.IsInt() && i < _passedOrderGp.Length)
{
argumets[i].Value1 = _passedOrderGp[i];
Used.Or(RegisterClass.Gp, Utils.Mask(argumets[i].Value1));
continue;
}
if (!varType.IsFp() || i >= _passedOrderXyz.Length) continue;
argumets[i].Value0 = varType.ToXmm();
argumets[i].Value1 = _passedOrderXyz[i];
Used.Or(RegisterClass.Xyz, Utils.Mask(argumets[i].Value1));
}
// Stack arguments (always right-to-left).
for (i = args.Length - 1; i != -1; i--)
{
varType = argumets[i].Value0.GetMappedType();
if (argumets[i].Value1 != Constants.InvalidValue) continue;
if (varType.IsInt())
{
stackOffset -= 8; // Always 8 bytes.
argumets[i].Value2 = stackOffset;
}
else if (varType.IsFp())
{
stackOffset -= 8; // Always 8 bytes (float/double).
argumets[i].Value2 = stackOffset;
}
}
// 32 bytes shadow space (X64W calling convention specific).
stackOffset -= 4 * 8;
}
else
{
// Register arguments (Gp), always left-to-right.
for (i = 0; i != args.Length; i++)
{
varType = argumets[i].Value0.GetMappedType();
if (!varType.IsInt() || gpPos >= _passedOrderGp.Length) continue;
if (_passedOrderGp[gpPos] == -1) continue;
argumets[i].Value1 = _passedOrderGp[gpPos++];
Used.Or(RegisterClass.Gp, Utils.Mask(argumets[i].Value1));
}
// Register arguments (Xmm), always left-to-right.
for (i = 0; i != args.Length; i++)
{
varType = argumets[i].Value0.GetMappedType();
if (!varType.IsFp()) continue;
argumets[i].Value0 = varType.ToXmm();
argumets[i].Value1 = _passedOrderXyz[xmmPos++];
Used.Or(RegisterClass.Xyz, Utils.Mask(argumets[i].Value1));
}
// Stack arguments.
for (i = args.Length - 1; i != -1; i--)
{
varType = argumets[i].Value0.GetMappedType();
if (argumets[i].Value1 != Constants.InvalidValue) continue;
if (varType.IsInt())
{
stackOffset -= 8;
argumets[i].Value2 = stackOffset;
}
else if (varType.IsFp())
{
var size = varType.GetVariableInfo().Size;
stackOffset -= size;
argumets[i].Value2 = stackOffset;
}
}
}
}
else
{
for (i = 0; i != args.Length; i++)
{
varType = args[i].GetMappedType();
if (!varType.IsInt() || gpPos >= _passedOrderGp.Length) continue;
if (_passedOrderGp[gpPos] == -1) continue;
argumets[i].Value1 = _passedOrderGp[gpPos++];
Used.Or(RegisterClass.Gp, Utils.Mask(argumets[i].Value1));
}
// Stack arguments.
var start = args.Length - 1;
var end = -1;
var step = -1;
if (_argumentPassingDirection == ArgumentPassingDirection.LeftToRight)
{
start = 0;
end = args.Length;
step = 1;
}
for (i = start; i != end; i += step)
{
varType = args[i].GetMappedType();
if (argumets[i].Value1 != Constants.InvalidValue) continue;
if (varType.IsInt())
{
stackOffset -= 4;
argumets[i].Value2 = stackOffset;
}
else if (varType.IsFp())
{
var size = varType.GetVariableInfo().Size;
stackOffset -= size;
argumets[i].Value2 = stackOffset;
}
}
}
// Modify the stack offset, thus in result all parameters would have positive
// non-zero stack offset.
for (i = 0; i < args.Length; i++)
{
if (argumets[i].Value1 == Constants.InvalidValue)
{
argumets[i].Value2 += Cpu.Info.RegisterSize - stackOffset;
}
_arguments[i] = new FunctionInOut(argumets[i].Value0, argumets[i].Value1, argumets[i].Value2);
}
ArgumentsStackSize = -stackOffset;
}
}
}
| 26.986547
| 156
| 0.6223
|
[
"MIT"
] |
hypeartist/AsmJ
|
AsmJit/Common/FunctionDeclaration.cs
| 12,036
|
C#
|
using System.Collections.Generic;
using BaseTests;
using FluentAssertions;
using Unity.VersionControl.Git;
using NUnit.Framework;
using Unity.VersionControl.Git.IO;
namespace IntegrationTests
{
[TestFixture]
class A_GitClientTests : BaseTest
{
readonly string[] m_CleanFiles = { "file1.txt", "file2.txt", "file3.txt" };
[Test]
public void AaSetupGitFirst()
{
// empty test that sets up git for the rest of the tests
using (var test = StartTest(TestData.TestRepoMasterCleanSynchronized))
{}
}
[Test]
public void ShouldGetGitVersion()
{
if (!SPath.IsWindows)
return;
using (var test = StartTest(TestData.TestRepoMasterCleanSynchronized))
{
var result = test.GitClient.Version().RunSynchronously();
var expected = TheVersion.Parse("2.21.0");
result.Major.Should().Be(expected.Major);
result.Minor.Should().Be(expected.Minor);
result.Patch.Should().Be(expected.Patch);
}
}
[Test]
public void ShouldGetGitLfsVersion()
{
if (!SPath.IsWindows)
return;
using (var test = StartTest(TestData.TestRepoMasterCleanSynchronized))
{
var result = test.GitClient.LfsVersion().RunSynchronously();
var expected = TheVersion.Parse("2.6.1");
result.Should().Be(expected);
}
}
[Test]
public void ShouldCleanFile()
{
using (var test = StartTest(TestData.TestRepoMasterCleanSynchronized))
{
foreach (var file in m_CleanFiles)
{
file.ToSPath().WriteAllText("Some test text.");
}
test.GitClient.Clean(new List<string> { m_CleanFiles[0], m_CleanFiles[2] }).RunSynchronously();
m_CleanFiles[0].ToSPath().Exists().Should().BeFalse();
m_CleanFiles[1].ToSPath().Exists().Should().BeTrue();
m_CleanFiles[2].ToSPath().Exists().Should().BeFalse();
}
}
[Test]
public void ShouldCleanAllFiles()
{
using (var test = StartTest(TestData.TestRepoMasterCleanSynchronized))
{
foreach (var file in m_CleanFiles)
{
file.ToSPath().WriteAllText("Some test text.");
}
test.GitClient.CleanAll().RunSynchronously();
m_CleanFiles[0].ToSPath().Exists().Should().BeFalse();
m_CleanFiles[1].ToSPath().Exists().Should().BeFalse();
m_CleanFiles[2].ToSPath().Exists().Should().BeFalse();
}
}
[Test]
public void ShouldResetRepositoryState()
{
using (var test = StartTest(TestData.TestRepoMasterCleanSynchronized))
{
const string initialFile = "init-file.txt";
const string testFile = "reset-file.txt";
// Initial commit
initialFile.ToSPath().WriteAllText("Some test text.");
test.GitClient.Add(new List<string> { initialFile }).RunSynchronously();
test.GitClient.Commit("initial", "commit").RunSynchronously();
// Add file
testFile.ToSPath().WriteAllText("Some test text.");
test.GitClient.Add(new List<string> { testFile }).RunSynchronously();
test.GitClient.Commit("test", "commit").RunSynchronously();
testFile.ToSPath().Exists().Should().BeTrue();
// Reset to commit without file
test.GitClient.Reset("HEAD~1", GitResetMode.Hard).RunSynchronously();
testFile.ToSPath().Exists().Should().BeFalse();
}
}
}
}
| 34.258621
| 111
| 0.54152
|
[
"MIT"
] |
Cdddo/Git-for-Unity
|
tests/IntegrationTests/Git/GitClientTests.cs
| 3,974
|
C#
|
// Copyright 2017 Esri.
//
// 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 ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System;
using System.Drawing;
using System.Threading.Tasks;
using Windows.UI.Popups;
namespace ArcGISRuntime.UWP.Samples.UseDistanceCompositeSym
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Distance composite scene symbol",
category: "Symbology",
description: "Change a graphic's symbol based on the camera's proximity to it.",
instructions: "The sample starts looking at a plane. Zoom out from the plane to see it turn into a cone. Keeping zooming out and it will turn into a point.",
tags: new[] { "3D", "data", "graphic", "range", "symbol" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("681d6f7694644709a7c830ec57a2d72b")]
public sealed partial class UseDistanceCompositeSym
{
public UseDistanceCompositeSym()
{
InitializeComponent();
// Create the Scene, basemap, graphic, and composite symbol.
Initialize();
}
private async void Initialize()
{
try
{
// Create a new Scene with an imagery basemap.
Scene myScene = new Scene(Basemap.CreateImagery());
// Add the Scene to the SceneView.
MySceneView.Scene = myScene;
// Create a new GraphicsOverlay and add it to the SceneView.
GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
graphicsOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Relative;
MySceneView.GraphicsOverlays.Add(graphicsOverlay);
// Call a function to create a new distance composite symbol with three ranges.
DistanceCompositeSceneSymbol compositeSymbol = await CreateCompositeSymbol();
// Create a new point graphic with the composite symbol, add it to the graphics overlay.
MapPoint locationPoint = new MapPoint(-2.708471, 56.096575, 5000, SpatialReferences.Wgs84);
Graphic pointGraphic = new Graphic(locationPoint, compositeSymbol);
graphicsOverlay.Graphics.Add(pointGraphic);
// Add an orbit camera controller to lock the camera to the graphic.
OrbitGeoElementCameraController cameraController = new OrbitGeoElementCameraController(pointGraphic, 20)
{
CameraPitchOffset = 80,
CameraHeadingOffset = -30
};
MySceneView.CameraController = cameraController;
}
catch (Exception e)
{
MessageDialog dialog = new MessageDialog(e.ToString(), "Error");
await dialog.ShowAsync();
}
}
private async Task<DistanceCompositeSceneSymbol> CreateCompositeSymbol()
{
// Get the path to the 3D model.
string modelPath = GetModelPath();
// Create three symbols for displaying a feature according to its distance from the camera.
// First, a 3D model symbol (airplane) for when the camera is near the feature.
ModelSceneSymbol plane3DSymbol = await ModelSceneSymbol.CreateAsync(new Uri(modelPath), 1.0);
// 3D (blue cone) symbol for when the feature is at an intermediate range.
SimpleMarkerSceneSymbol coneSym = new SimpleMarkerSceneSymbol(SimpleMarkerSceneSymbolStyle.Cone, Color.LightSkyBlue, 15, 6, 3, SceneSymbolAnchorPosition.Center)
{
// The cone will point in the same direction as the plane.
Pitch = -90
};
// Simple marker symbol (circle) when the feature is far from the camera.
SimpleMarkerSymbol markerSym = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.LightSkyBlue, 10.0);
// Create three new ranges for displaying each symbol.
DistanceSymbolRange closeRange = new DistanceSymbolRange(plane3DSymbol, 0, 100);
DistanceSymbolRange midRange = new DistanceSymbolRange(coneSym, 100, 500);
DistanceSymbolRange farRange = new DistanceSymbolRange(markerSym, 500, 0);
// Create a new DistanceCompositeSceneSymbol and add the ranges.
DistanceCompositeSceneSymbol compositeSymbol = new DistanceCompositeSceneSymbol();
compositeSymbol.Ranges.Add(closeRange);
compositeSymbol.Ranges.Add(midRange);
compositeSymbol.Ranges.Add(farRange);
// Return the new composite symbol.
return compositeSymbol;
}
private static string GetModelPath()
{
return DataManager.GetDataFolder("681d6f7694644709a7c830ec57a2d72b", "Bristol.dae");
}
}
}
| 46.974359
| 172
| 0.659753
|
[
"Apache-2.0"
] |
Druffl3/arcgis-runtime-samples-dotnet
|
src/UWP/ArcGISRuntime.UWP.Viewer/Samples/Symbology/UseDistanceCompositeSym/UseDistanceCompositeSym.xaml.cs
| 5,496
|
C#
|
using System;
using System.Runtime.Serialization;
namespace Capgemini.Xrm.CdsDataMigratorLibrary.Exceptions
{
[Serializable]
public class OrganizationalServiceException : Exception
{
public OrganizationalServiceException()
{
}
public OrganizationalServiceException(string message)
: base(message)
{
}
public OrganizationalServiceException(string message, Exception inner)
: base(message, inner)
{
}
protected OrganizationalServiceException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 24
| 98
| 0.639881
|
[
"MIT"
] |
Capgemini/xrm-datamigration-xrmtoolbox
|
Capgemini.Xrm.CdsDataMigrator/Capgemini.Xrm.CdsDataMigratorLibrary/Exceptions/OrganizationalServiceException.cs
| 674
|
C#
|
namespace Asia.Solid.Domain.Entities
{
public class DetalhePagamento
{
public string NumeroCartao { get; set; }
public int MesExpiracao { get; set; }
public int AnoExpiracao { get; set; }
public string NomeImpressoCartao { get; set; }
}
}
| 29.1
| 62
| 0.61512
|
[
"MIT"
] |
denniskalla/Asia---SOLID
|
src/Asia.Solid.Domain/Entities/DetalhePagamento.cs
| 293
|
C#
|
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Xamarin.MacDev.Tasks;
using Xamarin.MacDev;
namespace Xamarin.iOS.Tasks
{
public abstract class FindWatchOS1AppExtensionBundleTaskBase : Task
{
#region Inputs
public string SessionId { get; set; }
[Required]
public ITaskItem[] AppExtensionReferences { get; set; }
#endregion Inputs
#region Outputs
[Output]
public string WatchOS1AppExtensionBundle { get; set; }
#endregion
public override bool Execute ()
{
var pwd = PathUtils.ResolveSymbolicLink (Environment.CurrentDirectory);
Log.LogTaskName ("FindWatchOS1AppExtensionBundle");
Log.LogTaskProperty ("AppExtensionReferences", AppExtensionReferences);
for (int i = 0; i < AppExtensionReferences.Length; i++) {
var plist = PDictionary.FromFile (Path.Combine (AppExtensionReferences[i].ItemSpec, "Info.plist"));
PString expectedBundleIdentifier, bundleIdentifier, extensionPoint;
PDictionary extension, attributes;
if (!plist.TryGetValue ("NSExtension", out extension))
continue;
if (!extension.TryGetValue ("NSExtensionPointIdentifier", out extensionPoint))
continue;
if (extensionPoint.Value != "com.apple.watchkit")
continue;
// Okay, we've found the WatchKit App Extension...
if (!extension.TryGetValue ("NSExtensionAttributes", out attributes))
continue;
if (!attributes.TryGetValue ("WKAppBundleIdentifier", out expectedBundleIdentifier))
continue;
// Scan the *.app subdirectories to find the WatchApp bundle...
foreach (var bundle in Directory.GetDirectories (AppExtensionReferences[i].ItemSpec, "*.app")) {
if (!File.Exists (Path.Combine (bundle, "Info.plist")))
continue;
plist = PDictionary.FromFile (Path.Combine (bundle, "Info.plist"));
if (!plist.TryGetValue ("CFBundleIdentifier", out bundleIdentifier))
continue;
if (bundleIdentifier.Value != expectedBundleIdentifier.Value)
continue;
WatchOS1AppExtensionBundle = PathUtils.AbsoluteToRelative (pwd, PathUtils.ResolveSymbolicLink (bundle));
return true;
}
}
return !Log.HasLoggedErrors;
}
}
}
| 27.234568
| 109
| 0.722121
|
[
"BSD-3-Clause"
] |
ludovic-henry/xamarin-macios
|
msbuild/Xamarin.iOS.Tasks.Core/Tasks/FindWatchOS1AppExtensionBundleTaskBase.cs
| 2,208
|
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("Exoskeleton")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Exoskeleton")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("3f4ee168-9855-48e0-b98a-90531b4ba181")]
// 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")]
| 37.702703
| 84
| 0.744803
|
[
"MIT"
] |
bsitler/Exoskeleton
|
Exoskeleton/Exoskeleton/Properties/AssemblyInfo.cs
| 1,398
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** Purpose: Class for creating and managing a threadpool
**
**
=============================================================================*/
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.Win32;
namespace System.Threading
{
internal static class ThreadPoolGlobals
{
//Per-appDomain quantum (in ms) for which the thread keeps processing
//requests in the current domain.
public const uint TP_QUANTUM = 30U;
public static readonly int processorCount = Environment.ProcessorCount;
public static volatile bool vmTpInitialized;
public static bool enableWorkerTracking;
public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
}
[StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing
internal sealed class ThreadPoolWorkQueue
{
internal static class WorkStealingQueueList
{
private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0];
public static WorkStealingQueue[] Queues => _queues;
public static void Add(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
Debug.Assert(Array.IndexOf(oldQueues, queue) == -1);
var newQueues = new WorkStealingQueue[oldQueues.Length + 1];
Array.Copy(oldQueues, 0, newQueues, 0, oldQueues.Length);
newQueues[newQueues.Length - 1] = queue;
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
public static void Remove(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
if (oldQueues.Length == 0)
{
return;
}
int pos = Array.IndexOf(oldQueues, queue);
if (pos == -1)
{
Debug.Fail("Should have found the queue");
return;
}
var newQueues = new WorkStealingQueue[oldQueues.Length - 1];
if (pos == 0)
{
Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length);
}
else if (pos == oldQueues.Length - 1)
{
Array.Copy(oldQueues, 0, newQueues, 0, newQueues.Length);
}
else
{
Array.Copy(oldQueues, 0, newQueues, 0, pos);
Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos);
}
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
}
internal sealed class WorkStealingQueue
{
private const int INITIAL_SIZE = 32;
internal volatile IThreadPoolWorkItem[] m_array = new IThreadPoolWorkItem[INITIAL_SIZE];
private volatile int m_mask = INITIAL_SIZE - 1;
#if DEBUG
// in debug builds, start at the end so we exercise the index reset logic.
private const int START_INDEX = int.MaxValue;
#else
private const int START_INDEX = 0;
#endif
private volatile int m_headIndex = START_INDEX;
private volatile int m_tailIndex = START_INDEX;
private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false);
public void LocalPush(IThreadPoolWorkItem obj)
{
int tail = m_tailIndex;
// We're going to increment the tail; if we'll overflow, then we need to reset our counts
if (tail == int.MaxValue)
{
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_tailIndex == int.MaxValue)
{
//
// Rather than resetting to zero, we'll just mask off the bits we don't care about.
// This way we don't need to rearrange the items already in the queue; they'll be found
// correctly exactly where they are. One subtlety here is that we need to make sure that
// if head is currently < tail, it remains that way. This happens to just fall out from
// the bit-masking, because we only do this if tail == int.MaxValue, meaning that all
// bits are set, so all of the bits we're keeping will also be set. Thus it's impossible
// for the head to end up > than the tail, since you can't set any more bits than all of
// them.
//
m_headIndex = m_headIndex & m_mask;
m_tailIndex = tail = m_tailIndex & m_mask;
Debug.Assert(m_headIndex <= m_tailIndex);
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: true);
}
}
// When there are at least 2 elements' worth of space, we can take the fast path.
if (tail < m_headIndex + m_mask)
{
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
else
{
// We need to contend with foreign pops, so we lock.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
int head = m_headIndex;
int count = m_tailIndex - m_headIndex;
// If there is still space (one left), just add the element.
if (count >= m_mask)
{
// We're full; expand the queue by doubling its size.
var newArray = new IThreadPoolWorkItem[m_array.Length << 1];
for (int i = 0; i < m_array.Length; i++)
newArray[i] = m_array[(i + head) & m_mask];
// Reset the field values, incl. the mask.
m_array = newArray;
m_headIndex = 0;
m_tailIndex = tail = count;
m_mask = (m_mask << 1) | 1;
}
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
public bool LocalFindAndPop(IThreadPoolWorkItem obj)
{
// Fast path: check the tail. If equal, we can skip the lock.
if (m_array[(m_tailIndex - 1) & m_mask] == obj)
{
IThreadPoolWorkItem unused = LocalPop();
Debug.Assert(unused == null || unused == obj);
return unused != null;
}
// Else, do an O(N) search for the work item. The theory of work stealing and our
// inlining logic is that most waits will happen on recently queued work. And
// since recently queued work will be close to the tail end (which is where we
// begin our search), we will likely find it quickly. In the worst case, we
// will traverse the whole local queue; this is typically not going to be a
// problem (although degenerate cases are clearly an issue) because local work
// queues tend to be somewhat shallow in length, and because if we fail to find
// the work item, we are about to block anyway (which is very expensive).
for (int i = m_tailIndex - 2; i >= m_headIndex; i--)
{
if (m_array[i & m_mask] == obj)
{
// If we found the element, block out steals to avoid interference.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
// If we encountered a race condition, bail.
if (m_array[i & m_mask] == null)
return false;
// Otherwise, null out the element.
Volatile.Write(ref m_array[i & m_mask], null);
// And then check to see if we can fix up the indexes (if we're at
// the edge). If we can't, we just leave nulls in the array and they'll
// get filtered out eventually (but may lead to superfluous resizing).
if (i == m_tailIndex)
m_tailIndex -= 1;
else if (i == m_headIndex)
m_headIndex += 1;
return true;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
return false;
}
public IThreadPoolWorkItem LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null;
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
private IThreadPoolWorkItem LocalPopCore()
{
while (true)
{
int tail = m_tailIndex;
if (m_headIndex >= tail)
{
return null;
}
// Decrement the tail using a fence to ensure subsequent read doesn't come before.
tail -= 1;
Interlocked.Exchange(ref m_tailIndex, tail);
// If there is no interaction with a take, we can head down the fast path.
if (m_headIndex <= tail)
{
int idx = tail & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Interaction with takes: 0 or 1 elements left.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_headIndex <= tail)
{
// Element still available. Take it.
int idx = tail & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// If we encountered a race condition and element was stolen, restore the tail.
m_tailIndex = tail + 1;
return null;
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
}
public bool CanSteal => m_headIndex < m_tailIndex;
public IThreadPoolWorkItem TrySteal(ref bool missedSteal)
{
while (true)
{
if (CanSteal)
{
bool taken = false;
try
{
m_foreignLock.TryEnter(ref taken);
if (taken)
{
// Increment head, and ensure read of tail doesn't move before it (fence).
int head = m_headIndex;
Interlocked.Exchange(ref m_headIndex, head + 1);
if (head < m_tailIndex)
{
int idx = head & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Failed, restore head.
m_headIndex = head;
}
}
}
finally
{
if (taken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
missedSteal = true;
}
return null;
}
}
}
internal bool loggingEnabled;
internal readonly ConcurrentQueue<IThreadPoolWorkItem> workItems = new ConcurrentQueue<IThreadPoolWorkItem>();
private Internal.PaddingFor32 pad1;
private volatile int numOutstandingThreadRequests = 0;
private Internal.PaddingFor32 pad2;
public ThreadPoolWorkQueue()
{
loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
}
public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() =>
ThreadPoolWorkQueueThreadLocals.threadLocals ??
(ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this));
internal void EnsureThreadRequested()
{
//
// If we have not yet requested #procs threads from the VM, then request a new thread
// as needed
//
// Note that there is a separate count in the VM which will also be incremented in this case,
// which is handled by RequestWorkerThread.
//
int count = numOutstandingThreadRequests;
while (count < ThreadPoolGlobals.processorCount)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count);
if (prev == count)
{
ThreadPool.RequestWorkerThread();
break;
}
count = prev;
}
}
internal void MarkThreadRequestSatisfied()
{
//
// The VM has called us, so one of our outstanding thread requests has been satisfied.
// Decrement the count so that future calls to EnsureThreadRequested will succeed.
// Note that there is a separate count in the VM which has already been decremented by the VM
// by the time we reach this point.
//
int count = numOutstandingThreadRequests;
while (count > 0)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count);
if (prev == count)
{
break;
}
count = prev;
}
}
public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
{
if (loggingEnabled)
System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback);
ThreadPoolWorkQueueThreadLocals tl = null;
if (!forceGlobal)
tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
if (null != tl)
{
tl.workStealingQueue.LocalPush(callback);
}
else
{
workItems.Enqueue(callback);
}
EnsureThreadRequested();
}
internal bool LocalFindAndPop(IThreadPoolWorkItem callback)
{
ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
return tl != null && tl.workStealingQueue.LocalFindAndPop(callback);
}
public IThreadPoolWorkItem Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
{
WorkStealingQueue localWsq = tl.workStealingQueue;
IThreadPoolWorkItem callback;
if ((callback = localWsq.LocalPop()) == null && // first try the local queue
!workItems.TryDequeue(out callback)) // then try the global queue
{
// finally try to steal from another thread's local queue
WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
int c = queues.Length;
Debug.Assert(c > 0, "There must at least be a queue for this thread.");
int maxIndex = c - 1;
int i = tl.random.Next(c);
while (c > 0)
{
i = (i < maxIndex) ? i + 1 : 0;
WorkStealingQueue otherQueue = queues[i];
if (otherQueue != localWsq && otherQueue.CanSteal)
{
callback = otherQueue.TrySteal(ref missedSteal);
if (callback != null)
{
break;
}
}
c--;
}
}
return callback;
}
internal static bool Dispatch()
{
var workQueue = ThreadPoolGlobals.workQueue;
//
// The clock is ticking! We have ThreadPoolGlobals.TP_QUANTUM milliseconds to get some work done, and then
// we need to return to the VM.
//
int quantumStartTime = Environment.TickCount;
//
// Update our records to indicate that an outstanding request for a thread has now been fulfilled.
// From this point on, we are responsible for requesting another thread if we stop working for any
// reason, and we believe there might still be work in the queue.
//
// Note that if this thread is aborted before we get a chance to request another one, the VM will
// record a thread request on our behalf. So we don't need to worry about getting aborted right here.
//
workQueue.MarkThreadRequestSatisfied();
// Has the desire for logging changed since the last time we entered?
workQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
//
// Assume that we're going to need another thread if this one returns to the VM. We'll set this to
// false later, but only if we're absolutely certain that the queue is empty.
//
bool needAnotherThread = true;
IThreadPoolWorkItem workItem = null;
try
{
//
// Set up our thread-local data
//
ThreadPoolWorkQueueThreadLocals tl = workQueue.EnsureCurrentThreadHasQueue();
//
// Loop until our quantum expires.
//
while ((Environment.TickCount - quantumStartTime) < ThreadPoolGlobals.TP_QUANTUM)
{
bool missedSteal = false;
workItem = workQueue.Dequeue(tl, ref missedSteal);
if (workItem == null)
{
//
// No work. We're going to return to the VM once we leave this protected region.
// If we missed a steal, though, there may be more work in the queue.
// Instead of looping around and trying again, we'll just request another thread. This way
// we won't starve other AppDomains while we spin trying to get locks, and hopefully the thread
// that owns the contended work-stealing queue will pick up its own workitems in the meantime,
// which will be more efficient than this thread doing it anyway.
//
needAnotherThread = missedSteal;
// Tell the VM we're returning normally, not because Hill Climbing asked us to return.
return true;
}
if (workQueue.loggingEnabled)
System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolDequeueWorkObject(workItem);
//
// If we found work, there may be more work. Ask for another thread so that the other work can be processed
// in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
//
workQueue.EnsureThreadRequested();
//
// Execute the workitem outside of any finally blocks, so that it can be aborted if needed.
//
if (ThreadPoolGlobals.enableWorkerTracking)
{
bool reportedStatus = false;
try
{
ThreadPool.ReportThreadStatus(isWorking: true);
reportedStatus = true;
workItem.ExecuteWorkItem();
}
finally
{
if (reportedStatus)
ThreadPool.ReportThreadStatus(isWorking: false);
}
}
else
{
workItem.ExecuteWorkItem();
}
workItem = null;
//
// Notify the VM that we executed this workitem. This is also our opportunity to ask whether Hill Climbing wants
// us to return the thread to the pool or not.
//
if (!ThreadPool.NotifyWorkItemComplete())
return false;
}
// If we get here, it's because our quantum expired. Tell the VM we're returning normally.
return true;
}
catch (ThreadAbortException tae)
{
//
// This is here to catch the case where this thread is aborted between the time we exit the finally block in the dispatch
// loop, and the time we execute the work item. QueueUserWorkItemCallback uses this to update its accounting of whether
// it was executed or not (in debug builds only). Task uses this to communicate the ThreadAbortException to anyone
// who waits for the task to complete.
//
workItem?.MarkAborted(tae);
//
// In this case, the VM is going to request another thread on our behalf. No need to do it twice.
//
needAnotherThread = false;
// throw; //no need to explicitly rethrow a ThreadAbortException, and doing so causes allocations on amd64.
}
finally
{
//
// If we are exiting for any reason other than that the queue is definitely empty, ask for another
// thread to pick up where we left off.
//
if (needAnotherThread)
workQueue.EnsureThreadRequested();
}
// we can never reach this point, but the C# compiler doesn't know that, because it doesn't know the ThreadAbortException will be reraised above.
Debug.Fail("Should never reach this point");
return true;
}
}
// Simple random number generator. We don't need great randomness, we just need a little and for it to be fast.
internal struct FastRandom // xorshift prng
{
private uint _w, _x, _y, _z;
public FastRandom(int seed)
{
_x = (uint)seed;
_w = 88675123;
_y = 362436069;
_z = 521288629;
}
public int Next(int maxValue)
{
Debug.Assert(maxValue > 0);
uint t = _x ^ (_x << 11);
_x = _y; _y = _z; _z = _w;
_w = _w ^ (_w >> 19) ^ (t ^ (t >> 8));
return (int)(_w % (uint)maxValue);
}
}
// Holds a WorkStealingQueue, and removes it from the list when this object is no longer referenced.
internal sealed class ThreadPoolWorkQueueThreadLocals
{
[ThreadStatic]
public static ThreadPoolWorkQueueThreadLocals threadLocals;
public readonly ThreadPoolWorkQueue workQueue;
public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue;
public FastRandom random = new FastRandom(Thread.CurrentThread.ManagedThreadId); // mutable struct, do not copy or make readonly
public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq)
{
workQueue = tpq;
workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue();
ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue);
}
private void CleanUp()
{
if (null != workStealingQueue)
{
if (null != workQueue)
{
IThreadPoolWorkItem cb;
while ((cb = workStealingQueue.LocalPop()) != null)
{
Debug.Assert(null != cb);
workQueue.Enqueue(cb, forceGlobal: true);
}
}
ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue);
}
}
~ThreadPoolWorkQueueThreadLocals()
{
// Since the purpose of calling CleanUp is to transfer any pending workitems into the global
// queue so that they will be executed by another thread, there's no point in doing this cleanup
// if we're in the process of shutting down or unloading the AD. In those cases, the work won't
// execute anyway. And there are subtle race conditions involved there that would lead us to do the wrong
// thing anyway. So we'll only clean up if this is a "normal" finalization.
if (!(Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload()))
CleanUp();
}
}
internal sealed class RegisteredWaitHandleSafe : CriticalFinalizerObject
{
private static IntPtr InvalidHandle => Win32Native.INVALID_HANDLE_VALUE;
private IntPtr registeredWaitHandle = InvalidHandle;
private WaitHandle m_internalWaitObject;
private bool bReleaseNeeded = false;
private volatile int m_lock = 0;
internal IntPtr GetHandle() => registeredWaitHandle;
internal void SetHandle(IntPtr handle)
{
registeredWaitHandle = handle;
}
internal void SetWaitObject(WaitHandle waitObject)
{
// needed for DangerousAddRef
RuntimeHelpers.PrepareConstrainedRegions();
m_internalWaitObject = waitObject;
if (waitObject != null)
{
m_internalWaitObject.SafeWaitHandle.DangerousAddRef(ref bReleaseNeeded);
}
}
internal bool Unregister(
WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
)
{
bool result = false;
// needed for DangerousRelease
RuntimeHelpers.PrepareConstrainedRegions();
// lock(this) cannot be used reliably in Cer since thin lock could be
// promoted to syncblock and that is not a guaranteed operation
bool bLockTaken = false;
do
{
if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)
{
bLockTaken = true;
try
{
if (ValidHandle())
{
result = UnregisterWaitNative(GetHandle(), waitObject == null ? null : waitObject.SafeWaitHandle);
if (result == true)
{
if (bReleaseNeeded)
{
m_internalWaitObject.SafeWaitHandle.DangerousRelease();
bReleaseNeeded = false;
}
// if result not true don't release/suppress here so finalizer can make another attempt
SetHandle(InvalidHandle);
m_internalWaitObject = null;
GC.SuppressFinalize(this);
}
}
}
finally
{
m_lock = 0;
}
}
Thread.SpinWait(1); // yield to processor
}
while (!bLockTaken);
return result;
}
private bool ValidHandle() =>
registeredWaitHandle != InvalidHandle && registeredWaitHandle != IntPtr.Zero;
~RegisteredWaitHandleSafe()
{
// if the app has already unregistered the wait, there is nothing to cleanup
// we can detect this by checking the handle. Normally, there is no race condition here
// so no need to protect reading of handle. However, if this object gets
// resurrected and then someone does an unregister, it would introduce a race condition
//
// PrepareConstrainedRegions call not needed since finalizer already in Cer
//
// lock(this) cannot be used reliably even in Cer since thin lock could be
// promoted to syncblock and that is not a guaranteed operation
//
// Note that we will not "spin" to get this lock. We make only a single attempt;
// if we can't get the lock, it means some other thread is in the middle of a call
// to Unregister, which will do the work of the finalizer anyway.
//
// Further, it's actually critical that we *not* wait for the lock here, because
// the other thread that's in the middle of Unregister may be suspended for shutdown.
// Then, during the live-object finalization phase of shutdown, this thread would
// end up spinning forever, as the other thread would never release the lock.
// This will result in a "leak" of sorts (since the handle will not be cleaned up)
// but the process is exiting anyway.
//
// During AD-unload, we don�t finalize live objects until all threads have been
// aborted out of the AD. Since these locked regions are CERs, we won�t abort them
// while the lock is held. So there should be no leak on AD-unload.
//
if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)
{
try
{
if (ValidHandle())
{
WaitHandleCleanupNative(registeredWaitHandle);
if (bReleaseNeeded)
{
m_internalWaitObject.SafeWaitHandle.DangerousRelease();
bReleaseNeeded = false;
}
SetHandle(InvalidHandle);
m_internalWaitObject = null;
}
}
finally
{
m_lock = 0;
}
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void WaitHandleCleanupNative(IntPtr handle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle waitObject);
}
public sealed class RegisteredWaitHandle : MarshalByRefObject
{
private readonly RegisteredWaitHandleSafe internalRegisteredWait;
internal RegisteredWaitHandle()
{
internalRegisteredWait = new RegisteredWaitHandleSafe();
}
internal void SetHandle(IntPtr handle)
{
internalRegisteredWait.SetHandle(handle);
}
internal void SetWaitObject(WaitHandle waitObject)
{
internalRegisteredWait.SetWaitObject(waitObject);
}
// This is the only public method on this class
public bool Unregister(
WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
)
{
return internalRegisteredWait.Unregister(waitObject);
}
}
public delegate void WaitCallback(object state);
public delegate void WaitOrTimerCallback(object state, bool timedOut); // signaled or timed out
//
// This type is necessary because VS 2010's debugger looks for a method named _ThreadPoolWaitCallbacck.PerformWaitCallback
// on the stack to determine if a thread is a ThreadPool thread or not. We have a better way to do this for .NET 4.5, but
// still need to maintain compatibility with VS 2010. When compat with VS 2010 is no longer an issue, this type may be
// removed.
//
internal static class _ThreadPoolWaitCallback
{
internal static bool PerformWaitCallback() => ThreadPoolWorkQueue.Dispatch();
}
//
// Interface to something that can be queued to the TP. This is implemented by
// QueueUserWorkItemCallback, Task, and potentially other internal types.
// For example, SemaphoreSlim represents callbacks using its own type that
// implements IThreadPoolWorkItem.
//
// If we decide to expose some of the workstealing
// stuff, this is NOT the thing we want to expose to the public.
//
internal interface IThreadPoolWorkItem
{
void ExecuteWorkItem();
void MarkAborted(ThreadAbortException tae);
}
internal abstract class QueueUserWorkItemCallbackBase : IThreadPoolWorkItem
{
#if DEBUG
private volatile int executed;
~QueueUserWorkItemCallbackBase()
{
Debug.Assert(
executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallback was never called!");
}
protected void MarkExecuted(bool aborted)
{
GC.SuppressFinalize(this);
Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1) || aborted,
"A QueueUserWorkItemCallback was called twice!");
}
#endif
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
{
#if DEBUG
// This workitem didn't execute because we got a ThreadAbortException prior to the call to ExecuteWorkItem.
// This counts as being executed for our purposes.
MarkExecuted(aborted: true);
#endif
}
public virtual void ExecuteWorkItem()
{
#if DEBUG
MarkExecuted(aborted: false);
#endif
}
}
internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase
{
private WaitCallback _callback;
private readonly object _state;
private readonly ExecutionContext _context;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallback)state;
WaitCallback c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallback(WaitCallback callback, object state, ExecutionContext context)
{
_callback = callback;
_state = state;
_context = context;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
ExecutionContext context = _context;
if (context == null)
{
WaitCallback c = _callback;
_callback = null;
c(_state);
}
else
{
ExecutionContext.RunInternal(context, s_executionContextShim, this);
}
}
}
internal sealed class QueueUserWorkItemCallback<TState> : QueueUserWorkItemCallbackBase
{
private Action<TState> _callback;
private readonly TState _state;
private readonly ExecutionContext _context;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallback<TState>)state;
Action<TState> c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallback(Action<TState> callback, TState state, ExecutionContext context)
{
_callback = callback;
_state = state;
_context = context;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
ExecutionContext context = _context;
if (context == null)
{
Action<TState> c = _callback;
_callback = null;
c(_state);
}
else
{
ExecutionContext.RunInternal(context, s_executionContextShim, this);
}
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkItemCallbackBase
{
private WaitCallback _callback;
private readonly object _state;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallbackDefaultContext)state;
WaitCallback c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallbackDefaultContext(WaitCallback callback, object state)
{
_callback = callback;
_state = state;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
ExecutionContext.RunInternal(executionContext: null, s_executionContextShim, this); // null executionContext on RunInternal is Default context
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext<TState> : QueueUserWorkItemCallbackBase
{
private Action<TState> _callback;
private readonly TState _state;
internal static readonly ContextCallback s_executionContextShim = state =>
{
var obj = (QueueUserWorkItemCallbackDefaultContext<TState>)state;
Action<TState> c = obj._callback;
Debug.Assert(c != null);
obj._callback = null;
c(obj._state);
};
internal QueueUserWorkItemCallbackDefaultContext(Action<TState> callback, TState state)
{
_callback = callback;
_state = state;
}
public override void ExecuteWorkItem()
{
base.ExecuteWorkItem();
ExecutionContext.RunInternal(executionContext: null, s_executionContextShim, this); // null executionContext on RunInternal is Default context
}
}
internal class _ThreadPoolWaitOrTimerCallback
{
private WaitOrTimerCallback _waitOrTimerCallback;
private ExecutionContext _executionContext;
private object _state;
private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool compressStack)
{
_waitOrTimerCallback = waitOrTimerCallback;
_state = state;
if (compressStack)
{
// capture the exection context
_executionContext = ExecutionContext.Capture();
}
}
private static void WaitOrTimerCallback_Context_t(object state) =>
WaitOrTimerCallback_Context(state, timedOut: true);
private static void WaitOrTimerCallback_Context_f(object state) =>
WaitOrTimerCallback_Context(state, timedOut: false);
private static void WaitOrTimerCallback_Context(object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
helper._waitOrTimerCallback(helper._state, timedOut);
}
// call back helper
internal static void PerformWaitOrTimerCallback(object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
// call directly if it is an unsafe call OR EC flow is suppressed
ExecutionContext context = helper._executionContext;
if (context == null)
{
WaitOrTimerCallback callback = helper._waitOrTimerCallback;
callback(helper._state, timedOut);
}
else
{
ExecutionContext.Run(context, timedOut ? _ccbt : _ccbf, helper);
}
}
}
[CLSCompliant(false)]
public unsafe delegate void IOCompletionCallback(uint errorCode, // Error code
uint numBytes, // No. of bytes transferred
NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
);
public static class ThreadPool
{
public static bool SetMaxThreads(int workerThreads, int completionPortThreads)
{
return SetMaxThreadsNative(workerThreads, completionPortThreads);
}
public static void GetMaxThreads(out int workerThreads, out int completionPortThreads)
{
GetMaxThreadsNative(out workerThreads, out completionPortThreads);
}
public static bool SetMinThreads(int workerThreads, int completionPortThreads)
{
return SetMinThreadsNative(workerThreads, completionPortThreads);
}
public static void GetMinThreads(out int workerThreads, out int completionPortThreads)
{
GetMinThreadsNative(out workerThreads, out completionPortThreads);
}
public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads)
{
GetAvailableThreadsNative(out workerThreads, out completionPortThreads);
}
[CLSCompliant(false)]
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, true);
}
[CLSCompliant(false)]
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, false);
}
private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce, // NOTE: we do not allow other options that allow the callback to be queued as an APC
bool compressStack
)
{
RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle();
if (callBack != null)
{
_ThreadPoolWaitOrTimerCallback callBackHelper = new _ThreadPoolWaitOrTimerCallback(callBack, state, compressStack);
state = (object)callBackHelper;
// call SetWaitObject before native call so that waitObject won't be closed before threadpoolmgr registration
// this could occur if callback were to fire before SetWaitObject does its addref
registeredWaitHandle.SetWaitObject(waitObject);
IntPtr nativeRegisteredWaitHandle = RegisterWaitForSingleObjectNative(waitObject,
state,
millisecondsTimeOutInterval,
executeOnlyOnce,
registeredWaitHandle);
registeredWaitHandle.SetHandle(nativeRegisteredWaitHandle);
}
else
{
throw new ArgumentNullException(nameof(WaitOrTimerCallback));
}
return registeredWaitHandle;
}
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
TimeSpan timeout,
bool executeOnlyOnce
)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (tm > (long)int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
TimeSpan timeout,
bool executeOnlyOnce
)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (tm > (long)int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, false);
}
public static bool QueueUserWorkItem(WaitCallback callBack) =>
QueueUserWorkItem(callBack, null);
public static bool QueueUserWorkItem(WaitCallback callBack, object state)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
EnsureVMInitialized();
ExecutionContext context = ExecutionContext.Capture();
IThreadPoolWorkItem tpcallBack = (context != null && context.IsDefault) ?
new QueueUserWorkItemCallbackDefaultContext(callBack, state) :
(IThreadPoolWorkItem)new QueueUserWorkItemCallback(callBack, state, context);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
public static bool QueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
EnsureVMInitialized();
ExecutionContext context = ExecutionContext.Capture();
IThreadPoolWorkItem tpcallBack = (context != null && context.IsDefault) ?
new QueueUserWorkItemCallbackDefaultContext<TState>(callBack, state) :
(IThreadPoolWorkItem)new QueueUserWorkItemCallback<TState>(callBack, state, context);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: !preferLocal);
return true;
}
public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object state)
{
if (callBack == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
}
EnsureVMInitialized();
IThreadPoolWorkItem tpcallBack = new QueueUserWorkItemCallback(callBack, state, null);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
{
Debug.Assert(null != workItem);
EnsureVMInitialized();
ThreadPoolGlobals.workQueue.Enqueue(workItem, forceGlobal);
}
// This method tries to take the target callback out of the current thread's queue.
internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem)
{
Debug.Assert(null != workItem);
return
ThreadPoolGlobals.vmTpInitialized && // if not initialized, so there's no way this workitem was ever queued.
ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
}
// Get all workitems. Called by TaskScheduler in its debugger hooks.
internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
{
// Enumerate global queue
foreach (IThreadPoolWorkItem workItem in ThreadPoolGlobals.workQueue.workItems)
{
yield return workItem;
}
// Enumerate each local queue
foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues)
{
if (wsq != null && wsq.m_array != null)
{
IThreadPoolWorkItem[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
IThreadPoolWorkItem item = items[i];
if (item != null)
{
yield return item;
}
}
}
}
}
internal static IEnumerable<IThreadPoolWorkItem> GetLocallyQueuedWorkItems()
{
ThreadPoolWorkQueue.WorkStealingQueue wsq = ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue;
if (wsq != null && wsq.m_array != null)
{
IThreadPoolWorkItem[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
IThreadPoolWorkItem item = items[i];
if (item != null)
yield return item;
}
}
}
internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems;
private static object[] ToObjectArray(IEnumerable<IThreadPoolWorkItem> workitems)
{
int i = 0;
foreach (IThreadPoolWorkItem item in workitems)
{
i++;
}
object[] result = new object[i];
i = 0;
foreach (IThreadPoolWorkItem item in workitems)
{
if (i < result.Length) //just in case someone calls us while the queues are in motion
result[i] = item;
i++;
}
return result;
}
// This is the method the debugger will actually call, if it ends up calling
// into ThreadPool directly. Tests can use this to simulate a debugger, as well.
internal static object[] GetQueuedWorkItemsForDebugger() =>
ToObjectArray(GetQueuedWorkItems());
internal static object[] GetGloballyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetGloballyQueuedWorkItems());
internal static object[] GetLocallyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetLocallyQueuedWorkItems());
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern bool RequestWorkerThread();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern unsafe bool PostQueuedCompletionStatus(NativeOverlapped* overlapped);
[CLSCompliant(false)]
public static unsafe bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped) =>
PostQueuedCompletionStatus(overlapped);
// The thread pool maintains a per-appdomain managed work queue.
// New thread pool entries are added in the managed queue.
// The VM is responsible for the actual growing/shrinking of
// threads.
private static void EnsureVMInitialized()
{
if (!ThreadPoolGlobals.vmTpInitialized)
{
EnsureVMInitializedCore(); // separate out to help with inlining
}
}
private static void EnsureVMInitializedCore()
{
ThreadPool.InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking);
ThreadPoolGlobals.vmTpInitialized = true;
}
// Native methods:
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SetMaxThreadsNative(int workerThreads, int completionPortThreads);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetMinThreadsNative(out int workerThreads, out int completionPortThreads);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetMaxThreadsNative(out int workerThreads, out int completionPortThreads);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetAvailableThreadsNative(out int workerThreads, out int completionPortThreads);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool NotifyWorkItemComplete();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ReportThreadStatus(bool isWorking);
internal static void NotifyWorkItemProgress()
{
if (!ThreadPoolGlobals.vmTpInitialized)
ThreadPool.InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking);
NotifyWorkItemProgressNative();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void NotifyWorkItemProgressNative();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void InitializeVMTp(ref bool enableWorkerTracking);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr RegisterWaitForSingleObjectNative(
WaitHandle waitHandle,
object state,
uint timeOutInterval,
bool executeOnlyOnce,
RegisteredWaitHandle registeredWaitHandle
);
[Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)]
public static bool BindHandle(IntPtr osHandle)
{
return BindIOCompletionCallbackNative(osHandle);
}
public static bool BindHandle(SafeHandle osHandle)
{
if (osHandle == null)
throw new ArgumentNullException(nameof(osHandle));
bool ret = false;
bool mustReleaseSafeHandle = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
osHandle.DangerousAddRef(ref mustReleaseSafeHandle);
ret = BindIOCompletionCallbackNative(osHandle.DangerousGetHandle());
}
finally
{
if (mustReleaseSafeHandle)
osHandle.DangerousRelease();
}
return ret;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool BindIOCompletionCallbackNative(IntPtr fileHandle);
}
}
| 41.473514
| 183
| 0.550505
|
[
"MIT"
] |
ghuntley/coreclr
|
src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs
| 64,205
|
C#
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace SuperRocket.AspNetCoreVue.Migrations
{
public partial class Upgraded_To_Abp_v222 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "AbpUserOrganizationUnits",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "AbpUserOrganizationUnits");
}
}
}
| 28.541667
| 71
| 0.60438
|
[
"MIT"
] |
dystudio/SuperRocket.AspNetCoreVue
|
aspnet-core/src/SuperRocket.AspNetCoreVue.EntityFrameworkCore/Migrations/20170804083601_Upgraded_To_Abp_v2.2.2.cs
| 687
|
C#
|
using Application.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMappers();
builder.Services.AddQueries();
builder.Services.AddCommands();
var app = builder.Build();
app.Run();
| 21.4
| 49
| 0.780374
|
[
"MIT"
] |
gabrielfernandes320/csharp-ecom-api
|
Application/Program.cs
| 214
|
C#
|
/*
* IRN API v1
*
* Allows users to extract, create, update and configure IRN data.
*
* The version of the OpenAPI document: 1
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.IRNConfiguration.Client.OpenAPIDateConverter;
namespace FactSet.SDK.IRNConfiguration.Model
{
/// <summary>
/// IdentifierSettingsDto
/// </summary>
[DataContract(Name = "IdentifierSettingsDto")]
public partial class IdentifierSettingsDto : IEquatable<IdentifierSettingsDto>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="IdentifierSettingsDto" /> class.
/// </summary>
/// <param name="allowEdit">allowEdit.</param>
public IdentifierSettingsDto(bool allowEdit = default(bool))
{
this.AllowEdit = allowEdit;
}
/// <summary>
/// Gets or Sets AllowEdit
/// </summary>
[DataMember(Name = "AllowEdit", EmitDefaultValue = true)]
public bool AllowEdit { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class IdentifierSettingsDto {\n");
sb.Append(" AllowEdit: ").Append(AllowEdit).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as IdentifierSettingsDto);
}
/// <summary>
/// Returns true if IdentifierSettingsDto instances are equal
/// </summary>
/// <param name="input">Instance of IdentifierSettingsDto to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(IdentifierSettingsDto input)
{
if (input == null)
{
return false;
}
return
(
this.AllowEdit == input.AllowEdit ||
this.AllowEdit.Equals(input.AllowEdit)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = (hashCode * 59) + this.AllowEdit.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 31.92
| 128
| 0.592982
|
[
"Apache-2.0"
] |
factset/enterprise-sdk
|
code/dotnet/IRNConfiguration/v1/src/FactSet.SDK.IRNConfiguration/Model/IdentifierSettingsDto.cs
| 3,990
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.IO;
namespace Cake.Common.Tools.GitReleaseNotes;
/// <summary>
/// <para>Contains functionality related to <see href="https://github.com/gittools/gitreleasenotes">GitReleaseNotes</see>.</para>
/// <para>
/// In order to use the commands for this alias, include the following in your build.cake file to download and
/// install from nuget.org, or specify the ToolPath within the <see cref="GitReleaseNotesSettings" /> class:
/// <code>
/// #tool "nuget:?package=GitReleaseNotes"
/// </code>
/// </para>
/// </summary>
[CakeAliasCategory("GitReleaseNotes")]
public static class GitReleaseNotesAliases
{
/// <summary>
/// Generates a set of release notes based on the commit history of the repository and specified settings.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="outputFile">The output file.</param>
/// <param name="settings">The settings.</param>
/// <example>
/// <code>
/// GitReleaseNotes("c:/temp/releasenotes.md", new GitReleaseNotesSettings {
/// WorkingDirectory = "c:/temp",
/// Verbose = true,
/// IssueTracker = IssueTracker.GitHub,
/// AllTags = true,
/// RepoUserName = "bob",
/// RepoPassword = "password",
/// RepoUrl = "http://myrepo.co.uk",
/// RepoBranch = "master",
/// IssueTrackerUrl = "http://myissuetracker.co.uk",
/// IssueTrackerUserName = "bob",
/// IssueTrackerPassword = "password",
/// IssueTrackerProjectId = "1234",
/// Categories = "Category1",
/// Version = "1.2.3.4",
/// AllLabels = true
/// });
/// </code>
/// </example>
[CakeMethodAlias]
[CakeAliasCategory("GitReleaseNotes")]
public static void GitReleaseNotes(this ICakeContext context, FilePath outputFile, GitReleaseNotesSettings settings)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var runner = new GitReleaseNotesRunner(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
runner.Run(outputFile, settings);
}
}
| 40.671875
| 129
| 0.604687
|
[
"MIT"
] |
ecampidoglio/cake
|
src/Cake.Common/Tools/GitReleaseNotes/GitReleaseNotesAliases.cs
| 2,605
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using KASLibrary;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraReports.UI;
namespace CAS.Proses
{
public partial class FrmPOpenSO : XtraForm
{
MySqlDataAdapter daPeriod ;
/*= DB.sql.SelectAdapter("select *,(select sum(qty) from spb,spbd where spb.spb=spbd.spb and spb.oms=openpo.oms and spbd.inv=openpo.inv " +
" and spbd.remark=openpo.remark and spb.`delete`=0) as terpenuhi from openpo order by `no`");
*/
public FrmPOpenSO()
{
InitializeComponent();
dtpTglAwal.DateTime = Utility.FirstDateInMonth(DB.loginDate);
dtpTglAkhir.DateTime = Utility.LastDateInMonth(DB.loginDate);
daPeriod = DB.sql.SelectAdapter("select openpo.*,(select sum(qty) from sjh,sjd where sjh.sjh=sjd.sjh and sjd.okl=openpo.oms and sjd.inv=openpo.inv " +
" and sjd.remark=openpo.remark and sjh.`delete`=0) as terpenuhi from openpo,okl where openpo.oms=okl.okl and date(okl.date) between " + dtpTglAwal.DateTime.ToString("yyyyMMdd") + " and " + dtpTglAkhir.DateTime.ToString("yyyyMMdd") + " order by `no`");
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GridControlEx));
casDataSet.openpo.Columns.Add("terpenuhi", typeof(String));
gcPeriod.ExToolStrip.Items["tsbtnShow"].Visible = false;
gcPeriod.ExToolStrip.Items["copyToolStripButton"].Visible = false;
gcPeriod.ExToolStrip.Items["helpToolStripButton"].Visible = false;
gcPeriod.ExToolStrip.Items["tsbtnDelete"].Enabled = DB.casUser.AllowDelete("56");
ToolStripButton tsbtnSave = new System.Windows.Forms.ToolStripButton("Save", ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image"))), (ExGridView_Save_Click), "tsbtnSave");
gcPeriod.ExToolStrip.Items.Add(tsbtnSave);
daPeriod.Fill(casDataSet.openpo);
gcPeriod.ExGridControl.DataSource = casDataSet.openpo;
// gcPeriod.ExGridView.Columns["inv"].ColumnEdit = new GridLookUpEx(DB.sql, "select inv as `Kode Barang`,name as `Nama Barang` from inv", "inv", "inv", gcxFpjUM.ExGridView, "Nama Barang", true, true, "Master Barang");
gcPeriod.ExToolStrip.Items["tsbtnNew"].Click += new EventHandler(ExGridView_New_Click);
gcPeriod.ExToolStrip.Items["tsbtnDelete"].Click += new EventHandler(ExGridView_Delete_Click);
gcPeriod.ExGridView.OptionsBehavior.Editable = true;
gcPeriod.ExGridView.Columns["oms"].ColumnEdit = new GridLookUpEx(DB.sql, "", "oms", "oms", gcPeriod.ExGridView, "", true, true, "Sales Order");
gcPeriod.ExGridView.Columns["oms"].ColumnEdit.Enter += new EventHandler(ExGridView_OmsColumnEdit_Enter);
gcPeriod.ExGridView.Columns["no"].Caption = "No";
gcPeriod.ExGridView.Columns["oms"].Caption = "Nomor PO";
gcPeriod.ExGridView.Columns["inv"].Caption = "Kode Barang";
gcPeriod.ExGridView.Columns["remark"].Caption = "Nama Barang";
gcPeriod.ExGridView.Columns["tol"].Caption = "Toleransi %";
gcPeriod.ExGridView.Columns["qtypo"].Caption = "Qty PO";
gcPeriod.ExGridView.Columns["terpenuhi"].Caption = "Terpenuhi";
gcPeriod.ExGridView.Columns["rate"].Caption = "Rencana Terima";
gcPeriod.ExGridView.Columns["crate"].Caption = "Count Terima";
gcPeriod.ExGridView.Columns["qtypo"].ColumnEdit = new GridNumEx();
gcPeriod.ExGridView.Columns["tol"].ColumnEdit = new GridNumEx(false,true,0,100,1,false);
gcPeriod.ExGridView.Columns["rate"].ColumnEdit = new GridNumEx();
DB.SetNumberFormat(gcPeriod.ExGridView, "n2");
gcPeriod.ExGridView.BestFitColumns();
// gcxFpjUM.ExGridView.Columns["price"].Caption = "Price";
gcPeriod.ExGridView.Columns["no"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["chtime"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["chusr"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["crate"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["inv"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["remark"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["oms"].VisibleIndex = 1;
gcPeriod.ExGridView.Columns["terpenuhi"].VisibleIndex = 6;
gcPeriod.ExGridView.Columns["unit"].VisibleIndex = 7;
gcPeriod.ExGridView.Columns["close"].VisibleIndex = 13;
gcPeriod.ExGridView.Columns["unit"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["qtypo"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["terpenuhi"].OptionsColumn.AllowEdit = false;
gcPeriod.ExGridView.Columns["no"].Visible = false;
}
void ExGridView_OmsColumnEdit_Enter(object sender, EventArgs e)
{
GridLookUpEx omsLookUp = (GridLookUpEx)gcPeriod.ExGridView.Columns["oms"].ColumnEdit;
omsLookUp.Query = "select okl.okl as`Nomor PO`,okd.inv as `Kode Barang`,okd.remark as `Nama Barang`,okd.qty as `Qty PO`,okd.toleransi as `Toleransi %`,if(okl.`close`=1,1,0) as close, "+
"(select sum(qty) from sjh,sjd where sjh.sjh=sjd.sjh and sjd.okl=okd.okl and sjd.inv=okd.inv and sjd.remark=okd.remark and sjh.`delete`=0) as Terpenuhi, inv.unit as `unit` " +
" from okd left outer join okl on okd.okl=okl.okl left outer join inv on okd.inv=inv.inv where date(okl.date) between " + dtpTglAwal.DateTime.ToString("yyyyMMdd") + " and " + dtpTglAkhir.DateTime.ToString("yyyyMMdd") +
" and concat(trim(okd.okl),trim(okd.inv),trim(okd.remark)) not in (select concat(trim(openpo.oms),trim(openpo.inv),trim(openpo.remark)) from openpo) ";
omsLookUp.TableName = "oms";
}
private void FrmPOpenSO_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'casDataSet._close' table. You can move, or remove it, as needed.
//this._closeTableAdapter.Fill(this.casDataSet._close);
}
void ExGridView_Save_Click(object sender, EventArgs e)
{
try
{
this.ValidateChildren();
for (int i = casDataSet.openpo.Rows.Count - 1; i >= 0; i--)
{
DataRow row = casDataSet.openpo.Rows[i];
if (row != null && (row.RowState == DataRowState.Added || row.RowState == DataRowState.Modified))
{
string toleransi = row["tol"].ToString();
string inv = row["inv"].ToString();
string remark = row["remark"].ToString().Replace("'", "''");
string oms = row["oms"].ToString();
string chusr = row["chusr"].ToString();
string chtime = row["chtime"].ToString();
string open = row["close"].ToString();
DB.sql.Execute("update okd set toleransi=" + toleransi + " where okd.okl = '" + oms + "' and okd.inv= '" + inv + "' and okd.remark= '" + remark + "'");
DB.sql.Execute("update okl set okl.`close`="+ open +",chusr='" + chusr + "', chtime='" + chtime + "' where okl.okl = '" + oms + "'");
}
}
daPeriod.Update(casDataSet.openpo);
MessageBox.Show("Data telah berhasil di simpan!");
casDataSet.openpo.Clear();
daPeriod = DB.sql.SelectAdapter("select openpo.*,(select sum(qty) from sjh,sjd where sjh.sjh=sjd.sjh and sjd.okl=openpo.oms and sjd.inv=openpo.inv " +
" and sjd.remark=openpo.remark and sjh.`delete`=0) as terpenuhi from openpo,okl where openpo.oms=okl.okl and date(okl.date) between " + dtpTglAwal.DateTime.ToString("yyyyMMdd") + " and " + dtpTglAkhir.DateTime.ToString("yyyyMMdd") + " order by `no`");
daPeriod.Fill(casDataSet.openpo);
gcPeriod.ExGridControl.DataSource = casDataSet.openpo;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void ExGridView_Delete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete this item?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1) == DialogResult.Yes)
{
DB.DeleteDetailRows(gcPeriod.ExGridView);
// daPeriod.Update(casDataSet._close);
}
}
void ExGridView_New_Click(object sender, EventArgs e)
{
int maxno;
if (casDataSet.openpo.Rows.Count != 0)
maxno = (int) casDataSet.openpo.Compute("MAX(no)", "no>0") + 1;
else
maxno= 1 ;
DataRow row = casDataSet.openpo.NewRow();
row["no"]= maxno;
row["oms"] = "";
row["remark"] = "";
row["chusr"] = DB.casUser.User;
row["chtime"] = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
row["inv"] = "";
row["tol"] = 0;
row["close"] = 0;
row["rate"] = 0;
row["crate"] = 0;
casDataSet.openpo.Rows.Add(row);
// DB.InsertDetailRows(gcPeriod.ExGridView, row);
}
private void FrmPOpenSO_FormClosing(object sender, FormClosingEventArgs e)
{
// daPeriod.Update(casDataSet.openpo);
}
private void button1_Click(object sender, EventArgs e)
{
casDataSet.openpo.Clear();
daPeriod = DB.sql.SelectAdapter("select openpo.*,(select sum(qty) from sjh,sjd where sjh.sjh=sjd.sjh and sjd.okl=openpo.oms and sjd.inv=openpo.inv " +
" and sjd.remark=openpo.remark and sjh.`delete`=0) as terpenuhi from openpo,okl where openpo.oms=okl.okl and date(okl.date) between " + dtpTglAwal.DateTime.ToString("yyyyMMdd") + " and " + dtpTglAkhir.DateTime.ToString("yyyyMMdd") + " order by `no`");
daPeriod.Fill(casDataSet.openpo);
gcPeriod.ExGridControl.DataSource = casDataSet.openpo;
}
}
}
| 56.176768
| 291
| 0.603524
|
[
"MIT"
] |
husniaditya/it-inventory
|
Proses/FrmPOpenSO.cs
| 11,123
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collect : MonoBehaviour
{
public AudioSource collectSound;
void OnTriggerEnter(Collider other)
{
collectSound.Play();
ScoringSystem.theScore += 50;
Destroy (gameObject);
}
}
| 20.466667
| 39
| 0.697068
|
[
"CC0-1.0"
] |
HSMCode/hsm-wise2021-prototype103-party-merve-simsek
|
Assets/Scripts/Collect.cs
| 307
|
C#
|
using System;
using System.Windows;
using System.Windows.Input;
namespace Phony.Helpers.AttachedCommandBehavior
{
/// <summary>
/// Defines a Command Binding
/// This inherits from freezable so that it gets inheritance context for DataBinding to work
/// </summary>
public class BehaviorBinding : Freezable
{
CommandBehaviorBinding behavior;
/// <summary>
/// Stores the Command Behavior Binding
/// </summary>
internal CommandBehaviorBinding Behavior
{
get
{
if (behavior is null)
{
behavior = new CommandBehaviorBinding();
}
return behavior;
}
}
DependencyObject owner;
/// <summary>
/// Gets or sets the Owner of the binding
/// </summary>
public DependencyObject Owner
{
get { return owner; }
set
{
owner = value;
ResetEventBinding();
}
}
#region Command
/// <summary>
/// Command Dependency Property
/// </summary>
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(BehaviorBinding), new FrameworkPropertyMetadata((ICommand)null, new PropertyChangedCallback(OnCommandChanged)));
/// <summary>
/// Gets or sets the Command property.
/// </summary>
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
/// <summary>
/// Handles changes to the Command property.
/// </summary>
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((BehaviorBinding)d).OnCommandChanged(e);
}
/// <summary>
/// Provides derived classes an opportunity to handle changes to the Command property.
/// </summary>
protected virtual void OnCommandChanged(DependencyPropertyChangedEventArgs e)
{
Behavior.Command = Command;
}
#endregion
#region Action
/// <summary>
/// Action Dependency Property
/// </summary>
public static readonly DependencyProperty ActionProperty = DependencyProperty.Register("Action", typeof(Action<object>), typeof(BehaviorBinding), new FrameworkPropertyMetadata((Action<object>)null, new PropertyChangedCallback(OnActionChanged)));
/// <summary>
/// Gets or sets the Action property.
/// </summary>
public Action<object> Action
{
get { return (Action<object>)GetValue(ActionProperty); }
set { SetValue(ActionProperty, value); }
}
/// <summary>
/// Handles changes to the Action property.
/// </summary>
private static void OnActionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((BehaviorBinding)d).OnActionChanged(e);
}
/// <summary>
/// Provides derived classes an opportunity to handle changes to the Action property.
/// </summary>
protected virtual void OnActionChanged(DependencyPropertyChangedEventArgs e)
{
Behavior.Action = Action;
}
#endregion
#region CommandParameter
/// <summary>
/// CommandParameter Dependency Property
/// </summary>
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(BehaviorBinding), new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnCommandParameterChanged)));
/// <summary>
/// Gets or sets the CommandParameter property.
/// </summary>
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Handles changes to the CommandParameter property.
/// </summary>
private static void OnCommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((BehaviorBinding)d).OnCommandParameterChanged(e);
}
/// <summary>
/// Provides derived classes an opportunity to handle changes to the CommandParameter property.
/// </summary>
protected virtual void OnCommandParameterChanged(DependencyPropertyChangedEventArgs e)
{
Behavior.CommandParameter = CommandParameter;
}
#endregion
#region Event
/// <summary>
/// Event Dependency Property
/// </summary>
public static readonly DependencyProperty EventProperty = DependencyProperty.Register("Event", typeof(string), typeof(BehaviorBinding), new FrameworkPropertyMetadata((string)null, new PropertyChangedCallback(OnEventChanged)));
/// <summary>
/// Gets or sets the Event property.
/// </summary>
public string Event
{
get { return (string)GetValue(EventProperty); }
set { SetValue(EventProperty, value); }
}
/// <summary>
/// Handles changes to the Event property.
/// </summary>
private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((BehaviorBinding)d).OnEventChanged(e);
}
/// <summary>
/// Provides derived classes an opportunity to handle changes to the Event property.
/// </summary>
protected virtual void OnEventChanged(DependencyPropertyChangedEventArgs e)
{
ResetEventBinding();
}
#endregion
static void OwnerReset(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((BehaviorBinding)d).ResetEventBinding();
}
private void ResetEventBinding()
{
if (Owner is not null) //only do this when the Owner is set
{
//check if the Event is set. If yes we need to rebind the Command to the new event and unregister the old one
if (Behavior.Event is not null && Behavior.Owner is not null)
{
Behavior.Dispose();
}
//bind the new event to the command
Behavior.BindEvent(Owner, Event);
}
}
/// <summary>
/// This is not actually used. This is just a trick so that this object gets WPF Inheritance Context
/// </summary>
/// <returns></returns>
protected override Freezable CreateInstanceCore()
{
throw new NotImplementedException();
}
}
}
| 33.788462
| 267
| 0.593625
|
[
"MIT"
] |
ahmed-abdelrazek/Phony
|
src/Helpers/AttachedCommandBehavior/BehaviorBinding.cs
| 7,030
|
C#
|
using System;
using Formularizer.Core.FormulaDefinition;
using FunctionalExtensions;
namespace Formularizer.Core.FormulaCompiler
{
internal class SelfReferenceCompiledFormula : ICompiledFormula
{
private readonly string _reference;
private SelfReferenceCompiledFormula(string reference)
{
_reference = reference;
}
public string GetFormulaText()
{
return _reference;
}
public static Result<ICompiledFormula> Compile(SheetResolvingContext context, IFormulaPartDef definition)
{
var def = definition as SelfReferenceCommandDef;
Contract.Requires<ArgumentException>(def != null);
var compiledFormula = new SelfReferenceCompiledFormula(def.Reference);
context.AppendFormula(compiledFormula);
return Result.Ok((ICompiledFormula) compiledFormula);
}
}
}
| 25.709677
| 107
| 0.78921
|
[
"MIT"
] |
GrafGenerator/ssrs-formularize
|
src/Formularizer/Core/FormulaCompiler/SelfReferenceCompiledFormula.cs
| 799
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Twilio
{
public class Message : TwilioBase
{
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string Sid { get; set; }
/// <summary>
/// The date that this resource was created
/// </summary>
public DateTime DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated
/// </summary>
public DateTime DateUpdated { get; set; }
/// <summary>
/// The date that the Message was sent
/// </summary>
public DateTime DateSent { get; set; }
/// <summary>
/// The unique id of the Account that sent this Message.
/// </summary>
public string AccountSid { get; set; }
/// <summary>
/// The phone number that initiated the message in E.164 format. For
/// incoming messages, this will be the remote phone. For outgoing messages,
/// this will be one of your Twilio phone numbers.
/// </summary>
public string From { get; set; }
/// <summary>
/// The phone number that received the message in E.164 format. For
/// incoming messages, this will be one of your Twilio phone numbers.
/// For outgoing messages, this will be the remote phone.
/// </summary>
public string To { get; set; }
/// <summary>
/// The text body of the Message.
/// </summary>
public string Body { get; set; }
/// <summary>
/// The number of body segments associated with this message. In
/// a common case, an ASCII message of 180 characters will be split into
/// one segment with 160 characters and one with 20 characters, so
/// NumSegments would be 2 for that message.
/// </summary>
public int NumSegments { get; set; }
/// <summary>
/// The number of images associated with this MMS
/// </summary>
public int NumImages { get; set; }
/// <summary>
/// The status of this Message. Either queued, sending, sent, or failed.
/// </summary>
public string Status { get; set; }
/// <summary>
/// The direction of this Message. incoming for incoming messages,
/// outbound-api for messages initiated via the REST API, outbound-call
/// for messages initiated during a call or outbound-reply for messages
/// initiated in response to an incoming Message.
/// </summary>
public string Direction { get; set; }
/// <summary>
/// The amount billed for the Message.
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// The version of the Twilio API used to process the Message.
/// </summary>
public string ApiVersion { get; set; }
/// <summary>
/// The error code of this message. If the message was unable to be delivered
/// this property will contain the error code. Error codes are listed in
/// the Message docs: https://www.twilio.com/docs/api/rest/message.
/// </summary>
public int? ErrorCode { get; set; }
/// <summary>
/// The error message for this message. If the message was unable to be delivered
/// this property will contain the error message.
/// </summary>
public string ErrorMessage { get; set; }
}
}
| 38.021053
| 89
| 0.575858
|
[
"Apache-2.0"
] |
ArashMotamedi/Twilio.NetCore
|
src/Twilio.NetCore/Model/Message.cs
| 3,614
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace IRO.Common.EmbeddedResources
{
public static class EmbeddedResourcesHelpers
{
static IDictionary<Assembly, string[]> _manifestResourceNamesCache = new Dictionary<Assembly, string[]>();
/// <summary>
/// </summary>
/// <param name="assembly">Something like IRO.CmdLine</param>
/// <param name="resourceName">Something like "console_script.js"</param>
/// <returns></returns>
public static async Task<string> ReadEmbeddedResourceText(this Assembly assembly, string resourceName)
{
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
/// <summary>
/// </summary>
/// <param name="assembly">Something like IRO.CmdLine</param>
/// <param name="resourceName">Something like "console_script.js"</param>
/// <returns></returns>
public static bool IsEmbeddedResourceExists(this Assembly assembly, string resourceName)
{
return assembly.GetManifestResourceNamesWithCache().Contains(resourceName);
}
/// <summary>
/// </summary>
/// <param name="assembly">Something like IRO.CmdLine</param>
/// <param name="resourceName">Something like "console_script.js"</param>
/// <param name="extractPath"></param>
/// <returns></returns>
public static void ExtractEmbeddedResource(this Assembly assembly, string resourceName, string extractPath)
{
try
{
var dirPath=Path.GetDirectoryName(extractPath);
CreateDirectoryRecursively(dirPath);
var resNames = assembly.GetManifestResourceNamesWithCache();
if (!resNames.Contains(resourceName))
{
throw new Exception("Can't find resource.");
}
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var fileStream = File.Create(extractPath))
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
}
}
catch (Exception ex)
{
throw new Exception(nameof(EmbeddedResourcesHelpers) + " error.", ex);
}
}
/// <summary>
/// NOTE: last dot in resource name always recognized as dot before file extension.
/// </summary>
/// <param name="assembly">Something like IRO.CmdLine</param>
/// <param name="embeddedDirectoryPath">
/// Something like IRO.Common.MyFolder.MySubFolder, where last two - is folders with embedded resources.
/// Folders will be extracted too.
/// </param>
/// <param name="extractPath">Directory where it will be extracted.</param>
/// <param name="ignoreErrors">Extract files which can.</param>
/// <returns></returns>
public static void ExtractEmbeddedResourcesDirectory(this Assembly assembly, string embeddedDirectoryPath, string extractPath, bool ignoreErrors=false)
{
try
{
CreateDirectoryRecursively(extractPath);
var resNames = assembly.GetManifestResourceNamesWithCache();
foreach (var resourceName in resNames)
{
try
{
if (!resourceName.StartsWith(embeddedDirectoryPath))
{
continue;
}
//Remove embedded directory path part.
//embeddedDirectoryPath.Length + 1 to remove dot.
var extractFileRelativePath = resourceName.Substring(embeddedDirectoryPath.Length + 1);
//Replace dots.
extractFileRelativePath = extractFileRelativePath.Replace(".", "/");
//Last slash replaced with dot, because it is extension.
var dotIndex = extractFileRelativePath.LastIndexOf("/");
var sb = new StringBuilder(extractFileRelativePath);
sb[dotIndex] = '.';
extractFileRelativePath = sb.ToString();
var extractFilePath = Path.Combine(extractPath, extractFileRelativePath);
ExtractEmbeddedResource(assembly, resourceName, extractFilePath);
}
catch
{
if (!ignoreErrors)
throw;
}
}
}
catch (Exception ex)
{
throw new Exception(nameof(EmbeddedResourcesHelpers) + " error.", ex);
}
}
public static string[] GetManifestResourceNamesWithCache(this Assembly assembly)
{
if (!_manifestResourceNamesCache.ContainsKey(assembly))
{
_manifestResourceNamesCache[assembly] = assembly.GetManifestResourceNames();
}
return _manifestResourceNamesCache[assembly];
}
static void CreateDirectoryRecursively(string path)
{
if (Directory.Exists(path))
return;
var parentDirectory = Path.GetDirectoryName(path);
if (!Directory.Exists(parentDirectory))
CreateDirectoryRecursively(parentDirectory);
Directory.CreateDirectory(path);
}
}
}
| 40.710345
| 159
| 0.561071
|
[
"MIT"
] |
IT-rolling-out/IRO
|
src/Common/IRO.Common/EmbeddedResources/EmbeddedResourcesHelpers.cs
| 5,905
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrintLongSequence
{
class Program
{
static void Main(string[] args)
{
int b;
for (int i = 2; i < 1002; i++)
{
b = i;
if (b % 2 == 1)
{
b *= -1;
}
if (b == -1001)//after the last member of the array there is no comma
{
Console.Write(+b);
}
else
Console.Write(+b + ", ");
}
Console.ReadKey();
}
}
}
| 20.911765
| 85
| 0.389592
|
[
"MIT"
] |
aleksandra992/CSharp
|
CSharp Part 1/Intro-Programming-Homework/PrintLongSequence/Program.cs
| 713
|
C#
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using DynamicData;
using DynamicData.Binding;
using NBitcoin;
using ReactiveUI;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels.AddWallet.Create
{
public partial class ConfirmRecoveryWordsViewModel : RoutableViewModel
{
private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords;
[AutoNotify] private bool _isSkipEnable;
public ConfirmRecoveryWordsViewModel(List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager)
{
Title = "Confirm recovery words";
var confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>();
_isSkipEnable = walletManager.Network != Network.Main || System.Diagnostics.Debugger.IsAttached;
var nextCommandCanExecute =
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.WhenValueChanged(x => x.IsConfirmed)
.Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed));
NextCommand = ReactiveCommand.Create(
() => Navigate().To(new AddedWalletPageViewModel(walletManager, keyManager)),
nextCommandCanExecute);
if (_isSkipEnable)
{
SkipCommand = ReactiveCommand.Create(() => NextCommand.Execute(null));
}
CancelCommand = ReactiveCommand.Create(() => Navigate().Clear());
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.OnItemAdded(x => x.Reset())
.Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index))
.Bind(out _confirmationWords)
.Subscribe();
// Select 4 random words to confirm.
confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(_ => new Random().NextDouble()).Take(4));
}
public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords;
}
}
| 33.866667
| 133
| 0.776575
|
[
"MIT"
] |
planquer/WalletWasabi
|
WalletWasabi.Fluent/ViewModels/AddWallet/Create/ConfirmRecoveryWordsViewModel.cs
| 2,032
|
C#
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using GitRewrite.CleanupTask;
using GitRewrite.CleanupTask.Delete;
using GitRewrite.GitObjects;
using GitRewrite.IO;
using Commit = GitRewrite.GitObjects.Commit;
using Tree = GitRewrite.GitObjects.Tree;
namespace GitRewrite
{
public static class Program
{
static void Main(string[] args)
{
if (!CommandLineOptions.TryParse(args, out var options))
{
return;
}
PackReader.InitializePackFiles(options.RepositoryPath);
if (options.FixTrees)
{
var defectiveCommits = FindCommitsWithDuplicateTreeEntries(options.RepositoryPath).ToList();
var rewrittenCommits = FixDefectiveCommits(options.RepositoryPath, defectiveCommits);
if (rewrittenCommits.Any())
Refs.Update(options.RepositoryPath, rewrittenCommits);
}
else if (options.FilesToDelete.Any() || options.FoldersToDelete.Any())
{
using (var task = new DeletionTask(options.RepositoryPath, options.FilesToDelete, options.FoldersToDelete, options.ProtectRefs))
task.Run();
}
else if (options.RemoveEmptyCommits)
{
using (var removeEmptyCommitsTask = new RemoveEmptyCommitsTask(options.RepositoryPath))
removeEmptyCommitsTask.Run();
}
else if (!string.IsNullOrWhiteSpace(options.ContributorMappingFile))
{
using (var rewriteContributorTask = new RewriteContributorTask(options.RepositoryPath, options.ContributorMappingFile))
rewriteContributorTask.Run();
}
else if (options.ListContributorNames)
{
foreach (var contributor in CommitWalker.CommitsRandomOrder(options.RepositoryPath)
.SelectMany(commit => new[] {commit.GetAuthorName(), commit.GetCommitterName()})
.Distinct()
.AsParallel()
.OrderBy(x => x))
Console.WriteLine(contributor);
}
}
public static ObjectHash WriteFixedTree(string vcsPath, Tree tree)
{
var resultingTreeLines = new List<Tree.TreeLine>();
bool fixRequired = false;
foreach (var treeLine in tree.Lines)
{
if (!treeLine.IsDirectory())
{
resultingTreeLines.Add(treeLine);
continue;
}
var childTree = GitObjectFactory.ReadTree(vcsPath, treeLine.Hash);
var fixedTreeHash = WriteFixedTree(vcsPath, childTree);
resultingTreeLines.Add(new Tree.TreeLine(treeLine.TextBytes, fixedTreeHash));
if (fixedTreeHash != childTree.Hash)
fixRequired = true;
}
if (fixRequired || Tree.HasDuplicateLines(resultingTreeLines))
{
tree = Tree.GetFixedTree(resultingTreeLines);
HashContent.WriteObject(vcsPath, tree);
}
return tree.Hash;
}
private static bool HasDefectiveTree(string vcsPath, Commit commit)
{
if (SeenTrees.TryGetValue(commit.TreeHash, out bool isDefective))
return isDefective;
var tree = GitObjectFactory.ReadTree(vcsPath, commit.TreeHash);
return IsDefectiveTree(vcsPath, tree);
}
private static readonly ConcurrentDictionary<ObjectHash, bool> SeenTrees = new ConcurrentDictionary<ObjectHash, bool>();
public static bool IsDefectiveTree(string vcsPath, Tree tree)
{
if (SeenTrees.TryGetValue(tree.Hash, out bool isDefective))
return isDefective;
if (Tree.HasDuplicateLines(tree.Lines))
{
SeenTrees.TryAdd(tree.Hash, true);
return true;
}
var childTrees = tree.GetDirectories();
foreach (var childTree in childTrees)
{
if (SeenTrees.TryGetValue(childTree.Hash, out isDefective))
{
if (isDefective)
return true;
continue;
}
var childTreeObject = (Tree) GitObjectFactory.ReadGitObject(vcsPath, childTree.Hash);
if (IsDefectiveTree(vcsPath, childTreeObject))
{
return true;
}
}
SeenTrees.TryAdd(tree.Hash, false);
return false;
}
private static IEnumerable<ObjectHash> CorrectParents(IEnumerable<ObjectHash> oldParents, Dictionary<ObjectHash, ObjectHash> rewrittenCommitHashes)
{
foreach (var oldParentHash in oldParents)
{
if (rewrittenCommitHashes.TryGetValue(oldParentHash, out var newParentHash))
yield return newParentHash;
else
yield return oldParentHash;
}
}
static IEnumerable<ObjectHash> FindCommitsWithDuplicateTreeEntries(string vcsPath)
{
foreach (var commit in CommitWalker
.CommitsRandomOrder(vcsPath)
.AsParallel()
.AsUnordered()
.Select(commit => (commit.Hash, Defective: HasDefectiveTree(vcsPath, commit))))
{
if (commit.Defective)
yield return commit.Hash;
}
}
static Dictionary<ObjectHash, ObjectHash> FixDefectiveCommits(string vcsPath, List<ObjectHash> defectiveCommits)
{
var rewrittenCommitHashes = new Dictionary<ObjectHash, ObjectHash>();
foreach (var commit in CommitWalker.CommitsInOrder(vcsPath))
{
if (rewrittenCommitHashes.ContainsKey(commit.Hash))
continue;
// Rewrite this commit
byte[] newCommitBytes;
if (defectiveCommits.Contains(commit.Hash))
{
var fixedTreeHash = WriteFixedTree(vcsPath, GitObjectFactory.ReadTree(vcsPath, commit.TreeHash));
newCommitBytes = Commit.GetSerializedCommitWithChangedTreeAndParents(commit, fixedTreeHash,
CorrectParents(commit.Parents, rewrittenCommitHashes).ToList());
}
else
{
newCommitBytes = Commit.GetSerializedCommitWithChangedTreeAndParents(commit, commit.TreeHash,
CorrectParents(commit.Parents, rewrittenCommitHashes).ToList());
}
var fileObjectBytes = GitObjectFactory.GetBytesWithHeader(GitObjectType.Commit, newCommitBytes);
var newCommitHash = new ObjectHash(Hash.Create(fileObjectBytes));
if (newCommitHash != commit.Hash && !rewrittenCommitHashes.ContainsKey(commit.Hash))
{
HashContent.WriteFile(vcsPath, fileObjectBytes, newCommitHash.ToString());
rewrittenCommitHashes.Add(commit.Hash, newCommitHash);
}
}
return rewrittenCommitHashes;
}
}
}
| 38.678756
| 155
| 0.575218
|
[
"MIT"
] |
TimHeinrich/GitRewrite
|
GitRewrite/Program.cs
| 7,467
|
C#
|
using System;
using System.Threading.Tasks;
using Nest;
namespace Profiling.Async
{
public class ClusterRerouteAsync : IAsyncProfiledOperation
{
public Task RunAsync(IElasticClient client, ColoredConsoleWriter output)
{
throw new NotImplementedException();
}
}
}
| 19.642857
| 74
| 0.785455
|
[
"Apache-2.0"
] |
RossLieberman/NEST
|
src/Profiling/Async/ClusterRerouteAsync.cs
| 275
|
C#
|
namespace Gu.Wpf.DataGrid2D.Demo
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
public class JaggedVm : INotifyPropertyChanged
{
private IReadOnlyList<string>? currentRowHeaders;
private IReadOnlyList<string>? currentColumnHeaders;
private string? data;
public JaggedVm()
{
this.RowHeaders = new[] { "1", "2", "3" };
this.currentRowHeaders = this.RowHeaders;
this.ColumnHeaders = new[] { "A", "B", "C" };
this.currentColumnHeaders = this.ColumnHeaders;
this.SameLengths = new int[3][];
this.SameLengths[0] = new[] { 1, 2 };
this.SameLengths[1] = new[] { 3, 4 };
this.SameLengths[2] = new[] { 5, 6 };
this.DifferentLengths = new int[3][];
this.DifferentLengths[0] = new[] { 1 };
this.DifferentLengths[1] = new[] { 2, 3 };
this.DifferentLengths[2] = new[] { 4, 5, 6 };
this.UpdateDataCommand = new RelayCommand(this.UpdateData);
this.UseRowHeadersCommand = new RelayCommand(() => this.CurrentRowHeaders = this.RowHeaders);
this.NullRowHeadersCommand = new RelayCommand(() => this.CurrentRowHeaders = null);
this.UseColumnHeadersCommand = new RelayCommand(() => this.CurrentColumnHeaders = this.ColumnHeaders);
this.NullColumnHeadersCommand = new RelayCommand(() => this.CurrentColumnHeaders = null);
this.UpdateData();
}
public event PropertyChangedEventHandler? PropertyChanged;
public IReadOnlyList<string> RowHeaders { get; }
public IReadOnlyList<string> ColumnHeaders { get; }
public int[][] SameLengths { get; }
public int[][] DifferentLengths { get; }
public ICommand UpdateDataCommand { get; }
public ICommand UseRowHeadersCommand { get; }
public ICommand NullRowHeadersCommand { get; }
public ICommand UseColumnHeadersCommand { get; }
public ICommand NullColumnHeadersCommand { get; }
public IReadOnlyList<string>? CurrentRowHeaders
{
get => this.currentRowHeaders;
private set
{
if (ReferenceEquals(value, this.currentRowHeaders))
{
return;
}
this.currentRowHeaders = value;
this.OnPropertyChanged();
}
}
public IReadOnlyList<string>? CurrentColumnHeaders
{
get => this.currentColumnHeaders;
private set
{
if (ReferenceEquals(value, this.currentColumnHeaders))
{
return;
}
this.currentColumnHeaders = value;
this.OnPropertyChanged();
}
}
public string? Data
{
get => this.data;
private set
{
if (value == this.data)
{
return;
}
this.data = value;
this.OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void UpdateData()
{
this.Data = $"{{{string.Join(", ", this.SameLengths.Select(x => $"{{{string.Join(", ", x)}}}"))}}}";
}
}
}
| 31.75
| 114
| 0.547651
|
[
"MIT"
] |
GuOrg/Gu.Wpf.DataGrid2D
|
Gu.Wpf.DataGrid2D.Demo/JaggedVm.cs
| 3,683
|
C#
|
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using Hotcakes.Commerce.Shipping;
using Hotcakes.Commerce.Utilities;
using Hotcakes.Modules.Core.Admin.AppCode;
using Hotcakes.Shipping;
using Hotcakes.Shipping.USPostal;
using Hotcakes.Shipping.USPostal.v4;
namespace Hotcakes.Modules.Core.Modules.Shipping.US_Postal_Service___Domestic
{
partial class Edit : HccShippingPart
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
LocalizeView();
AddHighlightColors(lstHighlights);
LoadZones();
LoadServiceCodes();
LoadData();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
NotifyFinishedEditing("Canceled");
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SaveData();
NotifyFinishedEditing(NameField.Text.Trim());
}
}
private void LoadZones()
{
lstZones.DataSource = HccApp.OrderServices.ShippingZones.FindForStore(HccApp.CurrentStore.Id);
lstZones.DataTextField = "Name";
lstZones.DataValueField = "id";
lstZones.DataBind();
}
private void LoadServiceCodes()
{
var uspostal = AvailableServices.FindById(ShippingMethod.ShippingProviderId, HccApp.CurrentStore);
ShippingTypesCheckBoxList.DataSource = uspostal.ListAllServiceCodes();
ShippingTypesCheckBoxList.DataTextField = "DisplayName";
ShippingTypesCheckBoxList.DataValueField = "Code";
ShippingTypesCheckBoxList.DataBind();
}
private void LoadData()
{
NameField.Text = ShippingMethod.Name;
if (NameField.Text == string.Empty)
{
NameField.Text = Localization.GetString("USPostalService");
}
// Adjustment
AdjustmentDropDownList.SelectedValue = ((int) ShippingMethod.AdjustmentType).ToString();
if (ShippingMethod.AdjustmentType == ShippingMethodAdjustmentType.Amount)
{
AdjustmentTextBox.Text = string.Format("{0:c}", ShippingMethod.Adjustment);
}
else
{
AdjustmentTextBox.Text = string.Format("{0:f}", ShippingMethod.Adjustment);
}
// Zones
if (lstZones.Items.FindByValue(ShippingMethod.ZoneId.ToString()) != null)
{
lstZones.ClearSelection();
lstZones.Items.FindByValue(ShippingMethod.ZoneId.ToString()).Selected = true;
}
// Global
txtUserId.Text = HccApp.CurrentStore.Settings.ShippingUSPostalUserId;
chbDiagnostics.Checked = HccApp.CurrentStore.Settings.ShippingUSPostalDiagnostics;
var settings = new USPostalServiceSettings();
settings.Merge(ShippingMethod.Settings);
foreach (ServiceCode code in settings.ServiceCodeFilter)
{
foreach (ListItem item in ShippingTypesCheckBoxList.Items)
{
if (string.Compare(item.Value, code.Code, true) == 0)
{
item.Selected = true;
break;
}
}
}
var matchPackage = ((int) settings.PackageType).ToString();
if (lstPackageType.Items.FindByValue(matchPackage) != null)
{
lstPackageType.ClearSelection();
lstPackageType.Items.FindByValue(matchPackage).Selected = true;
}
// Select Hightlights
var highlight = settings.GetSettingOrEmpty("highlight");
if (lstHighlights.Items.FindByText(highlight) != null)
{
lstHighlights.ClearSelection();
lstHighlights.Items.FindByText(highlight).Selected = true;
}
}
private void SaveData()
{
ShippingMethod.Name = NameField.Text.Trim();
ShippingMethod.ZoneId = long.Parse(lstZones.SelectedItem.Value);
ShippingMethod.AdjustmentType =
(ShippingMethodAdjustmentType) int.Parse(AdjustmentDropDownList.SelectedValue);
ShippingMethod.Adjustment = decimal.Parse(AdjustmentTextBox.Text, NumberStyles.Currency);
if (ShippingMethod.AdjustmentType == ShippingMethodAdjustmentType.Amount)
{
ShippingMethod.Adjustment = Money.RoundCurrency(ShippingMethod.Adjustment);
}
// Global Settings
HccApp.CurrentStore.Settings.ShippingUSPostalUserId = txtUserId.Text.Trim();
HccApp.CurrentStore.Settings.ShippingUSPostalDiagnostics = chbDiagnostics.Checked;
HccApp.UpdateCurrentStore();
// Method Settings
var Settings = new USPostalServiceSettings();
Settings.Merge(ShippingMethod.Settings);
// Service Code
var filter = new List<IServiceCode>();
foreach (ListItem item in ShippingTypesCheckBoxList.Items)
{
if (item.Selected)
{
var code = new ServiceCode {Code = item.Value, DisplayName = item.Text};
filter.Add(code);
}
}
Settings.ServiceCodeFilter = filter;
Settings["highlight"] = lstHighlights.SelectedValue;
// Package
var packageCode = lstPackageType.SelectedItem.Value;
var packageCodeInt = -1;
if (int.TryParse(packageCode, out packageCodeInt))
{
Settings.PackageType = (DomesticPackageType) packageCodeInt;
}
ShippingMethod.Settings.Merge(Settings);
}
protected void cvAdjustmentTextBox_ServerValidate(object source, ServerValidateEventArgs args)
{
var val = 0m;
if (decimal.TryParse(AdjustmentTextBox.Text, NumberStyles.Currency, CultureInfo.CurrentCulture, out val))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
private void LocalizeView()
{
rfvAdjustmentTextBox.ErrorMessage = Localization.GetString("rfvAdjustmentTextBox.ErrorMessage");
cvAdjustmentTextBox.ErrorMessage = Localization.GetString("cvAdjustmentTextBox.ErrorMessage");
if (AdjustmentDropDownList.Items.Count == 0)
{
AdjustmentDropDownList.Items.Add(new ListItem(Localization.GetString("Amount"), "1"));
AdjustmentDropDownList.Items.Add(new ListItem(Localization.GetString("Percentage"), "2"));
AdjustmentDropDownList.Items[0].Selected = true;
}
if (lstPackageType.Items.Count == 0)
{
var separator = new ListItem
{
Text = "-------------------",
Value = "-1"
};
separator.Attributes.Add("disabled", "disabled");
lstPackageType.Items.Add(new ListItem(Localization.GetString("AutoSelectedPackaging"), "-1"));
lstPackageType.Items.Add(separator);
lstPackageType.Items.Add(new ListItem(Localization.GetString("FirstClassLetter"), "100"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FirstClassLargeEnvelope"), "101"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FirstClassParcel"), "102"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FirstClassPostCard"), "103"));
lstPackageType.Items.Add(separator);
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateBox"), "1"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateBoxSmall"), "2"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateBoxMedium"), "3"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateBoxLarge"), "4"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateEnvelope"), "5"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateEnvelopePadded"), "50"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateEnvelopeLegal"), "51"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateEnvelopeSmall"), "52"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateEnvelopeWindow"), "53"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("FlatRateEnvelopeGiftCard"), "53"));
lstPackageType.Items.Add(separator);
lstPackageType.Items.Add(new ListItem(Localization.GetString("Variable"), "0"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("Rectangular"), "6"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("NonRectangular"), "7"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("RegionalBoxRateA"), "200"));
lstPackageType.Items.Add(new ListItem(Localization.GetString("RegionalBoxRateB"), "201"));
}
}
}
}
| 42.115385
| 117
| 0.614247
|
[
"MIT"
] |
HotcakesCommerce/core
|
Website/DesktopModules/Hotcakes/Core/Admin/Parts/Shipping/US Postal Service - Domestic/Edit.ascx.cs
| 10,950
|
C#
|
using Newtonsoft.Json;
namespace CaptchaSharp.Services.AntiCaptcha.Responses
{
internal class Response
{
public int ErrorId { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
[JsonIgnore]
public bool IsError => ErrorId > 0;
}
}
| 21.933333
| 53
| 0.629179
|
[
"MIT"
] |
542980940984363224858439616269115634540/CaptchaSharp
|
CaptchaSharp/Services/AntiCaptcha/Responses/Response.cs
| 331
|
C#
|
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using System;
namespace Lucene.Net.Analysis.Miscellaneous
{
/*
* 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.
*/
/// <summary>
/// Removes words that are too long or too short from the stream.
/// <para>
/// Note: Length is calculated as the number of UTF-16 code units.
/// </para>
/// </summary>
public sealed class LengthFilter : FilteringTokenFilter
{
private readonly int min;
private readonly int max;
private readonly ICharTermAttribute termAtt;
[Obsolete("enablePositionIncrements=false is not supported anymore as of Lucene 4.4.")]
public LengthFilter(LuceneVersion version, bool enablePositionIncrements, TokenStream @in, int min, int max)
: base(version, enablePositionIncrements, @in)
{
if (min < 0)
{
throw new ArgumentOutOfRangeException(nameof(min), "minimum length must be greater than or equal to zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (min > max)
{
throw new ArgumentOutOfRangeException(nameof(max), "maximum length must not be greater than minimum length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.min = min;
this.max = max;
this.termAtt = AddAttribute<ICharTermAttribute>();
}
/// <summary>
/// Create a new <see cref="LengthFilter"/>. This will filter out tokens whose
/// <see cref="CharTermAttribute"/> is either too short (<see cref="ICharTermAttribute.Length"/>
/// < min) or too long (<see cref="ICharTermAttribute.Length"/> > max). </summary>
/// <param name="version"> the Lucene match version </param>
/// <param name="in"> the <see cref="TokenStream"/> to consume </param>
/// <param name="min"> the minimum length </param>
/// <param name="max"> the maximum length </param>
public LengthFilter(LuceneVersion version, TokenStream @in, int min, int max)
: base(version, @in)
{
if (min < 0)
{
throw new ArgumentOutOfRangeException(nameof(min), "minimum length must be greater than or equal to zero"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if (min > max)
{
throw new ArgumentOutOfRangeException(nameof(max), "maximum length must not be greater than minimum length"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.min = min;
this.max = max;
this.termAtt = AddAttribute<ICharTermAttribute>();
}
protected override bool Accept()
{
int len = termAtt.Length;
return (len >= min && len <= max);
}
}
}
| 47.023256
| 236
| 0.639713
|
[
"Apache-2.0"
] |
10088/lucenenet
|
src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/LengthFilter.cs
| 4,046
|
C#
|
// Copyright (c) Allan Nielsen.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using OurPresence.Modeller.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OurPresence.Modeller.Generator.Outputs
{
public class OutputStrategy : IOutputStrategy
{
private readonly IEnumerable<IFileCreator> _creators;
public OutputStrategy(IEnumerable<IFileCreator> creators)
{
_creators = creators ?? throw new ArgumentNullException(nameof(creators));
}
public void Create(IOutput output, string? path = null, bool overwrite = false)
{
var creator = _creators.FirstOrDefault(c => c.SupportedType.IsInstanceOfType(output));
if (creator is null)
throw new InvalidOperationException($"No IFileCreator implementation registered for {output.GetType().Name}");
if (path != null)
{
var s = new System.IO.DirectoryInfo(path);
if (!s.Exists)
s.Create();
}
creator.Create(output, path, overwrite);
}
}
}
| 32.648649
| 126
| 0.635762
|
[
"MIT"
] |
Allann/OurPresence
|
OurPresence.Modeller.Core/OurPresence.Modeller.Core/Generator/Outputs/OutputStrategy.cs
| 1,210
|
C#
|
using PKISharp.WACS.Clients.IIS;
using PKISharp.WACS.Plugins.Base;
using PKISharp.WACS.Plugins.Base.Options;
namespace PKISharp.WACS.Plugins.InstallationPlugins
{
[Plugin("ea6a5be3-f8de-4d27-a6bd-750b619b2ee2")]
internal class IISWebOptions : InstallationPluginOptions<IISWeb>
{
public long? SiteId { get; set; }
public string? NewBindingIp { get; set; }
public int? NewBindingPort { get; set; }
public override string Name => "IIS";
public override string Description => "Create or update https bindings in IIS";
public IISWebOptions() { }
public IISWebOptions(IISWebArguments? args)
{
var sslIp = args?.SSLIPAddress;
if (!string.IsNullOrEmpty(sslIp) && sslIp != IISClient.DefaultBindingIp)
{
NewBindingIp = sslIp;
}
var sslPortRaw = args?.SSLPort;
if (!string.IsNullOrEmpty(sslPortRaw))
{
// Already validated by the ArgumentsProvider
var sslPort = int.Parse(sslPortRaw);
if (sslPort != IISClient.DefaultBindingPort)
{
NewBindingPort = sslPort;
}
}
}
}
}
| 33.184211
| 87
| 0.582871
|
[
"Apache-2.0"
] |
Legacy777/win-acme
|
src/main.lib/Plugins/InstallationPlugins/IISWeb/IISWebOptions.cs
| 1,263
|
C#
|
using System.Collections.Generic;
using Abp.Localization;
namespace CBEApp.Web.Models
{
public class LanguageSelectionViewModel
{
public LanguageInfo CurrentLanguage { get; set; }
public IReadOnlyList<LanguageInfo> Languages { get; set; }
public string CurrentUrl { get; set; }
}
}
| 22.928571
| 66
| 0.694704
|
[
"MIT"
] |
MikeGitIt/CBEApp
|
src/CBEApp.Web/Models/LanguageSelectionViewModel.cs
| 323
|
C#
|
using TMPro;
using UnityEngine;
using UnityEngine.Assertions;
namespace SS3D.Engine.Examine
{
public class ExamineUI : MonoBehaviour
{
// These should be the AbstractExamineUIElements, listed in the same order
// as the corresponding ExamineTypes.
public AbstractExamineUIElement[] UIElements;
public int framesPerRefresh = 10;
private AbstractExamineUIElement CurrentUI;
private int frames = 0;
// Update will periodically update the displayed UI (for example, moving the panel around
// the screen); however, it will NOT pass any additional ExamineData to the UI.
private void Update()
{
// Routine refresh of the UI.
if (CurrentUI)
{
frames++;
if (frames >= framesPerRefresh)
{
frames = 0;
CurrentUI.RefreshDisplay();
}
// Disable UI if user not holding down Examine button.
if (!Input.GetButton("Examine"))
{
ClearData();
}
}
}
public void Start()
{
foreach (AbstractExamineUIElement UI in UIElements)
{
UI.DisableElement();
}
}
public void LoadExamineData(IExamineData[] data)
{
// If there's no data, can't load anything.
if (data.Length == 0){return;}
// The highest Examinable listed in the target's Inspector will decide the UI to use.
ExamineType dataType = data[0].GetExamineType();
// If the UI is not set, set the appropriate one.
if (!CurrentUI)
{
CurrentUI = UIElements[(int)dataType];
}
// If the current UI isn't the appropriate one, change it.
if (CurrentUI.GetExamineType() != dataType)
{
CurrentUI.DisableElement();
CurrentUI = UIElements[(int)dataType];
CurrentUI.gameObject.SetActive(true);
}
// Load the new data to the UI.
CurrentUI.LoadExamineData(data);
CurrentUI.RefreshDisplay();
}
public void ClearData()
{
if (CurrentUI)
{
CurrentUI.DisableElement();
CurrentUI = null;
}
}
}
}
| 22.941176
| 91
| 0.66
|
[
"MIT"
] |
Jdeedler/SS3D
|
Assets/Engine/Examine/ExamineUI.cs
| 1,952
|
C#
|
//
// Copyright (c) Autodesk, Inc. All rights reserved
// Copyright (c) .NET Foundation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0.
// See LICENSE in the project root for license information.
//
// Forge Proxy
// by Eason Kang - Autodesk Developer Network (ADN)
//
#region Namespace
using System;
using System.Linq;
using System.Net.Http;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
#endregion
namespace Autodesk.Forge.Proxy
{
internal static class ProxyAdvancedExtentions
{
private static readonly string[] NotForwardedWebSocketHeaders = new[] { "Connection", "Host", "Upgrade", "Sec-WebSocket-Key", "Sec-WebSocket-Version" };
private const int DefaultWebSocketBufferSize = 4096;
private const int StreamCopyBufferSize = 81920;
public static Uri ToWebSocketScheme(this Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
var uriBuilder = new UriBuilder(uri);
if (string.Equals(uriBuilder.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
uriBuilder.Scheme = "wss";
}
else if (string.Equals(uriBuilder.Scheme, "http", StringComparison.OrdinalIgnoreCase))
{
uriBuilder.Scheme = "ws";
}
return uriBuilder.Uri;
}
public static HttpRequestMessage CreateProxyHttpRequest(this HttpContext context, Uri uri)
{
var request = context.Request;
var requestMessage = new HttpRequestMessage();
var requestMethod = request.Method;
if (!HttpMethods.IsGet(requestMethod) &&
!HttpMethods.IsHead(requestMethod) &&
!HttpMethods.IsDelete(requestMethod) &&
!HttpMethods.IsTrace(requestMethod))
{
var streamContent = new StreamContent(request.Body);
requestMessage.Content = streamContent;
}
// Copy the request headers
foreach (var header in request.Headers)
{
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
}
requestMessage.Headers.Host = uri.Authority;
requestMessage.RequestUri = uri;
requestMessage.Method = new HttpMethod(request.Method);
return requestMessage;
}
public static async Task<bool> AcceptProxyWebSocketRequest(this HttpContext context, Uri destinationUri)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (destinationUri == null)
{
throw new ArgumentNullException(nameof(destinationUri));
}
if (!context.WebSockets.IsWebSocketRequest)
{
throw new InvalidOperationException();
}
var proxyService = context.RequestServices.GetRequiredService<ProxyService>();
using (var client = new ClientWebSocket())
{
foreach (var headerEntry in context.Request.Headers)
{
if (!NotForwardedWebSocketHeaders.Contains(headerEntry.Key, StringComparer.OrdinalIgnoreCase))
{
client.Options.SetRequestHeader(headerEntry.Key, headerEntry.Value);
}
}
if (proxyService.Options.WebSocketKeepAliveInterval.HasValue)
{
client.Options.KeepAliveInterval = proxyService.Options.WebSocketKeepAliveInterval.Value;
}
try
{
await client.ConnectAsync(destinationUri, context.RequestAborted);
}
catch (WebSocketException)
{
context.Response.StatusCode = 400;
return false;
}
using (var server = await context.WebSockets.AcceptWebSocketAsync(client.SubProtocol))
{
var bufferSize = proxyService.Options.WebSocketBufferSize ?? DefaultWebSocketBufferSize;
await Task.WhenAll(PumpWebSocket(client, server, bufferSize, context.RequestAborted), PumpWebSocket(server, client, bufferSize, context.RequestAborted));
}
return true;
}
}
private static async Task PumpWebSocket(WebSocket source, WebSocket destination, int bufferSize, CancellationToken cancellationToken)
{
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
var buffer = new byte[bufferSize];
while (true)
{
WebSocketReceiveResult result;
try
{
result = await source.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
}
catch (OperationCanceledException)
{
await destination.CloseOutputAsync(WebSocketCloseStatus.EndpointUnavailable, null, cancellationToken);
return;
}
if (result.MessageType == WebSocketMessageType.Close)
{
await destination.CloseOutputAsync(source.CloseStatus.Value, source.CloseStatusDescription, cancellationToken);
return;
}
await destination.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, cancellationToken);
}
}
public static Task<HttpResponseMessage> SendProxyHttpRequest(this HttpContext context, HttpRequestMessage requestMessage)
{
if (requestMessage == null)
{
throw new ArgumentNullException(nameof(requestMessage));
}
var proxyService = context.RequestServices.GetRequiredService<ProxyService>();
return proxyService.Client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted);
}
public static Task<HttpResponseMessage> SendForgeProxyHttpRequest(this HttpContext context, HttpRequestMessage requestMessage)
{
if (requestMessage == null)
{
throw new ArgumentNullException(nameof(requestMessage));
}
var proxyService = context.RequestServices.GetRequiredService<ForgeProxyService>();
return proxyService.Client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted);
}
public static async Task CopyProxyHttpResponse(this HttpContext context, HttpResponseMessage responseMessage)
{
if (responseMessage == null)
{
throw new ArgumentNullException(nameof(responseMessage));
}
var response = context.Response;
response.StatusCode = (int)responseMessage.StatusCode;
foreach (var header in responseMessage.Headers)
{
response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var header in responseMessage.Content.Headers)
{
response.Headers[header.Key] = header.Value.ToArray();
}
// SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
response.Headers.Remove("transfer-encoding");
using (var responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
await responseStream.CopyToAsync(response.Body, StreamCopyBufferSize, context.RequestAborted);
}
}
}
}
| 38.317972
| 173
| 0.596392
|
[
"Apache-2.0"
] |
yiskang/forge-api-aspnetcore-proxy
|
src/Autodesk.Forge.Proxy/ProxyAdvancedExtensions.cs
| 8,315
|
C#
|
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace neSchedular.schedular
{
[JsonConverter(typeof(StringEnumConverter))]
public enum JobHandlerEnumModel { start, exec, run}
}
| 24.923077
| 56
| 0.768519
|
[
"MIT"
] |
shreedee/neDockerSchedular
|
schedularServer/components/schedular/JobHandlerEnumModel.cs
| 326
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.