max_stars_repo_path
stringlengths
4
294
max_stars_repo_name
stringlengths
5
116
max_stars_count
float64
0
82k
id
stringlengths
1
8
content
stringlengths
1
1.04M
score
float64
-0.88
3.59
int_score
int64
0
4
libutils.tests/NiceIO/ParentContaining.cs
scottbilas/advent-of-code
3
4
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using NUnit.Framework; using Unity.Coding.Utils; namespace NiceIO.Tests { [TestFixture] class ParentContaining : TestWithTempDir { [Test] public void TwoLevelsDown() { PopulateTempDir(new[] { "somedir/", "somedir/dir2/", "somedir/dir2/myfile", "somedir/needle"}); Assert.AreEqual(_tempPath.Combine("somedir"), _tempPath.Combine("somedir/dir2/myfile").ParentContaining("needle")); } [Test] public void NonExisting() { PopulateTempDir(new[] { "somedir/", "somedir/dir2/", "somedir/dir2/myfile" }); Assert.IsNull(_tempPath.Combine("somedir/dir2/myfile").ParentContaining("nonexisting")); } [Test] public void WithComplexNeedle() { PopulateTempDir(new[] { "somedir/", "somedir/dir2/", "somedir/dir2/myfile" , "needledir/", "needledir/needlefile"}); Assert.AreEqual(_tempPath, _tempPath.Combine("somedir/dir2/myfile").ParentContaining(new NPath("needledir/needlefile"))); } [Test] public void InRelativePath() { Assert.Throws<ArgumentException>(() => new NPath("this/is/relative").ParentContaining("needle")); } } }
1.703125
2
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs.cs
alexbowers/pulumi-aws
0
12
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs : Pulumi.ResourceArgs { /// <summary> /// The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> [Input("priority", required: true)] public Input<int> Priority { get; set; } = null!; /// <summary> /// The transformation to apply, you can specify the following types: `NONE`, `COMPRESS_WHITE_SPACE`, `HTML_ENTITY_DECODE`, `LOWERCASE`, `CMD_LINE`, `URL_DECODE`. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArgs() { } } }
1.117188
1
Peeps.Monitoring.WebApp/Services/ModalService.cs
mc738/Peeps
0
20
using System; using Microsoft.AspNetCore.Components; namespace Peeps.Monitoring.WebApp.Services { public class ModalService { public event Action<string, RenderFragment> OnShow; public event Action OnClose; public void Show(string title, RenderFragment content) { // if (contentType.BaseType != typeof(ComponentBase)) // throw new ArgumentException($"{contentType.FullName} must be a Blazor Component"); // var content = new RenderFragment(x => { x.OpenComponent(1, contentType); x.CloseComponent(); }); OnShow?.Invoke(title, content); } public void Close() { OnClose?.Invoke(); } } }
1.101563
1
Ash.DefaultEC/UI/Containers/Container.cs
JonSnowbd/Nez
3
28
using System; using Microsoft.Xna.Framework; namespace Ash.UI { /// <summary> /// A group with a single child that sizes and positions the child using constraints. This provides layout similar to a /// {@link Table} with a single cell but is more lightweight. /// </summary> public class Container : Group { #region ILayout public override float MinWidth => GetMinWidth(); public override float MinHeight => GetPrefHeight(); public override float PreferredWidth => GetPrefWidth(); public override float PreferredHeight => GetPrefHeight(); public override float MaxWidth => GetMaxWidth(); public override float MaxHeight => GetMaxHeight(); #endregion Element _element; Value _minWidthValue = Value.MinWidth, _minHeightValue = Value.MinHeight; Value _prefWidthValue = Value.PrefWidth, _prefHeightValue = Value.PrefHeight; Value _maxWidthValue = Value.Zero, _maxHeightValue = Value.Zero; Value _padTop = Value.Zero, _padLeft = Value.Zero, _padBottom = Value.Zero, _padRight = Value.Zero; float _fillX, _fillY; int _align; IDrawable _background; bool _clip; bool _round = true; /// <summary> /// Creates a container with no element /// </summary> public Container() { SetTouchable(Touchable.ChildrenOnly); transform = false; } public Container(Element element) : this() { SetElement(element); } public override void Draw(Batcher batcher, float parentAlpha) { Validate(); if (transform) { ApplyTransform(batcher, ComputeTransform()); DrawBackground(batcher, parentAlpha, 0, 0); if (_clip) { //batcher.flush(); //float padLeft = this.padLeft.get( this ), padBottom = this.padBottom.get( this ); //if( clipBegin( padLeft, padBottom,minWidthValueh() - padLeft - padRight.get( tmaxWidth // getHeight() - padBottom - padTop.get( this ) ) ) { DrawChildren(batcher, parentAlpha); //batcher.flush(); //clipEnd(); } } else { DrawChildren(batcher, parentAlpha); } ResetTransform(batcher); } else { DrawBackground(batcher, parentAlpha, GetX(), GetY()); base.Draw(batcher, parentAlpha); } } /// <summary> /// Called to draw the background, before clipping is applied (if enabled). Default implementation draws the background drawable. /// </summary> /// <param name="batcher">Batcher.</param> /// <param name="parentAlpha">Parent alpha.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> protected void DrawBackground(Batcher batcher, float parentAlpha, float x, float y) { if (_background == null) return; _background.Draw(batcher, x, y, GetWidth(), GetHeight(), ColorExt.Create(color, (int) (color.A * parentAlpha))); } /// <summary> /// Sets the background drawable and adjusts the container's padding to match the background. /// </summary> /// <param name="background">Background.</param> public Container SetBackground(IDrawable background) { return SetBackground(background, true); } /// <summary> /// Sets the background drawable and, if adjustPadding is true, sets the container's padding to /// {@link Drawable#getBottomHeight()} , {@link Drawable#getTopHeight()}, {@link Drawable#getLeftWidth()}, and /// {@link Drawable#getRightWidth()}. /// If background is null, the background will be cleared and padding removed. /// </summary> /// <param name="background">Background.</param> /// <param name="adjustPadding">If set to <c>true</c> adjust padding.</param> public Container SetBackground(IDrawable background, bool adjustPadding) { if (_background == background) return this; _background = background; if (adjustPadding) { if (background == null) SetPad(Value.Zero); else SetPad(background.TopHeight, background.LeftWidth, background.BottomHeight, background.RightWidth); Invalidate(); } return this; } public IDrawable GetBackground() { return _background; } public override void Layout() { if (_element == null) return; float padLeft = _padLeft.Get(this), padBottom = _padBottom.Get(this); float containerWidth = GetWidth() - padLeft - _padRight.Get(this); float containerHeight = GetHeight() - padBottom - _padTop.Get(this); float minWidth = _minWidthValue.Get(_element), minHeight = _minHeightValue.Get(_element); float prefWidth = _prefWidthValue.Get(_element), prefHeight = _prefHeightValue.Get(_element); float maxWidth = _maxWidthValue.Get(_element), maxHeight = _maxHeightValue.Get(_element); float width; if (_fillX > 0) width = containerWidth * _fillX; else width = Math.Min(prefWidth, containerWidth); if (width < minWidth) width = minWidth; if (maxWidth > 0 && width > maxWidth) width = maxWidth; float height; if (_fillY > 0) height = containerHeight * _fillY; else height = Math.Min(prefHeight, containerHeight); if (height < minHeight) height = minHeight; if (maxHeight > 0 && height > maxHeight) height = maxHeight; var x = padLeft; if ((_align & AlignInternal.Right) != 0) x += containerWidth - width; else if ((_align & AlignInternal.Left) == 0) // center x += (containerWidth - width) / 2; var y = padBottom; if ((_align & AlignInternal.Top) != 0) y += containerHeight - height; else if ((_align & AlignInternal.Bottom) == 0) // center y += (containerHeight - height) / 2; if (_round) { x = Mathf.Round(x); y = Mathf.Round(y); width = Mathf.Round(width); height = Mathf.Round(height); } _element.SetBounds(x, y, width, height); if (_element is ILayout) ((ILayout) _element).Validate(); } /// <summary> /// element may be null /// </summary> /// <returns>The element.</returns> /// <param name="element">element.</param> public virtual Element SetElement(Element element) { if (element == this) throw new Exception("element cannot be the Container."); if (element == _element) return element; if (_element != null) base.RemoveElement(_element); _element = element; if (element != null) return AddElement(element); return null; } /// <summary> /// May be null /// </summary> /// <returns>The element.</returns> public T GetElement<T>() where T : Element { return _element as T; } /// <summary> /// May be null /// </summary> /// <returns>The element.</returns> public Element GetElement() { return _element; } public override bool RemoveElement(Element element) { if (element != _element) return false; SetElement(null); return true; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _minWidthValue = size; _minHeightValue = size; _prefWidthValue = size; _prefHeightValue = size; _maxWidthValue = size; _maxHeightValue = size; return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _minWidthValue = width; _minHeightValue = height; _prefWidthValue = width; _prefHeightValue = height; _maxWidthValue = width; _maxHeightValue = height; return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetSize(float size) { SetSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public new Container SetSize(float width, float height) { SetSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } /// <summary> /// Sets the minWidth, prefWidth, and maxWidth to the specified value /// </summary> /// <param name="width">Width.</param> public Container SetWidth(Value width) { if (width == null) throw new Exception("width cannot be null."); _minWidthValue = width; _prefWidthValue = width; _maxWidthValue = width; return this; } /// <summary> /// Sets the minWidth, prefWidth, and maxWidth to the specified value /// </summary> /// <param name="width">Width.</param> public new Container SetWidth(float width) { SetWidth(new Value.Fixed(width)); return this; } /// <summary> /// Sets the minHeight, prefHeight, and maxHeight to the specified value. /// </summary> /// <param name="height">Height.</param> public Container SetHeight(Value height) { if (height == null) throw new Exception("height cannot be null."); _minHeightValue = height; _prefHeightValue = height; _maxHeightValue = height; return this; } /// <summary> /// Sets the minHeight, prefHeight, and maxHeight to the specified value /// </summary> /// <param name="height">Height.</param> public new Container SetHeight(float height) { SetHeight(new Value.Fixed(height)); return this; } /// <summary> /// Sets the minWidth and minHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMinSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _minWidthValue = size; _minHeightValue = size; return this; } /// <summary> /// Sets the minimum size. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMinSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _minWidthValue = width; _minHeightValue = height; return this; } public Container SetMinWidth(Value minWidth) { if (minWidth == null) throw new Exception("minWidth cannot be null."); _minWidthValue = minWidth; return this; } public Container SetMinHeight(Value minHeight) { if (minHeight == null) throw new Exception("minHeight cannot be null."); _minHeightValue = minHeight; return this; } /// <summary> /// Sets the minWidth and minHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMinSize(float size) { SetMinSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the minWidth and minHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMinSize(float width, float height) { SetMinSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } public Container SetMinWidth(float minWidth) { _minWidthValue = new Value.Fixed(minWidth); return this; } public Container SetMinHeight(float minHeight) { _minHeightValue = new Value.Fixed(minHeight); return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified value. /// </summary> /// <param name="size">Size.</param> public Container PrefSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _prefWidthValue = size; _prefHeightValue = size; return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified values. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container PrefSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _prefWidthValue = width; _prefHeightValue = height; return this; } public Container SetPrefWidth(Value prefWidth) { if (prefWidth == null) throw new Exception("prefWidth cannot be null."); _prefWidthValue = prefWidth; return this; } public Container SetPrefHeight(Value prefHeight) { if (prefHeight == null) throw new Exception("prefHeight cannot be null."); _prefHeightValue = prefHeight; return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified value. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetPrefSize(float width, float height) { PrefSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } /// <summary> /// Sets the prefWidth and prefHeight to the specified values /// </summary> /// <param name="size">Size.</param> public Container SetPrefSize(float size) { PrefSize(new Value.Fixed(size)); return this; } public Container SetPrefWidth(float prefWidth) { _prefWidthValue = new Value.Fixed(prefWidth); return this; } public Container SetPrefHeight(float prefHeight) { _prefHeightValue = new Value.Fixed(prefHeight); return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified value. /// </summary> /// <param name="size">Size.</param> public Container SetMaxSize(Value size) { if (size == null) throw new Exception("size cannot be null."); _maxWidthValue = size; _maxHeightValue = size; return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMaxSize(Value width, Value height) { if (width == null) throw new Exception("width cannot be null."); if (height == null) throw new Exception("height cannot be null."); _maxWidthValue = width; _maxHeightValue = height; return this; } public Container SetMaxWidth(Value maxWidth) { if (maxWidth == null) throw new Exception("maxWidth cannot be null."); _maxWidthValue = maxWidth; return this; } public Container SetMaxHeight(Value maxHeight) { if (maxHeight == null) throw new Exception("maxHeight cannot be null."); _maxHeightValue = maxHeight; return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified value /// </summary> /// <param name="size">Size.</param> public Container SetMaxSize(float size) { SetMaxSize(new Value.Fixed(size)); return this; } /// <summary> /// Sets the maxWidth and maxHeight to the specified values /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public Container SetMaxSize(float width, float height) { SetMaxSize(new Value.Fixed(width), new Value.Fixed(height)); return this; } public Container SetMaxWidth(float maxWidth) { _maxWidthValue = new Value.Fixed(maxWidth); return this; } public Container SetMaxHeight(float maxHeight) { _maxHeightValue = new Value.Fixed(maxHeight); return this; } /// <summary> /// Sets the padTop, padLeft, padBottom, and padRight to the specified value. /// </summary> /// <param name="pad">Pad.</param> public Container SetPad(Value pad) { if (pad == null) throw new Exception("pad cannot be null."); _padTop = pad; _padLeft = pad; _padBottom = pad; _padRight = pad; return this; } public Container SetPad(Value top, Value left, Value bottom, Value right) { if (top == null) throw new Exception("top cannot be null."); if (left == null) throw new Exception("left cannot be null."); if (bottom == null) throw new Exception("bottom cannot be null."); if (right == null) throw new Exception("right cannot be null."); _padTop = top; _padLeft = left; _padBottom = bottom; _padRight = right; return this; } public Container SetPadTop(Value padTop) { if (padTop == null) throw new Exception("padTop cannot be null."); _padTop = padTop; return this; } public Container SetPadLeft(Value padLeft) { if (padLeft == null) throw new Exception("padLeft cannot be null."); _padLeft = padLeft; return this; } public Container SetPadBottom(Value padBottom) { if (padBottom == null) throw new Exception("padBottom cannot be null."); _padBottom = padBottom; return this; } public Container SetPadRight(Value padRight) { if (padRight == null) throw new Exception("padRight cannot be null."); _padRight = padRight; return this; } /// <summary> /// Sets the padTop, padLeft, padBottom, and padRight to the specified value /// </summary> /// <param name="pad">Pad.</param> public Container SetPad(float pad) { Value value = new Value.Fixed(pad); _padTop = value; _padLeft = value; _padBottom = value; _padRight = value; return this; } public Container SetPad(float top, float left, float bottom, float right) { _padTop = new Value.Fixed(top); _padLeft = new Value.Fixed(left); _padBottom = new Value.Fixed(bottom); _padRight = new Value.Fixed(right); return this; } public Container SetPadTop(float padTop) { _padTop = new Value.Fixed(padTop); return this; } public Container SetPadLeft(float padLeft) { _padLeft = new Value.Fixed(padLeft); return this; } public Container SetPadBottom(float padBottom) { _padBottom = new Value.Fixed(padBottom); return this; } public Container SetPadRight(float padRight) { _padRight = new Value.Fixed(padRight); return this; } /// <summary> /// Sets fillX and fillY to 1 /// </summary> public Container SetFill() { _fillX = 1f; _fillY = 1f; return this; } /// <summary> /// Sets fillX to 1 /// </summary> public Container SetFillX() { _fillX = 1f; return this; } /// <summary> /// Sets fillY to 1 /// </summary> public Container SetFillY() { _fillY = 1f; return this; } public Container SetFill(float x, float y) { _fillX = x; _fillY = y; return this; } /// <summary> /// Sets fillX and fillY to 1 if true, 0 if false /// </summary> /// <param name="x">If set to <c>true</c> x.</param> /// <param name="y">If set to <c>true</c> y.</param> public Container SetFill(bool x, bool y) { _fillX = x ? 1f : 0; _fillY = y ? 1f : 0; return this; } /// <summary> /// Sets fillX and fillY to 1 if true, 0 if false /// </summary> /// <param name="fill">If set to <c>true</c> fill.</param> public Container SetFill(bool fill) { _fillX = fill ? 1f : 0; _fillY = fill ? 1f : 0; return this; } /// <summary> /// Sets the alignment of the element within the container. Set to {@link Align#center}, {@link Align#top}, {@link Align#bottom}, /// {@link Align#left}, {@link Align#right}, or any combination of those. /// </summary> /// <param name="align">Align.</param> public Container SetAlign(Align align) { _align = (int) align; return this; } /// <summary> /// Sets the alignment of the element within the container to {@link Align#center}. This clears any other alignment. /// </summary> public Container SetAlignCenter() { _align = AlignInternal.Center; return this; } /// <summary> /// Sets {@link Align#top} and clears {@link Align#bottom} for the alignment of the element within the container. /// </summary> public Container SetTop() { _align |= AlignInternal.Top; _align &= ~AlignInternal.Bottom; return this; } /// <summary> /// Sets {@link Align#left} and clears {@link Align#right} for the alignment of the element within the container. /// </summary> public Container SetLeft() { _align |= AlignInternal.Left; _align &= ~AlignInternal.Right; return this; } /// <summary> /// Sets {@link Align#bottom} and clears {@link Align#top} for the alignment of the element within the container. /// </summary> public Container SetBottom() { _align |= AlignInternal.Bottom; _align &= ~AlignInternal.Top; return this; } /// <summary> /// Sets {@link Align#right} and clears {@link Align#left} for the alignment of the element within the container. /// </summary> public Container SetRight() { _align |= AlignInternal.Right; _align &= ~AlignInternal.Left; return this; } public float GetMinWidth() { return _minWidthValue.Get(_element) + _padLeft.Get(this) + _padRight.Get(this); } public Value GetMinHeightValue() { return _minHeightValue; } public float GetMinHeight() { return _minHeightValue.Get(_element) + _padTop.Get(this) + _padBottom.Get(this); } public Value GetPrefWidthValue() { return _prefWidthValue; } public float GetPrefWidth() { float v = _prefWidthValue.Get(_element); if (_background != null) v = Math.Max(v, _background.MinWidth); return Math.Max(GetMinWidth(), v + _padLeft.Get(this) + _padRight.Get(this)); } public Value GetPrefHeightValue() { return _prefHeightValue; } public float GetPrefHeight() { float v = _prefHeightValue.Get(_element); if (_background != null) v = Math.Max(v, _background.MinHeight); return Math.Max(GetMinHeight(), v + _padTop.Get(this) + _padBottom.Get(this)); } public Value GetMaxWidthValue() { return _maxWidthValue; } public float GetMaxWidth() { float v = _maxWidthValue.Get(_element); if (v > 0) v += _padLeft.Get(this) + _padRight.Get(this); return v; } public Value GetMaxHeightValue() { return _maxHeightValue; } public float GetMaxHeight() { float v = _maxHeightValue.Get(_element); if (v > 0) v += _padTop.Get(this) + _padBottom.Get(this); return v; } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad top value.</returns> public Value GetPadTopValue() { return _padTop; } public float GetPadTop() { return _padTop.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad left value.</returns> public Value GetPadLeftValue() { return _padLeft; } public float GetPadLeft() { return _padLeft.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad bottom value.</returns> public Value GetPadBottomValue() { return _padBottom; } public float GetPadBottom() { return _padBottom.Get(this); } /// <summary> /// May be null if this value is not set /// </summary> /// <returns>The pad right value.</returns> public Value GetPadRightValue() { return _padRight; } public float GetPadRight() { return _padRight.Get(this); } /// <summary> /// Returns {@link #getPadLeft()} plus {@link #getPadRight()}. /// </summary> /// <returns>The pad x.</returns> public float GetPadX() { return _padLeft.Get(this) + _padRight.Get(this); } /// <summary> /// Returns {@link #getPadTop()} plus {@link #getPadBottom()} /// </summary> /// <returns>The pad y.</returns> public float GetPadY() { return _padTop.Get(this) + _padBottom.Get(this); } public float GetFillX() { return _fillX; } public float GetFillY() { return _fillY; } public int GetAlign() { return _align; } /// <summary> /// If true (the default), positions and sizes are rounded to integers /// </summary> /// <param name="round">If set to <c>true</c> round.</param> public void SetRound(bool round) { _round = round; } /// <summary> /// Causes the contents to be clipped if they exceed the container bounds. Enabling clipping will set /// {@link #setTransform(bool)} to true /// </summary> /// <param name="enabled">If set to <c>true</c> enabled.</param> public void SetClip(bool enabled) { _clip = enabled; transform = enabled; Invalidate(); } public bool GetClip() { return _clip; } public override Element Hit(Vector2 point) { if (_clip) { if (GetTouchable() == Touchable.Disabled) return null; if (point.X < 0 || point.X >= GetWidth() || point.Y < 0 || point.Y >= GetHeight()) return null; } return base.Hit(point); } public override void DebugRender(Batcher batcher) { Validate(); if (transform) { ApplyTransform(batcher, ComputeTransform()); if (_clip) { //shapes.flush(); //float padLeft = this.padLeft.get( this ), padBottom = this.padBottom.get( this ); //bool draw = background == null ? clipBegin( 0, 0, getWidth(), getHeight() ) : clipBegin( padLeft, padBottom, // getWidth() - padLeft - padRight.get( this ), getHeight() - padBottom - padTop.get( this ) ); var draw = true; if (draw) { DebugRenderChildren(batcher, 1f); //clipEnd(); } } else { DebugRenderChildren(batcher, 1f); } ResetTransform(batcher); } else { base.DebugRender(batcher); } } } }
2.0625
2
PdfSharp/PdfSharp.Pdf.AcroForms/PdfAcroField.cs
alexiej/YATE
18
36
#region PDFsharp - A .NET library for processing PDF // // Authors: // <NAME> (mailto:<EMAIL>) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Collections; using PdfSharp.Pdf.Advanced; using PdfSharp.Pdf.Internal; namespace PdfSharp.Pdf.AcroForms { /// <summary> /// Represents the base class for all interactive field dictionaries. /// </summary> public abstract class PdfAcroField : PdfDictionary { /// <summary> /// Initializes a new instance of PdfAcroField. /// </summary> internal PdfAcroField(PdfDocument document) : base(document) { } /// <summary> /// Initializes a new instance of the <see cref="PdfAcroField"/> class. Used for type transformation. /// </summary> protected PdfAcroField(PdfDictionary dict) : base(dict) { } /// <summary> /// Gets the name of this field. /// </summary> public string Name { get { string name = Elements.GetString(Keys.T); return name; } } /// <summary> /// Gets the field flags of this instance. /// </summary> public PdfAcroFieldFlags Flags { // TODO: This entry is inheritable, thus the implementation is incorrect... id:102 gh:103 get { return (PdfAcroFieldFlags)Elements.GetInteger(Keys.Ff); } } internal PdfAcroFieldFlags SetFlags { get { return (PdfAcroFieldFlags)Elements.GetInteger(Keys.Ff); } set { Elements.SetInteger(Keys.Ff, (int)value); } } /// <summary> /// Gets or sets the value of the field. /// </summary> public PdfItem Value { get { return Elements[Keys.V]; } set { if (ReadOnly) throw new InvalidOperationException("The field is read only."); if (value is PdfString || value is PdfName) Elements[Keys.V] = value; else throw new NotImplementedException("Values other than string cannot be set."); } } /// <summary> /// Gets or sets a value indicating whether the field is read only. /// </summary> public bool ReadOnly { get { return (Flags & PdfAcroFieldFlags.ReadOnly) != 0; } set { if (value) SetFlags |= PdfAcroFieldFlags.ReadOnly; else SetFlags &= ~PdfAcroFieldFlags.ReadOnly; } } /// <summary> /// Gets the field with the specified name. /// </summary> public PdfAcroField this[string name] { get { return GetValue(name); } } /// <summary> /// Gets a child field by name. /// </summary> protected virtual PdfAcroField GetValue(string name) { if (name == null || name.Length == 0) return this; if (HasKids) return Fields.GetValue(name); return null; } /// <summary> /// Indicates whether the field has child fields. /// </summary> public bool HasKids { get { PdfItem item = Elements[Keys.Kids]; if (item == null) return false; if (item is PdfArray) return ((PdfArray)item).Elements.Count > 0; return false; } } /// <summary> /// Gets the names of all descendants of this field. /// </summary> public string[] DescendantNames { get { List<PdfName> names = new List<PdfName>(); if (HasKids) { PdfAcroFieldCollection fields = Fields; fields.GetDescendantNames(ref names, null); } List<string> temp = new List<string>(); foreach (PdfName name in names) temp.Add(name.ToString()); return temp.ToArray(); } } internal virtual void GetDescendantNames(ref List<PdfName> names, string partialName) { if (HasKids) { PdfAcroFieldCollection fields = Fields; string t = Elements.GetString(Keys.T); Debug.Assert(t != ""); if (t.Length > 0) { if (partialName != null && partialName.Length > 0) partialName += "." + t; else partialName = t; fields.GetDescendantNames(ref names, partialName); } } else { string t = Elements.GetString(Keys.T); Debug.Assert(t != ""); if (t.Length > 0) { if (!String.IsNullOrEmpty(partialName)) names.Add(new PdfName(partialName + "." + t)); else names.Add(new PdfName(t)); } } } /// <summary> /// Gets the collection of fields within this field. /// </summary> public PdfAcroField.PdfAcroFieldCollection Fields { get { if (this.fields == null) { object o = Elements.GetValue(Keys.Kids, VCF.CreateIndirect); this.fields = (PdfAcroField.PdfAcroFieldCollection)o; } return this.fields; } } PdfAcroField.PdfAcroFieldCollection fields; /// <summary> /// Holds a collection of interactive fields. /// </summary> public sealed class PdfAcroFieldCollection : PdfArray { PdfAcroFieldCollection(PdfArray array) : base(array) { } /// <summary> /// Gets the names of all fields in the collection. /// </summary> public string[] Names { get { int count = Elements.Count; string[] names = new string[count]; for (int idx = 0; idx < count; idx++) names[idx] = ((PdfDictionary)((PdfReference)Elements[idx]).Value).Elements.GetString(Keys.T); return names; } } /// <summary> /// Gets an array of all descendant names. /// </summary> public string[] DescendantNames { get { List<PdfName> names = new List<PdfName>(); GetDescendantNames(ref names, null); List<string> temp = new List<string>(); foreach (PdfName name in names) temp.Add(name.ToString()); return temp.ToArray(); } } internal void GetDescendantNames(ref List<PdfName> names, string partialName) { int count = Elements.Count; for (int idx = 0; idx < count; idx++) { PdfAcroField field = this[idx]; Debug.Assert(field != null); if (field != null) field.GetDescendantNames(ref names, partialName); } } /// <summary> /// Gets a field from the collection. For your convenience an instance of a derived class like /// PdfTextField or PdfCheckBox is returned if PDFsharp can guess the actual type of the dictionary. /// If the actual type cannot be guessed by PDFsharp the function returns an instance /// of PdfGenericField. /// </summary> public PdfAcroField this[int index] { get { PdfItem item = Elements[index]; Debug.Assert(item is PdfReference); PdfDictionary dict = ((PdfReference)item).Value as PdfDictionary; Debug.Assert(dict != null); PdfAcroField field = dict as PdfAcroField; if (field == null && dict != null) { // Do type transformation field = CreateAcroField(dict); //Elements[index] = field.XRef; } return field; } } /// <summary> /// Gets the field with the specified name. /// </summary> public PdfAcroField this[string name] { get { return GetValue(name); } } internal PdfAcroField GetValue(string name) { if (name == null || name.Length == 0) return null; int dot = name.IndexOf('.'); string prefix = dot == -1 ? name : name.Substring(0, dot); string suffix = dot == -1 ? "" : name.Substring(dot + 1); int count = Elements.Count; for (int idx = 0; idx < count; idx++) { PdfAcroField field = this[idx]; if (field.Name == prefix) return field.GetValue(suffix); } return null; } /// <summary> /// Create a derived type like PdfTextField or PdfCheckBox if possible. /// If the actual cannot be guessed by PDFsharp the function returns an instance /// of PdfGenericField. /// </summary> PdfAcroField CreateAcroField(PdfDictionary dict) { string ft = dict.Elements.GetName(Keys.FT); PdfAcroFieldFlags flags = (PdfAcroFieldFlags)dict.Elements.GetInteger(Keys.Ff); switch (ft) { case "/Btn": if ((flags & PdfAcroFieldFlags.Pushbutton) != 0) return new PdfPushButtonField(dict); else if ((flags & PdfAcroFieldFlags.Radio) != 0) return new PdfRadioButtonField(dict); else return new PdfCheckBoxField(dict); case "/Tx": return new PdfTextField(dict); case "/Ch": if ((flags & PdfAcroFieldFlags.Combo) != 0) return new PdfComboBoxField(dict); else return new PdfListBoxField(dict); case "/Sig": return new PdfSignatureField(dict); default: return new PdfGenericField(dict); } } } /// <summary> /// Predefined keys of this dictionary. /// The description comes from PDF 1.4 Reference. /// </summary> public class Keys : KeysBase { /// <summary> /// (Required for terminal fields; inheritable) The type of field that this dictionary /// describes: /// Btn Button /// Tx Text /// Ch Choice /// Sig (PDF 1.3) Signature /// Note: This entry may be present in a nonterminal field (one whose descendants /// are themselves fields) in order to provide an inheritable FT value. However, a /// nonterminal field does not logically have a type of its own; it is merely a container /// for inheritable attributes that are intended for descendant terminal fields of /// any type. /// </summary> [KeyInfo(KeyType.Name | KeyType.Required)] public const string FT = "/FT"; /// <summary> /// (Required if this field is the child of another in the field hierarchy; absent otherwise) /// The field that is the immediate parent of this one (the field, if any, whose Kids array /// includes this field). A field can have at most one parent; that is, it can be included /// in the Kids array of at most one other field. /// </summary> [KeyInfo(KeyType.Dictionary)] public const string Parent = "/Parent"; /// <summary> /// (Optional) An array of indirect references to the immediate children of this field. /// </summary> [KeyInfo(KeyType.Array | KeyType.Optional, typeof(PdfAcroField.PdfAcroFieldCollection))] public const string Kids = "/Kids"; /// <summary> /// (Optional) The partial field name. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string T = "/T"; /// <summary> /// (Optional; PDF 1.3) An alternate field name, to be used in place of the actual /// field name wherever the field must be identified in the user interface (such as /// in error or status messages referring to the field). This text is also useful /// when extracting the document�s contents in support of accessibility to disabled /// users or for other purposes. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string TU = "/TU"; /// <summary> /// (Optional; PDF 1.3) The mapping name to be used when exporting interactive form field /// data from the document. /// </summary> [KeyInfo(KeyType.TextString | KeyType.Optional)] public const string TM = "/TM"; /// <summary> /// (Optional; inheritable) A set of flags specifying various characteristics of the field. /// Default value: 0. /// </summary> [KeyInfo(KeyType.Integer | KeyType.Optional)] public const string Ff = "/Ff"; /// <summary> /// (Optional; inheritable) The field�s value, whose format varies depending on /// the field type; see the descriptions of individual field types for further information. /// </summary> [KeyInfo(KeyType.Various | KeyType.Optional)] public const string V = "/V"; /// <summary> /// (Optional; inheritable) The default value to which the field reverts when a /// reset-form action is executed. The format of this value is the same as that of V. /// </summary> [KeyInfo(KeyType.Various | KeyType.Optional)] public const string DV = "/DV"; /// <summary> /// (Optional; PDF 1.2) An additional-actions dictionary defining the field�s behavior /// in response to various trigger events. This entry has exactly the same meaning as /// the AA entry in an annotation dictionary. /// </summary> [KeyInfo(KeyType.Dictionary | KeyType.Optional)] public const string AA = "/AA"; // ----- Additional entries to all fields containing variable text -------------------------- /// <summary> /// (Required; inheritable) A resource dictionary containing default resources /// (such as fonts, patterns, or color spaces) to be used by the appearance stream. /// At a minimum, this dictionary must contain a Font entry specifying the resource /// name and font dictionary of the default font for displaying the field�s text. /// </summary> [KeyInfo(KeyType.Dictionary | KeyType.Required)] public const string DR = "/DR"; /// <summary> /// (Required; inheritable) The default appearance string, containing a sequence of /// valid page-content graphics or text state operators defining such properties as /// the field�s text size and color. /// </summary> [KeyInfo(KeyType.String | KeyType.Required)] public const string DA = "/DA"; /// <summary> /// (Optional; inheritable) A code specifying the form of quadding (justification) /// to be used in displaying the text: /// 0 Left-justified /// 1 Centered /// 2 Right-justified /// Default value: 0 (left-justified). /// </summary> [KeyInfo(KeyType.Integer | KeyType.Optional)] public const string Q = "/Q"; } } }
1.25
1
Manufaktura.Controls.Legacy/Rendering/ScoreRenderingModes.cs
prepare/Ajcek_manufakturalibraries
0
44
namespace Manufaktura.Controls.Rendering { public enum ScoreRenderingModes { /// <summary> /// All system breaks are ignored (the score is displayed in single staff system). /// </summary> Panorama, /// <summary> /// Only single page is displayed /// </summary> SinglePage, /// <summary> /// All pages are displayed /// </summary> AllPages } }
0.609375
1
Singonet.ir.UI.SQL_Connection/SQL_Connection_Class.cs
ShayanFiroozi/SQL_Server_Connection_Manager
1
52
/******************************************************************* * Forever <NAME> , Forever Persia * * * * ----> Singonet.ir <---- * * * * C# Singnet.ir * * * * By <NAME> 2017 <NAME> - Iran * * EMail : <EMAIL> * * Phone : +98 936 517 5800 * * * *******************************************************************/ using System; using System.Data.SqlClient; namespace Singonet.ir.UI.SQL_Connection { public static class SQL_Connection_Class { private static frm_theme_default _frm_connection; // main sql connection for user public static SqlConnection _SQL_Connection { get; internal set; } public enum UI_Theme { Default_Theme = 0, } public static void Show_SQL_Connection_Manager(string ApplicationName,UI_Theme _UI_Theme = UI_Theme.Default_Theme) { if (string.IsNullOrEmpty(ApplicationName)==true) { throw new Exception("Invalid Application Name."); } // Theme selection if (_UI_Theme == UI_Theme.Default_Theme) { _frm_connection = new frm_theme_default(ApplicationName); _frm_connection.ShowDialog(); } } } }
1.132813
1
src/EncompassRest/Loans/Enums/RefundableType.cs
Oxymoron290/EncompassRest
87
60
using System.ComponentModel; namespace EncompassRest.Loans.Enums { /// <summary> /// RefundableType /// </summary> public enum RefundableType { /// <summary> /// Non-Refundable /// </summary> [Description("Non-Refundable")] NonRefundable = 0, /// <summary> /// Refundable /// </summary> Refundable = 1, /// <summary> /// N/A (No funds collected at or prior to funding) /// </summary> [Description("N/A (No funds collected at or prior to funding)")] NA = 2 } }
1.195313
1
source/Brimborium.SchlangangerLibrary/Contracts/Interfaces.cs
grimmborium/Brimborium.Schlanganger
0
68
using Brimborium.Functional; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Brimborium.Contracts { public interface IEntity { } public interface IDynamicEntity : IEntity { } public interface IStaticEntity : IEntity { } public interface IMetaContainer : IEntity { } public interface IMetaEntity : IEntity { } public interface IMetaAction : IEntity { } public interface IMetaProperty : IEntity { } public interface IMetaBehaviour : IEntity { } public interface IMetaValue : IEntity { } public interface IEntityAdapter { MayBe<IMetaEntity> GetMetaEntityByType(Type type); MayBe<IMetaEntity> GetMetaEntityByObject(object entity); MayBe<IMetaEntity> GetMetaEntityByIEntity<TEntity>(TEntity entity) where TEntity: IEntity; } }
1.125
1
Test.Puzzle/Puzzle3x3/Builder.cs
JeffLeBert/RubiksCubeTrainer
0
76
namespace RubiksCubeTrainer.Puzzle3x3 { public static class Builder { public static Face BuildTestFace(FaceName faceName, int offset) => new Face( faceName, new PuzzleColor[Face.Size, Face.Size] { { (PuzzleColor)offset, (PuzzleColor)(offset + 3), (PuzzleColor)(offset + 6) }, { (PuzzleColor)(offset + 1), (PuzzleColor)(offset + 4), (PuzzleColor)(offset + 7) }, { (PuzzleColor)(offset + 2), (PuzzleColor)(offset + 5), (PuzzleColor)(offset + 8) } }); } }
1.203125
1
src/WireMock.Net/Settings/SimpleCommandLineParser.cs
leolplex/WireMock.Net
700
84
using System; using System.Collections.Generic; using System.Linq; namespace WireMock.Settings { // Based on http://blog.gauffin.org/2014/12/simple-command-line-parser/ internal class SimpleCommandLineParser { private const string Sigil = "--"; private IDictionary<string, string[]> Arguments { get; } = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); public void Parse(string[] arguments) { string currentName = null; var values = new List<string>(); // Split a single argument on a space character to fix issue (e.g. Azure Service Fabric) when an argument is supplied like "--x abc" or '--x abc' foreach (string arg in arguments.SelectMany(arg => arg.Split(' '))) { if (arg.StartsWith(Sigil)) { if (!string.IsNullOrEmpty(currentName)) { Arguments[currentName] = values.ToArray(); } values.Clear(); currentName = arg.Substring(Sigil.Length); } else if (string.IsNullOrEmpty(currentName)) { Arguments[arg] = new string[0]; } else { values.Add(arg); } } if (!string.IsNullOrEmpty(currentName)) { Arguments[currentName] = values.ToArray(); } } public bool Contains(string name) { return Arguments.ContainsKey(name); } public string[] GetValues(string name, string[] defaultValue = null) { return Contains(name) ? Arguments[name] : defaultValue; } public T GetValue<T>(string name, Func<string[], T> func, T defaultValue = default(T)) { return Contains(name) ? func(Arguments[name]) : defaultValue; } public bool GetBoolValue(string name, bool defaultValue = false) { return GetValue(name, values => { string value = values.FirstOrDefault(); return !string.IsNullOrEmpty(value) ? bool.Parse(value) : defaultValue; }, defaultValue); } public bool GetBoolSwitchValue(string name) { return Contains(name); } public int? GetIntValue(string name, int? defaultValue = null) { return GetValue(name, values => { string value = values.FirstOrDefault(); return !string.IsNullOrEmpty(value) ? int.Parse(value) : defaultValue; }, defaultValue); } public string GetStringValue(string name, string defaultValue = null) { return GetValue(name, values => values.FirstOrDefault() ?? defaultValue, defaultValue); } } }
1.695313
2
Assets/ThirdParty/First Person Drifter Controller/Scripts/LockMouse.cs
fernandoramallo/oikospiel-game-tools
26
92
// by @torahhorse using UnityEngine; using System.Collections; public class LockMouse : MonoBehaviour { void Start() { LockCursor(true); } void Update() { // lock when mouse is clicked if( Input.GetMouseButtonDown(0) && Time.timeScale > 0.0f ) { LockCursor(true); } // unlock when escape is hit if ( Input.GetKeyDown(KeyCode.Escape) ) { LockCursor(Cursor.lockState == CursorLockMode.None); } } public void LockCursor(bool lockCursor) { Cursor.lockState = lockCursor ? CursorLockMode.Locked : CursorLockMode.None; } }
1.84375
2
src_wip/Tests.Unit.Orm/Orm/Validation/Discovery/DefaultValidationRuleDiscoveryStrategyTest.cs
brianmains/Nucleo.NET
2
100
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using TypeMock.ArrangeActAssert; namespace Nucleo.Orm.Validation.Discovery { [TestClass] public class DefaultValidationRuleDiscoveryStrategyTest { protected class TestClass : IValidationRuleTarget { public ValidationRuleCollection GetValidationRules(ValidationRuleType ruleType) { return new ValidationRuleCollection { Isolate.Fake.Instance<IValidationRule>() }; } } [TestMethod] public void ValidatingNonValidatableEntityReturnsNull() { var strat = new DefaultValidationRuleDiscoveryStrategy(); var rules = strat.FindValidationRules(new object(), ValidationRuleType.Create); Assert.IsNull(rules); } [TestMethod] public void ValidatingValidatableEntityReturnsResults() { var strat = new DefaultValidationRuleDiscoveryStrategy(); var rules = strat.FindValidationRules(new TestClass(), ValidationRuleType.Create); Assert.AreEqual(1, rules.Count); } } }
1.453125
1
BookWeb.Shared/CalibreModels/BooksAuthorsLink.cs
seantrace/BookWeb
0
108
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; #nullable disable namespace BookWeb { [Table("books_authors_link")] [Index(nameof(Book), nameof(Author), IsUnique = true)] [Index(nameof(Author), Name = "books_authors_link_aidx")] [Index(nameof(Book), Name = "books_authors_link_bidx")] public partial record BooksAuthorsLink { [Key] [Column("id")] public long Id { get; set; } [Column("book")] public long Book { get; set; } [Column("author")] public long Author { get; set; } } }
0.867188
1
Xam-GLMap-Android/Additions/GLMapInfo.cs
charlenni/Xam-GLMap-Android
0
116
namespace GLMap { public partial class GLMapInfo { public GLMap.GLMapInfoState State { get { return (GLMap.GLMapInfoState)getState().Ordinal(); } } } }
0.384766
0
Deflector.Demos/Deflector.Demos/Program.cs
philiplaureano/deflectordotnet-demos
1
124
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleLibrary; namespace Deflector.Demos { class Program { static void Main(string[] args) { var targetAssembly = typeof(SampleClassWithInstanceMethod).Assembly; // Notice how modifying the sample assembly requires only one line of code var modifiedAssembly = targetAssembly.AddInterceptionHooks(); // Replace the DoSomethingElse() method call with a different method call Replace.Method<SampleClassThatCallsAnInstanceMethod>(c => c.DoSomethingElse()) .With(() => { Console.WriteLine("DoSomethingElse() method call intercepted"); }); var targetTypeName = nameof(SampleClassThatCallsAnInstanceMethod); // Use the createInstance lambda for syntactic sugar Func<string, dynamic> createInstance = typeName => { var targetType = modifiedAssembly.GetTypes().First(t => t.Name == typeName); return Activator.CreateInstance(targetType); }; // Create the modified type instance dynamic targetInstance = createInstance(targetTypeName); targetInstance.DoSomething(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
1.6875
2
KD.Dova/Extensions/ObjectExtensions.cs
Sejoslaw/KD.Dova
1
132
using KD.Dova.Core; using KD.Dova.Utils; using System.Collections.Generic; namespace KD.Dova.Extensions { internal static class ObjectExtensions { internal static JavaType[] ToJniSignatureArray(this object[] source) { List<JavaType> javaTypes = new List<JavaType>(); foreach (object obj in source) { javaTypes.Add(obj.GetType().ToJniSignature()); } return javaTypes.ToArray(); } internal static NativeValue[] ToNativeValueArray(this object[] source, JavaRuntime runtime) { List<NativeValue> values = new List<NativeValue>(); foreach (object obj in source) { values.Add(obj.ToNativeValue(runtime)); } return values.ToArray(); } internal static NativeValue ToNativeValue(this object source, JavaRuntime runtime) { JavaType jt = source.GetType().ToJniSignature(); if (jt != null) { return jt.ToNativeValue(runtime, source); } return new NativeValue(); } } }
0.796875
1
src/NTccTransaction/Persistence/TransactionManager.cs
wzl-bxg/NTcc-TransactionCore
21
140
using Microsoft.Extensions.DependencyInjection; using NTccTransaction.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace NTccTransaction { public class TransactionManager : ITransactionManager { private readonly IAmbientTransaction _ambientTransaction; private readonly IServiceScopeFactory _serviceScopeFactory; public ITransaction Current => _ambientTransaction.Transaction; public TransactionManager( IAmbientTransaction ambientTransaction, IServiceScopeFactory serviceScopeFactory) { _ambientTransaction = ambientTransaction; _serviceScopeFactory = serviceScopeFactory; } /// <summary> /// /// </summary> /// <returns></returns> public ITransaction Begin() { var transaction = new Transaction(TransactionType.ROOT); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="uniqueIdentity"></param> /// <returns></returns> public ITransaction Begin(object uniqueIdentity) { var transaction = new Transaction(TransactionType.ROOT); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="transactionContext"></param> /// <returns></returns> public ITransaction PropagationNewBegin(TransactionContext transactionContext) { var transaction = new Transaction(transactionContext); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Create(transaction); RegisterTransaction(transaction); return transaction; } } /// <summary> /// /// </summary> /// <param name="transactionContext"></param> /// <returns></returns> public ITransaction PropagationExistBegin(TransactionContext transactionContext) { using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); var transaction = transactionRepository.FindByXid(transactionContext.Xid); if (transaction == null) { throw new NoExistedTransactionException(); } transaction.ChangeStatus(transactionContext.Status); RegisterTransaction(transaction); return transaction; } } /// <summary> /// Commit /// </summary> public async Task CommitAsync() { var transaction = this.Current; // When confirm successfully, delete the NTccTransaction from database // The confirm action will be call from the top of stack, so delete the transaction data will not impact the excution under it using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transaction.ChangeStatus(TransactionStatus.CONFIRMING); transactionRepository.Update(transaction); try { await transaction.CommitAsync(_serviceScopeFactory); transactionRepository.Delete(transaction); } catch (Exception commitException) { throw new ConfirmingException("Confirm failed", commitException); } } } /// <summary> /// Rollback /// </summary> public async Task RollbackAsync() { var transaction = this.Current; using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transaction.ChangeStatus(TransactionStatus.CANCELLING); transactionRepository.Update(transaction); try { await transaction.RollbackAsync(_serviceScopeFactory); transactionRepository.Delete(transaction); } catch (Exception rollbackException) { throw new CancellingException("Rollback failed", rollbackException); } } } /// <summary> /// /// </summary> /// <param name="participant"></param> public void AddParticipant(IParticipant participant) { var transaction = this.Current; transaction.AddParticipant(participant); using (var scope = _serviceScopeFactory.CreateScope()) { var transactionRepository = scope.ServiceProvider.GetRequiredService<ITransactionRepository>(); transactionRepository.Update(transaction); } } /// <summary> /// /// </summary> /// <returns></returns> public bool IsTransactionActive() { return Current != null; } private void RegisterTransaction(ITransaction transaction) { _ambientTransaction.RegisterTransaction(transaction); } public bool IsDelayCancelException(Exception tryingException, HashSet<Type> allDelayCancelExceptionTypes) { if (null == allDelayCancelExceptionTypes || !allDelayCancelExceptionTypes.Any()) { return false; } var tryingExceptionType = tryingException.GetType(); return allDelayCancelExceptionTypes.Any(t => t.IsAssignableFrom(tryingExceptionType)); } } }
1.296875
1
vimage/Source/Display/Graphics.cs
Torrunt/vimage
57
148
using DevIL.Unmanaged; using SFML.Graphics; using SFML.System; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Tao.OpenGl; namespace vimage { /// <summary> /// Graphics Manager. /// Loads and stores Textures and AnimatedImageDatas. /// </summary> class Graphics { private static List<Texture> Textures = new List<Texture>(); private static List<string> TextureFileNames = new List<string>(); private static List<AnimatedImageData> AnimatedImageDatas = new List<AnimatedImageData>(); private static List<string> AnimatedImageDataFileNames = new List<string>(); private static List<DisplayObject> SplitTextures = new List<DisplayObject>(); private static List<string> SplitTextureFileNames = new List<string>(); public static uint MAX_TEXTURES = 80; public static uint MAX_ANIMATIONS = 8; public static int TextureMaxSize = (int)Texture.MaximumSize; public static dynamic GetTexture(string fileName) { int index = TextureFileNames.IndexOf(fileName); int splitTextureIndex = SplitTextureFileNames.Count == 0 ? -1 : SplitTextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return Textures[Textures.Count - 1]; } else if (splitTextureIndex >= 0) { // Texture Already Exists (as split texture) return SplitTextures[splitTextureIndex]; } else { // New Texture Texture texture = null; DisplayObject textureLarge = null; int imageID = IL.GenerateImage(); IL.BindImage(imageID); IL.Enable(ILEnable.AbsoluteOrigin); IL.SetOriginLocation(DevIL.OriginLocation.UpperLeft); bool loaded = false; using (FileStream fileStream = File.OpenRead(fileName)) loaded = IL.LoadImageFromStream(fileStream); if (loaded) { if (IL.GetImageInfo().Width > TextureMaxSize || IL.GetImageInfo().Height > TextureMaxSize) { // Image is larger than GPU's max texture size - split up textureLarge = GetCutUpTexturesFromBoundImage(TextureMaxSize / 2, fileName); } else { texture = GetTextureFromBoundImage(); if (texture == null) return null; Textures.Add(texture); TextureFileNames.Add(fileName); } // Limit amount of Textures in Memory if (Textures.Count > MAX_TEXTURES) RemoveTexture(); } IL.DeleteImages(new ImageID[] { imageID }); if (texture == null) return textureLarge; else return texture; } } private static Texture GetTextureFromBoundImage() { bool success = IL.ConvertImage(DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte); if (!success) return null; int width = IL.GetImageInfo().Width; int height = IL.GetImageInfo().Height; Texture texture = new Texture((uint)width, (uint)height); Texture.Bind(texture); { Gl.glTexImage2D( Gl.GL_TEXTURE_2D, 0, IL.GetInteger(ILIntegerMode.ImageBytesPerPixel), width, height, 0, IL.GetInteger(ILIntegerMode.ImageFormat), ILDefines.IL_UNSIGNED_BYTE, IL.GetData() ); } Texture.Bind(null); return texture; } private static DisplayObject GetCutUpTexturesFromBoundImage(int sectionSize, string fileName = "") { bool success = IL.ConvertImage(DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte); if (!success) return null; DisplayObject image = new DisplayObject(); Vector2i size = new Vector2i(IL.GetImageInfo().Width, IL.GetImageInfo().Height); Vector2u amount = new Vector2u((uint)Math.Ceiling(size.X / (float)sectionSize), (uint)Math.Ceiling(size.Y / (float)sectionSize)); Vector2i currentSize = new Vector2i(size.X, size.Y); Vector2i pos = new Vector2i(); for (int iy = 0; iy < amount.Y; iy++) { int h = Math.Min(currentSize.Y, sectionSize); currentSize.Y -= h; currentSize.X = size.X; for (int ix = 0; ix < amount.X; ix++) { int w = Math.Min(currentSize.X, sectionSize); currentSize.X -= w; Texture texture = new Texture((uint)w, (uint)h); IntPtr partPtr = Marshal.AllocHGlobal((w * h) * 4); IL.CopyPixels(pos.X, pos.Y, 0, w, h, 1, DevIL.DataFormat.RGBA, DevIL.DataType.UnsignedByte, partPtr); Texture.Bind(texture); { Gl.glTexImage2D( Gl.GL_TEXTURE_2D, 0, IL.GetInteger(ILIntegerMode.ImageBytesPerPixel), w, h, 0, IL.GetInteger(ILIntegerMode.ImageFormat), ILDefines.IL_UNSIGNED_BYTE, partPtr); } Texture.Bind(null); Marshal.FreeHGlobal(partPtr); Sprite sprite = new Sprite(texture); sprite.Position = new Vector2f(pos.X, pos.Y); image.AddChild(sprite); if (fileName != "") { Textures.Add(texture); TextureFileNames.Add(fileName + "_" + ix.ToString("00") + "_" + iy.ToString("00") + "^"); } pos.X += w; } pos.Y += h; pos.X = 0; } image.Texture.Size = new Vector2u((uint)size.X, (uint)size.Y); SplitTextures.Add(image); SplitTextureFileNames.Add(fileName); return image; } public static Sprite GetSpriteFromIcon(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .ico) try { System.Drawing.Icon icon = new System.Drawing.Icon(fileName, 256, 256); System.Drawing.Bitmap iconImage = ExtractVistaIcon(icon); if (iconImage == null) iconImage = icon.ToBitmap(); Sprite iconSprite; using (MemoryStream iconStream = new MemoryStream()) { iconImage.Save(iconStream, System.Drawing.Imaging.ImageFormat.Png); Texture iconTexture = new Texture(iconStream); Textures.Add(iconTexture); TextureFileNames.Add(fileName); iconSprite = new Sprite(new Texture(iconTexture)); } return iconSprite; } catch (Exception) { } } return null; } // http://stackoverflow.com/questions/220465/using-256-x-256-vista-icon-in-application/1945764#1945764 // Based on: http://www.codeproject.com/KB/cs/IconExtractor.aspx // And a hint from: http://www.codeproject.com/KB/cs/IconLib.aspx public static System.Drawing.Bitmap ExtractVistaIcon(System.Drawing.Icon icoIcon) { System.Drawing.Bitmap bmpPngExtracted = null; try { byte[] srcBuf = null; using (MemoryStream stream = new MemoryStream()) { icoIcon.Save(stream); srcBuf = stream.ToArray(); } const int SizeICONDIR = 6; const int SizeICONDIRENTRY = 16; int iCount = BitConverter.ToInt16(srcBuf, 4); for (int iIndex = 0; iIndex < iCount; iIndex++) { int iWidth = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex]; int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1]; int iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6); if (iWidth == 0 && iHeight == 0 && iBitCount == 32) { int iImageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8); int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12); MemoryStream destStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(destStream); writer.Write(srcBuf, iImageOffset, iImageSize); destStream.Seek(0, SeekOrigin.Begin); bmpPngExtracted = new System.Drawing.Bitmap(destStream); // This is PNG! :) break; } } } catch { return null; } return bmpPngExtracted; } public static Sprite GetSpriteFromSVG(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .svg) try { Svg.SvgDocument svg = Svg.SvgDocument.Open(fileName); System.Drawing.Bitmap bitmap = svg.Draw(); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Texture texture = new Texture(stream); Textures.Add(texture); TextureFileNames.Add(fileName); return new Sprite(new Texture(texture)); } } catch (Exception) { } } return null; } public static Sprite GetSpriteFromWebP(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return new Sprite(Textures[Textures.Count - 1]); } else { // New Texture (from .webp) try { var fileBytes = File.ReadAllBytes(fileName); System.Drawing.Bitmap bitmap = new Imazen.WebP.SimpleDecoder().DecodeFromBytes(fileBytes, fileBytes.Length); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Texture texture = new Texture(stream); Textures.Add(texture); TextureFileNames.Add(fileName); return new Sprite(new Texture(texture)); } } catch (Exception) { } } return null; } /// <param name="filename">Animated Image (ie: animated gif).</param> public static AnimatedImage GetAnimatedImage(string fileName) { return new AnimatedImage(GetAnimatedImageData(fileName)); } /// <param name="filename">Animated Image (ie: animated gif).</param> public static AnimatedImageData GetAnimatedImageData(string fileName) { lock (AnimatedImageDatas) { int index = AnimatedImageDataFileNames.IndexOf(fileName); if (index >= 0) { // AnimatedImageData Already Exists // move it to the end of the array and return it AnimatedImageData data = AnimatedImageDatas[index]; string name = AnimatedImageDataFileNames[index]; AnimatedImageDatas.RemoveAt(index); AnimatedImageDataFileNames.RemoveAt(index); AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(name); return AnimatedImageDatas[AnimatedImageDatas.Count - 1]; } else { // New AnimatedImageData System.Drawing.Image image = System.Drawing.Image.FromFile(fileName); AnimatedImageData data = new AnimatedImageData(); // Store AnimatedImageData AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(fileName); // Limit amount of Animations in Memory if (AnimatedImageDatas.Count > MAX_ANIMATIONS) RemoveAnimatedImage(); // Get Frames LoadingAnimatedImage loadingAnimatedImage = new LoadingAnimatedImage(image, data); Thread loadFramesThread = new Thread(new ThreadStart(loadingAnimatedImage.LoadFrames)) { Name = "AnimationLoadThread - " + fileName, IsBackground = true }; loadFramesThread.Start(); // Wait for at least one frame to be loaded while (data.Frames == null || data.Frames.Length <= 0 || data.Frames[0] == null) { Thread.Sleep(1); } return data; } } } public static void ClearMemory(dynamic image, string file = "") { // Remove all AnimatedImages (except the one that's currently being viewed) int s = image is AnimatedImage ? 1 : 0; int a = 0; while (AnimatedImageDatas.Count > s) { if (s == 1 && (image as AnimatedImage).Data == AnimatedImageDatas[a]) a++; RemoveAnimatedImage(a); } if (image is AnimatedImage) { // Remove all Textures while (TextureFileNames.Count > 0) RemoveTexture(); } else { // Remove all Textures (except ones being used by current image) if (file == "") return; s = 0; a = 0; if (SplitTextureFileNames.Contains(file)) { for (int i = 0; i < TextureFileNames.Count; i++) { if (TextureFileNames[i].IndexOf(file) == 0) s++; else if (s > 0) break; } while (TextureFileNames.Count > s) { if (TextureFileNames[a].IndexOf(file) == 0) a += s; RemoveTexture(a); } } else { while (TextureFileNames.Count > 1) { if (TextureFileNames[a] == file) a++; RemoveTexture(a); } } } } public static void RemoveTexture(int t = 0) { if (TextureFileNames[t].IndexOf('^') == TextureFileNames[t].Length - 1) { // if part of split texture - remove all parts string name = TextureFileNames[t].Substring(0, TextureFileNames[t].Length - 7); int i = t; for (i = t + 1; i < TextureFileNames.Count; i++) { if (TextureFileNames[i].IndexOf(name) != 0) break; } for (int d = t; d < i; d++) { Textures[t]?.Dispose(); Textures.RemoveAt(t); TextureFileNames.RemoveAt(t); } int splitIndex = SplitTextureFileNames.Count == 0 ? -1 : SplitTextureFileNames.IndexOf(name); if (splitIndex != -1) { SplitTextures.RemoveAt(splitIndex); SplitTextureFileNames.RemoveAt(splitIndex); } } else { Textures[t]?.Dispose(); Textures.RemoveAt(t); TextureFileNames.RemoveAt(t); } } public static void RemoveAnimatedImage(int a = 0) { AnimatedImageDatas[a].CancelLoading = true; for (int i = 0; i < AnimatedImageDatas[a].Frames.Length; i++) AnimatedImageDatas[a]?.Frames[i]?.Dispose(); AnimatedImageDatas.RemoveAt(a); AnimatedImageDataFileNames.RemoveAt(a); } } class LoadingAnimatedImage { private System.Drawing.Image Image; private ImageManipulation.OctreeQuantizer Quantizer; private AnimatedImageData Data; public LoadingAnimatedImage(System.Drawing.Image image, AnimatedImageData data) { Image = image; Data = data; } public void LoadFrames() { // Get Frame Count System.Drawing.Imaging.FrameDimension frameDimension = new System.Drawing.Imaging.FrameDimension(Image.FrameDimensionsList[0]); Data.FrameCount = Image.GetFrameCount(frameDimension); Data.Frames = new Texture[Data.FrameCount]; Data.FrameDelays = new int[Data.FrameCount]; // Get Frame Delays byte[] frameDelays = null; try { System.Drawing.Imaging.PropertyItem frameDelaysItem = Image.GetPropertyItem(0x5100); frameDelays = frameDelaysItem.Value; if (frameDelays.Length == 0 || (frameDelays[0] == 0 && frameDelays.All(d => d == 0))) frameDelays = null; } catch { } int defaultFrameDelay = AnimatedImage.DEFAULT_FRAME_DELAY; if (frameDelays != null && frameDelays.Length > 1) defaultFrameDelay = (frameDelays[0] + frameDelays[1] * 256) * 10; for (int i = 0; i < Data.FrameCount; i++) { if (Data.CancelLoading) return; Image.SelectActiveFrame(frameDimension, i); Quantizer = new ImageManipulation.OctreeQuantizer(255, 8); System.Drawing.Bitmap quantized = Quantizer.Quantize(Image); MemoryStream stream = new MemoryStream(); quantized.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Data.Frames[i] = new Texture(stream); stream.Dispose(); if (Data.CancelLoading) return; Data.Frames[i].Smooth = Data.Smooth; Data.Frames[i].Mipmap = Data.Mipmap; var fd = i * 4; if (frameDelays != null && frameDelays.Length > fd) Data.FrameDelays[i] = (frameDelays[fd] + frameDelays[fd + 1] * 256) * 10; else Data.FrameDelays[i] = defaultFrameDelay; } Data.FullyLoaded = true; } } }
1.867188
2
WuHu/WuHu.WebService/Models/TournamentData.cs
bloody-orange/WuHu
1
156
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Web; using WuHu.BL.Impl; using WuHu.Domain; namespace WuHu.WebService.Models { [DataContract] public class TournamentData { public TournamentData() { } public TournamentData(Tournament tournament) { if (tournament?.TournamentId == null) { throw new ArgumentNullException(nameof(tournament.TournamentId)); } TournamentId = tournament.TournamentId.Value; Name = tournament.Name; Datetime = tournament.Datetime; Players = null; Amount = 1; } [DataMember] public int TournamentId { get; set; } [DataMember] public string Name { get; set; } [DataMember] public DateTime Datetime { get; set; } [DataMember] [Required] public IList<Player> Players { get; set; } [DataMember] [Required] public int Amount { get; set; } } }
0.992188
1
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Types/AllTypes.cs
tapend/tebe-cms
0
164
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using GraphQL.Types; using Squidex.Domain.Apps.Core.Assets; using Squidex.Domain.Apps.Entities.Contents.GraphQL.Types.Utils; namespace Squidex.Domain.Apps.Entities.Contents.GraphQL.Types { public static class AllTypes { public const string PathName = "path"; public static readonly Type None = typeof(NoopGraphType); public static readonly Type NonNullTagsType = typeof(NonNullGraphType<ListGraphType<NonNullGraphType<StringGraphType>>>); public static readonly IGraphType Int = new IntGraphType(); public static readonly IGraphType DomainId = new StringGraphType(); public static readonly IGraphType Date = new InstantGraphType(); public static readonly IGraphType Json = new JsonGraphType(); public static readonly IGraphType Float = new FloatGraphType(); public static readonly IGraphType String = new StringGraphType(); public static readonly IGraphType Boolean = new BooleanGraphType(); public static readonly IGraphType AssetType = new EnumerationGraphType<AssetType>(); public static readonly IGraphType NonNullInt = new NonNullGraphType(Int); public static readonly IGraphType NonNullDomainId = new NonNullGraphType(DomainId); public static readonly IGraphType NonNullDate = new NonNullGraphType(Date); public static readonly IGraphType NonNullFloat = new NonNullGraphType(Float); public static readonly IGraphType NonNullString = new NonNullGraphType(String); public static readonly IGraphType NonNullBoolean = new NonNullGraphType(Boolean); public static readonly IGraphType NonNullAssetType = new NonNullGraphType(AssetType); public static readonly IGraphType NoopDate = new NoopGraphType(Date); public static readonly IGraphType NoopJson = new NoopGraphType(Json); public static readonly IGraphType NoopFloat = new NoopGraphType(Float); public static readonly IGraphType NoopString = new NoopGraphType(String); public static readonly IGraphType NoopBoolean = new NoopGraphType(Boolean); public static readonly IGraphType NoopTags = new NoopGraphType("TagsScalar"); public static readonly IGraphType NoopGeolocation = new NoopGraphType("GeolocationScalar"); public static readonly QueryArguments PathArguments = new QueryArguments(new QueryArgument(None) { Name = PathName, Description = "The path to the json value", DefaultValue = null, ResolvedType = String }); } }
1.21875
1
Wyrobot/Http/YouTube/YouTubeEventListener.cs
JustAeris/Wyrobot
0
172
using System; using System.Collections.Generic; using System.Threading.Tasks; using YoutubeExplode; using YoutubeExplode.Videos; namespace Wyrobot.Core.Http.YouTube { public class YouTubeEventListener { private YoutubeClient _client; public List<ChannelSubscription> Subscriptions { get; private set; } public event YouTubeEventHandler OnVideoUploaded; private YouTubeEventListener() { Subscriptions = new List<ChannelSubscription>(); } public YouTubeEventListener(YoutubeClient client) : this() { _client = client; } public async Task SubscribeChannels(ulong guildId, ulong channelId, string broadcast, List<string> channels) { if (channels == null) throw new ArgumentNullException(nameof(channels)); foreach (var url in channels) { var uploads = await _client.Channels.GetUploadsAsync(url); Subscriptions.Add(new ChannelSubscription(guildId, channelId, broadcast, url, uploads.Count > 0 ? uploads[0] : null)); } } public async Task SubscribeChannels(ulong guildId, ulong channelId, string broadcast, params string[] channels) { var channelsList = new List<string>(); for (var index = 0; index < channels.Length; ++index) channelsList.Add(channels[index]); await SubscribeChannels(guildId, channelId, broadcast, channelsList); } public void UnsubscribeChannel(ChannelSubscription subscription) { if (!Subscriptions.Contains(subscription)) return; Subscriptions.Remove(subscription); } public async Task PollEvents() { foreach (var subscription in Subscriptions) { var uploads = await _client.Channels.GetUploadsAsync(subscription.Url); var lastVideo = uploads.Count > 0 ? uploads[0] : null; if (lastVideo == null) continue; if (subscription.LastVideo != lastVideo) { if (OnVideoUploaded == null) continue; var channel = await _client.Channels.GetAsync(lastVideo.ChannelId); OnVideoUploaded(this, new YouTubeEventArgs(subscription.GuildId, subscription.ChannelId, subscription.Broadcast, channel, lastVideo )); subscription.LastVideo = lastVideo; } } } public class ChannelSubscription { public ulong GuildId { get; set; } public ulong ChannelId { get; set; } public string Broadcast { get; set; } public string Url { get; set; } public Video LastVideo { get; set; } public ChannelSubscription(ulong guildId, ulong channelId, string broadcast, string url, Video lastVideo = null) { GuildId = guildId; ChannelId = channelId; Broadcast = broadcast; Url = url; LastVideo = lastVideo; } } public delegate void YouTubeEventHandler(object sender, YouTubeEventArgs e); } }
1.679688
2
DigestingDuck/Pages/Ativos.xaml.cs
JorgeBeserra/DigestingDuck
2
180
using DigestingDuck.models; using Realms.Exceptions; 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.Shapes; namespace DigestingDuck.Pages { /// <summary> /// Lógica interna para Ativos.xaml /// </summary> public partial class Ativos : Page { public Ativos() { InitializeComponent(); } private void PageAtivos_Loaded(object sender, RoutedEventArgs e) { datagridAtivosBinaria.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosBinaria; datagridAtivosTurbo.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosTurbo; datagridAtivosDigital.ItemsSource = ((MainWindow)Application.Current.MainWindow).ativosDigital; } private void DatagridAtivosBinaria_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosBinaria.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria BINARIA foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria BINARIA foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } private void DatagridAtivosTurbo_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosTurbo.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria TURBO foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria TURBO foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } private void DatagridAtivosBinaria_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void DatagridAtivosDigital_MouseDoubleClick(object sender, MouseButtonEventArgs e) { try { if (sender != null) { DataGrid grid = (DataGrid)sender; if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1) { var value = ((AtivosStatus)grid.SelectedItem); var t = ((MainWindow)Application.Current.MainWindow).ativosDigital.Where(x => x.Id == value.Id).First(); if (value.Alvo == true) { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = false; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria DIGITAL foi REMOVIDO dos alvo."); } else { ((MainWindow)Application.Current.MainWindow).database.realm.Write(() => { t.Alvo = true; }); ((MainWindow)Application.Current.MainWindow).GerarTexto("O ativo " + value.Descricao + " [" + value.Id + "] da categoria DIGITAL foi MARCADO como alvo."); } } } } catch (RealmException ex) { ((MainWindow)Application.Current.MainWindow).clientBug.Notify(ex); MessageBox.Show(ex.Message.ToString()); } } } }
1.40625
1
src/Transports/MassTransit.KafkaIntegration/KafkaTopicAddress.cs
viktorshevchenko210/MassTransit
4,222
188
namespace MassTransit.KafkaIntegration { using System; using System.Diagnostics; [DebuggerDisplay("{" + nameof(DebuggerDisplay) + "}")] public readonly struct KafkaTopicAddress { public const string PathPrefix = "kafka"; public readonly string Topic; public readonly string Host; public readonly string Scheme; public readonly int? Port; public KafkaTopicAddress(Uri hostAddress, Uri address) { Host = default; Topic = default; Scheme = default; Port = default; var scheme = address.Scheme.ToLowerInvariant(); switch (scheme) { case "topic": ParseLeft(hostAddress, out Scheme, out Host, out Port); Topic = address.AbsolutePath; break; default: { if (string.Equals(address.Scheme, hostAddress.Scheme, StringComparison.InvariantCultureIgnoreCase)) { ParseLeft(hostAddress, out Scheme, out Host, out Port); Topic = address.AbsolutePath.Replace($"{PathPrefix}/", ""); } else throw new ArgumentException($"The address scheme is not supported: {address.Scheme}", nameof(address)); break; } } } public KafkaTopicAddress(Uri hostAddress, string topic) { ParseLeft(hostAddress, out Scheme, out Host, out Port); Topic = topic; } static void ParseLeft(Uri address, out string scheme, out string host, out int? port) { scheme = address.Scheme; host = address.Host; port = address.Port; } public static implicit operator Uri(in KafkaTopicAddress address) { var builder = new UriBuilder { Scheme = address.Scheme, Host = address.Host, Port = address.Port ?? 0, Path = $"{PathPrefix}/{address.Topic}" }; return builder.Uri; } Uri DebuggerDisplay => this; } }
1.382813
1
NGit.Test/NGit.Nls/TranslationBundleTest.cs
ashmind/ngit
1
196
/* This code is derived from jgit (http://eclipse.org/jgit). Copyright owners are documented in jgit's IP log. This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0 which accompanies this distribution, is reproduced below, and is available at http://www.eclipse.org/org/documents/edl-v10.php All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using NGit.Errors; using NGit.Nls; using Sharpen; namespace NGit.Nls { [NUnit.Framework.TestFixture] public class TranslationBundleTest { [NUnit.Framework.Test] public virtual void TestMissingPropertiesFile() { try { new NoPropertiesBundle().Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.Fail("Expected TranslationBundleLoadingException"); } catch (TranslationBundleLoadingException e) { NUnit.Framework.Assert.AreEqual(typeof(NoPropertiesBundle), e.GetBundleClass()); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, e.GetLocale()); } } // pass [NUnit.Framework.Test] public virtual void TestMissingString() { try { new MissingPropertyBundle().Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.Fail("Expected TranslationStringMissingException"); } catch (TranslationStringMissingException e) { NUnit.Framework.Assert.AreEqual("nonTranslatedKey", e.GetKey()); NUnit.Framework.Assert.AreEqual(typeof(MissingPropertyBundle), e.GetBundleClass() ); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, e.GetLocale()); } } // pass [NUnit.Framework.Test] public virtual void TestNonTranslatedBundle() { NonTranslatedBundle bundle = new NonTranslatedBundle(); bundle.Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); bundle.Load(Sharpen.Extensions.GetEnglishCulture()); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); bundle.Load(Sharpen.Extensions.GetGermanCulture()); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); } [NUnit.Framework.Test] public virtual void TestGermanTranslation() { GermanTranslatedBundle bundle = new GermanTranslatedBundle(); bundle.Load(NLS.ROOT_LOCALE); NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, bundle.EffectiveLocale()); NUnit.Framework.Assert.AreEqual("Good morning {0}", bundle.goodMorning); bundle.Load(Sharpen.Extensions.GetGermanCulture()); NUnit.Framework.Assert.AreEqual(Sharpen.Extensions.GetGermanCulture(), bundle.EffectiveLocale ()); NUnit.Framework.Assert.AreEqual("Guten Morgen {0}", bundle.goodMorning); } } }
1.25
1
src/GitVersionCore/Extensions/ExtensionMethods.git.cs
openkas/GitVersion
0
204
namespace GitVersion { static partial class ExtensionMethods { public static string GetCanonicalBranchName(this string branchName) { if (branchName.IsPullRequest()) { branchName = branchName.Replace("pull-requests/", "pull/"); branchName = branchName.Replace("pr/", "pull/"); return string.Format("refs/{0}/head", branchName); } return string.Format("refs/heads/{0}", branchName); } public static bool IsPullRequest(this string branchName) { return branchName.Contains("pull/") || branchName.Contains("pull-requests/") || branchName.Contains("pr/"); } } }
1.15625
1
test/Elastic.Apm.Tests.MockApmServer/AssertValidExtensions.cs
WeihanLi/apm-agent-dotnet
0
212
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using Elastic.Apm.Api; using Elastic.Apm.DistributedTracing; using Elastic.Apm.Model; using Elastic.Apm.Tests.Mocks; using FluentAssertions; namespace Elastic.Apm.Tests.MockApmServer { internal static class AssertValidExtensions { internal static void AssertValid(this Service thisObj) { thisObj.Should().NotBeNull(); thisObj.Agent.AssertValid(); thisObj.Framework.AssertValid(); thisObj.Language.AssertValid(); } internal static void AssertValid(this Service.AgentC thisObj) { thisObj.Should().NotBeNull(); thisObj.Name.Should().Be(Consts.AgentName); thisObj.Version.Should().Be(Service.GetDefaultService(new MockConfigSnapshot(new NoopLogger()), new NoopLogger()).Agent.Version); } private static void AssertValid(this Framework thisObj) { thisObj.Should().NotBeNull(); thisObj.Name.NonEmptyAssertValid(); thisObj.Version.NonEmptyAssertValid(); thisObj.Version.Should().MatchRegex("[1-9]*.*"); } private static void AssertValid(this Language thisObj) { thisObj.Should().NotBeNull(); thisObj.Name.Should().Be("C#"); } internal static void AssertValid(this Api.System thisObj) { thisObj.Should().NotBeNull(); thisObj.Container?.AssertValid(); } private static void AssertValid(this Container thisObj) { thisObj.Should().NotBeNull(); thisObj.Id.NonEmptyAssertValid(); } internal static void AssertValid(this Request thisObj) { thisObj.Should().NotBeNull(); thisObj.Headers?.HttpHeadersAssertValid(); thisObj.HttpVersion.HttpVersionAssertValid(); thisObj.Method.HttpMethodAssertValid(); thisObj.Socket.AssertValid(); thisObj.Url.AssertValid(); } internal static void AssertValid(this Response thisObj) { thisObj.Should().NotBeNull(); thisObj.Headers?.HttpHeadersAssertValid(); thisObj.StatusCode.HttpStatusCodeAssertValid(); } internal static void HttpStatusCodeAssertValid(this int thisObj) => thisObj.Should().BeInRange(100, 599); internal static void AssertValid(this User thisObj) { thisObj.Should().NotBeNull(); thisObj?.Id.AssertValid(); thisObj?.UserName.AssertValid(); thisObj?.Email.AssertValid(); } internal static void LabelsAssertValid(this Dictionary<string, string> thisObj) { thisObj.Should().NotBeNull(); foreach (var (key, value) in thisObj) { key.AssertValid(); value?.AssertValid(); } } private static void HttpHeadersAssertValid(this Dictionary<string, string> thisObj) { thisObj.Should().NotBeNull(); foreach (var headerNameValue in thisObj) { headerNameValue.Key.Should().NotBeNullOrEmpty(); headerNameValue.Value.Should().NotBeNull(); } } private static void HttpVersionAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); thisObj.Should().BeOneOf("1.0", "1.1", "2.0"); } private static void HttpMethodAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); var validValues = new List<string> { "GET", "POST", "PUT", "HEAD", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH" }; thisObj.ToUpperInvariant().Should().BeOneOf(validValues, $"Given value is `{thisObj}'"); } private static void AssertValid(this Url thisObj) { thisObj.Should().NotBeNull(); thisObj.Raw?.UrlStringAssertValid(); thisObj.Protocol?.UrlProtocolAssertValid(); thisObj.Full?.UrlStringAssertValid(); thisObj.HostName?.AssertValid(); thisObj.PathName?.AssertValid(); thisObj.Search?.AssertValid(); } private static void UrlProtocolAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); thisObj.Should().Be("HTTP"); } private static void UrlStringAssertValid(this string thisObj) { thisObj.NonEmptyAssertValid(); thisObj.Should() .Match(s => s.StartsWith("http://", StringComparison.InvariantCulture) || s.StartsWith("https://", StringComparison.InvariantCulture)); } private static void AssertValid(this Socket thisObj) { thisObj.Should().NotBeNull(); thisObj.RemoteAddress?.NonEmptyAssertValid(); } internal static void AssertValid(this SpanCountDto thisObj) => thisObj.Should().NotBeNull(); internal static void TimestampAssertValid(this long thisObj) => thisObj.Should().BeGreaterOrEqualTo(0); internal static void TraceIdAssertValid(this string thisObj) => thisObj.HexAssertValid(128 /* bits */); internal static void TransactionIdAssertValid(this string thisObj) => thisObj.HexAssertValid(64 /* bits */); internal static void SpanIdAssertValid(this string thisObj) => thisObj.HexAssertValid(64 /* bits */); internal static void ParentIdAssertValid(this string thisObj) => thisObj.HexAssertValid(64 /* bits */); internal static void ErrorIdAssertValid(this string thisObj) => thisObj.HexAssertValid(128 /* bits */); internal static void DurationAssertValid(this double thisObj) => thisObj.Should().BeGreaterOrEqualTo(0); internal static void NameAssertValid(this string thisObj) => thisObj.NonEmptyAssertValid(); private static void HexAssertValid(this string thisObj, int sizeInBits) { thisObj.NonEmptyAssertValid(); (sizeInBits % 8).Should().Be(0, $"sizeInBits should be divisible by 8 but sizeInBits is {sizeInBits}"); var numHexChars = sizeInBits / 8 * 2; var because = $"String should be {numHexChars} hex digits ({sizeInBits}-bits) but the actual value is `{thisObj}' (length: {thisObj.Length})"; thisObj.Length.Should().Be(numHexChars, because); // 2 hex chars per byte DistributedTracing.TraceContext.IsHex(thisObj).Should().BeTrue(because); } internal static void NonEmptyAssertValid(this string thisObj, int maxLength = 1024) { thisObj.AssertValid(); thisObj.Should().NotBeEmpty(); } internal static void AssertValid(this string thisObj, int maxLength = 1024) { thisObj.UnlimitedLengthAssertValid(); thisObj.Length.Should().BeLessOrEqualTo(maxLength); } internal static void UnlimitedLengthAssertValid(this string thisObj) => thisObj.Should().NotBeNull(); internal static void AssertValid(this CapturedException thisObj) { thisObj.Should().NotBeNull(); thisObj.Code?.AssertValid(); thisObj.StackTrace?.AssertValid(); if (string.IsNullOrEmpty(thisObj.Type)) thisObj.Message.AssertValid(); else thisObj.Message?.AssertValid(); if (string.IsNullOrEmpty(thisObj.Message)) thisObj.Type.AssertValid(); else thisObj.Type?.AssertValid(); } internal static void AssertValid(this Database thisObj) { thisObj.Should().NotBeNull(); thisObj.Instance?.AssertValid(); thisObj.Statement?.AssertValid(10_000); thisObj.Type?.AssertValid(); } internal static void AssertValid(this Http thisObj) { thisObj.Should().NotBeNull(); thisObj.Method.HttpMethodAssertValid(); thisObj.StatusCode.HttpStatusCodeAssertValid(); thisObj.Url.Should().NotBeNullOrEmpty(); } internal static void AssertValid(this Destination thisObj) { thisObj.Should().NotBeNull(); thisObj.Address.Should().NotBeNullOrEmpty(); thisObj.Address.AssertValid(); thisObj.Port?.Should().BeGreaterOrEqualTo(0); } internal static void AssertValid(this List<CapturedStackFrame> thisObj) { thisObj.Should().NotBeNull(); thisObj.Should().NotBeEmpty(); foreach (var stackFrame in thisObj) stackFrame.AssertValid(); } internal static void AssertValid(this CapturedStackFrame thisObj) { thisObj.Should().NotBeNull(); thisObj.FileName.Should().NotBeNullOrEmpty(); thisObj.LineNo.Should().BeGreaterOrEqualTo(0); thisObj.Module?.Should().NotBeEmpty(); thisObj.Function?.Should().NotBeEmpty(); } } }
1.242188
1
VideoWeb/VideoWeb.UnitTests/Controllers/ConferenceManagement/CallParticipantTests.cs
hmcts/vh-video-web
9
220
using System; using System.Linq; using System.Net; using System.Threading.Tasks; using FluentAssertions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using VideoWeb.Common.Models; using VideoApi.Client; using VideoApi.Contract.Requests; using VideoWeb.UnitTests.Builders; using ProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails; namespace VideoWeb.UnitTests.Controllers.ConferenceManagement { public class CallParticipantTests : ConferenceManagementControllerTestBase { [SetUp] public void Setup() { TestConference = BuildConferenceForTest(true); } [Test] public async Task should_return_unauthorised_if_participant_is_not_a_witness_or_quick_link_user() { var judge = TestConference.GetJudge(); var invalidParticipants = TestConference.Participants.Where(x => !x.IsJudge() && !x.IsWitness() && !x.IsQuickLinkUser() && x.LinkedParticipants.Count == 0); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); foreach(var participant in invalidParticipants) { var result = await controller.CallParticipantAsync(TestConference.Id, participant.Id); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("Participant is not callable"); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == participant.Id)), Times.Never); } } [Test] public async Task should_return_unauthorised_if_participant_does_not_exists() { var judge = TestConference.GetJudge(); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, Guid.NewGuid()); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("Participant is not callable"); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.IsAny<TransferParticipantRequest>()), Times.Never); } [Test] public async Task should_return_unauthorised_if_not_judge_conference() { var participant = TestConference.Participants.First(x => !x.IsJudge()); var user = new ClaimsPrincipalBuilder() .WithUsername(participant.Username) .WithRole(AppRoles.CitizenRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, participant.Id); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("User must be either Judge or StaffMember."); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == participant.Id)), Times.Never); } [Test] public async Task should_return_video_api_error() { var judge = TestConference.GetJudge(); var witness = TestConference.Participants.First(x => x.IsWitness()); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var responseMessage = "Could not start transfer participant"; var apiException = new VideoApiException<ProblemDetails>("Internal Server Error", (int)HttpStatusCode.InternalServerError, responseMessage, null, default, null); _mocker.Mock<IVideoApiClient>().Setup( x => x.TransferParticipantAsync(TestConference.Id, It.IsAny<TransferParticipantRequest>())).ThrowsAsync(apiException); var result = await controller.CallParticipantAsync(TestConference.Id, witness.Id); result.Should().BeOfType<ObjectResult>(); var typedResult = (ObjectResult)result; typedResult.Value.Should().Be(responseMessage); typedResult.StatusCode.Should().Be(StatusCodes.Status500InternalServerError); } [Test] public async Task should_return_accepted_when_participant_is_witness_and_judge_is_in_conference() { var judge = TestConference.GetJudge(); var witness = TestConference.Participants.First(x => x.IsWitness() && !x.LinkedParticipants.Any()); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, witness.Id); result.Should().BeOfType<AcceptedResult>(); var typedResult = (AcceptedResult)result; typedResult.Should().NotBeNull(); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == witness.Id && r.TransferType == TransferType.Call)), Times.Once); } [Test] public async Task should_return_accepted_when_participant_is_witness_and_has_an_interpreter_and_judge_is_in_conference() { var judge = TestConference.GetJudge(); var witness = TestConference.Participants.First(x => x.IsWitness() && x.LinkedParticipants.Any()); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var controller = SetupControllerWithClaims(user); var result = await controller.CallParticipantAsync(TestConference.Id, witness.Id); result.Should().BeOfType<AcceptedResult>(); var typedResult = (AcceptedResult)result; typedResult.Should().NotBeNull(); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == witness.Id && r.TransferType == TransferType.Call)), Times.Once); } [Test] public async Task should_return_unauthorised_when_witness_is_called_before_interpreter_joins() { var judge = TestConference.GetJudge(); var interpreterRoom = TestConference.CivilianRooms.First(); var witnessIds = TestConference.Participants .Where(p => p.IsWitness() && p.LinkedParticipants.Any()) .Select(p => p.Id).ToList(); // update room to not include interpreter interpreterRoom.Participants = interpreterRoom.Participants.Where(p => witnessIds.Contains(p)).ToList(); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var Controller = SetupControllerWithClaims(user); var result = await Controller.CallParticipantAsync(TestConference.Id, witnessIds.First()); result.Should().BeOfType<UnauthorizedObjectResult>(); var typedResult = (UnauthorizedObjectResult)result; typedResult.Should().NotBeNull(); typedResult.Value.Should().Be("Participant is not callable"); } [Test] [TestCase(Role.QuickLinkObserver)] [TestCase(Role.QuickLinkParticipant)] public async Task should_return_accepted_when_participant_is_quick_link_user_and_judge_is_in_conference(Role role) { var judge = TestConference.GetJudge(); var quickLinkUser = TestConference.Participants.First(x => x.Role == role); var user = new ClaimsPrincipalBuilder() .WithUsername(judge.Username) .WithRole(AppRoles.JudgeRole).Build(); var Controller = SetupControllerWithClaims(user); var result = await Controller.CallParticipantAsync(TestConference.Id, quickLinkUser.Id); result.Should().BeOfType<AcceptedResult>(); var typedResult = (AcceptedResult)result; typedResult.Should().NotBeNull(); _mocker.Mock<IVideoApiClient>().Verify( x => x.TransferParticipantAsync(TestConference.Id, It.Is<TransferParticipantRequest>(r => r.ParticipantId == quickLinkUser.Id && r.TransferType == TransferType.Call)), Times.Once); } } }
1.4375
1
EnvironmentAssessment.Wizard/Common/VimApi/A/AnswerFileCreateSpec.cs
octansIt/environmentassessment
1
228
namespace EnvironmentAssessment.Common.VimApi { public class AnswerFileCreateSpec : DynamicData { protected bool? _validating; public bool? Validating { get { return this._validating; } set { this._validating = value; } } } }
0.494141
0
src/MicroServices/StorageManagement/Core/StorageManagement.Application/Exceptions/ValidationException.cs
mrgrayhat/CleanMicroserviceArchitecture
4
236
using System; using System.Collections.Generic; using FluentValidation.Results; namespace StorageManagement.Application.Exceptions { public class ValidationException : Exception { public ValidationException() : base("One or more validation failures have occurred.") { Errors = new List<string>(); } public List<string> Errors { get; } public ValidationException(IEnumerable<ValidationFailure> failures) : this() { foreach (var failure in failures) { Errors.Add(failure.ErrorMessage); } } } }
1.546875
2
src/Potato.Net.Shared/Geolocation/GeolocateIp.cs
phogue/Potato
5
244
#region Copyright // Copyright 2014 Myrcon Pty. Ltd. // // 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.IO; using System.Linq; using Potato.Net.Shared.Geolocation.Maxmind; using Potato.Net.Shared.Models; namespace Potato.Net.Shared.Geolocation { /// <summary> /// Geolocation with an IP using Maxmind's library and database. /// </summary> public class GeolocateIp : IGeolocate { /// <summary> /// Used when determining a player's Country Name and Code. /// </summary> protected static CountryLookup CountryLookup = null; /// <summary> /// Loads the Maxmind GeoIP database, if available. /// </summary> static GeolocateIp() { try { String path = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "GeoIP.dat", SearchOption.AllDirectories).FirstOrDefault(); if (String.IsNullOrEmpty(path) == false) { GeolocateIp.CountryLookup = new CountryLookup(path); } } catch { GeolocateIp.CountryLookup = null; } } /// <summary> /// Validates the IP is roughly in ipv4 and gets the ip from a ip:port pair. /// </summary> /// <param name="value"></param> /// <returns></returns> protected String Ip(String value) { String ip = value; // Validate Ip has colon before trying to split. if (value != null && value.Contains(":")) { ip = value.Split(':').FirstOrDefault(); } // Validate Ip String was valid before continuing. if (string.IsNullOrEmpty(ip) == true || ip.Contains('.') == false) { ip = null; } return ip; } /// <summary> /// Fetch a location by ip /// </summary> /// <param name="value">The ip</param> /// <returns></returns> public Location Locate(String value) { Location location = null; if (GeolocateIp.CountryLookup != null) { String ip = this.Ip(value); if (ip != null) { // Try: In-case GeoIP.dat is not loaded properly try { location = new Location() { CountryName = GeolocateIp.CountryLookup.lookupCountryName(ip), CountryCode = GeolocateIp.CountryLookup.lookupCountryCode(ip) }; } catch { // Blank the location location = null; } } } return location; } } }
1.601563
2
src/Store/ArcGISRuntimeSamplesStore/Samples/Editing/EditRelatedData.xaml.cs
david-chambers/arcgis-runtime-samples-dotnet
3
252
using Esri.ArcGISRuntime.Controls; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Layers; using Esri.ArcGISRuntime.Tasks.Query; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace ArcGISRuntime.Samples.Store.Samples { /// <summary> /// Demonstrates how to query and edit related records. /// </summary> /// <title>Edit Related Data</title> /// <category>Editing</category> public partial class EditRelatedData : Page { // Query is done through this relationship. Esri.ArcGISRuntime.ArcGISServices.Relationship relationship; // Editing is done through this table. ServiceFeatureTable table; public EditRelatedData() { InitializeComponent(); var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; layer.VisibleLayers = new ObservableCollection<int>(new int[] { 0 }); } /// <summary> /// Identifies graphic to highlight and query its related records. /// </summary> private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e) { var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; var task = new IdentifyTask(new Uri(layer.ServiceUri)); var mapPoint = MyMapView.ScreenToLocation(e.Position); // Get current viewpoints extent from the MapView var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); var viewpointExtent = currentViewpoint.TargetGeometry.Extent; var parameter = new IdentifyParameters(mapPoint, viewpointExtent, 10, (int)MyMapView.ActualHeight, (int)MyMapView.ActualWidth); // Clears map of any highlights. var overlay = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay; overlay.Graphics.Clear(); SetRelatedRecordEditor(); string message = null; try { // Performs an identify and adds graphic result into overlay. var result = await task.ExecuteAsync(parameter); if (result == null || result.Results == null || result.Results.Count < 1) return; var graphic = (Graphic)result.Results[0].Feature; overlay.Graphics.Add(graphic); // Prepares related records editor. var featureID = Convert.ToInt64(graphic.Attributes["OBJECTID"], CultureInfo.InvariantCulture); string requestID = null; if (graphic.Attributes["Service Request ID"] != null) requestID = Convert.ToString(graphic.Attributes["Service Request ID"], CultureInfo.InvariantCulture); SetRelatedRecordEditor(featureID, requestID); await QueryRelatedRecordsAsync(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Prepares related record editor for add and query. /// </summary> private void SetRelatedRecordEditor(long featureID = 0, string requestID = null) { AddButton.Tag = featureID; AddButton.IsEnabled = featureID > 0 && !string.IsNullOrWhiteSpace(requestID); RelatedRecords.Tag = requestID; if (featureID == 0) { Records.IsEnabled = false; RelatedRecords.ItemsSource = null; RelatedRecords.SelectedItem = null; } SetAttributeEditor(); } /// <summary> /// Prepares attribute editor for update or delete of existing related record. /// </summary> private void SetAttributeEditor(Feature feature = null) { if (ChoiceList.ItemsSource == null && table != null && table.ServiceInfo != null && table.ServiceInfo.Fields != null) { var rangeDomain = (RangeDomain<IComparable>)table.ServiceInfo.Fields.FirstOrDefault(f => f.Name == "rank").Domain; ChoiceList.ItemsSource = GetRangeValues((int)rangeDomain.MinValue, (int)rangeDomain.MaxValue); } AttributeEditor.Tag = feature; if (feature != null) { if (feature.Attributes.ContainsKey("rank") && feature.Attributes["rank"] != null) ChoiceList.SelectedItem = Convert.ToInt32(feature.Attributes["rank"], CultureInfo.InvariantCulture); if (feature.Attributes.ContainsKey("comments") && feature.Attributes["comments"] != null) Comments.Text = Convert.ToString(feature.Attributes["comments"], CultureInfo.InvariantCulture); AttributeEditor.Visibility = Visibility.Visible; Records.Flyout.ShowAt(Records); } else { ChoiceList.SelectedItem = null; Comments.Text = string.Empty; AttributeEditor.Visibility = Visibility.Collapsed; } } /// <summary> /// Gets exclusive values between minimum and maximum values. /// </summary> private IEnumerable<int> GetRangeValues(int min, int max) { for (int i = min; i <= max; i++) yield return i; } /// <summary> /// Gets relationship information using service metadata. /// </summary> private async Task<Esri.ArcGISRuntime.ArcGISServices.Relationship> GetRelationshipAsync() { var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; if (layer == null || layer.VisibleLayers == null) return null; var id = layer.VisibleLayers.FirstOrDefault(); var details = await layer.GetDetailsAsync(id); if (details != null && details.Relationships != null) return details.Relationships.FirstOrDefault(); return null; } /// <summary> /// Queries related records for specified feature ID. /// </summary> private async Task QueryRelatedRecordsAsync() { var featureID = (Int64)AddButton.Tag; var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; var id = layer.VisibleLayers.FirstOrDefault(); var task = new QueryTask(new Uri(string.Format("{0}/{1}", layer.ServiceUri, id))); if (relationship == null) relationship = await GetRelationshipAsync(); var parameters = new RelationshipParameters(new List<long>(new long[] { featureID }), relationship.ID); parameters.OutFields = new OutFields(new string[] { "objectid" }); var result = await task.ExecuteRelationshipQueryAsync(parameters); if (result != null && result.RelatedRecordGroups != null && result.RelatedRecordGroups.ContainsKey(featureID)) { RelatedRecords.ItemsSource = result.RelatedRecordGroups[featureID]; Records.IsEnabled = true; } } /// <summary> /// Submits related record edits back to server. /// </summary> private async Task SaveEditsAsync() { if (table == null || !table.HasEdits) return; if (table is ServiceFeatureTable) { var serviceTable = (ServiceFeatureTable)table; // Pushes new graphic back to the server. var result = await serviceTable.ApplyEditsAsync(); if (result.AddResults == null || result.AddResults.Count < 1) return; var addResult = result.AddResults[0]; if (addResult.Error != null) throw addResult.Error; } } /// <summary> /// Gets related table for editing. /// </summary> private async Task<ServiceFeatureTable> GetRelatedTableAsync() { var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer; // Creates table based on related table ID of the visible layer in dynamic layer // using FeatureServer specifying rank and comments fields to enable editing. var id = relationship.RelatedTableID.Value; var url = layer.ServiceUri.Replace("MapServer", "FeatureServer"); url = string.Format("{0}/{1}", url, id); var table = await ServiceFeatureTable.OpenAsync(new Uri(url), null, MyMapView.SpatialReference); table.OutFields = new OutFields(new string[] { relationship.KeyField, "rank", "comments", "submitdt" }); return table; } /// <summary> /// Displays current attribute values of related record. /// </summary> private async void RelatedRecords_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (RelatedRecords.SelectedItem == null) return; var graphic = (Graphic)RelatedRecords.SelectedItem; SetAttributeEditor(); string message = null; try { if (table == null) table = await GetRelatedTableAsync(); var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture); var feature = await table.QueryAsync(featureID); SetAttributeEditor(feature); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Adds a new related record to highlighted feature. /// </summary> private async void AddButton_Click(object sender, RoutedEventArgs e) { SetAttributeEditor(); var featureID = (Int64)AddButton.Tag; var requestID = (string)RelatedRecords.Tag; string message = null; try { if (table == null) table = await GetRelatedTableAsync(); var feature = new GeodatabaseFeature(table.Schema); feature.Attributes[relationship.KeyField] = requestID; feature.Attributes["rank"] = 5; feature.Attributes["comments"] = "Describe service requirement here."; feature.Attributes["submitdt"] = DateTime.UtcNow; var relatedFeatureID = await table.AddAsync(feature); await SaveEditsAsync(); await QueryRelatedRecordsAsync(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Updates attributes of related record. /// </summary> private async void EditButton_Click(object sender, RoutedEventArgs e) { if (AttributeEditor.Tag == null) return; var feature = (GeodatabaseFeature)AttributeEditor.Tag; string message = null; try { if (ChoiceList.SelectedItem != null) feature.Attributes["rank"] = (int)ChoiceList.SelectedItem; feature.Attributes["comments"] = Comments.Text.Trim(); await table.UpdateAsync(feature); await SaveEditsAsync(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } /// <summary> /// Deletes related record. /// </summary> private async void DeleteButton_Click(object sender, RoutedEventArgs e) { if (RelatedRecords.SelectedItem == null) return; var graphic = (Graphic)RelatedRecords.SelectedItem; string message = null; try { if (table == null) table = await GetRelatedTableAsync(); var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture); await table.DeleteAsync(featureID); await SaveEditsAsync(); await QueryRelatedRecordsAsync(); SetAttributeEditor(); } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrWhiteSpace(message)) await new MessageDialog(message).ShowAsync(); } } }
1.40625
1
SyncPanel.cs
meyer-mcmains/musicbee-sync
0
260
using System.Windows.Forms; namespace MusicBeePlugin { public partial class SyncPanel : UserControl { public SyncPanel() { InitializeComponent(); } } }
0.734375
1
Enrollment.Parameters/Expressions/AsQueryableOperatorParameters.cs
BlaiseD/Enrollment.XPlatform
0
268
namespace Enrollment.Parameters.Expressions { public class AsQueryableOperatorParameters : IExpressionParameter { public AsQueryableOperatorParameters() { } public AsQueryableOperatorParameters(IExpressionParameter sourceOperand) { SourceOperand = sourceOperand; } public IExpressionParameter SourceOperand { get; set; } } }
0.601563
1
Advanced/Functional Programming - Exercise/09. List Of Predicates/Program.cs
tonkatawe/SoftUni-Advanced
0
276
using System; using System.Collections.Generic; using System.Linq; namespace _09._List_Of_Predicates { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); //it is maxBound var numbers = Console.ReadLine() .Split() .Select(int.Parse) .ToArray(); var result = new List<int>(); for (int i = 1; i <= n; i++) // start 1...n { var isDivde = true; foreach (var digit in numbers) { if (i % digit != 0) { isDivde = false; break; } } if (!isDivde) { continue; } result.Add(i); } Console.WriteLine(string.Join(' ', result)); } } }
2.34375
2
src/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.cs
rsumner31/corefx2
0
284
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() { AsyncValueTaskMethodBuilder<int> b = default; Assert.Equal(default(AsyncValueTaskMethodBuilder<int>), b); // implementation detail being verified } [Fact] public void SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = default; b.SetResult(42); ValueTask<int> vt = b.Task; Assert.True(vt.IsCompletedSuccessfully); Assert.False(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = default; ValueTask<int> vt = b.Task; b.SetResult(42); Assert.True(vt.IsCompletedSuccessfully); Assert.True(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = default; var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = default; var e = new FormatException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = default; var e = new OperationCanceledException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = default; int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = default; var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); Assert.True(WrapsTask(b.Task)); Assert.Equal(42, b.Task.Result); } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/22506", TargetFrameworkMonikers.UapAot)] public void SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = default; AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = default; b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); ValueTask<int> vt = b.Task; Assert.False(WrapsTask(vt)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42, await ValueTaskReturningAsyncMethod(42)); ValueTask<int> vt = ValueTaskReturningAsyncMethod(84); Assert.Equal(yields > 0, WrapsTask(vt)); Assert.Equal(84, await vt); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) await Task.Yield(); return result; } } /// <summary>Gets whether the ValueTask has a non-null Task.</summary> private static bool WrapsTask<T>(ValueTask<T> vt) => ReferenceEquals(vt.AsTask(), vt.AsTask()); private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } }
1.382813
1
VirusTotal.Library/ResponseCodes/DomainResponseCode.cs
tranvanphy/VirusTotal
0
292
namespace VirusTotal.Library.ResponseCodes { public enum DomainResponseCode { /// <summary> /// The item you searched for was not present in VirusTotal's dataset. /// </summary> NotPresent = 0, /// <summary> /// The item was present and it could be retrieved. /// </summary> Present = 1 } }
0.832031
1
DeadFishStudio.Product.Infrastructure.CrossCutting/CustomExtensionsMethods.cs
luca16s/Infnet-Pos-DevOpsPresentation
0
300
using System; using DeadFishStudio.Product.Infrastructure.Data.Context; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace DeadFishStudio.Product.Infrastructure.CrossCutting { internal static class CustomExtensionsMethods { public static IServiceCollection AddCustomDbContext(this IServiceCollection services, ProductConfiguration configuration) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); services.AddEntityFrameworkSqlServer() .AddDbContext<ProductContext>(options => { options .UseLazyLoadingProxies() .UseSqlServer(configuration.ConnectionString); }); return services; } } }
1.054688
1
AtlasBotNode/SmashggHandler/Models/TournamentRoot.cs
bartdebever/AtlasBotNetwork
1
308
using System.Collections.Generic; using Newtonsoft.Json; namespace SmashggHandler.Models { public class TournamentRoot { [JsonProperty("entities")] public TournamentEntities Entities { get; set; } } public class TournamentEntities { [JsonProperty("tournament")] public Tournament Tournament { get; set; } [JsonProperty("event")] public List<Event> Events { get; set; } [JsonProperty("videogame")] public List<Videogame> Videogames { get; set; } [JsonProperty("phase")] public List<Phase> Phases { get; set; } [JsonProperty("group")] public List<Group> Groups { get; set; } } }
0.890625
1
src/DocumentProcessing/Schulteisz.Document.PdfReader/Page.cs
schulzy/HouseholdBudget
0
316
using Schulteisz.Document.Interfaces; using System; using System.Collections.Generic; namespace Schulteisz.Document.PdfReader { public class Page : IPage { private UglyToad.PdfPig.Content.Page _page; private IEnumerable<string> _lines; public Page(UglyToad.PdfPig.Content.Page page) { _page = page; } public IEnumerable<string> Lines { get { if (_lines is null) InitPages(); return _lines; } } private void InitPages() { throw new NotImplementedException(); } } }
1.023438
1
NET.Undersoft.Vegas.Sdk/Undersoft.System.Uniques/Hasher/Algorithm/xxHash32.Array.cs
undersoft-org/NET.Undersoft.Vegas.Sdk.Develop
2
324
/************************************************* Copyright (c) 2021 Undersoft System.Uniques.xxHash32.Array.cs @project: Undersoft.Vegas.Sdk @stage: Development @author: <NAME> @date: (05.06.2021) @licence MIT *************************************************/ namespace System.Uniques { using System.Diagnostics; /// <summary> /// Defines the <see cref="xxHash32" />. /// </summary> public static partial class xxHash32 { #region Methods /// <summary> /// Compute xxHash for the data byte array. /// </summary> /// <param name="data">The source of data.</param> /// <param name="seed">The seed number.</param> /// <returns>hash.</returns> public static unsafe ulong ComputeHash(ArraySegment<byte> data, uint seed = 0) { Debug.Assert(data != null); return ComputeHash(data.Array, data.Offset, data.Count, seed); } /// <summary> /// Compute xxHash for the data byte array. /// </summary> /// <param name="data">The source of data.</param> /// <param name="length">The length of the data for hashing.</param> /// <param name="seed">The seed number.</param> /// <returns>hash.</returns> public static unsafe uint ComputeHash(byte[] data, int length, uint seed = 0) { Debug.Assert(data != null); Debug.Assert(length >= 0); Debug.Assert(length <= data.Length); fixed (byte* pData = &data[0]) { return UnsafeComputeHash(pData, length, seed); } } /// <summary> /// Compute xxHash for the data byte array. /// </summary> /// <param name="data">The source of data.</param> /// <param name="offset">The offset of the data for hashing.</param> /// <param name="length">The length of the data for hashing.</param> /// <param name="seed">The seed number.</param> /// <returns>hash.</returns> public static unsafe uint ComputeHash(byte[] data, int offset, int length, uint seed = 0) { Debug.Assert(data != null); Debug.Assert(length >= 0); Debug.Assert(offset < data.Length); Debug.Assert(length <= data.Length - offset); fixed (byte* pData = &data[0 + offset]) { return UnsafeComputeHash(pData, length, seed); } } #endregion } }
1.703125
2
src/Service.Registration.Grpc/Models/GetRestrictedCountriesGrpcResponse.cs
MyJetWallet/Service.Registration
0
332
using System.Collections.Generic; using System.Runtime.Serialization; namespace Service.Registration.Grpc.Models { [DataContract] public class GetRestrictedCountriesGrpcResponse { [DataMember(Order = 1)] public IEnumerable<string> RestrictedCountries { get; set; } } }
0.832031
1
src/Miru/IAppConfig.cs
MiruFx/Miru
11
340
using Microsoft.Extensions.DependencyInjection; namespace Miru { public interface IAppConfig { void ConfigureServices(IServiceCollection services); } }
0.539063
1
Source/LogBridge.Tests.Shared/When_logging_fatal_messages_with_null_parameters.cs
TorbenRahbekKoch/LogBridge
0
348
using System; using FluentAssertions; using Xunit; namespace SoftwarePassion.LogBridge.Tests.Shared { public abstract class When_logging_fatal_messages_with_null_parameters : LogTestBase { public When_logging_fatal_messages_with_null_parameters(ILogDataVerifier verifier) : base(Level.Fatal, verifier) {} [Fact] public void Verify_that_null_message_can_be_logged_without_failures() { Action action = () => Log.Fatal((string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_message_and_null_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (string)null, (object)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (string)null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal((string)null, null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_value_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal((object) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_extended_properties_and_null_message_and_null_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal((object) null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_extended_properties_and_null_message_and_null_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (object) null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (object) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_value_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception) null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (object)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_message_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (string)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_message_and_null_parameters_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception)null, (string)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_message_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_extended_properties_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), (Exception)null, (object)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_null_exception_and_null_extended_properties_and_null_message_and_null_formatting_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal((Exception)null, (object)null, (string)null, (string)null); action.ShouldNotThrow(); VerifyOneEventLogged(); } [Fact] public void Verify_that_correlationid_and_null_exception_and_null_extended_properties_and_null_message_and_null_formatting_parameter_can_be_logged_without_failures() { Action action = () => Log.Fatal(Guid.NewGuid(), null, (object)null, (string)null, null); action.ShouldNotThrow(); VerifyOneEventLogged(); } } }
1.234375
1
Managed/main/MinionAssignablesProxy.cs
undancer/oni-data
1
356
using System.Collections.Generic; using System.Runtime.Serialization; using KSerialization; using UnityEngine; [AddComponentMenu("KMonoBehaviour/scripts/MinionAssignablesProxy")] public class MinionAssignablesProxy : KMonoBehaviour, IAssignableIdentity { public List<Ownables> ownables; [Serialize] private int target_instance_id = -1; private bool slotsConfigured; private static readonly EventSystem.IntraObjectHandler<MinionAssignablesProxy> OnAssignablesChangedDelegate = new EventSystem.IntraObjectHandler<MinionAssignablesProxy>(delegate(MinionAssignablesProxy component, object data) { component.OnAssignablesChanged(data); }); public IAssignableIdentity target { get; private set; } public bool IsConfigured => slotsConfigured; public int TargetInstanceID => target_instance_id; public GameObject GetTargetGameObject() { if (target == null && target_instance_id != -1) { RestoreTargetFromInstanceID(); } KMonoBehaviour kMonoBehaviour = (KMonoBehaviour)target; if (kMonoBehaviour != null) { return kMonoBehaviour.gameObject; } return null; } public float GetArrivalTime() { if (GetTargetGameObject().GetComponent<MinionIdentity>() != null) { return GetTargetGameObject().GetComponent<MinionIdentity>().arrivalTime; } if (GetTargetGameObject().GetComponent<StoredMinionIdentity>() != null) { return GetTargetGameObject().GetComponent<StoredMinionIdentity>().arrivalTime; } Debug.LogError("Could not get minion arrival time"); return -1f; } public int GetTotalSkillpoints() { if (GetTargetGameObject().GetComponent<MinionIdentity>() != null) { return GetTargetGameObject().GetComponent<MinionResume>().TotalSkillPointsGained; } if (GetTargetGameObject().GetComponent<StoredMinionIdentity>() != null) { return MinionResume.CalculateTotalSkillPointsGained(GetTargetGameObject().GetComponent<StoredMinionIdentity>().TotalExperienceGained); } Debug.LogError("Could not get minion skill points time"); return -1; } public void SetTarget(IAssignableIdentity target, GameObject targetGO) { Debug.Assert(target != null, "target was null"); if (targetGO == null) { Debug.LogWarningFormat("{0} MinionAssignablesProxy.SetTarget {1}, {2}, {3}. DESTROYING", GetInstanceID(), target_instance_id, target, targetGO); Util.KDestroyGameObject(base.gameObject); } this.target = target; target_instance_id = targetGO.GetComponent<KPrefabID>().InstanceID; base.gameObject.name = "Minion Assignables Proxy : " + targetGO.name; } protected override void OnPrefabInit() { base.OnPrefabInit(); ownables = new List<Ownables> { base.gameObject.AddOrGet<Ownables>() }; Components.MinionAssignablesProxy.Add(this); ConfigureAssignableSlots(); } [OnDeserialized] private void OnDeserialized() { } public void ConfigureAssignableSlots() { if (slotsConfigured) { return; } Ownables component = GetComponent<Ownables>(); Equipment component2 = GetComponent<Equipment>(); if (component2 != null) { foreach (AssignableSlot resource in Db.Get().AssignableSlots.resources) { if (resource is OwnableSlot) { OwnableSlotInstance slot_instance = new OwnableSlotInstance(component, (OwnableSlot)resource); component.Add(slot_instance); } else if (resource is EquipmentSlot) { EquipmentSlotInstance slot_instance2 = new EquipmentSlotInstance(component2, (EquipmentSlot)resource); component2.Add(slot_instance2); } } } slotsConfigured = true; } public void RestoreTargetFromInstanceID() { if (target_instance_id == -1 || target != null) { return; } KPrefabID instance = KPrefabIDTracker.Get().GetInstance(target_instance_id); if ((bool)instance) { IAssignableIdentity component = instance.GetComponent<IAssignableIdentity>(); if (component != null) { SetTarget(component, instance.gameObject); return; } Debug.LogWarningFormat("RestoreTargetFromInstanceID target ID {0} was found but it wasn't an IAssignableIdentity, destroying proxy object.", target_instance_id); Util.KDestroyGameObject(base.gameObject); } else { Debug.LogWarningFormat("RestoreTargetFromInstanceID target ID {0} was not found, destroying proxy object.", target_instance_id); Util.KDestroyGameObject(base.gameObject); } } protected override void OnSpawn() { base.OnSpawn(); RestoreTargetFromInstanceID(); if (target != null) { Subscribe(-1585839766, OnAssignablesChangedDelegate); Game.Instance.assignmentManager.AddToAssignmentGroup("public", this); } } protected override void OnCleanUp() { base.OnCleanUp(); Game.Instance.assignmentManager.RemoveFromAllGroups(this); GetComponent<Ownables>().UnassignAll(); GetComponent<Equipment>().UnequipAll(); Components.MinionAssignablesProxy.Remove(this); } private void OnAssignablesChanged(object data) { if (!target.IsNull()) { ((KMonoBehaviour)target).Trigger(-1585839766, data); } } private void CheckTarget() { if (target != null) { return; } KPrefabID instance = KPrefabIDTracker.Get().GetInstance(target_instance_id); if (!(instance != null)) { return; } target = instance.GetComponent<IAssignableIdentity>(); if (target == null) { return; } MinionIdentity minionIdentity = target as MinionIdentity; if ((bool)minionIdentity) { minionIdentity.ValidateProxy(); return; } StoredMinionIdentity storedMinionIdentity = target as StoredMinionIdentity; if ((bool)storedMinionIdentity) { storedMinionIdentity.ValidateProxy(); } } public List<Ownables> GetOwners() { CheckTarget(); return target.GetOwners(); } public string GetProperName() { CheckTarget(); return target.GetProperName(); } public Ownables GetSoleOwner() { CheckTarget(); return target.GetSoleOwner(); } public bool HasOwner(Assignables owner) { CheckTarget(); return target.HasOwner(owner); } public int NumOwners() { CheckTarget(); return target.NumOwners(); } public bool IsNull() { CheckTarget(); return target.IsNull(); } public static Ref<MinionAssignablesProxy> InitAssignableProxy(Ref<MinionAssignablesProxy> assignableProxyRef, IAssignableIdentity source) { if (assignableProxyRef == null) { assignableProxyRef = new Ref<MinionAssignablesProxy>(); } GameObject targetGO = ((KMonoBehaviour)source).gameObject; MinionAssignablesProxy minionAssignablesProxy = assignableProxyRef.Get(); if (minionAssignablesProxy == null) { GameObject obj = GameUtil.KInstantiate(Assets.GetPrefab(MinionAssignablesProxyConfig.ID), Grid.SceneLayer.NoLayer); minionAssignablesProxy = obj.GetComponent<MinionAssignablesProxy>(); minionAssignablesProxy.SetTarget(source, targetGO); obj.SetActive(value: true); assignableProxyRef.Set(minionAssignablesProxy); } else { minionAssignablesProxy.SetTarget(source, targetGO); } return assignableProxyRef; } }
1.453125
1
Serenity.Core/Authorization/Authorization.cs
awesomegithubusername/Serenity
1
364
using Serenity.Abstractions; using Serenity.Services; using System; namespace Serenity { /// <summary> /// Provides a common access point for authorization related services /// </summary> public static class Authorization { /// <summary> /// Returns true if user is logged in. /// </summary> /// <remarks> /// Uses the IAuthorizationService dependency. /// </remarks> public static bool IsLoggedIn { get { return Dependency.Resolve<IAuthorizationService>().IsLoggedIn; } } /// <summary> /// Returns user definition for currently logged user. /// </summary> /// <remarks> /// Uses IUserRetrieveService to get definition of current user by /// its username. /// </remarks> public static IUserDefinition UserDefinition { get { var username = Username; if (username == null) return null; return Dependency.Resolve<IUserRetrieveService>().ByUsername(username); } } /// <summary> /// Returns currently logged user ID /// </summary> /// <remarks> /// This is a shortcut to UserDefinition.UserId. /// </remarks> public static string UserId { get { var user = UserDefinition; return user == null ? null : user.Id; } } /// <summary> /// Returns currently logged username. /// </summary> /// <remarks>Uses IAuthorizationService dependency.</remarks> public static string Username { get { return Dependency.Resolve<IAuthorizationService>().Username; } } /// <summary> /// Returns true if current user has given permission. /// </summary> /// <param name="permission">Permission key (e.g. Administration)</param> public static bool HasPermission(string permission) { return Dependency.Resolve<IPermissionService>().HasPermission(permission); } /// <summary> /// Checks if there is a currently logged user and throws a validation error with /// "NotLoggedIn" error code if not. /// </summary> public static void ValidateLoggedIn() { if (!IsLoggedIn) throw new ValidationError("NotLoggedIn", null, Serenity.Core.Texts.Authorization.NotLoggedIn); } /// <summary> /// Checks if current user has given permission and throws a validation error with /// "AccessDenied" error code if not. /// </summary> /// <param name="permission"></param> public static void ValidatePermission(string permission) { if (!HasPermission(permission)) throw new ValidationError("AccessDenied", null, Serenity.Core.Texts.Authorization.AccessDenied); } } }
1.460938
1
Yuki Theme.Core/Themes/ExternalThemeManager.cs
Dragon-0609/Yuki-Theme
15
372
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace Yuki_Theme.Core.Themes; public static class ExternalThemeManager { public static void LoadThemes () { string [] files = Directory.GetFiles (CLI.currentPath, "*Themes.dll"); if (files.Length > 0) AddThemesToDB (files); string path = Path.Combine (CLI.currentPath, "Themes"); if (Directory.Exists (path)) { files = Directory.GetFiles (path, "*.dll"); if (files.Length > 0) AddThemesToDB (files); } } private static void AddThemesToDB (string [] files) { foreach (string file in files) { Assembly assembly = Assembly.LoadFile (file); Type [] types = assembly.GetTypes (); Type themeHeader = types.FirstOrDefault (i => typeof (IThemeHeader).IsAssignableFrom (i) && i.IsClass); if (themeHeader != null) { IThemeHeader header = (IThemeHeader)Activator.CreateInstance (themeHeader); DefaultThemes.addHeader (header); } } } }
1.21875
1
src/VSPoll.API.UnitTest/Models/MappingTests.cs
valamistudio/vspoll
1
380
using System; using FluentAssertions; using VSPoll.API.Models.Output; using Xunit; using Entity = VSPoll.API.Persistence.Entities; namespace VSPoll.API.UnitTest.Models { public class Mapping { [Fact] public void Poll_Mapping() { Entity.Poll entity = new() { Description = "Description", EndDate = DateTime.UtcNow, Id = Guid.NewGuid(), }; var model = Poll.Of(entity); model.AllowAdd.Should().Be(entity.AllowAdd); model.Description.Should().Be(entity.Description); model.EndDate.Should().Be(entity.EndDate); model.Id.Should().Be(entity.Id); model.VotingSystem.Should().Be(entity.VotingSystem); model.ShowVoters.Should().Be(entity.ShowVoters); } [Fact] public void PollOption_Mapping() { Entity.PollOption entity = new() { Description = "Description", Id = Guid.NewGuid(), }; var model = PollOption.Of(entity); model.Description.Should().Be(entity.Description); model.Id.Should().Be(entity.Id); } [Fact] public void User_Mapping() { Entity.User entity = new() { FirstName = "First", Id = new Random().Next(), LastName = "Last", PhotoUrl = "Url", Username = "Username", }; User model = new(entity); model.FirstName.Should().Be(entity.FirstName); model.LastName.Should().Be(entity.LastName); model.PhotoUrl.Should().Be(entity.PhotoUrl); model.Username.Should().Be(entity.Username); } } }
1.335938
1
AlipaySDKNet/Response/MybankCreditGuaranteeSelleradmittanceQueryResponse.cs
alipay/alipay-sdk-net
117
388
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// MybankCreditGuaranteeSelleradmittanceQueryResponse. /// </summary> public class MybankCreditGuaranteeSelleradmittanceQueryResponse : AopResponse { /// <summary> /// 查询decision是否准入。为空表示不准入 /// </summary> [XmlElement("is_admitted")] public bool IsAdmitted { get; set; } /// <summary> /// 是否签约 /// </summary> [XmlElement("is_signed")] public bool IsSigned { get; set; } /// <summary> /// 是否解约AE提前收款,为空表示未解约 /// </summary> [XmlElement("is_unsigned")] public bool IsUnsigned { get; set; } /// <summary> /// 解约时间,为空表示无解约时间 /// </summary> [XmlElement("unsign_date")] public string UnsignDate { get; set; } } }
0.695313
1
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
26
Edit dataset card