content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Windows;
using System.Windows.Controls;
namespace HidWizards.UCR.Views.Controls.Plugin
{
class PluginViewTemplateSelector : DataTemplateSelector
{
public DataTemplate PluginTemplate { get; set; }
public Window Window { get; set; }
public PluginViewTemplateSelector()
{
Window = Application.Current.MainWindow;
}
//You override this function to select your data template based in the given item
public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
if (item == null) return PluginTemplate;
try
{
PluginTemplate = (DataTemplate)Window.FindResource(item.GetType().Name);
}
catch (ResourceReferenceKeyNotFoundException)
{
return null;
}
return PluginTemplate;
}
}
}
| 29.454545 | 107 | 0.598765 | [
"MIT"
] | INCENDE/UCR | UCR/Views/Controls/Plugin/PluginViewTemplateSelector.cs | 974 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace TaskList.Core
{
public class BaseViewModel : INotifyPropertyChanged
{
string _title = "";
public string Title
{
get => _title;
set => SetProperty(ref _title, value);
}
bool _isBusy = false;
public bool IsBusy
{
get => _isBusy;
set => SetProperty(ref _isBusy, value);
}
protected void SetProperty<T>(ref T backingStore, T value, Action onChanged = null, [CallerMemberName] string propertyName = "")
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return;
backingStore = value;
onChanged?.Invoke();
HandlePropertyChanged(propertyName);
}
protected void HandlePropertyChanged(string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 27.512195 | 136 | 0.613475 | [
"MIT"
] | Azure-Samples/azure-cosmos-db-mongodb-xamarin-getting-started | src/TaskList.Core/ViewModels/BaseViewModel.cs | 1,130 | C# |
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.Translation;
using System;
using System.Collections.Generic;
using System.Numerics;
namespace Ryujinx.Graphics.Shader.StructuredIr
{
static class StructuredProgram
{
public static StructuredProgramInfo MakeStructuredProgram(Function[] functions, ShaderConfig config)
{
StructuredProgramContext context = new StructuredProgramContext(config);
for (int funcIndex = 0; funcIndex < functions.Length; funcIndex++)
{
Function function = functions[funcIndex];
BasicBlock[] blocks = function.Blocks;
VariableType returnType = function.ReturnsValue ? VariableType.S32 : VariableType.None;
VariableType[] inArguments = new VariableType[function.InArgumentsCount];
VariableType[] outArguments = new VariableType[function.OutArgumentsCount];
for (int i = 0; i < inArguments.Length; i++)
{
inArguments[i] = VariableType.S32;
}
for (int i = 0; i < outArguments.Length; i++)
{
outArguments[i] = VariableType.S32;
}
context.EnterFunction(blocks.Length, function.Name, returnType, inArguments, outArguments);
PhiFunctions.Remove(blocks);
for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
{
BasicBlock block = blocks[blkIndex];
context.EnterBlock(block);
for (LinkedListNode<INode> opNode = block.Operations.First; opNode != null; opNode = opNode.Next)
{
Operation operation = (Operation)opNode.Value;
if (IsBranchInst(operation.Inst))
{
context.LeaveBlock(block, operation);
}
else if (operation.Inst != Instruction.CallOutArgument)
{
AddOperation(context, opNode);
}
}
}
GotoElimination.Eliminate(context.GetGotos());
AstOptimizer.Optimize(context);
context.LeaveFunction();
}
return context.Info;
}
private static void AddOperation(StructuredProgramContext context, LinkedListNode<INode> opNode)
{
Operation operation = (Operation)opNode.Value;
Instruction inst = operation.Inst;
bool isCall = inst == Instruction.Call;
int sourcesCount = operation.SourcesCount;
int outDestsCount = operation.DestsCount != 0 ? operation.DestsCount - 1 : 0;
List<Operand> callOutOperands = new List<Operand>();
if (isCall)
{
LinkedListNode<INode> scan = opNode.Next;
while (scan != null && scan.Value is Operation nextOp && nextOp.Inst == Instruction.CallOutArgument)
{
callOutOperands.Add(nextOp.Dest);
scan = scan.Next;
}
sourcesCount += callOutOperands.Count;
}
IAstNode[] sources = new IAstNode[sourcesCount + outDestsCount];
for (int index = 0; index < operation.SourcesCount; index++)
{
sources[index] = context.GetOperandUse(operation.GetSource(index));
}
if (isCall)
{
for (int index = 0; index < callOutOperands.Count; index++)
{
sources[operation.SourcesCount + index] = context.GetOperandDef(callOutOperands[index]);
}
callOutOperands.Clear();
}
for (int index = 0; index < outDestsCount; index++)
{
AstOperand oper = context.GetOperandDef(operation.GetDest(1 + index));
oper.VarType = InstructionInfo.GetSrcVarType(inst, sourcesCount + index);
sources[sourcesCount + index] = oper;
}
AstTextureOperation GetAstTextureOperation(TextureOperation texOp)
{
return new AstTextureOperation(
inst,
texOp.Type,
texOp.Format,
texOp.Flags,
texOp.CbufSlot,
texOp.Handle,
4, // TODO: Non-hardcoded array size.
texOp.Index,
sources);
}
if (operation.Dest != null)
{
AstOperand dest = context.GetOperandDef(operation.Dest);
if (inst == Instruction.LoadConstant)
{
Operand slot = operation.GetSource(0);
if (slot.Type == OperandType.Constant)
{
context.Info.CBuffers.Add(slot.Value);
}
else
{
// If the value is not constant, then we don't know
// how many constant buffers are used, so we assume
// all of them are used.
int cbCount = 32 - BitOperations.LeadingZeroCount(context.Config.GpuAccessor.QueryConstantBufferUse());
for (int index = 0; index < cbCount; index++)
{
context.Info.CBuffers.Add(index);
}
context.Info.UsesCbIndexing = true;
}
}
else if (UsesStorage(inst))
{
AddSBufferUse(context.Info.SBuffers, operation);
}
// If all the sources are bool, it's better to use short-circuiting
// logical operations, rather than forcing a cast to int and doing
// a bitwise operation with the value, as it is likely to be used as
// a bool in the end.
if (IsBitwiseInst(inst) && AreAllSourceTypesEqual(sources, VariableType.Bool))
{
inst = GetLogicalFromBitwiseInst(inst);
}
bool isCondSel = inst == Instruction.ConditionalSelect;
bool isCopy = inst == Instruction.Copy;
if (isCondSel || isCopy)
{
VariableType type = GetVarTypeFromUses(operation.Dest);
if (isCondSel && type == VariableType.F32)
{
inst |= Instruction.FP32;
}
dest.VarType = type;
}
else
{
dest.VarType = InstructionInfo.GetDestVarType(inst);
}
IAstNode source;
if (operation is TextureOperation texOp)
{
if (texOp.Inst == Instruction.ImageLoad || texOp.Inst == Instruction.ImageStore)
{
dest.VarType = texOp.Format.GetComponentType();
}
AstTextureOperation astTexOp = GetAstTextureOperation(texOp);
if (texOp.Inst == Instruction.ImageLoad)
{
context.Info.Images.Add(astTexOp);
}
else
{
context.Info.Samplers.Add(astTexOp);
}
source = astTexOp;
}
else if (!isCopy)
{
source = new AstOperation(inst, operation.Index, sources, operation.SourcesCount);
}
else
{
source = sources[0];
}
context.AddNode(new AstAssignment(dest, source));
}
else if (operation.Inst == Instruction.Comment)
{
context.AddNode(new AstComment(((CommentNode)operation).Comment));
}
else if (operation is TextureOperation texOp)
{
AstTextureOperation astTexOp = GetAstTextureOperation(texOp);
context.Info.Images.Add(astTexOp);
context.AddNode(astTexOp);
}
else
{
if (UsesStorage(inst))
{
AddSBufferUse(context.Info.SBuffers, operation);
}
context.AddNode(new AstOperation(inst, operation.Index, sources, operation.SourcesCount));
}
// Those instructions needs to be emulated by using helper functions,
// because they are NVIDIA specific. Those flags helps the backend to
// decide which helper functions are needed on the final generated code.
switch (operation.Inst)
{
case Instruction.AtomicMaxS32 | Instruction.MrShared:
case Instruction.AtomicMinS32 | Instruction.MrShared:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.AtomicMinMaxS32Shared;
break;
case Instruction.AtomicMaxS32 | Instruction.MrStorage:
case Instruction.AtomicMinS32 | Instruction.MrStorage:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.AtomicMinMaxS32Storage;
break;
case Instruction.MultiplyHighS32:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.MultiplyHighS32;
break;
case Instruction.MultiplyHighU32:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.MultiplyHighU32;
break;
case Instruction.Shuffle:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.Shuffle;
break;
case Instruction.ShuffleDown:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.ShuffleDown;
break;
case Instruction.ShuffleUp:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.ShuffleUp;
break;
case Instruction.ShuffleXor:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.ShuffleXor;
break;
case Instruction.SwizzleAdd:
context.Info.HelperFunctionsMask |= HelperFunctionsMask.SwizzleAdd;
break;
}
}
private static void AddSBufferUse(HashSet<int> sBuffers, Operation operation)
{
Operand slot = operation.GetSource(0);
if (slot.Type == OperandType.Constant)
{
sBuffers.Add(slot.Value);
}
else
{
// If the value is not constant, then we don't know
// how many storage buffers are used, so we assume
// all of them are used.
for (int index = 0; index < GlobalMemory.StorageMaxCount; index++)
{
sBuffers.Add(index);
}
}
}
private static VariableType GetVarTypeFromUses(Operand dest)
{
HashSet<Operand> visited = new HashSet<Operand>();
Queue<Operand> pending = new Queue<Operand>();
bool Enqueue(Operand operand)
{
if (visited.Add(operand))
{
pending.Enqueue(operand);
return true;
}
return false;
}
Enqueue(dest);
while (pending.TryDequeue(out Operand operand))
{
foreach (INode useNode in operand.UseOps)
{
if (!(useNode is Operation operation))
{
continue;
}
if (operation.Inst == Instruction.Copy)
{
if (operation.Dest.Type == OperandType.LocalVariable)
{
if (Enqueue(operation.Dest))
{
break;
}
}
else
{
return OperandInfo.GetVarType(operation.Dest.Type);
}
}
else
{
for (int index = 0; index < operation.SourcesCount; index++)
{
if (operation.GetSource(index) == operand)
{
return InstructionInfo.GetSrcVarType(operation.Inst, index);
}
}
}
}
}
return VariableType.S32;
}
private static bool AreAllSourceTypesEqual(IAstNode[] sources, VariableType type)
{
foreach (IAstNode node in sources)
{
if (!(node is AstOperand operand))
{
return false;
}
if (operand.VarType != type)
{
return false;
}
}
return true;
}
private static bool IsBranchInst(Instruction inst)
{
switch (inst)
{
case Instruction.Branch:
case Instruction.BranchIfFalse:
case Instruction.BranchIfTrue:
return true;
}
return false;
}
private static bool IsBitwiseInst(Instruction inst)
{
switch (inst)
{
case Instruction.BitwiseAnd:
case Instruction.BitwiseExclusiveOr:
case Instruction.BitwiseNot:
case Instruction.BitwiseOr:
return true;
}
return false;
}
private static Instruction GetLogicalFromBitwiseInst(Instruction inst)
{
switch (inst)
{
case Instruction.BitwiseAnd: return Instruction.LogicalAnd;
case Instruction.BitwiseExclusiveOr: return Instruction.LogicalExclusiveOr;
case Instruction.BitwiseNot: return Instruction.LogicalNot;
case Instruction.BitwiseOr: return Instruction.LogicalOr;
}
throw new ArgumentException($"Unexpected instruction \"{inst}\".");
}
private static bool UsesStorage(Instruction inst)
{
if (inst == Instruction.LoadStorage || inst == Instruction.StoreStorage)
{
return true;
}
return inst.IsAtomic() && (inst & Instruction.MrMask) == Instruction.MrStorage;
}
}
} | 35.490826 | 127 | 0.482099 | [
"MIT"
] | Andoryuuta/Ryujinx | Ryujinx.Graphics.Shader/StructuredIr/StructuredProgram.cs | 15,474 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a field in a class, struct or enum
/// </summary>
internal abstract partial class FieldSymbol : Symbol, IFieldSymbol
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Changes to the public interface of this class should remain synchronized with the VB version.
// Do not make any changes to the public interface without making the corresponding change
// to the VB version.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal FieldSymbol()
{
}
/// <summary>
/// The original definition of this symbol. If this symbol is constructed from another
/// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in
/// source or metadata.
/// </summary>
public new virtual FieldSymbol OriginalDefinition
{
get
{
return this;
}
}
protected override sealed Symbol OriginalSymbolDefinition
{
get
{
return this.OriginalDefinition;
}
}
/// <summary>
/// Gets the type of this field.
/// </summary>
public TypeSymbol Type
{
get
{
return GetFieldType(ConsList<FieldSymbol>.Empty);
}
}
internal abstract TypeSymbol GetFieldType(ConsList<FieldSymbol> fieldsBeingBound);
/// <summary>
/// Gets the list of custom modifiers, if any, associated with the field.
/// </summary>
public abstract ImmutableArray<CustomModifier> CustomModifiers { get; }
/// <summary>
/// If this field serves as a backing variable for an automatically generated
/// property or a field-like event, returns that
/// property/event. Otherwise returns null.
/// Note, the set of possible associated symbols might be expanded in the future to
/// reflect changes in the languages.
/// </summary>
public abstract Symbol AssociatedSymbol { get; }
/// <summary>
/// Returns true if this field was declared as "readonly".
/// </summary>
public abstract bool IsReadOnly { get; }
/// <summary>
/// Returns true if this field was declared as "volatile".
/// </summary>
public abstract bool IsVolatile { get; }
/// <summary>
/// Returns true if this field was declared as "fixed".
/// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which
/// the pointed-to type will be the declared element type of the fixed-size buffer.
/// </summary>
public virtual bool IsFixed { get { return false; } }
/// <summary>
/// If IsFixed is true, the value between brackets in the fixed-size-buffer declaration.
/// If IsFixed is false FixedSize is 0.
/// Note that for fixed-a size buffer declaration, this.Type will be a pointer type, of which
/// the pointed-to type will be the declared element type of the fixed-size buffer.
/// </summary>
public virtual int FixedSize { get { return 0; } }
/// <summary>
/// If this.IsFixed is true, returns the underlying implementation type for the
/// fixed-size buffer when emitted. Otherwise returns null.
/// </summary>
internal virtual NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule)
{
return null;
}
/// <summary>
/// Returns true when field is a backing field for a captured frame pointer (typically "this").
/// </summary>
internal virtual bool IsCapturedFrame { get { return false; } }
/// <summary>
/// Returns true if this field was declared as "const" (i.e. is a constant declaration).
/// Also returns true for an enum member.
/// </summary>
public abstract bool IsConst { get; }
// Gets a value indicating whether this instance is metadata constant. A constant field is considered to be
// metadata constant unless they are of type decimal, because decimals are not regarded as constant by the CLR.
public bool IsMetadataConstant
{
get { return this.IsConst && (this.Type.SpecialType != SpecialType.System_Decimal); }
}
/// <summary>
/// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous.
/// True otherwise.
/// </summary>
public virtual bool HasConstantValue
{
get
{
if (!IsConst)
{
return false;
}
ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
return constantValue != null && !constantValue.IsBad; //can be null in error scenarios
}
}
/// <summary>
/// If IsConst returns true, then returns the constant value of the field or enum member. If IsConst returns
/// false, then returns null.
/// </summary>
public virtual object ConstantValue
{
get
{
if (!IsConst)
{
return null;
}
ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
return constantValue == null ? null : constantValue.Value; //can be null in error scenarios
}
}
internal abstract ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes);
/// <summary>
/// Gets the kind of this symbol.
/// </summary>
public sealed override SymbolKind Kind
{
get
{
return SymbolKind.Field;
}
}
internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
{
return visitor.VisitField(this, argument);
}
public override void Accept(CSharpSymbolVisitor visitor)
{
visitor.VisitField(this);
}
public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
{
return visitor.VisitField(this);
}
/// <summary>
/// Returns false because field can't be abstract.
/// </summary>
public sealed override bool IsAbstract
{
get
{
return false;
}
}
/// <summary>
/// Returns false because field can't be defined externally.
/// </summary>
public sealed override bool IsExtern
{
get
{
return false;
}
}
/// <summary>
/// Returns false because field can't be overridden.
/// </summary>
public sealed override bool IsOverride
{
get
{
return false;
}
}
/// <summary>
/// Returns false because field can't be sealed.
/// </summary>
public sealed override bool IsSealed
{
get
{
return false;
}
}
/// <summary>
/// Returns false because field can't be virtual.
/// </summary>
public sealed override bool IsVirtual
{
get
{
return false;
}
}
/// <summary>
/// True if this symbol has a special name (metadata flag SpecialName is set).
/// </summary>
internal abstract bool HasSpecialName { get; }
/// <summary>
/// True if this symbol has a runtime-special name (metadata flag RuntimeSpecialName is set).
/// </summary>
internal abstract bool HasRuntimeSpecialName { get; }
/// <summary>
/// True if this field is not serialized (metadata flag NotSerialized is set).
/// </summary>
internal abstract bool IsNotSerialized { get; }
/// <summary>
/// True if this field has a pointer type.
/// </summary>
/// <remarks>
/// By default we defer to this.Type.IsPointerType()
/// However in some cases this may cause circular dependency via binding a
/// pointer that points to the type that contains the current field.
/// Fortunately in those cases we do not need to force binding of the field's type
/// and can just check the declaration syntax if the field type is not yet known.
/// </remarks>
internal virtual bool HasPointerType
{
get
{
return this.Type.IsPointerType();
}
}
/// <summary>
/// Describes how the field is marshalled when passed to native code.
/// Null if no specific marshalling information is available for the field.
/// </summary>
/// <remarks>PE symbols don't provide this information and always return null.</remarks>
internal abstract MarshalPseudoCustomAttributeData MarshallingInformation { get; }
/// <summary>
/// Returns the marshalling type of this field, or 0 if marshalling information isn't available.
/// </summary>
/// <remarks>
/// By default this information is extracted from <see cref="MarshallingInformation"/> if available.
/// Since the compiler does only need to know the marshalling type of symbols that aren't emitted
/// PE symbols just decode the type from metadata and don't provide full marshalling information.
/// </remarks>
internal virtual UnmanagedType MarshallingType
{
get
{
var info = MarshallingInformation;
return info != null ? info.UnmanagedType : 0;
}
}
/// <summary>
/// Offset assigned to the field when the containing type is laid out by the VM.
/// Null if unspecified.
/// </summary>
internal abstract int? TypeLayoutOffset { get; }
internal FieldSymbol AsMember(NamedTypeSymbol newOwner)
{
Debug.Assert(this.IsDefinition);
Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition));
return (newOwner == this.ContainingSymbol) ? this : new SubstitutedFieldSymbol(newOwner as SubstitutedNamedTypeSymbol, this);
}
#region Use-Site Diagnostics
internal override DiagnosticInfo GetUseSiteDiagnostic()
{
if (this.IsDefinition)
{
return base.GetUseSiteDiagnostic();
}
return this.OriginalDefinition.GetUseSiteDiagnostic();
}
internal bool CalculateUseSiteDiagnostic(ref DiagnosticInfo result)
{
Debug.Assert(IsDefinition);
// Check type, custom modifiers
if (DeriveUseSiteDiagnosticFromType(ref result, this.Type) ||
DeriveUseSiteDiagnosticFromCustomModifiers(ref result, this.CustomModifiers))
{
return true;
}
// If the member is in an assembly with unified references,
// we check if its definition depends on a type from a unified reference.
if (this.ContainingModule.HasUnifiedReferences)
{
HashSet<TypeSymbol> unificationCheckedTypes = null;
if (this.Type.GetUnificationUseSiteDiagnosticRecursive(ref result, this, ref unificationCheckedTypes) ||
GetUnificationUseSiteDiagnosticRecursive(ref result, this.CustomModifiers, this, ref unificationCheckedTypes))
{
return true;
}
}
return false;
}
/// <summary>
/// Return error code that has highest priority while calculating use site error for this symbol.
/// </summary>
protected override int HighestPriorityUseSiteError
{
get
{
return (int)ErrorCode.ERR_BindToBogus;
}
}
public sealed override bool HasUnsupportedMetadata
{
get
{
DiagnosticInfo info = GetUseSiteDiagnostic();
return (object)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus;
}
}
#endregion
/// <summary>
/// Is this a field of a tuple type?
/// </summary>
public virtual bool IsTupleField
{
get
{
return false;
}
}
/// <summary>
/// If this is a field of a tuple type, return corresponding underlying field from the
/// tuple underlying type. Otherwise, null. In case of a malformed underlying type
/// the corresponding underlying field might be missing, return null in this case too.
/// </summary>
public virtual FieldSymbol TupleUnderlyingField
{
get
{
return null;
}
}
/// <summary>
/// If this is a field representing a tuple element,
/// returns the index of the element (zero-based).
/// Otherwise, a negative number.
/// </summary>
public virtual int TupleElementIndex
{
get
{
return -1;
}
}
#region IFieldSymbol Members
ISymbol IFieldSymbol.AssociatedSymbol
{
get
{
return this.AssociatedSymbol;
}
}
ITypeSymbol IFieldSymbol.Type
{
get
{
return this.Type;
}
}
ImmutableArray<CustomModifier> IFieldSymbol.CustomModifiers
{
get { return this.CustomModifiers; }
}
IFieldSymbol IFieldSymbol.OriginalDefinition
{
get { return this.OriginalDefinition; }
}
#endregion
#region ISymbol Members
public override void Accept(SymbolVisitor visitor)
{
visitor.VisitField(this);
}
public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitField(this);
}
#endregion
}
}
| 33.473799 | 161 | 0.564347 | [
"Apache-2.0"
] | Unknown6656/roslyn | src/Compilers/CSharp/Portable/Symbols/FieldSymbol.cs | 15,333 | C# |
// This file isn't generated, but this comment is necessary to exclude it from StyleCop analysis.
// For more info see: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2108
// <auto-generated/>
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Alba.CsConsoleFormat.Framework.Collections;
using static System.ConsoleColor;
namespace Alba.CsConsoleFormat
{
[SuppressMessage("ReSharper", "RedundantExplicitArraySize", Justification = "Provides validation of array size.")]
internal static class ColorMaps
{
internal const int ConsoleColorCount = 16;
public static readonly IList<ConsoleColor> Dark = new ConsoleColor[ConsoleColorCount] {
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, DarkGray,
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray,
}.ToReadOnly();
public static readonly IList<ConsoleColor> Darkest = new ConsoleColor[ConsoleColorCount] {
Black, Black, Black, Black, Black, Black, Black, DarkGray,
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray,
}.ToReadOnly();
public static readonly IList<ConsoleColor> Light = new ConsoleColor[ConsoleColorCount] {
DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White,
Gray, Blue, Green, Cyan, Red, Magenta, Yellow, White,
}.ToReadOnly();
public static readonly IList<ConsoleColor> Lightest = new ConsoleColor[ConsoleColorCount] {
DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White,
Gray, White, White, White, White, White, White, White,
}.ToReadOnly();
public static readonly IList<ConsoleColor> Invert = new ConsoleColor[ConsoleColorCount] {
White, DarkYellow, DarkMagenta, DarkRed, DarkCyan, DarkGreen, DarkBlue, DarkGray,
Green, Yellow, Magenta, Red, Cyan, Green, Blue, Black,
}.ToReadOnly();
}
} | 51.820513 | 118 | 0.699654 | [
"MIT"
] | nseedio/nseed | lab/SeedingWeedingOutAndDestroyingStartup/NSeed/ThirdParty/CsConsoleFormat/Formatting/ColorMaps.cs | 2,021 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OnlineBankingApp.Data;
namespace OnlineBankingApp.Migrations
{
[DbContext(typeof(OnlineBankingAppContext))]
[Migration("20210220071509_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.2");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("TEXT");
b.Property<string>("ProviderKey")
.HasColumnType("TEXT");
b.Property<string>("ProviderDisplayName")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.HasColumnType("TEXT");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("LoginProvider")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("OnlineBankingApp.Models.Account", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AccountType")
.HasColumnType("INTEGER");
b.Property<decimal>("Balance")
.HasColumnType("decimal(18, 2)");
b.Property<string>("CustomerId")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(15)
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("CustomerId");
b.ToTable("Account");
});
modelBuilder.Entity("OnlineBankingApp.Models.Backup", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("BackupDate")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(15)
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("Backup");
});
modelBuilder.Entity("OnlineBankingApp.Models.Customer", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessFailedCount")
.HasColumnType("INTEGER");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<DateTime>("DateOfBirth")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("TEXT");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("TEXT");
b.Property<bool>("LockoutEnabled")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("TEXT");
b.Property<string>("MiddleName")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("TEXT");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("PhoneNumber")
.HasColumnType("TEXT");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("SecurityStamp")
.HasColumnType("TEXT");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("OnlineBankingApp.Models.FundTransfer", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AccountFrom")
.HasColumnType("INTEGER");
b.Property<int>("AccountTo")
.HasColumnType("INTEGER");
b.Property<decimal>("Amount")
.HasColumnType("decimal(18, 2)");
b.Property<string>("CustomerID")
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasMaxLength(60)
.HasColumnType("TEXT");
b.Property<DateTime>("TransactionDate")
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("CustomerID");
b.ToTable("FundTransfer");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("OnlineBankingApp.Models.Customer", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("OnlineBankingApp.Models.Customer", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("OnlineBankingApp.Models.Customer", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("OnlineBankingApp.Models.Customer", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("OnlineBankingApp.Models.Account", b =>
{
b.HasOne("OnlineBankingApp.Models.Customer", "Customer")
.WithMany("Accounts")
.HasForeignKey("CustomerId");
b.Navigation("Customer");
});
modelBuilder.Entity("OnlineBankingApp.Models.FundTransfer", b =>
{
b.HasOne("OnlineBankingApp.Models.Customer", "Customer")
.WithMany("FundTransfers")
.HasForeignKey("CustomerID");
b.Navigation("Customer");
});
modelBuilder.Entity("OnlineBankingApp.Models.Customer", b =>
{
b.Navigation("Accounts");
b.Navigation("FundTransfers");
});
#pragma warning restore 612, 618
}
}
}
| 34.743523 | 95 | 0.436955 | [
"MIT"
] | JWilh/ASP.NET-Core-Secure-Coding-Cookbook | Chapter07/disabled-security-features/after/OnlineBankingApp/Migrations/20210220071509_CreateIdentitySchema.Designer.cs | 13,413 | C# |
using System;
using Newtonsoft.Json;
using System.Xml.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayUserCharityForestSendModel Data Structure.
/// </summary>
[Serializable]
public class AlipayUserCharityForestSendModel : AlipayObject
{
/// <summary>
/// 唯一单据号,用于发能量幂等控制
/// </summary>
[JsonProperty("biz_no")]
[XmlElement("biz_no")]
public string BizNo { get; set; }
/// <summary>
/// 业务发生时间
/// </summary>
[JsonProperty("biz_time")]
[XmlElement("biz_time")]
public string BizTime { get; set; }
/// <summary>
/// 能量值,最小1g,最大100kg(100,000),不能有小数
/// </summary>
[JsonProperty("energy")]
[XmlElement("energy")]
public long Energy { get; set; }
/// <summary>
/// 能量气泡类型
/// </summary>
[JsonProperty("energy_type")]
[XmlElement("energy_type")]
public string EnergyType { get; set; }
/// <summary>
/// 业务来源
/// </summary>
[JsonProperty("source")]
[XmlElement("source")]
public string Source { get; set; }
/// <summary>
/// 用户的支付宝账户ID
/// </summary>
[JsonProperty("user_id")]
[XmlElement("user_id")]
public string UserId { get; set; }
}
}
| 25.035714 | 64 | 0.531384 | [
"MIT"
] | Aosir/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayUserCharityForestSendModel.cs | 1,514 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace SuperGlue.Web.Assets
{
public static class GenericEnumerableExtensions
{
public static bool IsEqualTo<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
{
var objArray1 = actual.ToArray();
var objArray2 = expected.ToArray();
if (objArray1.Length != objArray2.Length)
return false;
return !objArray1.Where((t, index) => !t.Equals(objArray2[index])).Any();
}
public static string Join(this string[] values, string separator)
{
return string.Join(separator, values);
}
public static string Join(this IEnumerable<string> values, string separator)
{
return Join(values.ToArray(), separator);
}
[DebuggerStepThrough]
public static IEnumerable<T> Each<T>(this IEnumerable<T> values, Action<T> eachAction)
{
var enumerable = values as T[] ?? values.ToArray();
foreach (var obj in enumerable)
eachAction(obj);
return enumerable;
}
[DebuggerStepThrough]
public static IEnumerable Each(this IEnumerable values, Action<object> eachAction)
{
var enumerable = values as object[] ?? values.Cast<object>().ToArray();
foreach (var obj in enumerable)
eachAction(obj);
return enumerable;
}
public static void Fill<T>(this IList<T> list, T value)
{
if (list.Contains(value))
return;
list.Add(value);
}
public static void Fill<T>(this IList<T> list, IEnumerable<T> values)
{
list.AddRange(values.Where(v => !list.Contains(v)));
}
public static IList<T> AddRange<T>(this IList<T> list, IEnumerable<T> items)
{
items.Each(((ICollection<T>)list).Add);
return list;
}
}
} | 30.071429 | 94 | 0.568171 | [
"MIT"
] | MattiasJakobsson/Jajo.Web | src/SuperGlue.Web.Assets/GenericEnumerableExtensions.cs | 2,107 | C# |
namespace ESFA.DC.ILR.Model.Interface
{
public interface ILearnerHEFinancialSupport
{
long? FINTYPENullable { get; }
long? FINAMOUNTNullable { get; }
}
}
| 20.333333 | 47 | 0.650273 | [
"MIT"
] | SkillsFundingAgency/DC-ILR-1718-Model | src/ESFA.DC.ILR.Model.Interface/ILearnerHEFinancialSupport.cs | 185 | C# |
using System.IO;
using System;
using System.Diagnostics;
using Aspose.Cells;
namespace Aspose.Cells.Examples.CSharp.Articles.WorkingWithCalculationEngine
{
public class DecreaseCalculationTime
{
public static void Run()
{
// ExStart:1
// Test calculation time after setting recursive true
TestCalcTimeRecursive(true);
// Test calculation time after setting recursive false
TestCalcTimeRecursive(false);
// ExEnd:1
}
// ExStart:TestCalcTimeRecursive
static void TestCalcTimeRecursive(bool rec)
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Load your sample workbook
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access first worksheet
Worksheet ws = wb.Worksheets[0];
// Set the calculation option, set recursive true or false as per parameter
CalculationOptions opts = new CalculationOptions();
opts.Recursive = rec;
// Start stop watch
Stopwatch sw = new Stopwatch();
sw.Start();
// Calculate cell A1 one million times
for (int i = 0; i < 1000000; i++)
{
ws.Cells["A1"].Calculate(opts);
}
// Stop the watch
sw.Stop();
// Calculate elapsed time in seconds
long second = 1000;
long estimatedTime = sw.ElapsedMilliseconds / second;
// Print the elapsed time in seconds
Console.WriteLine("Recursive " + rec + ": " + estimatedTime + " seconds");
}
// ExEnd:TestCalcTimeRecursive
}
}
| 31.3 | 115 | 0.568158 | [
"MIT"
] | Aspose/Aspose.Cells-for-.NET | Examples/CSharp/Articles/WorkingWithCalculationEngine/DecreaseCalculationTime.cs | 1,878 | C# |
using System;
using System.Collections.Generic;
namespace Fakultet.Models
{
public partial class Orgjed
{
public Orgjed()
{
InverseSifNadorgjedNavigation = new HashSet<Orgjed>();
Nastavnik = new HashSet<Nastavnik>();
Pred = new HashSet<Pred>();
}
public int SifOrgjed { get; set; }
public string NazOrgjed { get; set; }
public int? SifNadorgjed { get; set; }
public virtual Orgjed SifNadorgjedNavigation { get; set; }
public virtual ICollection<Orgjed> InverseSifNadorgjedNavigation { get; set; }
public virtual ICollection<Nastavnik> Nastavnik { get; set; }
public virtual ICollection<Pred> Pred { get; set; }
}
}
| 29.88 | 86 | 0.623829 | [
"MIT"
] | Csharp2020/csharp2020 | DanijelaK/MVC/Fakultet/Fakultet/Models/Orgjed.cs | 749 | 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/mfmediaengine.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("332EC562-3758-468D-A784-E38F23552128")]
[NativeTypeName("struct IMFExtendedDRMTypeSupport : IUnknown")]
public unsafe partial struct IMFExtendedDRMTypeSupport
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject)
{
return ((delegate* stdcall<IMFExtendedDRMTypeSupport*, Guid*, void**, int>)(lpVtbl[0]))((IMFExtendedDRMTypeSupport*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* stdcall<IMFExtendedDRMTypeSupport*, uint>)(lpVtbl[1]))((IMFExtendedDRMTypeSupport*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* stdcall<IMFExtendedDRMTypeSupport*, uint>)(lpVtbl[2]))((IMFExtendedDRMTypeSupport*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int IsTypeSupportedEx([NativeTypeName("BSTR")] ushort* type, [NativeTypeName("BSTR")] ushort* keySystem, [NativeTypeName("MF_MEDIA_ENGINE_CANPLAY *")] MF_MEDIA_ENGINE_CANPLAY* pAnswer)
{
return ((delegate* stdcall<IMFExtendedDRMTypeSupport*, ushort*, ushort*, MF_MEDIA_ENGINE_CANPLAY*, int>)(lpVtbl[3]))((IMFExtendedDRMTypeSupport*)Unsafe.AsPointer(ref this), type, keySystem, pAnswer);
}
}
}
| 46.404255 | 211 | 0.700138 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/mfmediaengine/IMFExtendedDRMTypeSupport.cs | 2,183 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
//
// Microsoft Cognitive Services (formerly Project Oxford) GitHub:
// https://github.com/Microsoft/ProjectOxford-ClientSDK
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Microsoft.ProjectOxford.Common;
namespace Microsoft.ProjectOxford.Emotion.Contract
{
public class Emotion
{
/// <summary>
/// Gets or sets the face rectangle.
/// </summary>
/// <value>
/// The face rectangle.
/// </value>
public Rectangle FaceRectangle { get; set; }
/// <summary>
/// Gets or sets the emotion scores.
/// </summary>
/// <value>
/// The emotion scores.
/// </value>
public Scores Scores { get; set; }
#region overrides
public override bool Equals(object o)
{
if (o == null) return false;
var other = o as Emotion;
if (other == null) return false;
if (this.FaceRectangle == null)
{
if (other.FaceRectangle != null) return false;
}
else
{
if (!this.FaceRectangle.Equals(other.FaceRectangle)) return false;
}
if (this.Scores == null)
{
return other.Scores == null;
}
else
{
return this.Scores.Equals(other.Scores);
}
}
public override int GetHashCode()
{
int r = (FaceRectangle == null) ? 0x33333333 : FaceRectangle.GetHashCode();
int s = (Scores == null) ? 0xccccccc : Scores.GetHashCode();
return r ^ s;
}
#endregion
}
}
| 32.397849 | 103 | 0.613342 | [
"MIT"
] | Archie-Sharma/ProjectOxford-ClientSDK | Emotion/Windows/ClientLibrary/Contract/Emotion.cs | 3,015 | C# |
using COL.UnityGameWheels.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using COL.UnityGameWheels.Core.Ioc;
using UnityEditor;
using UnityEngine;
namespace COL.UnityGameWheels.Unity.Editor
{
[UnityAppEditor(typeof(EventService))]
public class EventServiceInspector : BaseServiceInspector
{
private enum SortingOrder
{
EventId,
EventTypeFullName,
EventTypeName,
}
private const float FoldoutIndent = 10f;
private static readonly string SortingOrderKey = typeof(EventServiceInspector).FullName + ".SortingOrder";
private static readonly string ShowNoListenerEventsKey = typeof(EventServiceInspector).FullName + ".ShowNoListenerEventsKey";
private int m_ServiceInstanceHashCode;
private Dictionary<int, Type> m_EventIdToType = null;
private List<int> m_EventIds = null;
private int m_FoldoutEventId = 0;
private SortingOrder m_SortingOrder;
private bool m_ShowNoListenerEvents;
private bool m_ShowListeners = false;
private Dictionary<int, LinkedList<OnHearEvent>> m_Listeners = null;
protected internal override bool DrawContent(object serviceInstance)
{
var eventService = (EventService)serviceInstance;
EnsureInit(eventService);
DrawSortingOrderSection();
DrawShowNoListenerEventsSection();
DrawListeners();
return true;
}
private void DrawListeners()
{
m_ShowListeners = EditorGUILayout.Foldout(m_ShowListeners, "Listeners");
if (!m_ShowListeners)
{
return;
}
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(FoldoutIndent);
EditorGUILayout.BeginVertical();
{
int counter = 0;
foreach (var eventId in m_EventIds)
{
if (DrawListenersOfOneEventId(eventId))
{
counter++;
}
}
if (counter <= 0)
{
EditorGUILayout.HelpBox("Nothing to show.", MessageType.Info);
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndHorizontal();
}
private void DrawShowNoListenerEventsSection()
{
var newShowNoListenerEvents = EditorGUILayout.Toggle("Show No Listener Events", m_ShowNoListenerEvents);
if (newShowNoListenerEvents != m_ShowNoListenerEvents)
{
m_ShowNoListenerEvents = newShowNoListenerEvents;
EditorPrefs.SetBool(ShowNoListenerEventsKey, newShowNoListenerEvents);
}
}
private void DrawSortingOrderSection()
{
var newSortingOrder = (SortingOrder)EditorGUILayout.EnumPopup("Sorting Order", m_SortingOrder);
if (newSortingOrder != m_SortingOrder)
{
m_SortingOrder = newSortingOrder;
EditorPrefs.SetInt(SortingOrderKey, (int)m_SortingOrder);
RefreshEventIdsOrder();
}
}
private bool DrawListenersOfOneEventId(int eventId)
{
var listenerCount = m_Listeners.ContainsKey(eventId) ? m_Listeners[eventId].Count : 0;
if (!m_ShowNoListenerEvents && listenerCount <= 0)
{
return false;
}
var eventType = EventIdToTypeMap.GetEventType(eventId);
var displayName = m_SortingOrder == SortingOrder.EventTypeFullName ? eventType.FullName : eventType.Name;
var foldout = EditorGUILayout.Foldout(eventId == m_FoldoutEventId,
Core.Utility.Text.Format("[{0}] {1} ({2} listener(s))", eventId, displayName, listenerCount));
if (eventId == m_FoldoutEventId && !foldout)
{
m_FoldoutEventId = 0;
}
if (foldout)
{
m_FoldoutEventId = eventId;
}
if (!foldout || listenerCount <= 0)
{
return true;
}
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(FoldoutIndent);
EditorGUILayout.BeginVertical();
{
foreach (var listener in m_Listeners[eventId])
{
var targetName = listener.Target == null ? "<null>" : listener.Target.ToString();
var methodName = listener.Method.Name;
EditorGUILayout.LabelField(Core.Utility.Text.Format("Target: '{0}', Method: '{1}'",
targetName, methodName));
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndHorizontal();
return true;
}
private void EnsureInit(EventService eventService)
{
var newHashCode = eventService.GetHashCode();
if (newHashCode == m_ServiceInstanceHashCode)
{
return;
}
m_ServiceInstanceHashCode = newHashCode;
m_EventIdToType = typeof(EventIdToTypeMap)
.GetField("s_EventIdToType", BindingFlags.Static | BindingFlags.NonPublic)
.GetValue(null) as Dictionary<int, Type>;
m_EventIds = m_EventIdToType.Keys.ToList();
m_SortingOrder = (SortingOrder)EditorPrefs.GetInt(SortingOrderKey, (int)SortingOrder.EventId);
RefreshEventIdsOrder();
m_Listeners = typeof(EventService).GetField("m_Listeners", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(eventService) as Dictionary<int, LinkedList<OnHearEvent>>;
m_ShowNoListenerEvents = EditorPrefs.GetBool(ShowNoListenerEventsKey, false);
}
private void RefreshEventIdsOrder()
{
switch (m_SortingOrder)
{
case SortingOrder.EventTypeFullName:
m_EventIds.Sort((a, b) => m_EventIdToType[a].FullName.CompareTo(m_EventIdToType[b].FullName));
break;
case SortingOrder.EventTypeName:
m_EventIds.Sort((a, b) => m_EventIdToType[a].Name.CompareTo(m_EventIdToType[b].Name));
break;
default:
m_EventIds.Sort();
break;
}
}
}
} | 36.403226 | 133 | 0.560626 | [
"MIT"
] | GarfieldJiang/UnityGameWheels.Unity | Editor/Inspectors/EventServiceInspector.cs | 6,773 | C# |
namespace MassTransit.SignalR.Consumers
{
using Utils;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Context;
public class UserBaseConsumer<THub>
where THub : Hub
{
readonly BaseMassTransitHubLifetimeManager<THub> _hubLifetimeManager;
protected UserBaseConsumer(HubLifetimeManager<THub> hubLifetimeManager)
{
_hubLifetimeManager = hubLifetimeManager as BaseMassTransitHubLifetimeManager<THub> ?? throw new ArgumentNullException(nameof(hubLifetimeManager),
"HubLifetimeManager<> must be of type BaseMassTransitHubLifetimeManager<>");
}
public async Task Handle(string userId, IDictionary<string, byte[]> messages)
{
var message = new Lazy<SerializedHubMessage>(messages.ToSerializedHubMessage);
var userStore = _hubLifetimeManager.Users[userId];
if (userStore == null || userStore.Count <= 0)
return;
var tasks = new List<Task>();
foreach (var connection in userStore)
{
tasks.Add(connection.WriteAsync(message.Value).AsTask());
}
try
{
await Task.WhenAll(tasks);
}
catch (Exception e)
{
LogContext.Warning?.Log(e, "Failed to write message");
}
}
}
}
| 30.854167 | 158 | 0.608373 | [
"ECL-2.0",
"Apache-2.0"
] | ArmyMedalMei/MassTransit | src/MassTransit.SignalR/Consumers/UserBaseConsumer.cs | 1,483 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = PostFinanceCheckout.Client.SwaggerDateConverter;
namespace PostFinanceCheckout.Model
{
/// <summary>
/// HumanUserUpdate
/// </summary>
[DataContract]
public partial class HumanUserUpdate : AbstractHumanUserUpdate, IEquatable<HumanUserUpdate>
{
/// <summary>
/// Initializes a new instance of the <see cref="HumanUserUpdate" /> class.
/// </summary>
[JsonConstructorAttribute]
protected HumanUserUpdate() { }
/// <summary>
/// Initializes a new instance of the <see cref="HumanUserUpdate" /> class.
/// </summary>
/// <param name="version">The version number indicates the version of the entity. The version is incremented whenever the entity is changed. (required).</param>
/// <param name="id">The ID is the primary key of the entity. The ID identifies the entity uniquely. (required).</param>
public HumanUserUpdate(long? version, long? id)
{
// to ensure "version" is required (not null)
if (version == null)
{
throw new InvalidDataException("version is a required property for HumanUserUpdate and cannot be null");
}
this.Version = version;
// to ensure "id" is required (not null)
if (id == null)
{
throw new InvalidDataException("id is a required property for HumanUserUpdate and cannot be null");
}
this.Id = id;
}
/// <summary>
/// The ID is the primary key of the entity. The ID identifies the entity uniquely.
/// </summary>
/// <value>The ID is the primary key of the entity. The ID identifies the entity uniquely.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
/// <summary>
/// The version number indicates the version of the entity. The version is incremented whenever the entity is changed.
/// </summary>
/// <value>The version number indicates the version of the entity. The version is incremented whenever the entity is changed.</value>
[DataMember(Name="version", EmitDefaultValue=false)]
public long? Version { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class HumanUserUpdate {\n");
sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n");
sb.Append(" EmailAddress: ").Append(EmailAddress).Append("\n");
sb.Append(" Firstname: ").Append(Firstname).Append("\n");
sb.Append(" Language: ").Append(Language).Append("\n");
sb.Append(" Lastname: ").Append(Lastname).Append("\n");
sb.Append(" MobilePhoneNumber: ").Append(MobilePhoneNumber).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" TimeZone: ").Append(TimeZone).Append("\n");
sb.Append(" TwoFactorEnabled: ").Append(TwoFactorEnabled).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Version: ").Append(Version).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 override string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
/// <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 HumanUserUpdate);
}
/// <summary>
/// Returns true if HumanUserUpdate instances are equal
/// </summary>
/// <param name="input">Instance of HumanUserUpdate to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(HumanUserUpdate input)
{
if (input == null)
return false;
return base.Equals(input) &&
(
this.EmailAddress == input.EmailAddress ||
(this.EmailAddress != null &&
this.EmailAddress.Equals(input.EmailAddress))
) && base.Equals(input) &&
(
this.Firstname == input.Firstname ||
(this.Firstname != null &&
this.Firstname.Equals(input.Firstname))
) && base.Equals(input) &&
(
this.Language == input.Language ||
(this.Language != null &&
this.Language.Equals(input.Language))
) && base.Equals(input) &&
(
this.Lastname == input.Lastname ||
(this.Lastname != null &&
this.Lastname.Equals(input.Lastname))
) && base.Equals(input) &&
(
this.MobilePhoneNumber == input.MobilePhoneNumber ||
(this.MobilePhoneNumber != null &&
this.MobilePhoneNumber.Equals(input.MobilePhoneNumber))
) && base.Equals(input) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
) && base.Equals(input) &&
(
this.TimeZone == input.TimeZone ||
(this.TimeZone != null &&
this.TimeZone.Equals(input.TimeZone))
) && base.Equals(input) &&
(
this.TwoFactorEnabled == input.TwoFactorEnabled ||
(this.TwoFactorEnabled != null &&
this.TwoFactorEnabled.Equals(input.TwoFactorEnabled))
) && base.Equals(input) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) && base.Equals(input) &&
(
this.Version == input.Version ||
(this.Version != null &&
this.Version.Equals(input.Version))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = base.GetHashCode();
if (this.EmailAddress != null)
hashCode = hashCode * 59 + this.EmailAddress.GetHashCode();
if (this.Firstname != null)
hashCode = hashCode * 59 + this.Firstname.GetHashCode();
if (this.Language != null)
hashCode = hashCode * 59 + this.Language.GetHashCode();
if (this.Lastname != null)
hashCode = hashCode * 59 + this.Lastname.GetHashCode();
if (this.MobilePhoneNumber != null)
hashCode = hashCode * 59 + this.MobilePhoneNumber.GetHashCode();
if (this.State != null)
hashCode = hashCode * 59 + this.State.GetHashCode();
if (this.TimeZone != null)
hashCode = hashCode * 59 + this.TimeZone.GetHashCode();
if (this.TwoFactorEnabled != null)
hashCode = hashCode * 59 + this.TwoFactorEnabled.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Version != null)
hashCode = hashCode * 59 + this.Version.GetHashCode();
return hashCode;
}
}
}
}
| 41.349057 | 168 | 0.531599 | [
"Apache-2.0"
] | pfpayments/csharp-sdk | src/PostFinanceCheckout/Model/HumanUserUpdate.cs | 8,766 | C# |
namespace WeakReferenceExample
{
public class CustomWindow
{
public string WindowName { get; set; }
public void OnProgramClosed(object? sender, EventArgs e)
{
Console.WriteLine($"{WindowName} is detected that the program is closed");
}
}
public class Program
{
public static event EventHandler<EventArgs> ProgramClosed;
static CustomWindow? _tempWindow;
public static void Main()
{
Console.WriteLine("Demo0 is running");
SimulateDemo0();
Console.WriteLine();
Console.WriteLine("Demo1 is running");
SimulateDemo1();
Console.WriteLine();
Console.WriteLine("Demo2 is running");
SimulateDemo2();
ProgramClosed?.Invoke(null, EventArgs.Empty);
}
#region demo0
public static void SimulateDemo0()
{
NoMemoryLeak();
while (true)
{
Console.Write("Command: ");
string command = Console.ReadLine();
switch (command)
{
case "quit":
return;
case "find":
Console.WriteLine(MemorLeakTracer.FindSuspectedMemoryLeaks());
break;
}
}
}
public static void NoMemoryLeak()
{
CustomWindow window = new CustomWindow() { WindowName = "NoMemoryLeak Window" };
MemorLeakTracer.AddObject(window);
Console.WriteLine($"{window.WindowName} has been created.");
MemorLeakTracer.SetAsDone(window);
}
#endregion
#region demo1
public static void SimulateDemo1()
{
CauseAMemoryLeakByReferenceCount();
while (true)
{
Console.Write("Command: ");
string command = Console.ReadLine();
switch (command)
{
case "quit":
return;
case "find":
Console.WriteLine(MemorLeakTracer.FindSuspectedMemoryLeaks());
break;
case "fix":
_tempWindow = null;
break;
}
}
}
public static void CauseAMemoryLeakByReferenceCount()
{
CustomWindow window = new CustomWindow() { WindowName = "CauseAMemoryLeakByReferenceCount Window" };
MemorLeakTracer.AddObject(window);
Console.WriteLine($"{window.WindowName} has been created.");
//Causes a leakage
_tempWindow = window;
MemorLeakTracer.SetAsDone(window);
}
#endregion
#region demo2
public static void SimulateDemo2()
{
CauseAMemoryLeakByRegisteredEvent();
bool run = true;
while (run)
{
Console.Write("Command: ");
string command = Console.ReadLine();
switch (command)
{
case "quit":
run = false;
break;
case "find":
Console.WriteLine(MemorLeakTracer.FindSuspectedMemoryLeaks());
break;
case "fix":
ProgramClosed = null;
break;
}
}
Console.WriteLine();
NoMemoryLeakByUnRegisteredEvent();
while (true)
{
Console.Write("Command: ");
string command = Console.ReadLine();
switch (command)
{
case "quit":
return;
case "find":
Console.WriteLine(MemorLeakTracer.FindSuspectedMemoryLeaks());
break;
}
}
}
public static void CauseAMemoryLeakByRegisteredEvent()
{
CustomWindow window = new CustomWindow() { WindowName = "CauseAMemoryLeakByRegisteredEvent Window" };
MemorLeakTracer.AddObject(window);
Console.WriteLine($"{window.WindowName} has been created.");
//Causes a leakage
ProgramClosed += window.OnProgramClosed;
MemorLeakTracer.SetAsDone(window);
}
public static void NoMemoryLeakByUnRegisteredEvent()
{
CustomWindow window = new CustomWindow() { WindowName = "NoMemoryLeakByUnRegisteredEvent Window" };
MemorLeakTracer.AddObject(window);
Console.WriteLine($"{window.WindowName} has been created.");
//Causes a leakage
ProgramClosed += window.OnProgramClosed;
MemorLeakTracer.SetAsDone(window);
ProgramClosed -= window.OnProgramClosed;
}
#endregion
}
} | 29.606936 | 113 | 0.490043 | [
"MIT"
] | serhatzor/Medium | Medium/WeakReferenceExample/Program.cs | 5,124 | C# |
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Twilio;
namespace starter_dotnet_core
{
public class Program
{
public static void Main(string[] args)
{
try
{
TwilioClient.Init(
"sid", // Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"),
"token" // Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN")
);
}
catch (Twilio.Exceptions.AuthenticationException)
{
Console.WriteLine("You must configure your TWILIO_* variables first.");
Environment.Exit(-1);
}
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 30.34375 | 88 | 0.550978 | [
"MIT"
] | MichaelSDavid/TwilioQuest-Code | Intro/twilio_cs_starter/Program.cs | 973 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace VoiceBridge.Most.Directives
{
public class ImageDirective : IVirtualDirective
{
public IImage Image { get; set; }
}
}
| 18.083333 | 51 | 0.709677 | [
"MIT"
] | voicebridge/most | core/src/Directives/ImageDirective.cs | 219 | C# |
using System;
using System.Web;
using System.Web.UI;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using MiniVault.Models;
namespace MiniVault.Account
{
public partial class Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//RegisterHyperLink.NavigateUrl = "Register";
//// Enable this once you have account confirmation enabled for password reset functionality
////ForgotPasswordHyperLink.NavigateUrl = "Forgot";
//OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
//var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
//if (!String.IsNullOrEmpty(returnUrl))
//{
// RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
//}
this.Title = "Log in To Mini Vault";
}
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
//// Validate the user password
//var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
//var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
//// This doen't count login failures towards account lockout
//// To enable password failures to trigger lockout, change to shouldLockout: true
//var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
//switch (result)
//{
// case SignInStatus.Success:
// IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
// break;
// case SignInStatus.LockedOut:
// Response.Redirect("/Account/Lockout");
// break;
// case SignInStatus.RequiresVerification:
// Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
// Request.QueryString["ReturnUrl"],
// RememberMe.Checked),
// true);
// break;
// case SignInStatus.Failure:
// default:
// FailureText.Text = "Invalid login attempt";
// ErrorMessage.Visible = true;
// break;
//}
}
}
protected void Unnamed_CheckedChanged(object sender, EventArgs e)
{
//Set Remember Me on for In memory data. Use ASP.net Caching
}
}
} | 41.782609 | 129 | 0.535206 | [
"Apache-2.0"
] | TheArchitect123/MiniVault---XamarinForms | Cross.DataVault/MiniVault/MiniVault/Account/Login.aspx.cs | 2,885 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiMarketingCampaignItemBatchqueryModel Data Structure.
/// </summary>
public class KoubeiMarketingCampaignItemBatchqueryModel : AlipayObject
{
/// <summary>
/// 操作人id,必须和operator_type配对存在,不填时默认是商户
/// </summary>
[JsonPropertyName("operator_id")]
public string OperatorId { get; set; }
/// <summary>
/// 操作人类型,有以下值可填:MER(外部商户),MER_STAFF(外部商户操作员),PROVIDER(外部服务商),PROVIDER_STAFF(外部服务商员工),默认不需要填这个字段,默认为MER
/// </summary>
[JsonPropertyName("operator_type")]
public string OperatorType { get; set; }
}
}
| 31.347826 | 111 | 0.654646 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiMarketingCampaignItemBatchqueryModel.cs | 885 | C# |
using System;
using System.Data;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Hikari
{
/// <summary>
/// 创建驱动连接
///
/// Create driver connection
/// </summary>
public abstract class PoolBase
{
protected static int MAX_PERMITS = 10000;
protected HikariConfig config;
protected string poolName;
protected long connectionTimeout;
protected int validationTimeout;
protected string dllPath = ""; //dll路径 // dll path
protected int size = 0; //生成的连接数量 // Number of connections generated
protected int entryid = 0; //ID生成 // ID generation
/// <summary>
/// 已经创建的数据
///
/// Data that has been created
/// </summary>
public int Size { get { return size; } }
public PoolBase(HikariConfig config)
{
this.config = config;
this.poolName = config.PoolName;
this.connectionTimeout = config.ConnectionTimeout;
this.validationTimeout =(int) config.ValidationTimeout;
}
/// <summary>
/// 创建池中数据对象
///
/// Create a data object in the pool
/// </summary>
/// <returns></returns>
protected PoolEntry NewPoolEntry()
{
PoolEntry poolEntry= new PoolEntry(NewConnection(), this);
if (poolEntry.IsValidate)
{
//创建无效
// create invalid
poolEntry = null;
}
if(poolEntry!=null)
{
poolEntry.ID=Interlocked.Increment(ref entryid);
Interlocked.Increment(ref size);
}
return poolEntry;
}
/// <summary>
/// 关闭驱动连接
/// 按照设计,只有连接池能够操作驱动连接
///
/// Close the drive connection
/// According to the design, only the connection pool can operate the driver connection
/// </summary>
/// <param name="connection"></param>
protected void CloseConnection(IDbConnection connection)
{
if(connection!=null)
{
connection.Close();
connection.Dispose();
Interlocked.Decrement(ref size);
}
}
/// <summary>
/// 创建驱动的连接
///
/// Create a driver connection
/// </summary>
/// <returns></returns>
private IDbConnection NewConnection()
{
long start = DateTime.Now.Ticks;
IDbConnection connection = null;
try
{
if (string.IsNullOrEmpty(dllPath))
{
if (config.DriverDir == null)
{
throw new Exception("config DriverDir null unexpectedly");
}
if (config.DriverDLLFile == null)
{
throw new Exception("config DriverDLLFile null unexpectedly");
}
dllPath = Path.Combine(config.DriverDir, config.DriverDLLFile);
}
connection = DbProviderFactories.GetConnection(dllPath);
if (connection == null)
{
throw new Exception("DataSource returned null unexpectedly");
}
SetupConnection(connection);
if (connection == null)
{
throw new Exception("Open Connection returned null unexpectedly");
}
if(connection.State!=ConnectionState.Open)
{
connection.Dispose();
connection = null;
return null;
}
return connection;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// 测试连接及设置
///
/// Test connection and settings
/// </summary>
/// <param name="connection"></param>
private void SetupConnection(IDbConnection connection)
{
try
{
connection.ConnectionString = config.ConnectString;
ExecuteSql(connection, config.ConnectionInitSql, true);
}
catch (SQLException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 连接验证
///
/// Connection verification
/// </summary>
/// <param name="connection"></param>
/// <param name="sql"></param>
/// <param name="v"></param>
private void ExecuteSql(IDbConnection connection, string sql, bool v)
{
var task= Task.Factory.StartNew(() =>
{
try
{
connection.Open();
}
catch
{
return;
}
}
);
if(!task.Wait((int)config.ConnectionTimeout))
{
HealthCheckRegistry.Singleton.Add(poolName, this);
//Logger.Singleton.Warn("数据库连接异常,连接池:" + poolName);
Logger.Singleton.Warn("Abnormal database connection, connection pool:" + poolName);
return;
}
if (string.IsNullOrEmpty(sql))
{
return;
}
var cts = new CancellationTokenSource(validationTimeout);
//var cancell = cts.Token.Register(() => Logger.Singleton.Warn("当前连接执行测试超时,数据库异常,SQL:" + sql));
var cancell = cts.Token.Register(() => Logger.Singleton.Warn("The current connection execution test timed out, the database is abnormal, SQL:" + sql));
var result = Task.Factory.StartNew(() =>
{
try
{
IDbCommand command = connection.CreateCommand();
command.CommandText = sql;
int r = command.ExecuteNonQuery();
command.Dispose();
}
catch(Exception ex)
{
connection.Close();
connection.Dispose();
connection = null;
//Logger.Singleton.Error("执行验证SQL失败,连接关闭!原因:"+ex.Message);
Logger.Singleton.Error("The execution of the verification SQL failed and the connection was closed! Reason:" + ex.Message);
}
}, cts.Token
);
cancell.Dispose();
cts.Dispose();
}
public override string ToString()
{
return poolName;
}
#region 数据库主要对象 The main object of the database
public IDbCommand GetDbCommand()
{
return DbProviderFactories.GetDbCommand(dllPath);
}
public IDbDataParameter GetDataParameter()
{
return DbProviderFactories.GetDataParameter(dllPath);
}
public IDbDataAdapter GetDataAdapter()
{
return DbProviderFactories.GetDataAdapter(dllPath);
}
public Type GetBulkCopy()
{
return DbProviderFactories.GetBulkCopyClass(dllPath);
}
#endregion
}
} | 30.681633 | 163 | 0.480245 | [
"MIT"
] | agausachs/Hikari | Hikari/Pool/PoolBase.cs | 7,773 | C# |
using LunaCommon.Message.Types;
namespace LunaCommon.Message.Data.Color
{
public class PlayerColorSetMsgData : PlayerColorBaseMsgData
{
public override PlayerColorMessageType PlayerColorMessageType => PlayerColorMessageType.Set;
public string PlayerName { get; set; }
public string Color { get; set; }
}
} | 31.181818 | 100 | 0.728863 | [
"MIT"
] | Fierce-Cat/LunaMultiPlayer | Common/Message/Data/Color/PlayerColorSetMsgData.cs | 345 | C# |
using Pathfinding;
using UnityEngine;
namespace DefaultNamespace {
public class Hero : MonoBehaviour {
public Pathfinder pathfinder;
public CellController cellController;
private float _moveTimer;
private void Update() {
// Move toward exit door.
var target = cellController.endCell.transform.position;
var targetGridPos = NodeGrid.Instance.grid.WorldToCell(target);
var myGridPos = NodeGrid.Instance.grid.WorldToCell(transform.position);
var path = pathfinder.FindPath(new Vector2Int(myGridPos.x, myGridPos.y), new Vector2Int(targetGridPos.x, targetGridPos.y));
if (path.Count > 0) {
_moveTimer += Time.deltaTime;
if (_moveTimer >= 1) {
_moveTimer = 0;
transform.position = NodeGrid.Instance.grid.CellToWorld(path[0]);
cellController.UpdateAround(NodeGrid.Instance.grid.WorldToCell(transform.position), this);
}
}
}
}
} | 37.034483 | 135 | 0.606145 | [
"MIT"
] | Rover656/FNGJ-2020 | 35/Assets/Scripts/Hero.cs | 1,076 | C# |
namespace MiShotService
{
partial class HelperForm
{
/// <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.SuspendLayout();
//
// HelperForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1, 1);
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "HelperForm";
this.Opacity = 0D;
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "HelperForm";
this.TopMost = true;
this.Load += new System.EventHandler(this.HelperForm_Load);
this.ResumeLayout(false);
}
#endregion
}
} | 32.381818 | 107 | 0.54913 | [
"MIT"
] | athdesk/MiShotService | MiShotService/HelperForm.Designer.cs | 1,783 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ResourceManager.V3.Snippets
{
// [START cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync_flattened_resourceNames]
using Google.Api.Gax;
using Google.Cloud.Iam.V1;
using Google.Cloud.ResourceManager.V3;
public sealed partial class GeneratedOrganizationsClientSnippets
{
/// <summary>Snippet for SetIamPolicy</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void SetIamPolicyResourceNames()
{
// Create client
OrganizationsClient organizationsClient = OrganizationsClient.Create();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
// Make the request
Policy response = organizationsClient.SetIamPolicy(resource);
}
}
// [END cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync_flattened_resourceNames]
}
| 40.627907 | 104 | 0.716657 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.ResourceManager.V3/Google.Cloud.ResourceManager.V3.GeneratedSnippets/OrganizationsClient.SetIamPolicyResourceNamesSnippet.g.cs | 1,747 | C# |
using Llvm.NET.Native;
namespace Llvm.NET.Instructions
{
public class IntToPointer
: Cast
{
internal IntToPointer( LLVMValueRef valueRef )
: base( valueRef )
{
}
}
}
| 16.928571 | 55 | 0.527426 | [
"MIT"
] | m4rs-mt/Llvm.NET | src/Llvm.NET/Instructions/IntToPointer.cs | 226 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SumNum
{
class Program
{
static void Main(string[] args)
{
int count = int.Parse(Console.ReadLine());
int sum = 0;
int maxNum = int.MinValue;
for (int i = 0; i < count; i++)
{
int num = int.Parse(Console.ReadLine());
sum += num;
if (num > maxNum)
{
maxNum = num;
}
}
if (maxNum == sum - maxNum)
{
Console.WriteLine("Yes");
Console.WriteLine($"Sum = {maxNum}");
}
else
{
int difference = Math.Abs(maxNum - (sum - maxNum));
Console.WriteLine("No");
Console.WriteLine($"Diff = {difference}");
}
}
}
}
| 24.097561 | 67 | 0.427126 | [
"MIT"
] | Karamihova/Programming-Basics | LoopsExcercise/SumNum/Program.cs | 990 | C# |
// <auto-generated />
// This file was generated by a T4 template.
// Don't change it directly as your change would get overwritten. Instead, make changes
// to the .tt file (i.e. the T4 template) and save it to regenerate this file.
// Make sure the compiler doesn't complain about missing Xml comments
#pragma warning disable 1591
#region T4MVC
using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using T4MVC;
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class MVC
{
public static CandorMvcApplication.Controllers.AccountController Account = new CandorMvcApplication.Controllers.T4MVC_AccountController();
public static CandorMvcApplication.Controllers.ErrorController Error = new CandorMvcApplication.Controllers.T4MVC_ErrorController();
public static CandorMvcApplication.Controllers.HomeController Home = new CandorMvcApplication.Controllers.T4MVC_HomeController();
public static T4MVC.SharedController Shared = new T4MVC.SharedController();
}
namespace T4MVC
{
}
namespace T4MVC
{
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class Dummy
{
private Dummy() { }
public static Dummy Instance = new Dummy();
}
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
internal partial class T4MVC_System_Web_Mvc_ActionResult : System.Web.Mvc.ActionResult, IT4MVCActionResult
{
public T4MVC_System_Web_Mvc_ActionResult(string area, string controller, string action, string protocol = null): base()
{
this.InitMVCT4Result(area, controller, action, protocol);
}
public override void ExecuteResult(System.Web.Mvc.ControllerContext context) { }
public string Controller { get; set; }
public string Action { get; set; }
public string Protocol { get; set; }
public RouteValueDictionary RouteValueDictionary { get; set; }
}
namespace Links
{
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class Scripts {
private const string URLPATH = "~/Scripts";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
public static readonly string _references_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/_references.min.js") ? Url("_references.min.js") : Url("_references.js");
public static readonly string jquery_1_7_1_intellisense_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery-1.7.1.intellisense.min.js") ? Url("jquery-1.7.1.intellisense.min.js") : Url("jquery-1.7.1.intellisense.js");
public static readonly string jquery_1_7_1_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery-1.7.1.min.js") ? Url("jquery-1.7.1.min.js") : Url("jquery-1.7.1.js");
public static readonly string jquery_1_7_1_min_js = Url("jquery-1.7.1.min.js");
public static readonly string jquery_ui_1_8_20_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery-ui-1.8.20.min.js") ? Url("jquery-ui-1.8.20.min.js") : Url("jquery-ui-1.8.20.js");
public static readonly string jquery_ui_1_8_20_min_js = Url("jquery-ui-1.8.20.min.js");
public static readonly string jquery_unobtrusive_ajax_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.unobtrusive-ajax.min.js") ? Url("jquery.unobtrusive-ajax.min.js") : Url("jquery.unobtrusive-ajax.js");
public static readonly string jquery_unobtrusive_ajax_min_js = Url("jquery.unobtrusive-ajax.min.js");
public static readonly string jquery_validate_vsdoc_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.validate-vsdoc.min.js") ? Url("jquery.validate-vsdoc.min.js") : Url("jquery.validate-vsdoc.js");
public static readonly string jquery_validate_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.validate.min.js") ? Url("jquery.validate.min.js") : Url("jquery.validate.js");
public static readonly string jquery_validate_min_js = Url("jquery.validate.min.js");
public static readonly string jquery_validate_unobtrusive_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.validate.unobtrusive.min.js") ? Url("jquery.validate.unobtrusive.min.js") : Url("jquery.validate.unobtrusive.js");
public static readonly string jquery_validate_unobtrusive_min_js = Url("jquery.validate.unobtrusive.min.js");
public static readonly string knockout_2_1_0_debug_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/knockout-2.1.0.debug.min.js") ? Url("knockout-2.1.0.debug.min.js") : Url("knockout-2.1.0.debug.js");
public static readonly string knockout_2_1_0_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/knockout-2.1.0.min.js") ? Url("knockout-2.1.0.min.js") : Url("knockout-2.1.0.js");
public static readonly string modernizr_2_5_3_js = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/modernizr-2.5.3.min.js") ? Url("modernizr-2.5.3.min.js") : Url("modernizr-2.5.3.js");
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class Content {
private const string URLPATH = "~/Content";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
public static readonly string Site_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/Site.min.css") ? Url("Site.min.css") : Url("Site.css");
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class themes {
private const string URLPATH = "~/Content/themes";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class @base {
private const string URLPATH = "~/Content/themes/base";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class images {
private const string URLPATH = "~/Content/themes/base/images";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
public static readonly string ui_bg_flat_0_aaaaaa_40x100_png = Url("ui-bg_flat_0_aaaaaa_40x100.png");
public static readonly string ui_bg_flat_75_ffffff_40x100_png = Url("ui-bg_flat_75_ffffff_40x100.png");
public static readonly string ui_bg_glass_55_fbf9ee_1x400_png = Url("ui-bg_glass_55_fbf9ee_1x400.png");
public static readonly string ui_bg_glass_65_ffffff_1x400_png = Url("ui-bg_glass_65_ffffff_1x400.png");
public static readonly string ui_bg_glass_75_dadada_1x400_png = Url("ui-bg_glass_75_dadada_1x400.png");
public static readonly string ui_bg_glass_75_e6e6e6_1x400_png = Url("ui-bg_glass_75_e6e6e6_1x400.png");
public static readonly string ui_bg_glass_95_fef1ec_1x400_png = Url("ui-bg_glass_95_fef1ec_1x400.png");
public static readonly string ui_bg_highlight_soft_75_cccccc_1x100_png = Url("ui-bg_highlight-soft_75_cccccc_1x100.png");
public static readonly string ui_icons_222222_256x240_png = Url("ui-icons_222222_256x240.png");
public static readonly string ui_icons_2e83ff_256x240_png = Url("ui-icons_2e83ff_256x240.png");
public static readonly string ui_icons_454545_256x240_png = Url("ui-icons_454545_256x240.png");
public static readonly string ui_icons_888888_256x240_png = Url("ui-icons_888888_256x240.png");
public static readonly string ui_icons_cd0a0a_256x240_png = Url("ui-icons_cd0a0a_256x240.png");
}
public static readonly string jquery_ui_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery-ui.min.css") ? Url("jquery-ui.min.css") : Url("jquery-ui.css");
public static readonly string jquery_ui_accordion_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.accordion.min.css") ? Url("jquery.ui.accordion.min.css") : Url("jquery.ui.accordion.css");
public static readonly string jquery_ui_all_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.all.min.css") ? Url("jquery.ui.all.min.css") : Url("jquery.ui.all.css");
public static readonly string jquery_ui_autocomplete_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.autocomplete.min.css") ? Url("jquery.ui.autocomplete.min.css") : Url("jquery.ui.autocomplete.css");
public static readonly string jquery_ui_base_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.base.min.css") ? Url("jquery.ui.base.min.css") : Url("jquery.ui.base.css");
public static readonly string jquery_ui_button_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.button.min.css") ? Url("jquery.ui.button.min.css") : Url("jquery.ui.button.css");
public static readonly string jquery_ui_core_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.core.min.css") ? Url("jquery.ui.core.min.css") : Url("jquery.ui.core.css");
public static readonly string jquery_ui_datepicker_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.datepicker.min.css") ? Url("jquery.ui.datepicker.min.css") : Url("jquery.ui.datepicker.css");
public static readonly string jquery_ui_dialog_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.dialog.min.css") ? Url("jquery.ui.dialog.min.css") : Url("jquery.ui.dialog.css");
public static readonly string jquery_ui_progressbar_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.progressbar.min.css") ? Url("jquery.ui.progressbar.min.css") : Url("jquery.ui.progressbar.css");
public static readonly string jquery_ui_resizable_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.resizable.min.css") ? Url("jquery.ui.resizable.min.css") : Url("jquery.ui.resizable.css");
public static readonly string jquery_ui_selectable_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.selectable.min.css") ? Url("jquery.ui.selectable.min.css") : Url("jquery.ui.selectable.css");
public static readonly string jquery_ui_slider_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.slider.min.css") ? Url("jquery.ui.slider.min.css") : Url("jquery.ui.slider.css");
public static readonly string jquery_ui_tabs_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.tabs.min.css") ? Url("jquery.ui.tabs.min.css") : Url("jquery.ui.tabs.css");
public static readonly string jquery_ui_theme_css = T4MVCHelpers.IsProduction() && T4Extensions.FileExists(URLPATH + "/jquery.ui.theme.min.css") ? Url("jquery.ui.theme.min.css") : Url("jquery.ui.theme.css");
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class minified {
private const string URLPATH = "~/Content/themes/base/minified";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class images {
private const string URLPATH = "~/Content/themes/base/minified/images";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
public static readonly string ui_bg_flat_0_aaaaaa_40x100_png = Url("ui-bg_flat_0_aaaaaa_40x100.png");
public static readonly string ui_bg_flat_75_ffffff_40x100_png = Url("ui-bg_flat_75_ffffff_40x100.png");
public static readonly string ui_bg_glass_55_fbf9ee_1x400_png = Url("ui-bg_glass_55_fbf9ee_1x400.png");
public static readonly string ui_bg_glass_65_ffffff_1x400_png = Url("ui-bg_glass_65_ffffff_1x400.png");
public static readonly string ui_bg_glass_75_dadada_1x400_png = Url("ui-bg_glass_75_dadada_1x400.png");
public static readonly string ui_bg_glass_75_e6e6e6_1x400_png = Url("ui-bg_glass_75_e6e6e6_1x400.png");
public static readonly string ui_bg_glass_95_fef1ec_1x400_png = Url("ui-bg_glass_95_fef1ec_1x400.png");
public static readonly string ui_bg_highlight_soft_75_cccccc_1x100_png = Url("ui-bg_highlight-soft_75_cccccc_1x100.png");
public static readonly string ui_icons_222222_256x240_png = Url("ui-icons_222222_256x240.png");
public static readonly string ui_icons_2e83ff_256x240_png = Url("ui-icons_2e83ff_256x240.png");
public static readonly string ui_icons_454545_256x240_png = Url("ui-icons_454545_256x240.png");
public static readonly string ui_icons_888888_256x240_png = Url("ui-icons_888888_256x240.png");
public static readonly string ui_icons_cd0a0a_256x240_png = Url("ui-icons_cd0a0a_256x240.png");
}
public static readonly string jquery_ui_min_css = Url("jquery-ui.min.css");
public static readonly string jquery_ui_accordion_min_css = Url("jquery.ui.accordion.min.css");
public static readonly string jquery_ui_autocomplete_min_css = Url("jquery.ui.autocomplete.min.css");
public static readonly string jquery_ui_button_min_css = Url("jquery.ui.button.min.css");
public static readonly string jquery_ui_core_min_css = Url("jquery.ui.core.min.css");
public static readonly string jquery_ui_datepicker_min_css = Url("jquery.ui.datepicker.min.css");
public static readonly string jquery_ui_dialog_min_css = Url("jquery.ui.dialog.min.css");
public static readonly string jquery_ui_progressbar_min_css = Url("jquery.ui.progressbar.min.css");
public static readonly string jquery_ui_resizable_min_css = Url("jquery.ui.resizable.min.css");
public static readonly string jquery_ui_selectable_min_css = Url("jquery.ui.selectable.min.css");
public static readonly string jquery_ui_slider_min_css = Url("jquery.ui.slider.min.css");
public static readonly string jquery_ui_tabs_min_css = Url("jquery.ui.tabs.min.css");
public static readonly string jquery_ui_theme_min_css = Url("jquery.ui.theme.min.css");
}
}
}
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static partial class Bundles
{
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static partial class Scripts {}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static partial class Styles {}
}
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
internal static class T4MVCHelpers {
// You can change the ProcessVirtualPath method to modify the path that gets returned to the client.
// e.g. you can prepend a domain, or append a query string:
// return "http://localhost" + path + "?foo=bar";
private static string ProcessVirtualPathDefault(string virtualPath) {
// The path that comes in starts with ~/ and must first be made absolute
string path = VirtualPathUtility.ToAbsolute(virtualPath);
// Add your own modifications here before returning the path
return path;
}
// Calling ProcessVirtualPath through delegate to allow it to be replaced for unit testing
public static Func<string, string> ProcessVirtualPath = ProcessVirtualPathDefault;
// Calling T4Extension.TimestampString through delegate to allow it to be replaced for unit testing and other purposes
public static Func<string, string> TimestampString = System.Web.Mvc.T4Extensions.TimestampString;
// Logic to determine if the app is running in production or dev environment
public static bool IsProduction() {
return (HttpContext.Current != null && !HttpContext.Current.IsDebuggingEnabled);
}
}
#endregion T4MVC
#pragma warning restore 1591
| 74.674797 | 259 | 0.68552 | [
"MIT"
] | michael-lang/candor-common | Candor.Web.Mvc.Bootstrap/T4MVC.cs | 18,372 | C# |
using System.Collections.Generic;
namespace SST.Domain.Entities
{
public class Lector
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string AcademicStatus { get; set; }
public string UserRef { get; set; }
public User User { get; set; }
public ICollection<Subject> Subjects { get; private set; }
}
}
| 20 | 66 | 0.6 | [
"Apache-2.0"
] | DthRazak/Student-Success | src/SST.Domain/Entities/Lector.cs | 442 | C# |
using Mono.Cecil;
using Mono.Cecil.Cil;
using RedArrow.Argo.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RedArrow.Argo
{
public partial class ModuleWeaver
{
private void AddInitialize(ModelWeavingContext context)
{
// public void __argo__generated_Initialize(IResourceIdentifier resource, IModelSession session)
// {
// this.__argo__generated_Resource = resource;
// this.__argo__generated_session = session;
// this.__argo__generated_includePath = "model.include.path";
// this.Id = __argo__generated_session.GetId<TModel>();
// }
var initialize = new MethodDefinition(
"__argo__generated_Initialize",
MethodAttributes.Public,
TypeSystem.Void);
initialize.Parameters.Add(
new ParameterDefinition(
"resource",
ParameterAttributes.None,
context.ImportReference(_resourceIdentifierTypeDef)));
initialize.Parameters.Add(
new ParameterDefinition(
"session",
ParameterAttributes.None,
context.ImportReference(_sessionTypeDef)));
var idBackingField = context
.IdPropDef
?.GetMethod
?.Body
?.Instructions
?.SingleOrDefault(x => x.OpCode == OpCodes.Ldfld)
?.Operand as FieldReference;
// supply generic type arguments to template
var sessionGetId = _session_GetId.MakeGenericMethod(context.ModelTypeDef);
var proc = initialize.Body.GetILProcessor();
proc.Emit(OpCodes.Ldarg_0); // load 'this' onto stack
proc.Emit(OpCodes.Ldarg_1); // load arg 'resource' onto stack
proc.Emit(OpCodes.Callvirt, context.ResourcePropDef.SetMethod);
proc.Emit(OpCodes.Ldarg_0); // load 'this' onto stack
proc.Emit(OpCodes.Ldarg_2); // load arg 'session' onto stack
proc.Emit(OpCodes.Stfld, context.SessionField); // this.__argo__generated_session = session;
proc.Emit(OpCodes.Ldarg_0); // load 'this' onto stack
proc.Emit(OpCodes.Ldarg_0); // load 'this' onto stack
proc.Emit(OpCodes.Ldfld, context.SessionField); // load this.__argo__generated_session
proc.Emit(OpCodes.Ldarg_0); // load 'this' onto stack
proc.Emit(OpCodes.Callvirt, context.ImportReference(sessionGetId));
proc.Emit(OpCodes.Stfld, idBackingField); // this.<Id>K_backingField = this.__argo__generated_session.GetId<TModel>();
// this._attrBackingField = this.__argo__generated_session.GetAttribute
WeaveAttributeFieldInitializers(context, proc, context.MappedAttributes);
// this._attrBackingField = this.__argo__generated_session.GetMeta
WeaveMetaFieldInitializers(context, proc, context.MappedMeta);
proc.Emit(OpCodes.Ret); // return
context.Methods.Add(initialize);
}
private void WeaveAttributeFieldInitializers(
ModelWeavingContext context,
ILProcessor proc,
IEnumerable<PropertyDefinition> attrPropDefs)
{
foreach (var attrPropDef in attrPropDefs)
{
// supply generic type arguments to template
var sessionGetAttr = _session_GetAttribute
.MakeGenericMethod(context.ModelTypeDef, attrPropDef.PropertyType);
var backingField = attrPropDef.BackingField();
if (backingField == null)
{
throw new Exception($"Failed to load backing field for property {attrPropDef?.FullName}");
}
var propAttr = attrPropDef.CustomAttributes.GetAttribute(Constants.Attributes.Property);
var attrName = propAttr.ConstructorArguments
.Select(x => x.Value as string)
.SingleOrDefault() ?? attrPropDef.Name.Camelize();
proc.Emit(OpCodes.Ldarg_0);
proc.Emit(OpCodes.Ldarg_0); // load 'this' onto stack to reference session field
proc.Emit(OpCodes.Ldfld, context.SessionField); // load __argo__generated_session field from 'this'
proc.Emit(OpCodes.Ldarg_0); // load 'this'
proc.Emit(OpCodes.Ldstr, attrName); // load attrName onto stack
proc.Emit(OpCodes.Callvirt, context.ImportReference(
sessionGetAttr,
attrPropDef.PropertyType.IsGenericParameter
? context.ModelTypeDef
: null)); // invoke session.GetAttribute(..)
proc.Emit(OpCodes.Stfld, backingField); // store return value in 'this'.<backing field>
}
}
private void WeaveMetaFieldInitializers(
ModelWeavingContext context,
ILProcessor proc,
IEnumerable<PropertyDefinition> metaPropDefs)
{
foreach (var def in metaPropDefs)
{
// supply generic type arguments to template
var sessionGetAttr = _session_GetMeta.MakeGenericMethod(context.ModelTypeDef, def.PropertyType);
var backingField = def.BackingField();
if (backingField == null)
{
throw new Exception($"Failed to load backing field for property {def?.FullName}");
}
var propAttr = def.CustomAttributes.GetAttribute(Constants.Attributes.Meta);
var metaName = propAttr.ConstructorArguments
.Select(x => x.Value as string)
.SingleOrDefault() ?? def.Name.Camelize();
proc.Emit(OpCodes.Ldarg_0);
proc.Emit(OpCodes.Ldarg_0); // load 'this' onto stack to reference session field
proc.Emit(OpCodes.Ldfld, context.SessionField); // load __argo__generated_session field from 'this'
proc.Emit(OpCodes.Ldarg_0); // load 'this'
proc.Emit(OpCodes.Ldstr, metaName); // load attrName onto stack
proc.Emit(OpCodes.Callvirt, context.ImportReference(
sessionGetAttr,
def.PropertyType.IsGenericParameter
? context.ModelTypeDef
: null)); // invoke session.GetMeta(..)
proc.Emit(OpCodes.Stfld, backingField); // store return value in 'this'.<backing field>
}
}
}
}
| 44.522876 | 130 | 0.587786 | [
"MIT"
] | redarrowlabs/Argo | src/RedArrow.Argo.Fody.Shared/InitializeWeaver.cs | 6,814 | C# |
using Microsoft.WindowsAzure.Storage.Table;
using Nethereum.LogProcessing.Dynamic.Configuration;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Nethereum.LogProcessing.Dynamic.Db.Azure.Entities
{
public class EventSubscriptionStateEntity : TableEntity, IEventSubscriptionStateDto
{
public long Id
{
get => this.RowKeyToLong();
set => RowKey = value.ToString();
}
public long EventSubscriptionId
{
get => this.PartionKeyToLong();
set => PartitionKey = value.ToString();
}
public string ValuesAsJson
{
get { return JsonConvert.SerializeObject(Values);}
set { Values = JsonConvert.DeserializeObject<Dictionary<string, object>>(value); }
}
public Dictionary<string, object> Values {get;set; } = new Dictionary<string, object>();
}
}
| 28.78125 | 96 | 0.639522 | [
"MIT"
] | Dave-Whiffin/Nethereum.BlockchainProcessing | src/Nethereum.LogProcessing.Dynamic.Db.Azure/Entities/EventSubscriptionStateEntity.cs | 923 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Razor.Language;
namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X
{
/// <summary>
/// A <see cref="RazorTemplateEngine"/> for Mvc Razor views.
/// </summary>
public class MvcRazorTemplateEngine : RazorTemplateEngine
{
/// <summary>
/// Initializes a new instance of <see cref="MvcRazorTemplateEngine"/>.
/// </summary>
/// <param name="engine">The <see cref="RazorEngine"/>.</param>
/// <param name="project">The <see cref="RazorProject"/>.</param>
public MvcRazorTemplateEngine(
RazorEngine engine,
RazorProject project)
: base(engine, project)
{
Options.ImportsFileName = "_ViewImports.cshtml";
Options.DefaultImports = GetDefaultImports();
}
public override RazorCodeDocument CreateCodeDocument(RazorProjectItem projectItem)
{
return base.CreateCodeDocument(projectItem);
}
// Internal for testing.
internal static RazorSourceDocument GetDefaultImports()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.WriteLine("@using System");
writer.WriteLine("@using System.Collections.Generic");
writer.WriteLine("@using System.Linq");
writer.WriteLine("@using System.Threading.Tasks");
writer.WriteLine("@using Microsoft.AspNetCore.Mvc");
writer.WriteLine("@using Microsoft.AspNetCore.Mvc.Rendering");
writer.WriteLine("@using Microsoft.AspNetCore.Mvc.ViewFeatures");
writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<TModel> Html");
writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json");
writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component");
writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.IUrlHelper Url");
writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider");
writer.WriteLine("@addTagHelper Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper, Microsoft.AspNetCore.Mvc.Razor");
writer.Flush();
stream.Position = 0;
return RazorSourceDocument.ReadFrom(stream, fileName: null, encoding: Encoding.UTF8);
}
}
}
}
| 46.52459 | 147 | 0.643058 | [
"Apache-2.0"
] | AmadeusW/Razor | src/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/MvcRazorTemplateEngine.cs | 2,840 | C# |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Kodestruct.Loads.ASCE7.Lateral.Wind
{
/// <summary>
/// Interaction logic for Loads.ASCE7v10.Lateral.Wind.EnclosureTypeView.xaml
/// </summary>
public partial class EnclosureTypeView: UserControl
{
public EnclosureTypeView()
{
InitializeComponent();
}
}
}
| 29.108696 | 80 | 0.743092 | [
"Apache-2.0"
] | Kodestruct/Kodestruct.Dynamo | Kodestruct.Dynamo.UI/Views/Loads/ASCE7/Wind/EnclosureTypeView.xaml.cs | 1,339 | C# |
using System;
using Microsoft.Xna.Framework;
namespace Atestat2._0.Entities
{
public class Player : Actor
{
public Player(Color foreground, Color background) : base (foreground,background, '@')
{
Attack = 10;
AttackChance = 40;
Defense = 5;
DefenseChance = 20;
Gold = 0;
Name = "Homer";
}
}
}
| 21.210526 | 93 | 0.523573 | [
"MIT"
] | CallMeCamus/Into-the-dungeon | Atestat2.0/Atestat2.0/Entities/Player.cs | 405 | C# |
namespace EasyCaching.PerformanceTests
{
using BenchmarkDotNet.Attributes;
using EasyCaching.Core;
using EasyCaching.Core.Serialization;
using EasyCaching.Serialization.Json;
using EasyCaching.Serialization.MessagePack;
using EasyCaching.Serialization.Protobuf;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
[MemoryDiagnoser]
[AllStatisticsColumn]
public abstract class SerializerBenchmark
{
private DefaultJsonSerializer _json = new DefaultJsonSerializer(new OptionsWrapper<EasyCachingJsonSerializerOptions>(new EasyCachingJsonSerializerOptions()));
private DefaultMessagePackSerializer _messagepack = new DefaultMessagePackSerializer();
private DefaultProtobufSerializer _protobuf = new DefaultProtobufSerializer();
private DefaultBinaryFormatterSerializer _binary = new DefaultBinaryFormatterSerializer();
protected MyPoco _single;
protected List<MyPoco> _list;
private int _count;
[GlobalSetup]
public void Setup()
{
_count = 1000;
_single = new MyPoco { Id = 1, Name = "123" };
var items = new List<MyPoco>();
for (var iter = 0; iter < _count; iter++)
{
items.Add(new MyPoco() { Id = iter, Name = $"name-{iter.ToString()}" });
}
_list = items;
}
[Benchmark]
public void BinaryFormatter()
{
Exec(_binary);
}
[Benchmark]
public void Json()
{
Exec(_json);
}
[Benchmark]
public void MessagePack()
{
Exec(_messagepack);
}
[Benchmark]
public void Protobuf()
{
Exec(_protobuf);
}
protected abstract void Exec(IEasyCachingSerializer serializer);
}
public class SerializeSingleObject2BytesBenchmark : SerializerBenchmark
{
protected override void Exec(IEasyCachingSerializer serializer)
{
var data = serializer.Serialize(_single);
var result = serializer.Deserialize<MyPoco>(data);
if (result == null)
{
throw new Exception();
}
}
}
public class SerializeMultiObject2BytesBenchmark : SerializerBenchmark
{
protected override void Exec(IEasyCachingSerializer serializer)
{
var data = serializer.Serialize(_list);
var result = serializer.Deserialize<List<MyPoco>>(data);
if (result == null)
{
throw new Exception();
}
}
}
public class SerializerSingleObject2ArraySegmentBenchmark : SerializerBenchmark
{
protected override void Exec(IEasyCachingSerializer serializer)
{
var data = serializer.SerializeObject(_single);
var result = serializer.DeserializeObject(data);
if (result == null)
{
throw new Exception();
}
}
}
public class SerializerMultiObject2ArraySegmentBenchmark : SerializerBenchmark
{
protected override void Exec(IEasyCachingSerializer serializer)
{
var data = serializer.SerializeObject(_list);
var result = serializer.DeserializeObject(data);
if (result == null)
{
throw new Exception();
}
}
}
}
| 29.475 | 166 | 0.596551 | [
"MIT"
] | appman-agm/EasyCaching | test/EasyCaching.PerformanceTests/SerializerBenchmark.cs | 3,539 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Slack.Api.CSharp.WebApi.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Channel Object
/// </summary>
public partial class ObjsChannel
{
/// <summary>
/// Initializes a new instance of the ObjsChannel class.
/// </summary>
public ObjsChannel()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ObjsChannel class.
/// </summary>
/// <param name="unlinked">Field to determine whether a channel has
/// ever been shared/disconnected in the past</param>
public ObjsChannel(int created, string creator, string id, bool isChannel, bool isMpim, bool isOrgShared, bool isPrivate, bool isShared, IList<string> members, string name, string nameNormalized, ObjsChannelPurpose purpose, ObjsChannelTopic topic, string acceptedUser = default(string), bool? isArchived = default(bool?), bool? isGeneral = default(bool?), bool? isMember = default(bool?), int? isMoved = default(int?), bool? isPendingExtShared = default(bool?), bool? isReadOnly = default(bool?), string lastRead = default(string), object latest = default(object), int? numMembers = default(int?), IList<string> pendingShared = default(IList<string>), IList<string> previousNames = default(IList<string>), int? priority = default(int?), int? unlinked = default(int?), int? unreadCount = default(int?), int? unreadCountDisplay = default(int?))
{
AcceptedUser = acceptedUser;
Created = created;
Creator = creator;
Id = id;
IsArchived = isArchived;
IsChannel = isChannel;
IsGeneral = isGeneral;
IsMember = isMember;
IsMoved = isMoved;
IsMpim = isMpim;
IsOrgShared = isOrgShared;
IsPendingExtShared = isPendingExtShared;
IsPrivate = isPrivate;
IsReadOnly = isReadOnly;
IsShared = isShared;
LastRead = lastRead;
Latest = latest;
Members = members;
Name = name;
NameNormalized = nameNormalized;
NumMembers = numMembers;
PendingShared = pendingShared;
PreviousNames = previousNames;
Priority = priority;
Purpose = purpose;
Topic = topic;
Unlinked = unlinked;
UnreadCount = unreadCount;
UnreadCountDisplay = unreadCountDisplay;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "accepted_user")]
public string AcceptedUser { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "created")]
public int Created { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "creator")]
public string Creator { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_archived")]
public bool? IsArchived { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_channel")]
public bool IsChannel { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_general")]
public bool? IsGeneral { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_member")]
public bool? IsMember { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_moved")]
public int? IsMoved { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_mpim")]
public bool IsMpim { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_org_shared")]
public bool IsOrgShared { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_pending_ext_shared")]
public bool? IsPendingExtShared { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_private")]
public bool IsPrivate { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_read_only")]
public bool? IsReadOnly { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_shared")]
public bool IsShared { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "last_read")]
public string LastRead { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "latest")]
public object Latest { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "members")]
public IList<string> Members { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "name_normalized")]
public string NameNormalized { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "num_members")]
public int? NumMembers { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "pending_shared")]
public IList<string> PendingShared { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "previous_names")]
public IList<string> PreviousNames { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "purpose")]
public ObjsChannelPurpose Purpose { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "topic")]
public ObjsChannelTopic Topic { get; set; }
/// <summary>
/// Gets or sets field to determine whether a channel has ever been
/// shared/disconnected in the past
/// </summary>
[JsonProperty(PropertyName = "unlinked")]
public int? Unlinked { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "unread_count")]
public int? UnreadCount { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "unread_count_display")]
public int? UnreadCountDisplay { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Creator == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Creator");
}
if (Id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Id");
}
if (Members == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Members");
}
if (Name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Name");
}
if (NameNormalized == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "NameNormalized");
}
if (Purpose == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Purpose");
}
if (Topic == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Topic");
}
if (Members != null)
{
if (Members.Count < 0)
{
throw new ValidationException(ValidationRules.MinItems, "Members", 0);
}
if (Members.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(Members)))
{
throw new ValidationException(ValidationRules.UniqueItems, "Members");
}
}
if (PendingShared != null)
{
if (PendingShared.Count < 0)
{
throw new ValidationException(ValidationRules.MinItems, "PendingShared", 0);
}
if (PendingShared.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(PendingShared)))
{
throw new ValidationException(ValidationRules.UniqueItems, "PendingShared");
}
}
if (PreviousNames != null)
{
if (PreviousNames.Count < 0)
{
throw new ValidationException(ValidationRules.MinItems, "PreviousNames", 0);
}
if (PreviousNames.Count != System.Linq.Enumerable.Count(System.Linq.Enumerable.Distinct(PreviousNames)))
{
throw new ValidationException(ValidationRules.UniqueItems, "PreviousNames");
}
}
if (Purpose != null)
{
Purpose.Validate();
}
if (Topic != null)
{
Topic.Validate();
}
}
}
}
| 34.341137 | 850 | 0.537787 | [
"MIT"
] | JamesMarcogliese/slack-api-csharp | src/Slack.Api.CSharp/WebApi/Models/ObjsChannel.cs | 10,268 | C# |
using Unity.Collections;
using CareBoo.Burst.Delegates;
using Unity.Jobs;
namespace CareBoo.Blinq
{
public static partial class Sequence
{
public static int Count<T, TPredicate>(
this in NativeArray<T> source,
ValueFunc<T, bool>.Struct<TPredicate> predicate
)
where T : struct
where TPredicate : struct, IFunc<T, bool>
{
var count = 0;
for (var i = 0; i < source.Length; i++)
if (predicate.Invoke(source[i]))
count++;
return count;
}
public struct ArrayCountFunc<T, TPredicate>
: IFunc<NativeArray<T>, int>
where T : struct
where TPredicate : struct, IFunc<T, bool>
{
public ValueFunc<T, bool>.Struct<TPredicate> Predicate;
public int Invoke(NativeArray<T> arg0)
{
return arg0.Count(Predicate);
}
}
public static ValueFunc<NativeArray<T>, int>.Struct<ArrayCountFunc<T, TPredicate>>
CountAsFunc<T, TPredicate>(
this in NativeArray<T> source,
ValueFunc<T, bool>.Struct<TPredicate> predicate
)
where T : struct
where TPredicate : struct, IFunc<T, bool>
{
var funcStruct = new ArrayCountFunc<T, TPredicate> { Predicate = predicate };
return ValueFunc<NativeArray<T>, int>.New<ArrayCountFunc<T, TPredicate>>(funcStruct);
}
public static int RunCount<T, TPredicate>(
this in NativeArray<T> source,
ValueFunc<T, bool>.Struct<TPredicate> predicate
)
where T : struct
where TPredicate : struct, IFunc<T, bool>
{
var func = source.CountAsFunc(predicate);
return source.Run(func);
}
public static JobHandle<int> ScheduleCount<T, TPredicate>(
this in NativeArray<T> source,
ValueFunc<T, bool>.Struct<TPredicate> predicate
)
where T : struct
where TPredicate : struct, IFunc<T, bool>
{
var func = source.CountAsFunc(predicate);
return source.Schedule(func);
}
public static JobHandle ScheduleCount<T, TPredicate>(
this in NativeArray<T> source,
ref NativeArray<int> output,
ValueFunc<T, bool>.Struct<TPredicate> predicate
)
where T : struct
where TPredicate : struct, IFunc<T, bool>
{
var func = source.CountAsFunc(predicate);
return source.Schedule(func, ref output);
}
public static int Count<T>(this in NativeArray<T> source)
where T : struct
{
return source.Length;
}
public struct ArrayCountFunc<T>
: IFunc<NativeArray<T>, int>
where T : struct
{
public int Invoke(NativeArray<T> arg0)
{
return arg0.Count();
}
}
public static ValueFunc<NativeArray<T>, int>.Struct<ArrayCountFunc<T>>
CountAsFunc<T>(
this in NativeArray<T> source
)
where T : struct
{
return ValueFunc<NativeArray<T>, int>.New<ArrayCountFunc<T>>();
}
public static int RunCount<T>(
this in NativeArray<T> source
)
where T : struct
{
var func = source.CountAsFunc();
return source.Run(func);
}
public static JobHandle<int> ScheduleCount<T>(
this in NativeArray<T> source
)
where T : struct
{
var func = source.CountAsFunc();
return source.Schedule(func);
}
public static JobHandle ScheduleCount<T>(
this in NativeArray<T> source,
ref NativeArray<int> output
)
where T : struct
{
var func = source.CountAsFunc();
return source.Schedule(func, ref output);
}
}
}
| 31.632353 | 98 | 0.51046 | [
"MIT"
] | CareBoo/BLinq | Packages/com.careboo.blinq/CareBoo.Blinq/NativeArray/NativeArray.Count.cs | 4,304 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using BookLovers.Base.Domain.Events;
namespace BookLovers.Base.Infrastructure.Events.DomainEvents
{
public interface IDomainEventPublisher
{
Task PublishAsync<TEvent>(TEvent @event)
where TEvent : IEvent;
Task PublishAsync<TEvent>(IEnumerable<TEvent> events)
where TEvent : IEvent;
}
} | 26.933333 | 61 | 0.712871 | [
"MIT"
] | kamilk08/BookLoversApi | BookLovers.Base.Infrastructure/Events/DomainEvents/IDomainEventPublisher.cs | 406 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.KinesisFirehose;
using Amazon.KinesisFirehose.Model;
namespace Amazon.PowerShell.Cmdlets.KINF
{
/// <summary>
/// Enables server-side encryption (SSE) for the delivery stream.
///
///
/// <para>
/// This operation is asynchronous. It returns immediately. When you invoke it, Kinesis
/// Data Firehose first sets the encryption status of the stream to <code>ENABLING</code>,
/// and then to <code>ENABLED</code>. The encryption status of a delivery stream is the
/// <code>Status</code> property in <a>DeliveryStreamEncryptionConfiguration</a>. If the
/// operation fails, the encryption status changes to <code>ENABLING_FAILED</code>. You
/// can continue to read and write data to your delivery stream while the encryption status
/// is <code>ENABLING</code>, but the data is not encrypted. It can take up to 5 seconds
/// after the encryption status changes to <code>ENABLED</code> before all records written
/// to the delivery stream are encrypted. To find out whether a record or a batch of records
/// was encrypted, check the response elements <a>PutRecordOutput$Encrypted</a> and <a>PutRecordBatchOutput$Encrypted</a>,
/// respectively.
/// </para><para>
/// To check the encryption status of a delivery stream, use <a>DescribeDeliveryStream</a>.
/// </para><para>
/// Even if encryption is currently enabled for a delivery stream, you can still invoke
/// this operation on it to change the ARN of the CMK or both its type and ARN. If you
/// invoke this method to change the CMK, and the old CMK is of type <code>CUSTOMER_MANAGED_CMK</code>,
/// Kinesis Data Firehose schedules the grant it had on the old CMK for retirement. If
/// the new CMK is of type <code>CUSTOMER_MANAGED_CMK</code>, Kinesis Data Firehose creates
/// a grant that enables it to use the new CMK to encrypt and decrypt data and to manage
/// the grant.
/// </para><para>
/// If a delivery stream already has encryption enabled and then you invoke this operation
/// to change the ARN of the CMK or both its type and ARN and you get <code>ENABLING_FAILED</code>,
/// this only means that the attempt to change the CMK failed. In this case, encryption
/// remains enabled with the old CMK.
/// </para><para>
/// If the encryption status of your delivery stream is <code>ENABLING_FAILED</code>,
/// you can invoke this operation again with a valid CMK. The CMK must be enabled and
/// the key policy mustn't explicitly deny the permission for Kinesis Data Firehose to
/// invoke KMS encrypt and decrypt operations.
/// </para><para>
/// You can enable SSE for a delivery stream only if it's a delivery stream that uses
/// <code>DirectPut</code> as its source.
/// </para><para>
/// The <code>StartDeliveryStreamEncryption</code> and <code>StopDeliveryStreamEncryption</code>
/// operations have a combined limit of 25 calls per delivery stream per 24 hours. For
/// example, you reach the limit if you call <code>StartDeliveryStreamEncryption</code>
/// 13 times and <code>StopDeliveryStreamEncryption</code> 12 times for the same delivery
/// stream in a 24-hour period.
/// </para>
/// </summary>
[Cmdlet("Start", "KINFDeliveryStreamEncryption", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("None")]
[AWSCmdlet("Calls the Amazon Kinesis Firehose StartDeliveryStreamEncryption API operation.", Operation = new[] {"StartDeliveryStreamEncryption"}, SelectReturnType = typeof(Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionResponse))]
[AWSCmdletOutput("None or Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionResponse",
"This cmdlet does not generate any output." +
"The service response (type Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class StartKINFDeliveryStreamEncryptionCmdlet : AmazonKinesisFirehoseClientCmdlet, IExecutor
{
#region Parameter DeliveryStreamName
/// <summary>
/// <para>
/// <para>The name of the delivery stream for which you want to enable server-side encryption
/// (SSE).</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String DeliveryStreamName { get; set; }
#endregion
#region Parameter DeliveryStreamEncryptionConfigurationInput_KeyARN
/// <summary>
/// <para>
/// <para>If you set <code>KeyType</code> to <code>CUSTOMER_MANAGED_CMK</code>, you must specify
/// the Amazon Resource Name (ARN) of the CMK. If you set <code>KeyType</code> to <code>AWS_OWNED_CMK</code>,
/// Kinesis Data Firehose uses a service-account CMK.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String DeliveryStreamEncryptionConfigurationInput_KeyARN { get; set; }
#endregion
#region Parameter DeliveryStreamEncryptionConfigurationInput_KeyType
/// <summary>
/// <para>
/// <para>Indicates the type of customer master key (CMK) to use for encryption. The default
/// setting is <code>AWS_OWNED_CMK</code>. For more information about CMKs, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys">Customer
/// Master Keys (CMKs)</a>. When you invoke <a>CreateDeliveryStream</a> or <a>StartDeliveryStreamEncryption</a>
/// with <code>KeyType</code> set to CUSTOMER_MANAGED_CMK, Kinesis Data Firehose invokes
/// the Amazon KMS operation <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateGrant.html">CreateGrant</a>
/// to create a grant that allows the Kinesis Data Firehose service to use the customer
/// managed CMK to perform encryption and decryption. Kinesis Data Firehose manages that
/// grant. </para><para>When you invoke <a>StartDeliveryStreamEncryption</a> to change the CMK for a delivery
/// stream that is encrypted with a customer managed CMK, Kinesis Data Firehose schedules
/// the grant it had on the old CMK for retirement.</para><para>You can use a CMK of type CUSTOMER_MANAGED_CMK to encrypt up to 500 delivery streams.
/// If a <a>CreateDeliveryStream</a> or <a>StartDeliveryStreamEncryption</a> operation
/// exceeds this limit, Kinesis Data Firehose throws a <code>LimitExceededException</code>.
/// </para><important><para>To encrypt your delivery stream, use symmetric CMKs. Kinesis Data Firehose doesn't
/// support asymmetric CMKs. For information about symmetric and asymmetric CMKs, see
/// <a href="https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-concepts.html">About
/// Symmetric and Asymmetric CMKs</a> in the AWS Key Management Service developer guide.</para></important>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.KinesisFirehose.KeyType")]
public Amazon.KinesisFirehose.KeyType DeliveryStreamEncryptionConfigurationInput_KeyType { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionResponse).
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the DeliveryStreamName parameter.
/// The -PassThru parameter is deprecated, use -Select '^DeliveryStreamName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^DeliveryStreamName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.DeliveryStreamName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Start-KINFDeliveryStreamEncryption (StartDeliveryStreamEncryption)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionResponse, StartKINFDeliveryStreamEncryptionCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.DeliveryStreamName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.DeliveryStreamEncryptionConfigurationInput_KeyARN = this.DeliveryStreamEncryptionConfigurationInput_KeyARN;
context.DeliveryStreamEncryptionConfigurationInput_KeyType = this.DeliveryStreamEncryptionConfigurationInput_KeyType;
context.DeliveryStreamName = this.DeliveryStreamName;
#if MODULAR
if (this.DeliveryStreamName == null && ParameterWasBound(nameof(this.DeliveryStreamName)))
{
WriteWarning("You are passing $null as a value for parameter DeliveryStreamName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionRequest();
// populate DeliveryStreamEncryptionConfigurationInput
var requestDeliveryStreamEncryptionConfigurationInputIsNull = true;
request.DeliveryStreamEncryptionConfigurationInput = new Amazon.KinesisFirehose.Model.DeliveryStreamEncryptionConfigurationInput();
System.String requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyARN = null;
if (cmdletContext.DeliveryStreamEncryptionConfigurationInput_KeyARN != null)
{
requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyARN = cmdletContext.DeliveryStreamEncryptionConfigurationInput_KeyARN;
}
if (requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyARN != null)
{
request.DeliveryStreamEncryptionConfigurationInput.KeyARN = requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyARN;
requestDeliveryStreamEncryptionConfigurationInputIsNull = false;
}
Amazon.KinesisFirehose.KeyType requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyType = null;
if (cmdletContext.DeliveryStreamEncryptionConfigurationInput_KeyType != null)
{
requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyType = cmdletContext.DeliveryStreamEncryptionConfigurationInput_KeyType;
}
if (requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyType != null)
{
request.DeliveryStreamEncryptionConfigurationInput.KeyType = requestDeliveryStreamEncryptionConfigurationInput_deliveryStreamEncryptionConfigurationInput_KeyType;
requestDeliveryStreamEncryptionConfigurationInputIsNull = false;
}
// determine if request.DeliveryStreamEncryptionConfigurationInput should be set to null
if (requestDeliveryStreamEncryptionConfigurationInputIsNull)
{
request.DeliveryStreamEncryptionConfigurationInput = null;
}
if (cmdletContext.DeliveryStreamName != null)
{
request.DeliveryStreamName = cmdletContext.DeliveryStreamName;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionResponse CallAWSServiceOperation(IAmazonKinesisFirehose client, Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Kinesis Firehose", "StartDeliveryStreamEncryption");
try
{
#if DESKTOP
return client.StartDeliveryStreamEncryption(request);
#elif CORECLR
return client.StartDeliveryStreamEncryptionAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String DeliveryStreamEncryptionConfigurationInput_KeyARN { get; set; }
public Amazon.KinesisFirehose.KeyType DeliveryStreamEncryptionConfigurationInput_KeyType { get; set; }
public System.String DeliveryStreamName { get; set; }
public System.Func<Amazon.KinesisFirehose.Model.StartDeliveryStreamEncryptionResponse, StartKINFDeliveryStreamEncryptionCmdlet, object> Select { get; set; } =
(response, cmdlet) => null;
}
}
}
| 56.966767 | 289 | 0.672571 | [
"Apache-2.0"
] | QPC-database/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/KinesisFirehose/Basic/Start-KINFDeliveryStreamEncryption-Cmdlet.cs | 18,856 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5.Calculate_Triangle_Area
{
class Program
{
static void Main(string[] args)
{
double linebase = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
double area = CalculateAreaOfTrangle(linebase, height);
Console.WriteLine(area);
}
static double CalculateAreaOfTrangle(double linebase, double height)
{
return linebase * height / 2;
}
}
}
| 23.111111 | 76 | 0.625 | [
"MIT"
] | tanyta78/ProgramingFundamentals | 02Methods/MethodsLab/5. Calculate Triangle Area/Program.cs | 626 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Objectidadoxioleconnection operations.
/// </summary>
public partial class Objectidadoxioleconnection : IServiceOperations<DynamicsClient>, IObjectidadoxioleconnection
{
/// <summary>
/// Initializes a new instance of the Objectidadoxioleconnection class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Objectidadoxioleconnection(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get objectid_adoxio_leconnection from principalobjectattributeaccessset
/// </summary>
/// <param name='principalobjectattributeaccessid'>
/// key: principalobjectattributeaccessid of principalobjectattributeaccess
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioLeconnection>> GetWithHttpMessagesAsync(string principalobjectattributeaccessid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (principalobjectattributeaccessid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "principalobjectattributeaccessid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("principalobjectattributeaccessid", principalobjectattributeaccessid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "principalobjectattributeaccessset({principalobjectattributeaccessid})/objectid_adoxio_leconnection").ToString();
_url = _url.Replace("{principalobjectattributeaccessid}", System.Uri.EscapeDataString(principalobjectattributeaccessid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioLeconnection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioLeconnection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 43.061033 | 369 | 0.582425 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/Objectidadoxioleconnection.cs | 9,172 | C# |
#region License
// =================================================================================================
// Copyright 2018 DataArt, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =================================================================================================
#endregion
namespace DataArt.Atlas.AlphaService.Communication
{
public enum CommunicationType
{
Esb,
WebAPi
}
}
| 41.076923 | 100 | 0.525281 | [
"Apache-2.0"
] | DamirAinullin/Atlas | tests/core/DataArt.Atlas.AlphaService/Communication/CommunicationType.cs | 1,068 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MySql.Data.MySqlClient;
using RepoDb.Attributes;
using RepoDb.DbSettings;
using RepoDb.Extensions;
namespace RepoDb.MySql.UnitTests.Attributes
{
[TestClass]
public class MySqlTypeMapAttributeTest
{
[TestInitialize]
public void Initialize()
{
DbSettingMapper.Add<MySqlConnection>(new MySqlDbSetting(), true);
}
#region Classes
private class MySqlDbTypeAttributeTestClass
{
[MySqlTypeMap(MySqlDbType.Geometry)]
public object ColumnName { get; set; }
}
#endregion
[TestMethod]
public void TestMySqlTypeMapAttributeViaEntityViaCreateParameters()
{
// Act
using (var connection = new MySqlConnection())
{
using (var command = connection.CreateCommand())
{
DbCommandExtension
.CreateParameters(command, new MySqlDbTypeAttributeTestClass
{
ColumnName = "Test"
});
// Assert
Assert.AreEqual(1, command.Parameters.Count);
// Assert
var parameter = command.Parameters["@ColumnName"];
Assert.AreEqual(MySqlDbType.Geometry, parameter.MySqlDbType);
}
}
}
[TestMethod]
public void TestMySqlTypeMapAttributeViaAnonymousViaCreateParameters()
{
// Act
using (var connection = new MySqlConnection())
{
using (var command = connection.CreateCommand())
{
DbCommandExtension
.CreateParameters(command, new
{
ColumnName = "Test"
},
typeof(MySqlDbTypeAttributeTestClass));
// Assert
Assert.AreEqual(1, command.Parameters.Count);
// Assert
var parameter = command.Parameters["@ColumnName"];
Assert.AreEqual(MySqlDbType.Geometry, parameter.MySqlDbType);
}
}
}
}
}
| 30.153846 | 84 | 0.507228 | [
"Apache-2.0"
] | RepoDb/RepoDb | RepoDb.MySql/RepoDb.MySql.UnitTests/Attributes/MySqlTypeMapAttributeTest.cs | 2,354 | C# |
namespace repeticao
{
partial class Form1
{
/// <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.bt1 = new System.Windows.Forms.Button();
this.lsTeste = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// bt1
//
this.bt1.Location = new System.Drawing.Point(436, 390);
this.bt1.Name = "bt1";
this.bt1.Size = new System.Drawing.Size(165, 42);
this.bt1.TabIndex = 0;
this.bt1.Text = "go";
this.bt1.UseVisualStyleBackColor = true;
this.bt1.Click += new System.EventHandler(this.bt1_Click);
//
// lsTeste
//
this.lsTeste.FormattingEnabled = true;
this.lsTeste.Location = new System.Drawing.Point(12, 12);
this.lsTeste.Name = "lsTeste";
this.lsTeste.Size = new System.Drawing.Size(401, 420);
this.lsTeste.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(626, 450);
this.Controls.Add(this.lsTeste);
this.Controls.Add(this.bt1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button bt1;
private System.Windows.Forms.ListBox lsTeste;
}
}
| 32.958904 | 107 | 0.536991 | [
"MIT"
] | Joaquim1302/csharp | repeticao/repeticao/Form1.Designer.cs | 2,408 | C# |
using System;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
using Meadow.CLI.Core.NewDeviceManagement;
using Microsoft.Extensions.Logging;
namespace Meadow.CommandLine.Commands.FileSystem
{
[Command("filesystem mount", Description = "Mount the File System on the Meadow Board")]
public class MountFileSystemCommand : MeadowSerialCommand
{
#if USE_PARTITIONS
[CommandOption("Partition", 'p', Description = "The partition to write to on the Meadow")]
#endif
public int Partition { get; init; } = 0;
private readonly ILogger<MountFileSystemCommand> _logger;
public MountFileSystemCommand(ILoggerFactory loggerFactory, MeadowDeviceManager meadowDeviceManager)
: base(loggerFactory, meadowDeviceManager)
{
_logger = LoggerFactory.CreateLogger<MountFileSystemCommand>();
}
public override async ValueTask ExecuteAsync(IConsole console)
{
var cancellationToken = console.RegisterCancellationHandler();
_logger.LogInformation($"Mounting partition {Partition}");
using var device = await MeadowDeviceManager.GetMeadowForSerialPort(SerialPortName, true, cancellationToken)
.ConfigureAwait(false);
await device.MountFileSystem(Partition, cancellationToken)
.ConfigureAwait(false);
}
}
} | 37.692308 | 120 | 0.679592 | [
"Apache-2.0"
] | 0xStuart/Meadow.CLI | Meadow.CommandLine/Commands/FileSystem/MountFileSystemCommand.cs | 1,472 | 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 System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace ICSharpCode.Core.Presentation
{
/// <summary>
/// A button that opens a drop-down menu when clicked.
/// </summary>
public class DropDownButton : ButtonBase
{
public static readonly DependencyProperty DropDownMenuProperty
= DependencyProperty.Register("DropDownMenu", typeof(ContextMenu),
typeof(DropDownButton), new FrameworkPropertyMetadata(null));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
protected static readonly DependencyPropertyKey IsDropDownMenuOpenPropertyKey
= DependencyProperty.RegisterReadOnly("IsDropDownMenuOpen", typeof(bool),
typeof(DropDownButton), new FrameworkPropertyMetadata(false));
public static readonly DependencyProperty IsDropDownMenuOpenProperty = IsDropDownMenuOpenPropertyKey.DependencyProperty;
static DropDownButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DropDownButton), new FrameworkPropertyMetadata(typeof(DropDownButton)));
}
public ContextMenu DropDownMenu {
get { return (ContextMenu)GetValue(DropDownMenuProperty); }
set { SetValue(DropDownMenuProperty, value); }
}
public bool IsDropDownMenuOpen {
get { return (bool)GetValue(IsDropDownMenuOpenProperty); }
protected set { SetValue(IsDropDownMenuOpenPropertyKey, value); }
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (DropDownMenu != null && !IsDropDownMenuOpen) {
DropDownMenu.Placement = PlacementMode.Bottom;
DropDownMenu.PlacementTarget = this;
DropDownMenu.IsOpen = true;
DropDownMenu.Closed += DropDownMenu_Closed;
this.IsDropDownMenuOpen = true;
}
}
void DropDownMenu_Closed(object sender, RoutedEventArgs e)
{
((ContextMenu)sender).Closed -= DropDownMenu_Closed;
this.IsDropDownMenuOpen = false;
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (!IsMouseCaptured) {
e.Handled = true;
}
}
}
}
| 40.240964 | 125 | 0.75509 | [
"MIT"
] | TetradogOther/SharpDevelop | src/Main/ICSharpCode.Core.Presentation/DropDownButton.cs | 3,342 | C# |
// <copyright file="ZipkinTraceExporterOptions.cs" company="OpenCensus Authors">
// Copyright 2018, OpenCensus Authors
//
// 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 theLicense 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.
// </copyright>
namespace OpenCensus.Exporter.Zipkin
{
using System;
/// <summary>
/// Zipkin trace exporter options.
/// </summary>
public sealed class ZipkinTraceExporterOptions
{
/// <summary>
/// Gets or sets Zipkin endpoint address. See https://zipkin.io/zipkin-api/#/default/post_spans.
/// Typically https://zipkin-server-name:9411/api/v2/spans.
/// </summary>
public Uri Endpoint { get; set; } = new Uri("http://localhost:9411/api/v2/spans");
/// <summary>
/// Gets or sets timeout in seconds.
/// </summary>
public TimeSpan TimeoutSeconds { get; set; } = TimeSpan.FromSeconds(10);
/// <summary>
/// Gets or sets the name of the service reporting telemetry.
/// </summary>
public string ServiceName { get; set; } = "Open Census Exporter";
/// <summary>
/// Gets or sets a value indicating whether short trace id should be used.
/// </summary>
public bool UseShortTraceIds { get; set; } = false;
}
}
| 36.520833 | 104 | 0.653166 | [
"Apache-2.0"
] | miknoj/opencensus-csharp | src/OpenCensus.Exporter.Zipkin/ZipkinTraceExporterOptions.cs | 1,755 | C# |
using System.Threading;
using Assets.Scripts.InMaze.Controllers;
using Assets.Scripts.InMaze.GameElements;
using Assets.Scripts.InMaze.Networking.Jsonify;
using Assets.Scripts.InMaze.Networking.Jsonify.Extension;
using Assets.Scripts.InMaze.Networking.UDP;
using Assets.Scripts.InMaze.UI.Mapify;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Assets.Scripts.InMaze.Multiplayer
{
public abstract class AbsClientController : MonoBehaviour
{
// Should be instantiated or not for this class
public static bool IsPresent;
protected UDP Client;
protected PlayerNodes Previous;
protected MiniMapOthers Others;
protected CostarsController CostarController;
// Correction value for escalated Player
private float yCorrection = 1f;
protected virtual void Awake()
{
// Bindings
Others = GameObject
.Find("SliderHUD/MapUI")
.GetComponent<MiniMapOthers>();
CostarController = GameObject
.Find("MultiplayerScripts")
.GetComponent<CostarsController>();
}
// Use this for initialization
protected virtual void Start()
{
// Use broadcast address as Anonymous targeting server
Client = new UClient(Essentials.GetBroadcastAddress(
Essentials.GetCurrentIP(),
Essentials.GetSubnetMask()
).ToString());
new Thread(() => { Client.start(); }).Start();
UpdatePlayer();
}
protected virtual void ClientUpdate()
{
// Invoke all Join()/Quit()
if (PlayerNodes.present != null)
// If player quitted
if (Previous != null && Previous.Count > PlayerNodes.present.Count)
{
// Find which player left
foreach (PlayerNode p in Previous.GetPlayers())
if (PlayerNodes.present.GetPlayer(p.id) == null)
{
Others.Quit(p);
CostarController.Quit(p);
break;
}
}
// If player joined
else if (Previous == null || Previous.Count < PlayerNodes.present.Count)
{
// Find which player joined
foreach (PlayerNode p in PlayerNodes.present.GetPlayers())
if (Previous == null || Previous.GetPlayer(p.id) == null)
// if not my id
if (p.id != PlayerNode.present.id)
{
Others.Join(p);
CostarController.Join(p);
break;
}
}
// Check if statusCode encountered in client
switch (Client.statusCode)
{
case StatusCode.NOT_FOUND:
new MessageBox(
this,
"Server connection error",
MessageBox.DURATION_SHORT,
MessageBox.Y_LOW)
.ShowOnlyAvailable();
break;
case StatusCode.SERVER_CLOSED:
new MessageBox(
this,
"Server closed",
MessageBox.DURATION_LONG,
MessageBox.Y_LOW)
.SetFadedEventHandler(() =>
{
SceneManager.LoadScene("MenuScreen");
})
.Show();
break;
}
// Update previous PlayerNodes
Previous = PlayerNodes.present;
}
// Update current player
protected virtual PlayerNode UpdatePlayer()
{
GameObject player = GameObject.Find("Player");
if (PlayerNode.present == null)
PlayerNode.present = new PlayerNode();
PlayerNode pl = PlayerNode.present;
pl.id = (PlayerNode.present != null) ? PlayerNode.present.id : -1;
// Y-axis 0 for fixing character floating
pl.position = new Vector3(
player.transform.localPosition.x,
player.transform.localPosition.y - yCorrection,
player.transform.localPosition.z
);
pl.eulerAngles = Camera.main.transform.eulerAngles;
// Check if paused
InputController ic = GameObject.Find("MapScripts").GetComponent<InputController>();
if (ic != null && !ic.IsPaused)
{
pl.jump = Input.GetKeyDown(TransScene.Present.Controller.A);
pl.horizontal = TransScene.Present.Controller.GetAxis("Horizontal");
pl.vertical = TransScene.Present.Controller.GetAxis("Vertical");
}
return pl;
}
// Leave scene
protected virtual void OnDestroy()
{
if (Client != null) Client.stop();
IsPresent = false;
StopAllCoroutines();
MessageBox.Clear();
}
// Update is called once per frame
protected virtual void Update()
{
// Base update cycle
ClientUpdate();
UpdatePlayer();
}
}
}
| 35.436709 | 95 | 0.499196 | [
"Apache-2.0"
] | myze/Unity-App | Assets/Scripts/InMaze/Multiplayer/AbsClientController.cs | 5,601 | C# |
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.MultiTenancy;
using AbpCompanyName.AbpProjectName.Editions;
using AbpCompanyName.AbpProjectName.MultiTenancy;
namespace AbpCompanyName.AbpProjectName.EntityFrameworkCore.Seed.Tenants
{
public class DefaultTenantBuilder
{
private readonly AbpProjectNameDbContext _context;
public DefaultTenantBuilder(AbpProjectNameDbContext context)
{
_context = context;
}
public void Create()
{
CreateDefaultTenant();
}
private void CreateDefaultTenant()
{
// Default tenant
var defaultTenant = _context.Tenants.IgnoreQueryFilters().FirstOrDefault(t => t.TenancyName == AbpTenantBase.DefaultTenantName);
if (defaultTenant == null)
{
defaultTenant = new Tenant(AbpTenantBase.DefaultTenantName, AbpTenantBase.DefaultTenantName);
var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);
if (defaultEdition != null)
{
defaultTenant.EditionId = defaultEdition.Id;
}
_context.Tenants.Add(defaultTenant);
_context.SaveChanges();
}
}
}
}
| 30.377778 | 141 | 0.632772 | [
"MIT"
] | ngthaiquy/abplus-zero-template | aspnet-core/src/AbpCompanyName.AbpProjectName.EntityFrameworkCore/EntityFrameworkCore/Seed/Tenants/DefaultTenantBuilder.cs | 1,369 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.AppService
{
/// <summary> A Class representing a SiteSlotInstanceProcessModule along with the instance operations that can be performed on it. </summary>
public partial class SiteSlotInstanceProcessModule : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="SiteSlotInstanceProcessModule"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string name, string slot, string instanceId, string processId, string baseAddress)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/instances/{instanceId}/processes/{processId}/modules/{baseAddress}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _siteSlotInstanceProcessModuleWebAppsClientDiagnostics;
private readonly WebAppsRestOperations _siteSlotInstanceProcessModuleWebAppsRestClient;
private readonly ProcessModuleInfoData _data;
/// <summary> Initializes a new instance of the <see cref="SiteSlotInstanceProcessModule"/> class for mocking. </summary>
protected SiteSlotInstanceProcessModule()
{
}
/// <summary> Initializes a new instance of the <see cref = "SiteSlotInstanceProcessModule"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal SiteSlotInstanceProcessModule(ArmClient client, ProcessModuleInfoData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="SiteSlotInstanceProcessModule"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal SiteSlotInstanceProcessModule(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_siteSlotInstanceProcessModuleWebAppsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.AppService", ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(ResourceType, out string siteSlotInstanceProcessModuleWebAppsApiVersion);
_siteSlotInstanceProcessModuleWebAppsRestClient = new WebAppsRestOperations(_siteSlotInstanceProcessModuleWebAppsClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, siteSlotInstanceProcessModuleWebAppsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Web/sites/slots/instances/processes/modules";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual ProcessModuleInfoData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary>
/// Description for Get process information by its ID for a specific scaled-out instance in a web site.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/instances/{instanceId}/processes/{processId}/modules/{baseAddress}
/// Operation Id: WebApps_GetInstanceProcessModuleSlot
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<SiteSlotInstanceProcessModule>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _siteSlotInstanceProcessModuleWebAppsClientDiagnostics.CreateScope("SiteSlotInstanceProcessModule.Get");
scope.Start();
try
{
var response = await _siteSlotInstanceProcessModuleWebAppsRestClient.GetInstanceProcessModuleSlotAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Parent.Name, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _siteSlotInstanceProcessModuleWebAppsClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new SiteSlotInstanceProcessModule(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Get process information by its ID for a specific scaled-out instance in a web site.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/instances/{instanceId}/processes/{processId}/modules/{baseAddress}
/// Operation Id: WebApps_GetInstanceProcessModuleSlot
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<SiteSlotInstanceProcessModule> Get(CancellationToken cancellationToken = default)
{
using var scope = _siteSlotInstanceProcessModuleWebAppsClientDiagnostics.CreateScope("SiteSlotInstanceProcessModule.Get");
scope.Start();
try
{
var response = _siteSlotInstanceProcessModuleWebAppsRestClient.GetInstanceProcessModuleSlot(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Parent.Name, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _siteSlotInstanceProcessModuleWebAppsClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new SiteSlotInstanceProcessModule(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 56.41791 | 316 | 0.700265 | [
"MIT"
] | LeszekKalibrate/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/SiteSlotInstanceProcessModule.cs | 7,560 | C# |
namespace PrimeFuncPack.DependencyRegistry.Tests;
public sealed partial class DependencyRegistryExtensionsTest
{
}
| 19.333333 | 60 | 0.87069 | [
"MIT"
] | pfpack/early-dependency-registry | src/dependency-registry/DependencyRegistry.Tests/Tests.DependencyRegistryExtensions/DependencyRegistryExtensionsTest.cs | 116 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2015 Ingo Herbote
* http://www.yetanotherforum.net/
*
* 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.
*/
namespace YAF.Types.Interfaces.Data
{
#region Using
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
/// <summary>
/// The db specific function extensions.
/// </summary>
public static class IDbSpecificFunctionExtensions
{
#region Public Methods
/// <summary>
/// Returns IEnumerable where the provider name is supported.
/// </summary>
/// <param name="functions">
/// The functions.
/// </param>
/// <param name="providerName">
/// The provider name.
/// </param>
/// <returns>
/// The is operation supported.
/// </returns>
[NotNull]
public static IEnumerable<IDbSpecificFunction> WhereProviderName([NotNull] this IEnumerable<IDbSpecificFunction> functions, [NotNull] string providerName)
{
CodeContracts.VerifyNotNull(functions, "functions");
CodeContracts.VerifyNotNull(providerName, "providerName");
return functions.Where(p => string.Equals(p.ProviderName, providerName, StringComparison.OrdinalIgnoreCase));
}
#endregion
}
} | 35 | 163 | 0.654911 | [
"Apache-2.0"
] | TristanTong/bbsWirelessTag | yafsrc/YAF.Types/Interfaces/Data/IDbSpecificFunctionExtensions.cs | 2,178 | C# |
/****************************************************************************
* Copyright (c) 2019.1 liangxie
*
* http://qframework.io
* https://github.com/liangxiegame/QFramework
*
* 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.CodeDom;
using QFramework.GraphDesigner;
namespace QFramework
{
[TemplateClass(TemplateLocation.DesignerFile)]
[RequiresNamespace("UnityEngine")]
[RequiresNamespace("UnityEngine.UI")]
[AsPartial]
public class UIPanelDesignerTemplate : IClassTemplate<PanelCodeData>,ITemplateCustomFilename
{
public string OutputPath { get; private set; }
public bool CanGenerate
{
get { return true; }
}
public void TemplateSetup()
{
Ctx.CurrentDeclaration.BaseTypes.Clear();
Ctx.CurrentDeclaration.Name = Ctx.Data.PanelName;
var dataTypeName = Ctx.Data.PanelName + "Data";
var nameField = new CodeMemberField(typeof(string), "NAME")
{
Attributes = MemberAttributes.Const | MemberAttributes.Public,
InitExpression = Ctx.Data.PanelName.ToCodeSnippetExpression()
};
Ctx.CurrentDeclaration.Members.Add(nameField);
Ctx.Data.MarkedObjInfos.ForEach(info =>
{
var field = Ctx.CurrentDeclaration._public_(info.MarkObj.ComponentName, info.Name);
if (info.MarkObj.Comment.IsNotNullAndEmpty())
{
field.Comments.Add(new CodeCommentStatement(info.MarkObj.Comment));
}
field.CustomAttributes.Add(new CodeAttributeDeclaration("SerializeField".ToCodeReference()));
});
var data = Ctx.CurrentDeclaration._private_(dataTypeName, "mPrivateData");
data.InitExpression = new CodeSnippetExpression("null");
}
[GenerateMethod, AsOverride]
protected void ClearUIComponents()
{
Ctx.Data.MarkedObjInfos.ForEach(info => { Ctx._("{0} = null", info.Name); });
Ctx._("mData = null");
}
[GenerateProperty]
public string mData
{
get
{
var dataTypeName = Ctx.Data.PanelName + "Data";
Ctx._("return mPrivateData ?? (mPrivateData = new {0}())",dataTypeName);
Ctx.CurrentProperty.Type = dataTypeName.ToCodeReference();
return dataTypeName;
}
set
{
Ctx._("mUIData = value");
Ctx._("mPrivateData = value");
}
}
public TemplateContext<PanelCodeData> Ctx { get; set; }
public string Filename { get; private set; }
}
} | 38.82 | 109 | 0.606646 | [
"MIT"
] | DiazGames/oneGame | Assets/QFramework/Framework/2.UIKit/1.UI/Editor/CodeGen/Templates/UIPanelDesignerTemplate.cs | 3,882 | C# |
using System.Collections.Generic;
namespace SFA.DAS.RoATPService.Data.Helpers
{
public interface ICacheHelper
{
List<T> Get<T>();
void Cache<T>(IEnumerable<T> dataList, int minutesToCache);
void Cache<T>(IEnumerable<T> dataList);
void PurgeAllCaches();
}
} | 23.230769 | 67 | 0.655629 | [
"MIT"
] | SkillsFundingAgency/das-roatp-service | src/SFA.DAS.RoATPService.Data/Helpers/ICacheHelper.cs | 302 | C# |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Alexander Taylor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using FingerboxLib;
using KSPPluginFramework;
using System.Reflection;
namespace CrewQueue.Interface
{
public abstract class SceneModule : MonoBehaviourExtended
{
public void CleanManifest()
{
if (CMAssignmentDialog.Instance != null)
{
VesselCrewManifest originalVesselManifest = CMAssignmentDialog.Instance.GetManifest();
IList<PartCrewManifest> partCrewManifests = originalVesselManifest.GetCrewableParts();
if (partCrewManifests != null && partCrewManifests.Count > 0)
{
PartCrewManifest partManifest = partCrewManifests[0];
foreach (ProtoCrewMember crewMember in partManifest.GetPartCrew())
{
if (crewMember != null)
{
// Clean the root part
partManifest.RemoveCrewFromSeat(partManifest.GetCrewSeat(crewMember));
}
}
if (CrewQueueSettings.Instance.AssignCrews)
{
partManifest.AddCrewToOpenSeats(CrewQueue.Instance.GetCrewForPart(partManifest.PartInfo.partPrefab, new List<ProtoCrewMember>(), true));
}
}
CMAssignmentDialog.Instance.RefreshCrewLists(originalVesselManifest, true, true);
}
}
public void RemapFillButton()
{
BTButton[] buttons = MiscUtils.GetFields<BTButton>(CMAssignmentDialog.Instance);
buttons[0].RemoveInputDelegate(new EZInputDelegate(CMAssignmentDialog.Instance.ButtonFill));
buttons[0].AddInputDelegate(new EZInputDelegate(OnFillButton));
}
public void OnFillButton(ref POINTER_INFO eventPointer)
{
if (eventPointer.evt == POINTER_INFO.INPUT_EVENT.TAP)
{
VesselCrewManifest manifest = CMAssignmentDialog.Instance.GetManifest();
Logging.Debug("Attempting to fill...");
foreach (PartCrewManifest partManifest in manifest.GetCrewableParts())
{
Logging.Debug("Attempting to fill part - " + partManifest.PartInfo.name);
bool vets = (partManifest == manifest.GetCrewableParts()[0]) ? true : false;
partManifest.AddCrewToOpenSeats(CrewQueue.Instance.GetCrewForPart(partManifest.PartInfo.partPrefab, manifest.GetAllCrew(false), vets));
}
CMAssignmentDialog.Instance.RefreshCrewLists(manifest, true, true);
}
}
}
}
| 41.526316 | 160 | 0.641825 | [
"MIT"
] | PapaJoesSoup/CrewQueue | Source/Interface/SceneModule.cs | 3,947 | C# |
namespace BECounter
{
partial class MainWindow
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow));
this.panelMain = new System.Windows.Forms.Panel();
this.countingControl = new BECounter.Controls.CountingControl();
this.topBarControl = new BECounter.Controls.TopBarControl();
this.panelMain.SuspendLayout();
this.SuspendLayout();
//
// panelMain
//
this.panelMain.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(24)))), ((int)(((byte)(39)))));
this.panelMain.Controls.Add(this.countingControl);
this.panelMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelMain.Location = new System.Drawing.Point(2, 25);
this.panelMain.Margin = new System.Windows.Forms.Padding(0);
this.panelMain.Name = "panelMain";
this.panelMain.Size = new System.Drawing.Size(601, 493);
this.panelMain.TabIndex = 1;
//
// countingControl
//
this.countingControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.countingControl.Location = new System.Drawing.Point(0, 0);
this.countingControl.Name = "countingControl";
this.countingControl.Size = new System.Drawing.Size(601, 493);
this.countingControl.TabIndex = 0;
//
// topBarControl
//
this.topBarControl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(5)))), ((int)(((byte)(12)))), ((int)(((byte)(19)))));
this.topBarControl.BarText = "BECounter";
this.topBarControl.ConfigButton = true;
this.topBarControl.Dock = System.Windows.Forms.DockStyle.Top;
this.topBarControl.ExitButton = true;
this.topBarControl.HelpButton = true;
this.topBarControl.Location = new System.Drawing.Point(2, 0);
this.topBarControl.Margin = new System.Windows.Forms.Padding(0);
this.topBarControl.Name = "topBarControl";
this.topBarControl.Size = new System.Drawing.Size(601, 25);
this.topBarControl.TabIndex = 0;
//
// MainWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(5)))), ((int)(((byte)(12)))), ((int)(((byte)(19)))));
this.ClientSize = new System.Drawing.Size(605, 520);
this.Controls.Add(this.panelMain);
this.Controls.Add(this.topBarControl);
this.DoubleBuffered = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(989, 697);
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(605, 520);
this.Name = "MainWindow";
this.Padding = new System.Windows.Forms.Padding(2, 0, 2, 2);
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.panelMain.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Controls.TopBarControl topBarControl;
private System.Windows.Forms.Panel panelMain;
private Controls.CountingControl countingControl;
}
}
| 44.970588 | 142 | 0.593416 | [
"MIT"
] | SlawomirPalewski/BECounter | BECounter/MainWindow.Designer.cs | 4,589 | C# |
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace QD.EntityFrameworkCore.UnitOfWork.Abstractions
{
/// <summary>
/// Repository of <see cref="TEntity"/>.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
public interface IRepository<TEntity> : IReadOnlyRepository<TEntity> where TEntity : class
{
#region Create
/// <summary>
/// Inserts a new entity synchronously.
/// </summary>
/// <param name="entity">The entity to insert.</param>
void Insert(TEntity entity);
/// <summary>
/// Inserts a range of entities synchronously.
/// </summary>
/// <param name="entities">The entities to insert.</param>
void Insert(IEnumerable<TEntity> entities);
/// <summary>
/// Inserts a new entity asynchronously.
/// </summary>
/// <param name="entity">The entity to insert.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for the task to complete.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous insert operation.</returns>
ValueTask<TEntity> InsertAsync(TEntity entity, CancellationToken cancellationToken = default);
/// <summary>
/// Inserts a range of entities asynchronously.
/// </summary>
/// <param name="entities">The entities to insert.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for the task to complete.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous insert operation.</returns>
Task InsertAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken = default);
#endregion
#region Update
/// <summary>
/// Updates the specified entity.
/// </summary>
/// <param name="entity">The entity.</param>
void Update(TEntity entity);
/// <summary>
/// Updates the specified entities.
/// </summary>
/// <param name="entities">The entities.</param>
void Update(params TEntity[] entities);
/// <summary>
/// Updates the specified entities.
/// </summary>
/// <param name="entities">The entities.</param>
void Update(IEnumerable<TEntity> entities);
#endregion
#region Delete
/// <summary>
/// Deletes the entity by the specified primary key.
/// </summary>
/// <param name="keyValues">The primary key value.</param>
void Delete(params object[] keyValues);
/// <summary>
/// Deletes the specified entity.
/// </summary>
/// <param name="entity">The entity to delete.</param>
void Delete(TEntity entity);
/// <summary>
/// Deletes the specified entities.
/// </summary>
/// <param name="entities">The entities.</param>
void Delete(IEnumerable<TEntity> entities);
#endregion
}
}
| 37 | 136 | 0.602544 | [
"MIT"
] | Daniel127/EF-Unit-Of-Work | QD.EntityFrameworkCore.UnitOfWork.Abstractions/IRepository.cs | 3,147 | C# |
namespace GMap.NET
{
using System;
using System.Globalization;
/// <summary>
/// the point of coordinates
/// </summary>
[Serializable]
public struct PointLatLng
{
public static readonly PointLatLng Empty = new PointLatLng();
private double lat;
private double lng;
bool NotEmpty;
public PointLatLng(double lat, double lng)
{
this.lat = lat;
this.lng = lng;
NotEmpty = true;
}
/// <summary>
/// returns true if coordinates wasn't assigned
/// </summary>
public bool IsEmpty
{
get
{
return !NotEmpty;
}
}
public double Lat
{
get
{
return this.lat;
}
set
{
this.lat = value;
NotEmpty = true;
}
}
public double Lng
{
get
{
return this.lng;
}
set
{
this.lng = value;
NotEmpty = true;
}
}
public static bool operator ==(PointLatLng left, PointLatLng right)
{
return ((left.Lng == right.Lng) && (left.Lat == right.Lat));
}
public static bool operator !=(PointLatLng left, PointLatLng right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
if (!(obj is PointLatLng))
{
return false;
}
PointLatLng tf = (PointLatLng)obj;
return (((tf.Lng == this.Lng) && (tf.Lat == this.Lat)) && tf.GetType().Equals(base.GetType()));
}
public void Offset(PointLatLng pos)
{
this.Offset(pos.Lat, pos.Lng);
}
public void Offset(double lat, double lng)
{
this.Lng += lng;
this.Lat -= lat;
}
public override int GetHashCode()
{
return (this.Lng.GetHashCode() ^ this.Lat.GetHashCode());
}
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "{{Lat={0}, Lng={1}}}", this.Lat, this.Lng);
}
}
} | 23.058252 | 107 | 0.445474 | [
"MIT"
] | mihaly044/ppserver-linux | src/ppnetlib/Prototypes/PointLatLng.cs | 2,377 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using QIES.Api.Models;
using QIES.Api.Responses;
using QIES.Core.Services;
using QIES.Core.Users;
using static System.Net.Mime.MediaTypeNames;
namespace QIES.Web.Controllers
{
[ApiController]
[Consumes(Application.Json)]
[Produces(Application.Json)]
[Route("api/v1/[controller]")]
public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> logger;
private readonly ILoginService loginService;
private readonly ILogoutService logoutService;
public UsersController(
ILogger<UsersController> logger,
ILoginService loginService,
ILogoutService logoutService)
{
this.logger = logger;
this.loginService = loginService;
this.logoutService = logoutService;
}
/// <summary>
/// Start a session.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
/// <response code="200">Successful login.</response>
/// <response code="400">Invalid login requested.</response>
[HttpPost("login")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesDefaultResponseType]
public async Task<ActionResult<LoginResponse>> Login(LoginRequest request)
{
var login = request.Login switch
{
"planner" => LoginType.Planner,
"agent" => LoginType.Agent,
_ => LoginType.None
};
logger.LogInformation("Requested login {loginRequested} resolved as type {loginResolved}", request.Login, login);
if (login == LoginType.None)
{
return BadRequest();
}
var user = await loginService.DoLogin(login);
var response = new LoginResponse
{
UserId = user.Id,
Type = user.Type
};
return Ok(response);
}
/// <summary>
/// End a session.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
/// <response code="200">Successful logout.</response>
/// <response code="400">Failed to logout.</response>
[HttpPost("logout")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesDefaultResponseType]
public async Task<IActionResult> Logout(LogoutRequest request)
{
var success = await logoutService.DoLogout(request.UserId);
if (success)
{
logger.LogInformation("User {id} logged out.", request.UserId);
return Ok();
}
return BadRequest();
}
}
}
| 33.043478 | 125 | 0.585197 | [
"MIT"
] | OmriHarary/QIES-redux | QIES/src/QIES.Web/Controllers/UsersController.cs | 3,040 | C# |
namespace Zsharp.Elysium.Tests
{
using System;
using System.Buffers;
using Moq;
using NBitcoin;
sealed class FakeTransactionPayloadSerializer : TransactionPayloadSerializer
{
public FakeTransactionPayloadSerializer(int transactionId)
{
this.StubbedDeserialize = new Mock<Func<BitcoinAddress?, BitcoinAddress?, byte[], int, Elysium.Transaction>>();
this.StubbedSerialize = new Mock<Action<IBufferWriter<byte>, Elysium.Transaction>>();
this.TransactionId = transactionId;
}
public Mock<Func<BitcoinAddress?, BitcoinAddress?, byte[], int, Elysium.Transaction>> StubbedDeserialize { get; }
public Mock<Action<IBufferWriter<byte>, Elysium.Transaction>> StubbedSerialize { get; }
public override int TransactionId { get; }
public override Elysium.Transaction Deserialize(
BitcoinAddress? sender,
BitcoinAddress? receiver,
ref SequenceReader<byte> reader,
int version)
{
var length = Convert.ToInt32(reader.Remaining);
using (var memory = MemoryPool<byte>.Shared.Rent(length))
{
var buffer = memory.Memory.Span.Slice(0, length);
reader.TryCopyTo(buffer);
reader.Advance(length);
return this.StubbedDeserialize.Object(sender, receiver, buffer.ToArray(), version);
}
}
public override void Serialize(IBufferWriter<byte> writer, Elysium.Transaction transaction)
{
this.StubbedSerialize.Object(writer, transaction);
}
}
}
| 34.416667 | 123 | 0.634383 | [
"MIT"
] | firoorg/zsharp | src/Zsharp.Elysium.Tests/FakeTransactionPayloadSerializer.cs | 1,652 | C# |
/*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* 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.Management.Automation;
using Trisoft.ISHRemote.Objects;
using Trisoft.ISHRemote.Objects.Public;
using Trisoft.ISHRemote.Exceptions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
namespace Trisoft.ISHRemote.Cmdlets.Folder
{
public abstract class FolderCmdlet : TrisoftCmdlet
{
public Enumerations.ISHType[] ISHType
{
get { return new Enumerations.ISHType[] { Enumerations.ISHType.ISHFolder }; }
}
}
}
| 31.277778 | 89 | 0.742451 | [
"Apache-2.0"
] | jlaridon/ISHRemote | Source/ISHRemote/Trisoft.ISHRemote/Cmdlets/Folder/FolderCmdlet.cs | 1,126 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.TestPlatform.AcceptanceTests
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.TestPlatform.TestUtilities;
/// <summary>
/// The custom data test method attribute.
/// </summary>
public class CustomDataTestMethodAttribute : TestMethodAttribute
{
/// <summary>
/// Find all data rows and execute.
/// </summary>
/// <param name="testMethod">
/// The test Method.
/// </param>
/// <returns>
/// The <see cref="TestResult[]"/>.
/// </returns>
public override TestResult[] Execute(ITestMethod testMethod)
{
List<DataRowAttribute> dataRows = new List<DataRowAttribute>();
var net46Rows = testMethod.GetAttributes<NET46TargetFramework>(false);
if (net46Rows != null && net46Rows.Length > 0 && net46Rows[0].DataRows.Count > 0)
{
dataRows.AddRange(net46Rows[0].DataRows);
}
var netcoreappRows = testMethod.GetAttributes<NETCORETargetFramework>(false);
if (netcoreappRows != null && netcoreappRows.Length > 0 && netcoreappRows[0].DataRows.Count > 0)
{
dataRows.AddRange(netcoreappRows[0].DataRows);
}
if (dataRows.Count == 0)
{
return new TestResult[] { new TestResult() { Outcome = UnitTestOutcome.Failed, TestFailureException = new Exception("No DataRowAttribute specified. Atleast one DataRowAttribute is required with DataTestMethodAttribute.") } };
}
return RunDataDrivenTest(testMethod, dataRows.ToArray());
}
/// <summary>
/// Run data driven test method.
/// </summary>
/// <param name="testMethod"> Test method to execute. </param>
/// <param name="dataRows"> Data Row. </param>
/// <returns> Results of execution. </returns>
internal static TestResult[] RunDataDrivenTest(ITestMethod testMethod, DataRowAttribute[] dataRows)
{
List<TestResult> results = new List<TestResult>();
foreach (var dataRow in dataRows)
{
TestResult result = testMethod.Invoke(dataRow.Data);
if (!string.IsNullOrEmpty(dataRow.DisplayName))
{
result.DisplayName = dataRow.DisplayName;
}
else
{
result.DisplayName = string.Format(CultureInfo.CurrentCulture, "{0} ({1})", testMethod.TestMethodName, string.Join(",", dataRow.Data));
}
results.Add(result);
}
return results.ToArray();
}
}
/// <summary>
/// The attribute defining runner framework, target framework and target runtime for net46.
/// </summary>
public class NET46TargetFramework : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="NET46TargetFramework"/> class.
/// </summary>
public NET46TargetFramework()
{
this.DataRows = new List<DataRowAttribute>(2);
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.CoreRunnerFramework, AcceptanceTestBase.DesktopTargetFramework, AcceptanceTestBase.CoreRunnerTargetRuntime));
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.DesktopRunnerFramework, AcceptanceTestBase.DesktopTargetFramework, AcceptanceTestBase.DesktopRunnerTargetRuntime));
}
/// <summary>
/// Gets or sets the data rows.
/// </summary>
public List<DataRowAttribute> DataRows { get; set; }
}
/// <summary>
/// The attribute defining runner framework, target framework and target runtime for netcoreapp1.*
/// </summary>
public class NETCORETargetFramework : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="NETCORETargetFramework"/> class.
/// </summary>
public NETCORETargetFramework()
{
this.DataRows = new List<DataRowAttribute>(4);
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.CoreRunnerFramework, AcceptanceTestBase.CoreTargetFramework, AcceptanceTestBase.CoreRunnerTargetRuntime));
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.DesktopRunnerFramework, AcceptanceTestBase.CoreTargetFramework, AcceptanceTestBase.DesktopRunnerTargetRuntime));
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.CoreRunnerFramework, AcceptanceTestBase.Core11TargetFramework, AcceptanceTestBase.CoreRunnerTargetRuntime));
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.DesktopRunnerFramework, AcceptanceTestBase.Core11TargetFramework, AcceptanceTestBase.DesktopRunnerTargetRuntime));
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.CoreRunnerFramework, AcceptanceTestBase.Core20TargetFramework, AcceptanceTestBase.CoreRunnerTargetRuntime));
this.DataRows.Add(new DataRowAttribute(IntegrationTestBase.DesktopRunnerFramework, AcceptanceTestBase.Core20TargetFramework, AcceptanceTestBase.DesktopRunnerTargetRuntime));
}
/// <summary>
/// Gets or sets the data rows.
/// </summary>
public List<DataRowAttribute> DataRows { get; set; }
}
}
| 44.390625 | 241 | 0.651883 | [
"MIT"
] | eerhardt/vstest | test/Microsoft.TestPlatform.AcceptanceTests/Extension/CustomDataTestMethodAttribute.cs | 5,684 | C# |
using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace GongSolutions.Wpf.DragDrop
{
public interface IDropInfo
{
/// <summary>
/// Gets the drag data.
/// </summary>
/// <remarks>
/// If the drag came from within the framework, this will hold:
///
/// - The dragged data if a single item was dragged.
/// - A typed IEnumerable if multiple items were dragged.
/// </remarks>
object Data { get; }
/// <summary>
/// Gets a <see cref="DragInfo"/> object holding information about the source of the drag,
/// if the drag came from within the framework.
/// </summary>
IDragInfo DragInfo { get; }
/// <summary>
/// Gets the mouse position relative to the VisualTarget
/// </summary>
Point DropPosition { get; }
/// <summary>
/// Gets or sets the class of drop target to display.
/// </summary>
/// <remarks>
/// The standard drop target Adorner classes are held in the <see cref="DropTargetAdorners"/>
/// class.
/// </remarks>
Type DropTargetAdorner { get; set; }
/// <summary>
/// Gets or sets the allowed effects for the drop.
/// </summary>
/// <remarks>
/// This must be set to a value other than <see cref="DragDropEffects.None"/> by a drop handler in order
/// for a drop to be possible.
/// </remarks>
DragDropEffects Effects { get; set; }
/// <summary>
/// Gets the current insert position within <see cref="TargetCollection"/>.
/// </summary>
int InsertIndex { get; }
/// <summary>
/// Gets the current insert position within the source (unfiltered) <see cref="TargetCollection"/>.
/// </summary>
/// <remarks>
/// This should be only used in a Drop action.
/// This works only correct with different objects (string, int, etc won't work correct).
/// </remarks>
int UnfilteredInsertIndex { get; }
/// <summary>
/// Gets the collection that the target ItemsControl is bound to.
/// </summary>
/// <remarks>
/// If the current drop target is unbound or not an ItemsControl, this will be null.
/// </remarks>
IEnumerable TargetCollection { get; }
/// <summary>
/// Gets the object that the current drop target is bound to.
/// </summary>
/// <remarks>
/// If the current drop target is unbound or not an ItemsControl, this will be null.
/// </remarks>
object TargetItem { get; }
/// <summary>
/// Gets the current group target.
/// </summary>
/// <remarks>
/// If the drag is currently over an ItemsControl with groups, describes the group that
/// the drag is currently over.
/// </remarks>
CollectionViewGroup TargetGroup { get; }
/// <summary>
/// Gets the control that is the current drop target.
/// </summary>
UIElement VisualTarget { get; }
/// <summary>
/// Gets the item in an ItemsControl that is the current drop target.
/// </summary>
/// <remarks>
/// If the current drop target is unbound or not an ItemsControl, this will be null.
/// </remarks>
UIElement VisualTargetItem { get; }
/// <summary>
/// Gets the orientation of the current drop target.
/// </summary>
Orientation VisualTargetOrientation { get; }
/// <summary>
/// Gets the FlowDirection of the current drop target.
/// </summary>
FlowDirection VisualTargetFlowDirection { get; }
/// <summary>
/// Gets and sets the text displayed in the DropDropEffects Adorner.
/// </summary>
string DestinationText { get; set; }
/// <summary>
/// Gets and sets the effect text displayed in the DropDropEffects Adorner.
/// </summary>
string EffectText { get; set; }
/// <summary>
/// Gets the relative position the item will be inserted to compared to the TargetItem
/// </summary>
RelativeInsertPosition InsertPosition { get; }
/// <summary>
/// Gets a flag enumeration indicating the current state of the SHIFT, CTRL, and ALT keys, as well as the state of the mouse buttons.
/// </summary>
DragDropKeyStates KeyStates { get; }
/// <summary>
/// Indicates if the drop info should be handled by itself (useful for child elements)
/// </summary>
bool NotHandled { get; set; }
/// <summary>
/// Gets a value indicating whether the target is in the same context as the source, <see cref="DragDrop.DragDropContextProperty" />.
/// </summary>
bool IsSameDragDropContextAsSource { get; }
/// <summary>
/// Gets the current mode of the underlying routed event.
/// </summary>
EventType EventType { get; }
}
} | 35.175676 | 141 | 0.570688 | [
"BSD-3-Clause"
] | AlexVance/gong-wpf-dragdrop | src/GongSolutions.WPF.DragDrop/IDropInfo.cs | 5,208 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v2/enums/conversion_action_counting_type.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V2.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v2/enums/conversion_action_counting_type.proto</summary>
public static partial class ConversionActionCountingTypeReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v2/enums/conversion_action_counting_type.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConversionActionCountingTypeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkNnb29nbGUvYWRzL2dvb2dsZWFkcy92Mi9lbnVtcy9jb252ZXJzaW9uX2Fj",
"dGlvbl9jb3VudGluZ190eXBlLnByb3RvEh1nb29nbGUuYWRzLmdvb2dsZWFk",
"cy52Mi5lbnVtcxocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byKHAQog",
"Q29udmVyc2lvbkFjdGlvbkNvdW50aW5nVHlwZUVudW0iYwocQ29udmVyc2lv",
"bkFjdGlvbkNvdW50aW5nVHlwZRIPCgtVTlNQRUNJRklFRBAAEgsKB1VOS05P",
"V04QARIRCg1PTkVfUEVSX0NMSUNLEAISEgoOTUFOWV9QRVJfQ0xJQ0sQA0L2",
"AQohY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnYyLmVudW1zQiFDb252ZXJz",
"aW9uQWN0aW9uQ291bnRpbmdUeXBlUHJvdG9QAVpCZ29vZ2xlLmdvbGFuZy5v",
"cmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMvZ29vZ2xlYWRzL3YyL2VudW1z",
"O2VudW1zogIDR0FBqgIdR29vZ2xlLkFkcy5Hb29nbGVBZHMuVjIuRW51bXPK",
"Ah1Hb29nbGVcQWRzXEdvb2dsZUFkc1xWMlxFbnVtc+oCIUdvb2dsZTo6QWRz",
"OjpHb29nbGVBZHM6OlYyOjpFbnVtc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V2.Enums.ConversionActionCountingTypeEnum), global::Google.Ads.GoogleAds.V2.Enums.ConversionActionCountingTypeEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V2.Enums.ConversionActionCountingTypeEnum.Types.ConversionActionCountingType) }, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing the conversion deduplication mode for
/// conversion optimizer.
/// </summary>
public sealed partial class ConversionActionCountingTypeEnum : pb::IMessage<ConversionActionCountingTypeEnum> {
private static readonly pb::MessageParser<ConversionActionCountingTypeEnum> _parser = new pb::MessageParser<ConversionActionCountingTypeEnum>(() => new ConversionActionCountingTypeEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ConversionActionCountingTypeEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V2.Enums.ConversionActionCountingTypeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConversionActionCountingTypeEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConversionActionCountingTypeEnum(ConversionActionCountingTypeEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConversionActionCountingTypeEnum Clone() {
return new ConversionActionCountingTypeEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ConversionActionCountingTypeEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ConversionActionCountingTypeEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ConversionActionCountingTypeEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the ConversionActionCountingTypeEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Indicates how conversions for this action will be counted. For more
/// information, see https://support.google.com/google-ads/answer/3438531.
/// </summary>
public enum ConversionActionCountingType {
/// <summary>
/// Not specified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Used for return value only. Represents value unknown in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// Count only one conversion per click.
/// </summary>
[pbr::OriginalName("ONE_PER_CLICK")] OnePerClick = 2,
/// <summary>
/// Count all conversions per click.
/// </summary>
[pbr::OriginalName("MANY_PER_CLICK")] ManyPerClick = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 39.820106 | 342 | 0.714058 | [
"Apache-2.0"
] | chrisdunelm/google-ads-dotnet | src/V2/Stubs/ConversionActionCountingType.cs | 7,526 | C# |
using System;
namespace Core.UserClient.Data.DB
{
public abstract class BaseOperationResult
{
public bool IsSuccessful => Exception == null;
public Exception Exception { get; set; } = null;
}
public class EntityOperationResult : BaseOperationResult
{
public bool HasEntity => Entity != null;
public IEntity Entity { get; set; } = null;
public bool Evaluate(Action<EntityOperationResult> OnInternalFailure = null)
{
if (!IsSuccessful)
{
if (OnInternalFailure != null)
OnInternalFailure.Invoke(this);
return false;
}
return true;
}
public bool Evaluate<T>(out T entity, Action<EntityOperationResult> OnInternalFailure = null, Action<EntityOperationResult> OnEntityNotFound = null) where T : IEntity
{
entity = default(T);
if (!IsSuccessful)
{
if (OnInternalFailure != null)
OnInternalFailure.Invoke(this);
return false;
}
if (!HasEntity)
{
if (OnEntityNotFound != null)
OnEntityNotFound.Invoke(this);
return false;
}
entity = (T) Entity;
return true;
}
}
}
| 25.163636 | 174 | 0.524566 | [
"MIT"
] | GitAyanC/SecurityTokenService | Core.UserClient/Data/DB/EntityOperationResult.cs | 1,386 | C# |
using k8s.Exceptions;
#if !NET5_0_OR_GREATER
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
#endif
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace k8s
{
internal static class CertUtils
{
/// <summary>
/// Load pem encoded cert file
/// </summary>
/// <param name="file">Path to pem encoded cert file</param>
/// <returns>List of x509 instances.</returns>
public static X509Certificate2Collection LoadPemFileCert(string file)
{
var certCollection = new X509Certificate2Collection();
using (var stream = FileUtils.FileSystem().File.OpenRead(file))
{
#if NET5_0_OR_GREATER
certCollection.ImportFromPem(new StreamReader(stream).ReadToEnd());
#else
var certs = new X509CertificateParser().ReadCertificates(stream);
// Convert BouncyCastle X509Certificates to the .NET cryptography implementation and add
// it to the certificate collection
//
foreach (Org.BouncyCastle.X509.X509Certificate cert in certs)
{
certCollection.Add(new X509Certificate2(cert.GetEncoded()));
}
#endif
}
return certCollection;
}
/// <summary>
/// Generates pfx from client configuration
/// </summary>
/// <param name="config">Kubernetes Client Configuration</param>
/// <returns>Generated Pfx Path</returns>
public static X509Certificate2 GeneratePfx(KubernetesClientConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
#if NET5_0_OR_GREATER
string keyData = null;
string certData = null;
if (!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData))
{
keyData = Encoding.UTF8.GetString(Convert.FromBase64String(config.ClientCertificateKeyData));
}
if (!string.IsNullOrWhiteSpace(config.ClientKeyFilePath))
{
keyData = File.ReadAllText(config.ClientKeyFilePath);
}
if (keyData == null)
{
throw new KubeConfigException("keyData is empty");
}
if (!string.IsNullOrWhiteSpace(config.ClientCertificateData))
{
certData = Encoding.UTF8.GetString(Convert.FromBase64String(config.ClientCertificateData));
}
if (!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath))
{
certData = File.ReadAllText(config.ClientCertificateFilePath);
}
if (certData == null)
{
throw new KubeConfigException("certData is empty");
}
var cert = X509Certificate2.CreateFromPem(certData, keyData);
// see https://github.com/kubernetes-client/csharp/issues/737
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
cert = new X509Certificate2(cert.Export(X509ContentType.Pkcs12));
}
return cert;
#else
byte[] keyData = null;
byte[] certData = null;
if (!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData))
{
keyData = Convert.FromBase64String(config.ClientCertificateKeyData);
}
if (!string.IsNullOrWhiteSpace(config.ClientKeyFilePath))
{
keyData = File.ReadAllBytes(config.ClientKeyFilePath);
}
if (keyData == null)
{
throw new KubeConfigException("keyData is empty");
}
if (!string.IsNullOrWhiteSpace(config.ClientCertificateData))
{
certData = Convert.FromBase64String(config.ClientCertificateData);
}
if (!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath))
{
certData = File.ReadAllBytes(config.ClientCertificateFilePath);
}
if (certData == null)
{
throw new KubeConfigException("certData is empty");
}
var cert = new X509CertificateParser().ReadCertificate(new MemoryStream(certData));
// key usage is a bit string, zero-th bit is 'digitalSignature'
// See https://www.alvestrand.no/objectid/2.5.29.15.html for more details.
if (cert != null && cert.GetKeyUsage() != null && !cert.GetKeyUsage()[0])
{
throw new Exception(
"Client certificates must be marked for digital signing. " +
"See https://github.com/kubernetes-client/csharp/issues/319");
}
object obj;
using (var reader = new StreamReader(new MemoryStream(keyData)))
{
obj = new PemReader(reader).ReadObject();
var key = obj as AsymmetricCipherKeyPair;
if (key != null)
{
var cipherKey = key;
obj = cipherKey.Private;
}
}
var keyParams = (AsymmetricKeyParameter)obj;
var store = new Pkcs12StoreBuilder().Build();
store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(keyParams), new[] { new X509CertificateEntry(cert) });
using (var pkcs = new MemoryStream())
{
store.Save(pkcs, new char[0], new SecureRandom());
if (config.ClientCertificateKeyStoreFlags.HasValue)
{
return new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value);
}
else
{
return new X509Certificate2(pkcs.ToArray());
}
}
#endif
}
/// <summary>
/// Retrieves Client Certificate PFX from configuration
/// </summary>
/// <param name="config">Kubernetes Client Configuration</param>
/// <returns>Client certificate PFX</returns>
public static X509Certificate2 GetClientCert(KubernetesClientConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
if ((!string.IsNullOrWhiteSpace(config.ClientCertificateData) ||
!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath)) &&
(!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData) ||
!string.IsNullOrWhiteSpace(config.ClientKeyFilePath)))
{
return GeneratePfx(config);
}
return null;
}
}
}
| 34.668293 | 117 | 0.568594 | [
"Apache-2.0"
] | Binyang2014/csharp | src/KubernetesClient/CertUtils.cs | 7,107 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V23.Segment;
using NHapi.Model.V23.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V23.Group
{
///<summary>
///Represents the SRM_S10_SERVICE Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: AIS (Appointment Information - Service) </li>
///<li>1: APR (Appointment Preferences) optional </li>
///<li>2: NTE (Notes and comments segment) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class SRM_S10_SERVICE : AbstractGroup {
///<summary>
/// Creates a new SRM_S10_SERVICE Group.
///</summary>
public SRM_S10_SERVICE(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(AIS), true, false);
this.add(typeof(APR), false, false);
this.add(typeof(NTE), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating SRM_S10_SERVICE - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns AIS (Appointment Information - Service) - creates it if necessary
///</summary>
public AIS AIS {
get{
AIS ret = null;
try {
ret = (AIS)this.GetStructure("AIS");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns APR (Appointment Preferences) - creates it if necessary
///</summary>
public APR APR {
get{
APR ret = null;
try {
ret = (APR)this.GetStructure("APR");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of NTE (Notes and comments segment) - creates it if necessary
///</summary>
public NTE GetNTE() {
NTE ret = null;
try {
ret = (NTE)this.GetStructure("NTE");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of NTE
/// * (Notes and comments segment) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public NTE GetNTE(int rep) {
return (NTE)this.GetStructure("NTE", rep);
}
/**
* Returns the number of existing repetitions of NTE
*/
public int NTERepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("NTE").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the NTE results
*/
public IEnumerable<NTE> NTEs
{
get
{
for (int rep = 0; rep < NTERepetitionsUsed; rep++)
{
yield return (NTE)this.GetStructure("NTE", rep);
}
}
}
///<summary>
///Adds a new NTE
///</summary>
public NTE AddNTE()
{
return this.AddStructure("NTE") as NTE;
}
///<summary>
///Removes the given NTE
///</summary>
public void RemoveNTE(NTE toRemove)
{
this.RemoveStructure("NTE", toRemove);
}
///<summary>
///Removes the NTE at the given index
///</summary>
public void RemoveNTEAt(int index)
{
this.RemoveRepetition("NTE", index);
}
}
}
| 28.238411 | 154 | 0.637899 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Model.V23/Group/SRM_S10_SERVICE.cs | 4,264 | C# |
using EnTTSharp.Entities.Helpers;
using FluentAssertions;
using NUnit.Framework;
namespace EnTTSharp.Test.Helpers
{
public class SegmentedRawListTest
{
[Test]
public void Validate_RawList_Enumerator_When_Empty()
{
SegmentedRawList<int> list = new SegmentedRawList<int>();
list.GetEnumerator().MoveNext().Should().BeFalse();
}
[Test]
public void ValidateAdd()
{
SegmentedRawList<int> list = new SegmentedRawList<int>(2);
list.Add(0);
}
}
} | 24.521739 | 70 | 0.608156 | [
"MIT"
] | RabbitStewDio/EnTTSharp | tests/EnTTSharp.Test/Helpers/SegmentedRawListTest.cs | 564 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LRS.Lib
{
public class RobotException : Exception
{
public RobotException() : base() { }
public RobotException(string message) : base(message) { }
public RobotException(string message, Exception innerException) : base(message, innerException) { }
public RobotException(string message, params object[] args) : base(string.Format(message, args)) { }
}
}
| 26.35 | 108 | 0.70019 | [
"MIT"
] | sem-onyalo/LRS | LRS.Lib/Exceptions/RobotException.cs | 529 | C# |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace LeetCode
{
[TestClass]
public class RottingOranges
{
/*
*/
[TestMethod]
public void Test_1()
{
//Input:[[2,1,1],[1,1,0],[0,1,1]]
//Output: 4
var input = JsonConvert.DeserializeObject<int[][]>("[[2,1,1],[1,1,0],[0,1,1]]");
var output = OrangesRotting(input);
output.Should().Be(4);
}
[TestMethod]
public void Test_2()
{
var input = JsonConvert.DeserializeObject<int[][]>("[[2,1,1],[0,1,1],[1,0,1]]");
var output = OrangesRotting(input);
output.Should().Be(-1);
}
public int OrangesRotting(int[][] grid)
{
var minutes = 0;
while (true)
{
var changes = false;
var fresh = false;
var newGrid = CloneGrid(grid);
for (var i = 0; i < grid.Length; i++)
for (var j = 0; j < grid[0].Length; j++)
{
var cell = grid[i][j];
if (cell == 2)
{
changes = RotNeighbor(newGrid, i - 1, j) || changes;
changes = RotNeighbor(newGrid, i + 1, j) || changes;
changes = RotNeighbor(newGrid, i, j - 1) || changes;
changes = RotNeighbor(newGrid, i, j + 1) || changes;
}
fresh = fresh || cell == 1;
}
if (!changes)
{
if (fresh) return -1;
return minutes;
}
grid = newGrid;
minutes++;
}
}
private int[][] CloneGrid(int[][] grid)
{
var newGrid = new int[grid.Length][];
for (var i = 0; i < grid.Length; i++)
{
newGrid[i] = new int[grid[i].Length];
for (var j = 0; j < grid[0].Length; j++)
{
newGrid[i][j] = grid[i][j];
}
}
return newGrid;
}
private bool RotNeighbor(int[][] grid, int i, int j)
{
if (i >= 0 && i < grid.Length &&
j >= 0 && j < grid[0].Length &&
grid[i][j] == 1)
{
grid[i][j] = 2;
return true;
}
return false;
}
}
}
| 27.989899 | 92 | 0.395164 | [
"MIT"
] | TravisTX/leetcode | LeetCode/RottingOranges.cs | 2,773 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301
{
using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions;
/// <summary>Object reference to a Kubernetes object on a cluster</summary>
public partial class ObjectReferenceDefinition
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json serialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <paramref name= "returnNow" />
/// output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <paramref name="returnNow" /> output
/// parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IObjectReferenceDefinition.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IObjectReferenceDefinition.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IObjectReferenceDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new ObjectReferenceDefinition(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of <see cref="ObjectReferenceDefinition" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from.</param>
internal ObjectReferenceDefinition(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_namespace = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString>("namespace"), out var __jsonNamespace) ? (string)__jsonNamespace : (string)Namespace;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="ObjectReferenceDefinition" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="ObjectReferenceDefinition" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
AddIf( null != (((object)this._namespace)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._namespace.ToString()) : null, "namespace" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 73.081818 | 305 | 0.706431 | [
"MIT"
] | AlanFlorance/azure-powershell | src/KubernetesConfiguration/generated/api/Models/Api20220301/ObjectReferenceDefinition.json.cs | 7,930 | C# |
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
//using System.ServiceModel.Web;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace WcfMtomService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class DataAccessService : IDataAccessService
{
public void SetFileInfo(FileInfo[] files)
{
foreach (FileInfo fi in files)
{
Debug.WriteLine(fi.Name);
Debug.WriteLine(fi.Size);
}
}
#region IDataAccessService Members
public MtomData GetData(int value)
{
MtomData ret = new MtomData();
if (value == 0)
{
// less than 1000 bytes uses Base64 encoding
ret.Data = UTF8Encoding.UTF8.GetBytes(
@"Understanding how to name your services on the Service Bus is of central importance.");
}
else if (value == 1)
{
ret.Data = UTF8Encoding.UTF8.GetBytes(
@"The M777 began as the Ultralight-weight Field Howitzer (UFH), developed by VSEL's armaments division in Barrow-in-Furness, United Kingdom. In 1999, after acquisition by BAE, VSEL was merged into the new BAE Systems RO Defence. This unit became part of BAE Systems Land Systems in 2004. Although developed by a British company, final assembly is in the US. BAE System's original US partner was United Defense. However in 2005, BAE acquired United Defense and hence is responsible for design, construction and assembly (through its US-based Land and Armaments group). The M777 uses about 70% US built parts including the gun barrel manufactured at the Watervliet Arsenal.
The M777 is smaller and 42% lighter, at under 4,100 kg (9,000 lb), than the M198 it replaces. Most of the weight reduction is due to the use of titanium. The lighter weight and smaller size allows the M777 to be transported by USMC MV-22 Osprey, CH-47 helicopter or truck with ease, so that it can be moved in and out of the battlefield more quickly than the M198. The smaller size also improves storage and transport efficiency in military warehouses and Air/Naval Transport. The gun crew required is an Operational Minimum of five, compared to a previous size of nine.[1]
The M777 uses a digital fire-control system similar to that found on self propelled howitzers such as the M109A6 Paladin to provide navigation, pointing and self-location, allowing it to be put into action more quickly than earlier towed and air-transported howitzers. The Canadian M777 in conjunction with the traditional 'glass and iron sights/mounts' also uses a digital fire control system called Digital Gun Management System (DGMS) produced by SELEX. This system has been proven on the British Army Artillery's L118 Light Gun over the past three to four years."
);
}
else
{
ret.Data = new byte[2048];
for (int i = 0; i < ret.Data.Length; i++)
{
ret.Data[i] = (byte)i;
}
}
return ret;
}
public void SetData(MtomData data)
{
Debug.WriteLine(new string(UTF8Encoding.UTF8.GetChars(data.Data)));
}
#endregion
#region IDataAccessService Members
public NestedClass GetNestedData()
{
NestedClass ret = new NestedClass();
ret.MTData = GetData(3);
ret.MyData = GetData(1).Data;
return ret;
}
public void SetNestedData(NestedClass data)
{
Debug.WriteLine(new string(UTF8Encoding.UTF8.GetChars(data.MyData)));
Debug.WriteLine(new string(UTF8Encoding.UTF8.GetChars(data.MTData.Data)));
}
#endregion
}
}
| 44.5 | 671 | 0.659925 | [
"Apache-2.0"
] | Sirokujira/MicroFrameworkPK_v4_3 | Framework/UnitTest/DpwsWcf/Mtom/Service/WcfMtomService/Service1.svc.cs | 4,007 | C# |
namespace MultiLanguage
{
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[ComImport, InterfaceType((short) 1), Guid("F5BE2EE1-BFD7-11D0-B188-00AA0038C969")]
public interface IMLangLineBreakConsole
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void BreakLineML([In, MarshalAs(UnmanagedType.Interface)] CMLangString pSrcMLStr, [In] int lSrcPos, [In] int lSrcLen, [In] int cMinColumns, [In] int cMaxColumns, out int plLineLen, out int plSkipLen);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void BreakLineW([In] uint locale, [In] ref ushort pszSrc, [In] int cchSrc, [In] int cMaxColumns, out int pcchLine, out int pcchSkip);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void BreakLineA([In] uint locale, [In] uint uCodePage, [In] ref sbyte pszSrc, [In] int cchSrc, [In] int cMaxColumns, out int pcchLine, out int pcchSkip);
}
}
| 61.588235 | 208 | 0.74212 | [
"Apache-2.0"
] | VahidN/SubtitleTools | 3rdparty/EncodingTools/Multilang/IMLangLineBreakConsole.cs | 1,047 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Skyline.Infrastructure.Data;
namespace Skyline.Infrastructure.Data.Migrations
{
[DbContext(typeof(SkylineDbContext))]
[Migration("20200422065621_InitializeSkylineDbConfiguration")]
partial class InitializeSkylineDbConfiguration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Skyline.ApplicationCore.Entities.ContactAggregate.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("City")
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("MobileNumber")
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("OwnerId")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Province")
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int>("Status")
.HasColumnType("int");
b.Property<string>("Zip")
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.HasKey("Id");
b.ToTable("Contacts");
});
#pragma warning restore 612, 618
}
}
}
| 37.333333 | 125 | 0.531786 | [
"MIT"
] | zhaobingwang/Skyline | CleanArchitecture/src/Skyline.Infrastructure/Data/Migrations/20200422065621_InitializeSkylineDbConfiguration.Designer.cs | 2,802 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace LoRaWan.NetworkServer.Test
{
using System;
using System.Collections.Generic;
using LoRaWan.NetworkServer;
using Xunit;
public class CaseInsensitiveEnvironmentVariablesTest
{
[Fact]
public void Should_Return_Null_If_Not_Found()
{
var variables = new Dictionary<string, string>()
{
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("NOT_EXISTS", (string)null);
Assert.Null(actual);
}
[Fact]
public void Should_Return_StringEmpty_If_Not_Found()
{
var variables = new Dictionary<string, string>()
{
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("NOT_EXISTS", string.Empty);
Assert.NotNull(actual);
Assert.Equal(0, actual.Length);
}
[Fact]
public void Should_Find_String_If_Case_Matches()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "VALUE" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", string.Empty);
Assert.NotNull(actual);
Assert.Equal("VALUE", actual);
}
[Fact]
public void Should_Find_String_If_Case_Does_Not_Match()
{
var variables = new Dictionary<string, string>()
{
{ "myvar", "VALUE" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", string.Empty);
Assert.NotNull(actual);
Assert.Equal("VALUE", actual);
}
[Fact]
public void Should_Return_Default_Bool_Value_False_If_Not_Found()
{
var variables = new Dictionary<string, string>()
{
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", false);
Assert.False(actual);
}
[Fact]
public void Should_Return_Default_Bool_Value_True_If_Not_Found()
{
var variables = new Dictionary<string, string>()
{
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", true);
Assert.True(actual);
}
[Fact]
public void Should_Return_Default_Bool_Value_If_Cannot_Parse()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "ABC" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", true);
Assert.True(actual);
}
[Fact]
public void Should_Find_Bool_If_Case_Matches()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "true" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", false);
Assert.True(actual);
}
[Fact]
public void Should_Find_Bool_If_Case_Does_Not_Match()
{
var variables = new Dictionary<string, string>()
{
{ "myvar", "true" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", false);
Assert.True(actual);
}
[Fact]
public void Should_Return_Default_Double_Value_True_If_Not_Found()
{
var variables = new Dictionary<string, string>()
{
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 10.0);
Assert.Equal(10.0, actual);
}
[Fact]
public void Should_Return_Default_Double_Value_If_Cannot_Parse()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "ABC" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 12.0);
Assert.Equal(12.0, actual);
}
[Fact]
public void Should_Find_Double_If_Case_Matches()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "20" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 0.0);
Assert.Equal(20.0, actual);
}
[Fact]
public void Should_Find_Double_If_Case_Does_Not_Match()
{
var variables = new Dictionary<string, string>()
{
{ "myvar", "89.31" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 0.0);
Assert.Equal(89.31, actual);
}
[Fact]
public void Should_Return_Default_Int_Value_True_If_Not_Found()
{
var variables = new Dictionary<string, string>()
{
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 10);
Assert.Equal(10, actual);
}
[Fact]
public void Should_Return_Default_Int_Value_If_Cannot_Parse()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "ABC" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 12);
Assert.Equal(12, actual);
}
[Fact]
public void Should_Find_Int_If_Case_Matches()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "20" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 0);
Assert.Equal(20, actual);
}
[Fact]
public void Should_Find_Int_If_Case_Does_Not_Match()
{
var variables = new Dictionary<string, string>()
{
{ "myvar", "8931" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 0);
Assert.Equal(8931, actual);
}
[Fact]
public void Should_Return_Default_Uint_Value_True_If_Not_Found()
{
var variables = new Dictionary<string, string>()
{
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 10u);
Assert.Equal(10u, actual);
}
[Fact]
public void Should_Return_Default_Uint_Value_If_Cannot_Parse()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "ABC" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 12u);
Assert.Equal(12u, actual);
}
[Fact]
public void Should_Find_Uint_If_Case_Matches()
{
var variables = new Dictionary<string, string>()
{
{ "MYVAR", "20" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 0u);
Assert.Equal(20u, actual);
}
[Fact]
public void Should_Find_Uint_If_Case_Does_Not_Match()
{
var variables = new Dictionary<string, string>()
{
{ "myvar", "8931" }
};
var target = new CaseInsensitiveEnvironmentVariables(variables);
var actual = target.GetEnvVar("MYVAR", 0u);
Assert.Equal(8931u, actual);
}
}
} | 30.818505 | 101 | 0.541455 | [
"MIT"
] | LauraDamianTNA/iotedge-lorawan-starterkit | LoRaEngine/test/LoRaWanNetworkServer.Test/CaseInsensitiveEnvironmentVariablesTest.cs | 8,660 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace Microsoft.Data.Entity.Design.Model.Commands
{
using System;
using System.Diagnostics;
using Microsoft.Data.Entity.Design.Model.Entity;
internal class DeleteAssociationCommand : DeleteEFElementCommand
{
internal string DeletedAssociationName { get; private set; }
protected internal Association Association
{
get
{
var elem = EFElement as Association;
Debug.Assert(elem != null, "underlying element does not exist or is not an Association");
if (elem == null)
{
throw new InvalidModelItemException();
}
return elem;
}
}
internal DeleteAssociationCommand(Association association)
: base(association)
{
CommandValidation.ValidateAssociation(association);
SaveDeletedInformation();
}
internal DeleteAssociationCommand(Func<Command, CommandProcessorContext, bool> bindingAction)
: base(bindingAction)
{
}
private void SaveDeletedInformation()
{
DeletedAssociationName = Association.Name.Value;
}
protected override void PreInvoke(CommandProcessorContext cpc)
{
// We need to save off the deleted association name so that it can be identified by the Storage->Conceptual
// translator after the element is gone.
SaveDeletedInformation();
base.PreInvoke(cpc);
}
}
}
| 31.545455 | 145 | 0.608646 | [
"MIT"
] | dotnet/ef6tools | src/EFTools/EntityDesignModel/Commands/DeleteAssociationCommand.cs | 1,737 | C# |
/*******************************************************************************
* Copyright 2009-2016 Amazon Services. 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://aws.amazon.com/apache2.0
* 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.
*******************************************************************************
* Asin List
* API Version: 2010-10-01
* Library Version: 2016-10-05
* Generated: Wed Oct 05 06:15:39 PDT 2016
*/
using System;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
using AmazonAccess.Services.Common;
namespace AmazonAccess.Services.FBAInbound.Model
{
[XmlTypeAttribute(Namespace = "http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/")]
[XmlRootAttribute(Namespace = "http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/", IsNullable = false)]
public class AsinList : AbstractMwsObject
{
private List<string> _id;
/// <summary>
/// Gets and sets the Id property.
/// </summary>
[XmlElementAttribute(ElementName = "Id")]
public List<string> Id
{
get
{
if(this._id == null)
{
this._id = new List<string>();
}
return this._id;
}
set { this._id = value; }
}
/// <summary>
/// Sets the Id property.
/// </summary>
/// <param name="id">Id property.</param>
/// <returns>this instance.</returns>
public AsinList WithId(string[] id)
{
this._id.AddRange(id);
return this;
}
/// <summary>
/// Checks if Id property is set.
/// </summary>
/// <returns>true if Id property is set.</returns>
public bool IsSetId()
{
return this.Id.Count > 0;
}
public override void ReadFragmentFrom(IMwsReader reader)
{
_id = reader.ReadList<string>("Id");
}
public override void WriteFragmentTo(IMwsWriter writer)
{
writer.WriteList("Id", _id);
}
public override void WriteTo(IMwsWriter writer)
{
writer.Write("http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/", "AsinList", this);
}
public AsinList() : base()
{
}
}
}
| 30.043478 | 121 | 0.549204 | [
"BSD-3-Clause"
] | skuvault-integrations/amazonAccess | src/AmazonAccess/Services/FBAInbound/Model/AsinList.cs | 2,764 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Moq;
using StoreBL;
using StoreModels;
using StoreMVC.Controllers;
using StoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
namespace StoreTests
{
public class ProductControllerTest
{
[Fact]
public void ProductControllerShouldReturnIndex()
{
//Arrange
//Creating a stub of IProductBL using Moq the framework and in Moq, fake objects
// are called Mock
var mockRepo = new Mock<IProductBL>();
// This is just us defining what the stub would do/return if the method GetProductes() is called
// We're returning a static list of customeres
mockRepo.Setup(x => x.GetProducts())
.Returns(new List<Product>()
{
new Product
{
Id = 1,
ProdName = "bProduct",
ProdPrice = 24,
ProdCategory = (Category)4,
ProdBrandName = "bBrand",
Description = "Pending",
},
new Product
{
Id = 2,
ProdName = "aProduct",
ProdPrice = 420,
ProdCategory = (Category)2,
ProdBrandName = "aBrand",
Description = "Pending",
}
}
);
//I really don't need to create a fake mapper because the real one doesn't affect the
// state of my data, just its type, (it just casts stuff)
var controller = new ProductController(mockRepo.Object, new Mapper());
//Act
var result = controller.Index();
//Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<IEnumerable<ProductIndexVM>>(viewResult.ViewData.Model);
Assert.Equal(2, model.Count());
}
}
}
| 33.151515 | 108 | 0.508684 | [
"MIT"
] | rjhakes/Rich_Hakes-P1 | StoreApp/StoreTests/ProductControllerTest.cs | 2,190 | C# |
namespace CaliburnMicroSample.Helpers
{
using System.Threading.Tasks;
public static class TaskHelper
{
#if SILVERLIGHT
public static Task<T> FromResult<T>(T result)
{
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(result);
return tcs.Task;
}
public static Task Delay(int milliseconds)
{
return Task.Factory.StartNew(() => Thread.Sleep(milliseconds));
}
#else
public static Task<T> FromResult<T>(T result) => Task.FromResult(result);
public static Task Delay(int milliseconds) => Task.Delay(milliseconds);
#endif
}
}
| 23.5 | 81 | 0.609422 | [
"MIT"
] | KKKKKKi/Caliburn.Micro-Sample | CaliburnMicroSample/Helpers/TaskHelper.cs | 660 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly: AssemblyTitle("Dev.DevKit.CustomApi.Test")]
[assembly: AssemblyDescription("Generated by DynamicsCrm.DevKit - 2.13.33 - https://github.com/phuocle/Dynamics-Crm-DevKit")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dev.DevKit.CustomApi.Test")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("en")]
[assembly: SecurityRules(SecurityRuleSet.Level2)]
[assembly: ComVisible(false)]
[assembly: Guid("a8dba8e7-2209-49c3-81da-670927f30bbe")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 36.636364 | 125 | 0.772953 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.13.33/TestUnitTest/Dev.DevKit.CustomApi.Test/Properties/AssemblyInfo.cs | 809 | C# |
using System;
using System.Collections.Generic;
namespace IngameScript
{
public struct RefineryType
{
public readonly string BlockDefinitionName;
public readonly ICollection<string> SupportedBlueprints;
public double Efficiency;
public double Speed;
public RefineryType(string subTypeName) : this()
{
BlockDefinitionName = String.Intern("MyObjectBuilder_Refinery/" + subTypeName);
Efficiency = 1;
Speed = 1;
SupportedBlueprints = new HashSet<string>();
}
public bool Supports(Blueprint bp)
{
return SupportedBlueprints.Contains(bp.Name);
}
}
}
| 24.4 | 92 | 0.598361 | [
"Unlicense"
] | alex-davidson/SEScriptDev | Script.RefineryBalance.v2/RefineryType.cs | 734 | C# |
namespace PF {
/** Simple implementation of a GUID.
* \version Since 3.6.4 this struct works properly on platforms with different endianness such as Wii U.
*/
public struct Guid {
const string hex = "0123456789ABCDEF";
public static readonly Guid zero = new Guid(new byte[16]);
public static readonly string zeroString = new Guid(new byte[16]).ToString();
readonly ulong _a, _b;
public Guid (byte[] bytes) {
// Pack 128 bits into 2 longs
ulong a = ((ulong)bytes[0] << 8*0) |
((ulong)bytes[1] << 8*1) |
((ulong)bytes[2] << 8*2) |
((ulong)bytes[3] << 8*3) |
((ulong)bytes[4] << 8*4) |
((ulong)bytes[5] << 8*5) |
((ulong)bytes[6] << 8*6) |
((ulong)bytes[7] << 8*7);
ulong b = ((ulong)bytes[8] << 8*0) |
((ulong)bytes[9] << 8*1) |
((ulong)bytes[10] << 8*2) |
((ulong)bytes[11] << 8*3) |
((ulong)bytes[12] << 8*4) |
((ulong)bytes[13] << 8*5) |
((ulong)bytes[14] << 8*6) |
((ulong)bytes[15] << 8*7);
// Need to swap endianness on e.g Wii U
_a = System.BitConverter.IsLittleEndian ? a : SwapEndianness(a);
_b = System.BitConverter.IsLittleEndian ? b : SwapEndianness(b);
}
public Guid (string str) {
_a = 0;
_b = 0;
if (str.Length < 32)
throw new System.FormatException("Invalid Guid format");
int counter = 0;
int i = 0;
int offset = 15*4;
for (; counter < 16; i++) {
if (i >= str.Length)
throw new System.FormatException("Invalid Guid format. String too short");
char c = str[i];
if (c == '-') continue;
//Neat trick, perhaps a bit slow, but one will probably not use Guid parsing that much
int value = hex.IndexOf(char.ToUpperInvariant(c));
if (value == -1)
throw new System.FormatException("Invalid Guid format : "+c+" is not a hexadecimal character");
_a |= (ulong)value << offset;
//SetByte (counter,(byte)value);
offset -= 4;
counter++;
}
offset = 15*4;
for (; counter < 32; i++) {
if (i >= str.Length)
throw new System.FormatException("Invalid Guid format. String too short");
char c = str[i];
if (c == '-') continue;
//Neat trick, perhaps a bit slow, but one will probably not use Guid parsing that much
int value = hex.IndexOf(char.ToUpperInvariant(c));
if (value == -1)
throw new System.FormatException("Invalid Guid format : "+c+" is not a hexadecimal character");
_b |= (ulong)value << offset;
//SetByte (counter,(byte)value);
offset -= 4;
counter++;
}
}
public static Guid Parse (string input) {
return new Guid(input);
}
/** Swaps between little and big endian */
static ulong SwapEndianness (ulong value) {
var b1 = (value >> 0) & 0xff;
var b2 = (value >> 8) & 0xff;
var b3 = (value >> 16) & 0xff;
var b4 = (value >> 24) & 0xff;
var b5 = (value >> 32) & 0xff;
var b6 = (value >> 40) & 0xff;
var b7 = (value >> 48) & 0xff;
var b8 = (value >> 56) & 0xff;
return b1 << 56 | b2 << 48 | b3 << 40 | b4 << 32 | b5 << 24 | b6 << 16 | b7 << 8 | b8 << 0;
}
public byte[] ToByteArray () {
var bytes = new byte[16];
byte[] ba = System.BitConverter.GetBytes(!System.BitConverter.IsLittleEndian ? SwapEndianness(_a) : _a);
byte[] bb = System.BitConverter.GetBytes(!System.BitConverter.IsLittleEndian ? SwapEndianness(_b) : _b);
for (int i = 0; i < 8; i++) {
bytes[i] = ba[i];
bytes[i+8] = bb[i];
}
return bytes;
}
private static System.Random random = new System.Random();
public static Guid NewGuid () {
var bytes = new byte[16];
random.NextBytes(bytes);
return new Guid(bytes);
}
public static bool operator == (Guid lhs, Guid rhs) {
return lhs._a == rhs._a && lhs._b == rhs._b;
}
public static bool operator != (Guid lhs, Guid rhs) {
return lhs._a != rhs._a || lhs._b != rhs._b;
}
public override bool Equals (System.Object _rhs) {
if (!(_rhs is Guid)) return false;
var rhs = (Guid)_rhs;
return _a == rhs._a && _b == rhs._b;
}
public override int GetHashCode () {
ulong ab = _a ^ _b;
return (int)(ab >> 32) ^ (int)ab;
}
private static System.Text.StringBuilder text;
public override string ToString () {
if (text == null) {
text = new System.Text.StringBuilder();
}
lock (text) {
text.Length = 0;
text.Append(_a.ToString("x16")).Append('-').Append(_b.ToString("x16"));
return text.ToString();
}
}
}
}
| 27.411043 | 107 | 0.585273 | [
"MIT"
] | 13294029724/ET | Unity/Assets/Model/Module/Pathfinding/Recast/Guid.cs | 4,468 | C# |
/*
Copyright 2007-2017 The NGenerics Team
(https://github.com/ngenerics/ngenerics/wiki/Team)
This program is licensed under the MIT License. You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at https://opensource.org/licenses/MIT.
*/
using System;
using NGenerics.DataStructures.Mathematical;
using NUnit.Framework;
namespace NGenerics.Tests.DataStructures.Mathematical.Vector3DTests
{
[TestFixture]
public class GreaterThanOperator
{
[Test]
public void Simple()
{
var vector1 = new Vector3D(1, 1, 1);
var vector2 = new Vector3D(2, 2, 2);
var vector3 = new Vector3D(2, 2, 2);
Assert.IsFalse(vector1 > vector2);
Assert.IsTrue(vector2 > vector1);
Assert.IsFalse(vector2 > vector3);
}
[Test]
public void ExceptionLeftNull()
{
const Vector3D vector1 = null;
var vector2 = new Vector3D(2, 2, 2);
bool condition;
Assert.Throws<ArgumentNullException>(() => condition = vector1 > vector2);
}
[Test]
public void ExceptionRightNull()
{
var vector1 = new Vector3D(2, 2, 2);
const Vector3D vector2 = null;
bool condition;
Assert.Throws<ArgumentNullException>(() => condition = vector1 > vector2);
}
}
} | 28.72549 | 88 | 0.603413 | [
"MIT"
] | ngenerics/ngenerics | src/NGenerics.Tests/DataStructures/Mathematical/Vector3DTests/GreaterThanOperator.cs | 1,465 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Request to get all the information of a Route Point instance.
/// The response is either GroupRoutePointGetInstanceResponse19sp1 or ErrorResponse.
/// The Following elements are only used in AS data mode and ignored in XS data mode:
/// - sendCallAdmissionNotification, use value ‘false’ in XS data mode.
/// - callAdmissionTimerSeconds, use value ‘3’ in XS data mode.
/// <see cref="GroupRoutePointGetInstanceResponse19sp1"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""a27224a048c30ff69eab9209dec841cc:606""}]")]
public class GroupRoutePointGetInstanceRequest23 : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.GroupRoutePointGetInstanceResponse19sp1>
{
private string _serviceUserId;
[XmlElement(ElementName = "serviceUserId", IsNullable = false, Namespace = "")]
[Group(@"a27224a048c30ff69eab9209dec841cc:606")]
[MinLength(1)]
[MaxLength(161)]
public string ServiceUserId
{
get => _serviceUserId;
set
{
ServiceUserIdSpecified = true;
_serviceUserId = value;
}
}
[XmlIgnore]
protected bool ServiceUserIdSpecified { get; set; }
}
}
| 35.782609 | 172 | 0.674362 | [
"MIT"
] | cwmiller/broadworks-connector-net | BroadworksConnector/Ocip/Models/GroupRoutePointGetInstanceRequest23.cs | 1,654 | C# |
using System;
using System.Diagnostics;
namespace Lucene.Net.Util.Fst
{
/*
* 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 DataInput = Lucene.Net.Store.DataInput;
using DataOutput = Lucene.Net.Store.DataOutput;
/// <summary>
/// An FST <seealso cref="Outputs"/> implementation where each output
/// is a non-negative long value.
///
/// @lucene.experimental
/// </summary>
public sealed class PositiveIntOutputs : Outputs<long>
{
private static readonly long NO_OUTPUT = new long();
private static readonly PositiveIntOutputs singleton = new PositiveIntOutputs();
private PositiveIntOutputs()
{
}
public static PositiveIntOutputs Singleton
{
get
{
return singleton;
}
}
public override long Common(long output1, long output2)
{
Debug.Assert(Valid(output1));
Debug.Assert(Valid(output2));
if (output1 == NO_OUTPUT || output2 == NO_OUTPUT)
{
return NO_OUTPUT;
}
else
{
Debug.Assert(output1 > 0);
Debug.Assert(output2 > 0);
return Math.Min(output1, output2);
}
}
public override long Subtract(long output, long inc)
{
Debug.Assert(Valid(output));
Debug.Assert(Valid(inc));
Debug.Assert(output >= inc);
if (inc == NO_OUTPUT)
{
return output;
}
else if (output.Equals(inc))
{
return NO_OUTPUT;
}
else
{
return output - inc;
}
}
public override long Add(long prefix, long output)
{
Debug.Assert(Valid(prefix));
Debug.Assert(Valid(output));
if (prefix == NO_OUTPUT)
{
return output;
}
else if (output == NO_OUTPUT)
{
return prefix;
}
else
{
return prefix + output;
}
}
public override void Write(long output, DataOutput @out)
{
Debug.Assert(Valid(output));
@out.WriteVLong(output);
}
public override long Read(DataInput @in)
{
long v = @in.ReadVLong();
if (v == 0)
{
return NO_OUTPUT;
}
else
{
return v;
}
}
private bool Valid(long o)
{
Debug.Assert(o != null);
Debug.Assert(o == NO_OUTPUT || o > 0, "o=" + o);
return true;
}
public override long NoOutput
{
get
{
return NO_OUTPUT;
}
}
public override string OutputToString(long output)
{
return output.ToString();
}
public override string ToString()
{
return "PositiveIntOutputs";
}
}
} | 27.209459 | 88 | 0.508567 | [
"Apache-2.0"
] | paulirwin/lucene.net | src/Lucene.Net.Core/Util/Fst/PositiveIntOutputs.cs | 4,027 | C# |
using System;
namespace JustAssembly.CommandLineTool.Nodes
{
public class ModuleNode : INode
{
}
} | 12.333333 | 44 | 0.702703 | [
"Apache-2.0"
] | rubicon-oss/Fork.JustAssembly | UI/JustAssembly.CommandLineTool/ModuleNode.cs | 113 | C# |
/*
© Cutter Systems spol. s r.o., 2018
Author: Petr Kalandra (kalandra@cutter.cz)
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 Newtonsoft.Json;
using System.Collections.Generic;
using RosSharp.RosBridgeClient.Messages.Standard;
namespace RosSharp.RosBridgeClient.Messages.Gazebo
{
public class ModelState
{
[JsonIgnore]
public const string RosMessageName = "gazebo_msgs/ModelState";
// Set Gazebo Model pose and twist
public string model_name;
public RosSharp.RosBridgeClient.Messages.Geometry.Pose pose;
public RosSharp.RosBridgeClient.Messages.Geometry.Twist twist;
public string reference_frame;
// leave empty or "world" or "map" defaults to world-frame
public ModelState()
{
model_name = string.Empty;
pose = new RosSharp.RosBridgeClient.Messages.Geometry.Pose();
twist = new RosSharp.RosBridgeClient.Messages.Geometry.Twist();
reference_frame = string.Empty;
}
}
}
| 29.829787 | 72 | 0.773894 | [
"Apache-2.0"
] | kaldap/ros-sharp | Libraries/RosBridgeClient/Messages/Gazebo/ModelState.cs | 1,403 | C# |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit
{
using System;
using RabbitMqTransport.Specifications;
public static class DelayedExchangeSchedulerExtensions
{
/// <summary>
/// Uses the RabbitMQ Delayed ExchangeName plugin to schedule messages for future delivery. A lightweight
/// alternative to Quartz, which does not require any storage outside of RabbitMQ.
/// </summary>
/// <param name="configurator"></param>
public static void UseDelayedExchangeMessageScheduler(this IBusFactoryConfigurator configurator)
{
if (configurator == null)
throw new ArgumentNullException(nameof(configurator));
var specification = new DelayedExchangeMessageSchedulerSpecification();
configurator.AddPipeSpecification(specification);
}
}
} | 42.083333 | 114 | 0.689109 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit.RabbitMqTransport/Configuration/DelayedExchangeSchedulerExtensions.cs | 1,517 | C# |
using System;
using Server;
using Server.Misc;
namespace Server.Items
{
public class RuinedTapestry : Item
{
public override string DefaultName{ get { return "Ruined Tapestry "; } }
[Constructable]
public RuinedTapestry()
: base( Utility.RandomBool() ? 0x4699 : 0x469A )
{
}
public RuinedTapestry( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( ( int )0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
}
| 17.27027 | 74 | 0.668232 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Holiday Stuff/Halloween/2006/Items/RuinedTapestry.cs | 641 | C# |
using System;
using Android.App;
using HockeyApp;
using liquidtorque.DataAccessLayer;
using Parse;
using WizarDroid.NET;
using WizarDroid.NET.Infrastructure.Layouts;
using WizarDroid.NET.Persistence;
namespace liquidtorque.Wizards.SignUpWizard
{
[Activity(Label = "User signup form wizard")]
public class SignUpWizard : BasicWizardLayout
{
[WizardState] public UserProfile UserProfile;
[WizardState] public DealerProfile DealerProfile;
readonly DataManager _dataManager = DataManager.GetInstance();
private bool _alreadyRun;
string _message = "Signup not successfull, please try again";
public SignUpWizard()
{
WizardCompleted += OnWizardComplete;
}
public override WizardFlow OnSetup()
{
return new WizardFlow.Builder()
.AddStep(new AccountTypeFragment(), true /*isRequired*/)
.AddStep(new CountryFragment(), true /*isRequired*/)
.AddStep(new UserProfileFragment(), true /*isRequired*/)
.AddStep(new TermsOfService(), true /*isRequired*/)
.AddStep(new EmailCodeFragment(), true /*isRequired*/)
.AddStep(new SmsCodeFragment(), true /*isRequired*/)
.Create();
}
async void OnWizardComplete()
{
ParseUser.LogOut(); //clear any sessions
try
{
string jsonObj = null;
string selectedAccountType = null;
bool successFull = false;
//sequential checking
if (DealerProfile != null && DealerProfile.userProfile != null &&
DealerProfile.userProfile.userType != null)
{
selectedAccountType = DealerProfile.userProfile.userType;
}
else if (UserProfile != null && UserProfile.userType != null)
{
selectedAccountType = UserProfile.userType;
}
if (!_alreadyRun)
{
_alreadyRun = true;
//now we can post to parse and tell the user that the sign up is successfull
if (selectedAccountType == "Dealer")
{
if (DealerProfile != null)
{
var licensePath = DealerProfile.dealerLicense;
//save the dealer
successFull = await _dataManager.signUpDealer(DealerProfile, licensePath);
jsonObj = Newtonsoft.Json.JsonConvert.SerializeObject(DealerProfile);
}
}
else if (selectedAccountType == "Private Party")
{
//save the regular user
successFull = await _dataManager.signUpPrivateParty(UserProfile);
jsonObj = Newtonsoft.Json.JsonConvert.SerializeObject(UserProfile);
}
if (successFull)
{
_message = "Signup Successfull";
}
}
Android.Util.Log.Info("CustomerWizard", jsonObj);
Android.Widget.Toast.MakeText(Application.Context, _message, Android.Widget.ToastLength.Long)
.Show();
Activity.Finish();
}
catch (ParseException ex)
{
var message = "Error saving to parse " + ex.Message + ex.StackTrace;
Console.WriteLine(message);
MetricsManager.TrackEvent(message);
}
catch (Exception ex)
{
var message = "Error saving to profile data " + ex.Message + ex.StackTrace;
Console.WriteLine(message);
MetricsManager.TrackEvent(message);
}
}
}
} | 37.64486 | 109 | 0.522344 | [
"Apache-2.0"
] | fatelord/automotive | LiquidTorque/Wizards/SignUpWizard/SignUpWizard.cs | 4,028 | C# |
// <copyright file="OauthRequests.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using Stormpath.SDK.Impl.Oauth;
namespace Stormpath.SDK.Oauth
{
/// <summary>
/// Static entry point for working with OAuth 2.0 requests.
/// </summary>
public static class OauthRequests
{
/// <summary>
/// Start a new Password Grant request.
/// </summary>
/// <returns>
/// A new <see cref="IPasswordGrantRequestBuilder"/> instance, used to construct <see cref="IPasswordGrantRequest">Password Grant requests</see>.
/// </returns>
[Obsolete("Use new PasswordGrantRequest()")]
public static IPasswordGrantRequestBuilder NewPasswordGrantRequest()
=> new DefaultPasswordGrantRequestBuilder();
/// <summary>
/// Start a new JSON Web Token Authentication request.
/// </summary>
/// <returns>
/// A new <see cref="IJwtAuthenticationRequestBuilder"/> instance, used to construct <see cref="IJwtAuthenticationRequest">JWT Authentication requests</see>.
/// </returns>
public static IJwtAuthenticationRequestBuilder NewJwtAuthenticationRequest()
=> new DefaultJwtAuthenticationRequestBuilder();
/// <summary>
/// Start a new ID Site Token Authentication request.
/// </summary>
/// <returns>
/// A new <see cref="IIdSiteTokenAuthenticationRequestBuilder"/> instance, used to construct <see cref="IIdSiteTokenAuthenticationRequest">ID Site Token Authentication requests</see>.
/// </returns>
[Obsolete("Use new StormpathTokenGrantRequest()")]
public static IIdSiteTokenAuthenticationRequestBuilder NewIdSiteTokenAuthenticationRequest()
=> new DefaultIdSiteTokenAuthenticationRequestBuilder();
/// <summary>
/// Start a new Refresh Grant request.
/// </summary>
/// <returns>
/// A new <see cref="IRefreshGrantRequestBuilder"/> instance, used to construct <see cref="IRefreshGrantRequest">Refresh Grant requests</see>.
/// </returns>
[Obsolete("Use new RefreshGrantRequest()")]
public static IRefreshGrantRequestBuilder NewRefreshGrantRequest()
=> new DefaultRefreshGrantRequestBuilder();
}
}
| 43.328358 | 191 | 0.673441 | [
"Apache-2.0"
] | stormpath/stormpath-sdk-csharp | src/Stormpath.SDK.Core/Oauth/OauthRequests.cs | 2,905 | C# |
using Orchard.OpenId.Models;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Orchard.OpenId.ViewModels
{
public class CreateOpenIdApplicationViewModel
{
[Required]
public string ClientId { get; set; }
[Required]
public string DisplayName { get; set; }
[Url]
public string RedirectUri { get; set; }
[Url]
public string LogoutRedirectUri { get; set; }
public ClientType Type { get; set; }
public bool SkipConsent { get; set; }
[DataType(DataType.Password)]
public string ClientSecret { get; set; }
[DataType(DataType.Password)]
[Compare("ClientSecret")]
public string ConfirmClientSecret { get; set; }
public List<RoleEntry> RoleEntries { get; set; } = new List<RoleEntry>();
public bool AllowPasswordFlow { get; set; }
public bool AllowClientCredentialsFlow { get; set; }
public bool AllowAuthorizationCodeFlow { get; set; }
public bool AllowRefreshTokenFlow { get; set; }
public bool AllowImplicitFlow { get; set; }
public bool AllowHybridFlow { get; set; }
}
public class RoleEntry
{
public string Name { get; set; }
public bool Selected { get; set; }
}
}
| 32.95 | 81 | 0.631259 | [
"BSD-3-Clause"
] | hishamco/Orchard2 | src/OrchardCore.Modules/Orchard.OpenId/ViewModels/CreateOpenIdApplicationViewModel.cs | 1,320 | C# |
using System;
using System.Collections.Generic;
namespace CombatTest.Utils
{
public static class ListExtensions
{
public static T GetRandomElement<T>(this IList<T> list, Random rng)
{
return list[rng.Next(list.Count)];
}
}
}
| 20.571429 | 76 | 0.604167 | [
"MIT"
] | joaokucera/csharp-combat-system | src/CombatTest/Utils/ListExtensions.cs | 290 | C# |
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class UES_WireRope : MonoBehaviour
{
public float hang = 0.5F, vertexCount = 3, width = 0.25F;
public LineRenderer rope;
public List<Vector3> ropeLocalPositions = new List<Vector3>();
public Color emissionColor = Color.blue;
public ARX_Script_IndividualColor mo_colorer;
public GameObject mo_endObject;
ARX_Script_IndividualColor GetColorer
{
get
{
if (mo_colorer == null)
mo_colorer = GetComponent<ARX_Script_IndividualColor>();
return mo_colorer;
}
}
ARX.UnityTimer timer = new ARX.UnityTimer();
private void FixedUpdate()
{
if (timer.mb_active == false)
return;
timer.Tick();
if (timer.IsFinished)
{
OnPowerDown();
timer.mb_active = false;
}
}
private void Start()
{
OnPowerDown();
}
private void Update()
{
rope.widthCurve = new AnimationCurve(new Keyframe(1, width));
UpdateRopePositions();
GetColorer.mo_color = emissionColor;
if (ropeLocalPositions.Count < 1)
{
ropeLocalPositions.Add(Vector3.zero);
}
if (mo_endObject != null && ropeLocalPositions.Count < 2)
{
ropeLocalPositions.Add(Vector3.zero);
}
if (mo_endObject != null && ropeLocalPositions.Count > 1)
{
int nLastPosition = ropeLocalPositions.Count - 1;
ropeLocalPositions.Remove(ropeLocalPositions[nLastPosition]);
Vector3 dif = mo_endObject.transform.position - transform.position;
ropeLocalPositions.Add(dif);
}
}
public List<Vector3> GetTranslatedRopePositions()
{
List<Vector3> bufRopePivotPoints = new List<Vector3>(ropeLocalPositions);
if (bufRopePivotPoints.Count <= 1)
return bufRopePivotPoints;
var pointList = new List<Vector3>();
//Add this object's current position to the points
//since they are local positions
for (int i = 0; i < bufRopePivotPoints.Count; i++)
{
bufRopePivotPoints[i] += transform.position;
}
//Create curved sub points
for (int i = 0; i < bufRopePivotPoints.Count -1; i++)
{
Vector3 Point1, Point2, Point3;
Point1 = bufRopePivotPoints[i];
Point3 = bufRopePivotPoints[i + 1];
float Point2Ypositio = Point3.y - hang;
Point2 = new Vector3((Point1.x + Point3.x)/2, Point2Ypositio, (Point1.z + Point3.z) / 2);
for (float ratio = 0; ratio <= 1; ratio += 1 / vertexCount)
{
var tangent1 = Vector3.Lerp(Point1, Point2, ratio);
var tangent2 = Vector3.Lerp(Point2, Point3, ratio);
var curve = Vector3.Lerp(tangent1, tangent2, ratio);
pointList.Add(curve);
}
}
////Create the curve of the last point
//{
// Vector3 Point1, Point2, Point3;
// Point1 = pointList[pointList.Count - 1];
// Point3 = bufRopePivotPoints[bufRopePivotPoints.Count - 1];
// float Point2Ypositio = Point3.y - hang;
// Point2 = new Vector3((Point1.x + Point3.x), Point2Ypositio, (Point1.z + Point3.z) / 2);
// for (float ratio = 0; ratio <= 1; ratio += 1 / vertexCount)
// {
// var tangent1 = Vector3.Lerp(Point1, Point2, ratio);
// var tangent2 = Vector3.Lerp(Point2, Point3, ratio);
// var curve = Vector3.Lerp(tangent1, tangent2, ratio);
// pointList.Add(curve);
// }
//}
pointList.Add(bufRopePivotPoints[bufRopePivotPoints.Count - 1]);
return pointList;
}
private void UpdateRopePositions()
{
List<Vector3> bufRope = GetTranslatedRopePositions();
rope.positionCount = bufRope.Count;
rope.SetPositions(bufRope.ToArray());
}
private void OnDrawGizmos()
{
float gizmoWidth = 0.05F;
Gizmos.DrawSphere(transform.position, gizmoWidth);
}
public void OnPowerUp() {
emissionColor = Color.blue;
}
public void OnPowerDown() {
emissionColor = Color.black;
}
public void OnTriggered()
{
emissionColor = Color.green;
timer.Start(0.1F);
}
} | 28.031056 | 101 | 0.573676 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | DeathCharm/Unity-Electric-Systems | Assets/UES_WireRope.cs | 4,513 | C# |
using ParkEco.CoreAPI.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ParkEco.CoreAPI.Repositories.Interfaces
{
public interface IParkingLotAttendantRepository
{
void Create(ParkingLotAttendant parkingLotAttendent);
void Update(ParkingLotAttendant parkingLotAttendant);
ParkingLotAttendant Get(string username);
List<ParkingLotAttendant> GetAll();
void Delete(string username);
bool IsPasswordCorrect(string username, string toBeVerifiedPassword);
}
}
| 28 | 77 | 0.756803 | [
"MIT"
] | park-eco/park-eco-server | ParkEco.CoreAPI/ParkEco.CoreAPI/Repositories/Interfaces/IParkingLotAttendantRepository.cs | 590 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Live-Video
* 直播管理API
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Live.Apis
{
/// <summary>
/// 删除录制回调配置
/// ///
/// </summary>
public class DeleteLiveStreamRecordNotifyConfigResult : JdcloudResult
{
}
} | 24.97619 | 76 | 0.701621 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Live/Apis/DeleteLiveStreamRecordNotifyConfigResult.cs | 1,073 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Bit.Model.Contracts;
namespace Bit.Model.DomainModels
{
[Table("UsersSettingsView", Schema = "Bit")]
public class UserSetting : IEntity, IDto
{
[Key]
public virtual long Id { get; set; }
[MaxLength(50)]
public virtual string Theme { get; set; }
[MaxLength(50)]
public virtual string Culture { get; set; }
[MaxLength(50)]
public virtual string DesiredTimeZone { get; set; }
[Required]
public virtual string UserId { get; set; }
[ConcurrencyCheck]
public virtual long Version { get; set; }
}
} | 25.068966 | 59 | 0.632737 | [
"MIT"
] | moshtaba/bit-framework | src/Server/Bit.Model/DomainModels/UserSetting.cs | 729 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("TESt")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DDGroup")]
[assembly: AssemblyProduct("TESt")]
[assembly: AssemblyCopyright("Copyright © DDGroup 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("2a9d83fb-e0e1-4f8c-8bd5-2df2d77a7f31")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер построения
// Редакция
//
// Можно задать все значения или принять номер построения и номер редакции по умолчанию,
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.486486 | 99 | 0.758427 | [
"MIT"
] | Innazvrtn/Algotask | Properties/AssemblyInfo.cs | 1,996 | C# |
//
// PersistentColumnController.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Hyena.Data;
using Hyena.Data.Gui;
using Banshee.Sources;
using Banshee.Configuration;
namespace Banshee.Collection.Gui
{
public class PersistentColumnController : ColumnController
{
private string root_namespace;
private bool loaded = false;
private bool pending_changes;
private uint timer_id = 0;
private string parent_source_ns;
private string source_ns;
private Source source;
public Source Source {
get { return source; }
set {
if (source == value) {
return;
}
if (source != null) {
Save ();
}
source = value;
source_ns = parent_source_ns = null;
if (source != null) {
// If we have a parent, use their UniqueId as a fallback in
// case this source's column settings haven't been changed
// from its parents
parent_source_ns = String.Format ("{0}.{1}.", root_namespace, source.ParentConfigurationId);
source_ns = String.Format ("{0}.{1}.", root_namespace, source.ConfigurationId);
Load ();
}
}
}
public PersistentColumnController (string rootNamespace) : base ()
{
if (String.IsNullOrEmpty (rootNamespace)) {
throw new ArgumentException ("Argument must not be null or empty", "rootNamespace");
}
root_namespace = rootNamespace;
}
public void Load ()
{
lock (this) {
if (source == null) {
return;
}
loaded = false;
int i = 0;
foreach (Column column in this) {
if (column.Id != null) {
column.Visible = Get<bool> (column.Id, "visible", column.Visible);
column.Width = Get<double> (column.Id, "width", column.Width);
column.OrderHint = Get<int> (column.Id, "order", i);
} else {
column.OrderHint = -1;
}
i++;
}
Columns.Sort ((a, b) => a.OrderHint.CompareTo (b.OrderHint));
string sort_column_id = Get<string> ("sort", "column", null);
if (sort_column_id != null) {
ISortableColumn sort_column = null;
foreach (Column column in this) {
if (column.Id == sort_column_id) {
sort_column = column as ISortableColumn;
break;
}
}
if (sort_column != null) {
int sort_dir = Get<int> ("sort", "direction", 0);
SortType sort_type = sort_dir == 0 ? SortType.None : sort_dir == 1 ? SortType.Ascending : SortType.Descending;
sort_column.SortType = sort_type;
base.SortColumn = sort_column;
}
} else {
base.SortColumn = null;
}
loaded = true;
}
OnUpdated ();
}
public override ISortableColumn SortColumn {
set { base.SortColumn = value; Save (); }
}
public void Save ()
{
if (timer_id == 0) {
timer_id = GLib.Timeout.Add (500, OnTimeout);
} else {
pending_changes = true;
}
}
private bool OnTimeout ()
{
if (pending_changes) {
pending_changes = false;
return true;
} else {
SaveCore ();
timer_id = 0;
return false;
}
}
private void SaveCore ()
{
lock (this) {
if (source == null) {
return;
}
for (int i = 0; i < Count; i++) {
if (Columns[i].Id != null) {
Save (Columns[i], i);
}
}
if (SortColumn != null) {
Set<string> ("sort", "column", SortColumn.Id);
Set<int> ("sort", "direction", (int)SortColumn.SortType);
}
}
}
private void Set<T> (string ns, string key, T val)
{
string conf_ns = source_ns + ns;
T result;
if (source_ns != parent_source_ns) {
if (!ConfigurationClient.TryGet<T> (conf_ns, key, out result) &&
val != null && val.Equals (ConfigurationClient.Get<T> (parent_source_ns + ns, key, default(T)))) {
conf_ns = null;
}
}
if (conf_ns != null) {
ConfigurationClient.Set<T> (conf_ns, key, val);
}
}
private T Get<T> (string ns, string key, T fallback)
{
T result;
if (ConfigurationClient.TryGet<T> (source_ns + ns, key, out result)) {
return result;
}
if (source_ns != parent_source_ns) {
return ConfigurationClient.Get<T> (parent_source_ns + ns, key, fallback);
}
return fallback;
}
private void Save (Column column, int index)
{
Set<int> (column.Id, "order", index);
Set<bool> (column.Id, "visible", column.Visible);
Set<double> (column.Id, "width", column.Width);
}
protected override void OnWidthsChanged ()
{
if (loaded) {
Save ();
}
base.OnWidthsChanged ();
}
public override bool EnableColumnMenu {
get { return true; }
}
}
}
| 32.113043 | 134 | 0.493772 | [
"MIT"
] | Dynalon/banshee-osx | src/Core/Banshee.ThickClient/Banshee.Collection.Gui/PersistentColumnController.cs | 7,386 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.