content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Microsoft.AspNetCore.Authorization;
using Plus.DependencyInjection;
using Plus.DynamicProxy;
using System;
using System.Linq;
using System.Reflection;
namespace Plus.Authorization
{
public static class AuthorizationInterceptorRegistrar
{
public static void RegisterIfNeeded(IOnServiceRegistredContext context)
{
if (ShouldIntercept(context.ImplementationType))
{
context.Interceptors.TryAdd<AuthorizationInterceptor>();
}
}
private static bool ShouldIntercept(Type type)
{
return !DynamicProxyIgnoreTypes.Contains(type) &&
(type.IsDefined(typeof(AuthorizeAttribute), true) || AnyMethodHasAuthorizeAttribute(type));
}
private static bool AnyMethodHasAuthorizeAttribute(Type implementationType)
{
return implementationType
.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Any(HasAuthorizeAttribute);
}
private static bool HasAuthorizeAttribute(MemberInfo methodInfo)
{
return methodInfo.IsDefined(typeof(AuthorizeAttribute), true);
}
}
} | 32.289474 | 110 | 0.666667 | [
"MIT"
] | Meowv/Plus.Core | Plus.Core/Plus/Authorization/AuthorizationInterceptorRegistrar.cs | 1,229 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class ExprClass : ExprWithType
{
public ExprClass(CType type)
: base(ExpressionKind.Class, type)
{
Debug.Assert(type != null);
}
}
}
| 27.388889 | 71 | 0.677485 | [
"MIT"
] | 06needhamt/runtime | src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Class.cs | 493 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("DHSegmentedControl.IOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("davehumphreys")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 35.714286 | 81 | 0.748 | [
"MIT"
] | Humbatt/DHSegmentControl | DHSegmentedControl.IOS/Properties/AssemblyInfo.cs | 1,002 | C# |
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.Reflection;
using System.Linq;
namespace AlmostEngine.Screenshot
{
/// <summary>
/// Game View Utils is used to control the game view sizes.
/// Part of this code was inspired and adapted from http://answers.unity3d.com/questions/956123/add-and-select-game-view-resolution.html
/// </summary>
public static class GameViewUtils
{
public enum SizeType
{
RATIO,
FIXED_RESOLUTION
}
;
#region SizeGroups Management
public static object GetCurrentGameViewSizeGroup()
{
// Get the instance of the asset of type GameViewSizes containing all gameview size data
var sizesType = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSizes");
var instanceProp = sizesType.GetProperty("instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy);
object gameViewSizesInstance = instanceProp.GetValue(null, null);
// Get the current group GameViewSizeGroup
// containing resolutions data for Standalone, or iOS, or Android ...
var currentGroupProp = sizesType.GetProperty("currentGroup", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
return currentGroupProp.GetValue(gameViewSizesInstance, null);
}
public static int GetCurrentSizeIndex()
{
var gameviewType = typeof(Editor).Assembly.GetType("UnityEditor.GameView");
var selectedSizeIndex = gameviewType.GetProperty("selectedSizeIndex", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
var gameView = GetGameView();
return (int)selectedSizeIndex.GetValue(gameView, null);
}
public static void SetCurrentSizeIndex(int index)
{
var gameviewType = typeof(Editor).Assembly.GetType("UnityEditor.GameView");
var gameView = GetGameView();
// #if (UNITY_5_4_OR_NEWER && UNITY_STANDALONE)
// var SizeSelectionCallback = gameviewType.GetMethod ("SizeSelectionCallback", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
// SizeSelectionCallback.Invoke (gameView, new object[] { index, null });
// #else
var selectedSizeIndex = gameviewType.GetProperty("selectedSizeIndex", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
selectedSizeIndex.SetValue(gameView, index, null);
// #endif
}
public static List<string>
GetAllSizeNames()
{
List<string> names = new List<string>();
object group = GetCurrentGameViewSizeGroup();
System.Reflection.MethodInfo getTotalCount = group.GetType().GetMethod("GetTotalCount", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
System.Reflection.MethodInfo getGameViewSize = group.GetType().GetMethod("GetGameViewSize", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
int size = (int)getTotalCount.Invoke(group, null);
for (int i = 0; i < size; i++)
{
object gameViewSize = getGameViewSize.Invoke(group, new object[] { i });
string name = (string)gameViewSize.GetType().GetProperty("baseText", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(gameViewSize, null);
names.Add(name);
}
return names;
}
public static int FindSize(string baseText)
{
List<string> names = GetAllSizeNames();
for (int i = 0; i < names.Count; i++)
{
if (names[i] == baseText)
{
return i;
}
}
return -1;
}
public static void AddCustomSize(SizeType sizeType, int width, int height, string baseText)
{
// Create a new game view size
var sizesType = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSize");
var gameviewsizetypeType = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSizeType");
System.Reflection.ConstructorInfo constructor = sizesType.GetConstructor(new System.Type[] {
gameviewsizetypeType,
typeof(int),
typeof(int),
typeof(string)
});
object customGameViewSize = constructor.Invoke(new object[] {
(int)sizeType,
width,
height,
baseText
});
// Add it to the view size group
object group = GetCurrentGameViewSizeGroup();
System.Reflection.MethodInfo addCustomSize = group.GetType().GetMethod("AddCustomSize", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
addCustomSize.Invoke(group, new object[] { customGameViewSize });
}
public static void RemoveCustomSize(int id)
{
object group = GetCurrentGameViewSizeGroup();
System.Reflection.MethodInfo removeCustomSize = group.GetType().GetMethod("RemoveCustomSize", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
removeCustomSize.Invoke(group, new object[] { id });
}
public static bool SizeExists(string name)
{
return FindSize(name) != -1;
}
public static SizeType GetCurrentSizeType()
{
object group = GetCurrentGameViewSizeGroup();
System.Reflection.MethodInfo getGameViewSize = group.GetType().GetMethod("GetGameViewSize", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
int i = GetCurrentSizeIndex();
object gameViewSize = getGameViewSize.Invoke(group, new object[] { i });
return (SizeType)gameViewSize.GetType().GetProperty("sizeType", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(gameViewSize, null);
}
#endregion
#region Size Management
public static void SetGameViewSize(int width, int height)
{
var gameviewType = typeof(Editor).Assembly.GetType("UnityEditor.GameView");
var gameView = GetGameView();
var currentGameViewSizeProp = gameviewType.GetProperty("currentGameViewSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
if (currentGameViewSizeProp == null)
{
Debug.LogError("Can not get currentGameViewSize prop");
return;
}
var currentGameViewSize = currentGameViewSizeProp.GetValue(gameView, null);
var gameViewSizeType = currentGameViewSize.GetType();
var w = gameViewSizeType.GetProperty("width", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var h = gameViewSizeType.GetProperty("height", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
w.SetValue(currentGameViewSize, width, null);
h.SetValue(currentGameViewSize, height, null);
// Force repaint
gameView.Repaint();
}
public static Vector2 GetCurrentGameViewSize()
{
var gameView = GetGameView();
var currentGameViewSizeProp = gameView.GetType().GetProperty("currentGameViewSize", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var currentGameViewSize = currentGameViewSizeProp.GetValue(gameView, null);
var gameViewSizeType = currentGameViewSize.GetType();
var w = gameViewSizeType.GetProperty("width", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var h = gameViewSizeType.GetProperty("height", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
Vector2 size = new Vector2();
size.x = (int)w.GetValue(currentGameViewSize, new object[0] { });
size.y = (int)h.GetValue(currentGameViewSize, new object[0] { });
return size;
}
public static Vector2 GetCurrentGameViewRectSize()
{
var gameviewType = typeof(Editor).Assembly.GetType("UnityEditor.GameView");
var gameView = GetGameView();
#if (UNITY_5_4_OR_NEWER)
var targetSize = gameviewType.GetProperty("targetSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
return (Vector2)targetSize.GetValue(gameView, null);
#else
var method = gameviewType.GetMethod ("GetConstrainedGameViewRenderRect", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
Rect size = (Rect)method.Invoke (gameView, null);
return size.size;
#endif
}
public static EditorWindow GetGameView()
{
var gameviewType = typeof(Editor).Assembly.GetType("UnityEditor.GameView");
return EditorWindow.GetWindow(gameviewType);
}
#endregion
#region Rect Management
public static Rect GetCurrentGameViewRect()
{
return GetGameView().position;
}
public static void SetGameViewRect(Rect pos)
{
GetGameView().position = pos;
}
#endregion
}
}
#endif | 43.809322 | 238 | 0.643196 | [
"MIT"
] | assemyasser200/the_clothing_shop | Assets/Third Party/AlmostEngine/UltimateScreenshotCreator/Assets/Scripts/Utils/GameViewUtils.cs | 10,339 | C# |
using System;
public abstract class DataInspector {
public abstract bool canFoldout();
public virtual bool printHead(ref object data, Type type) { return false; }
public abstract bool inspect(ref object data, Type type, string name, string path);
protected bool applyData(ref object data, object newData)
{
if (data == null)
{
if (newData == null) return false;
else {
data = newData;
return true;
}
}
else
{
bool changed = !data.Equals(newData);
if (changed) data = newData;
return changed;
}
}
}
| 18.333333 | 84 | 0.667273 | [
"MIT"
] | sric0880/unity-framework | Assets/DataInspector/Editor/DataInspector.cs | 552 | C# |
using NitroSharp.Text;
using NitroSharp.Utilities;
using System;
using System.Text;
using NitroSharp.NsScript;
using NitroSharp.NsScript.VM;
namespace NitroSharp
{
internal readonly struct BacklogEntry
{
public readonly string Text;
public BacklogEntry(string text)
{
Text = text;
}
}
internal sealed class Backlog
{
private readonly SystemVariableLookup _systemVariables;
private ArrayBuilder<BacklogEntry> _entries;
private readonly StringBuilder _sb;
public Backlog(SystemVariableLookup systemVariables)
{
_systemVariables = systemVariables;
_entries = new ArrayBuilder<BacklogEntry>(1024);
_sb = new StringBuilder();
}
public void Append(TextSegment text)
{
_sb.Clear();
foreach (TextRun textRun in text.TextRuns)
{
_sb.Append(textRun.Text);
}
if (_sb.Length > 0)
{
string s = _sb.ToString();
_systemVariables.LastText = ConstantValue.String(s);
_entries.Add(new BacklogEntry(s));
}
}
public ReadOnlySpan<BacklogEntry> Entries => _entries.AsReadonlySpan();
public void Clear()
{
_entries.Clear();
}
}
}
| 24.280702 | 79 | 0.575145 | [
"MIT"
] | Cred0utofnames/nitrosharp | src/NitroSharp/Backlog.cs | 1,386 | C# |
using System.Collections.Generic;
namespace DancingGoat.Models
{
public class SearchResultsModel
{
public string Query { get; set; }
public List<SearchResultItemModel> Items { get; set; }
public int CurrentPage { get; set; }
public int NumberOfPages { get; set; }
public Dictionary<string, string> GetRouteData(int page) =>
new Dictionary<string, string>() { { "searchText", Query }, { "page", page.ToString() } };
}
} | 24.333333 | 103 | 0.598826 | [
"MIT"
] | Kentico/xperience-module-intercom | src/DancingGoatCore/Models/Search/ViewModels/SearchResultsModel.cs | 513 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace TransportApiSharpSample.Converters
{
public class BoolFalseToVisibleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (value is bool && (bool)value) ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return value is Visibility && (Visibility)value == Visibility.Collapsed;
}
}
} | 30.826087 | 99 | 0.703808 | [
"MIT"
] | marknotgeorge/TransportAPISharp | TransportApiSharpSample/Converters/BoolFalseToVisibleConverter.cs | 711 | C# |
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Nerdbank.GitVersioning;
internal class VersionOptionsContractResolver : CamelCasePropertyNamesContractResolver
{
private static readonly object TypeContractCacheLock = new object();
private static readonly Dictionary<Tuple<bool, bool, Type>, JsonContract> ContractCache = new Dictionary<Tuple<bool, bool, Type>, JsonContract>();
public VersionOptionsContractResolver()
{
}
internal bool IncludeSchemaProperty { get; set; }
internal bool IncludeDefaults { get; set; } = true;
/// <summary>
/// Obtains a contract for a given type.
/// </summary>
/// <param name="type">The type to obtain a contract for.</param>
/// <returns>The contract.</returns>
/// <remarks>
/// This override changes the caching policy from the base class, which caches based on this.GetType().
/// The inherited policy is problematic because we have instance properties that change the contract.
/// So instead, we cache with a complex key to capture the settings as well.
/// </remarks>
public override JsonContract ResolveContract(Type type)
{
var contractKey = Tuple.Create(this.IncludeSchemaProperty, this.IncludeDefaults, type);
JsonContract contract;
lock (TypeContractCacheLock)
{
if (ContractCache.TryGetValue(contractKey, out contract))
{
return contract;
}
}
contract = this.CreateContract(type);
lock (TypeContractCacheLock)
{
if (!ContractCache.ContainsKey(contractKey))
{
ContractCache.Add(contractKey, contract);
}
}
return contract;
}
/// <inheritdoc/>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(VersionOptions) && member.Name == nameof(VersionOptions.Schema))
{
property.ShouldSerialize = instance => this.IncludeSchemaProperty;
}
if (!this.IncludeDefaults)
{
if (property.DeclaringType == typeof(VersionOptions) && member.Name == nameof(VersionOptions.AssemblyVersion))
{
property.ShouldSerialize = instance => !((VersionOptions)instance).AssemblyVersionOrDefault.IsDefault;
}
#pragma warning disable CS0618 // Type or member is obsolete
if (property.DeclaringType == typeof(VersionOptions) && member.Name == nameof(VersionOptions.BuildNumberOffset))
#pragma warning restore CS0618 // Type or member is obsolete
{
property.ShouldSerialize = instance => false; // always serialized by its new name
}
if (property.DeclaringType == typeof(VersionOptions) && member.Name == nameof(VersionOptions.VersionHeightOffset))
{
property.ShouldSerialize = instance => ((VersionOptions)instance).VersionHeightOffsetOrDefault != 0;
}
if (property.DeclaringType == typeof(VersionOptions) && member.Name == nameof(VersionOptions.NuGetPackageVersion))
{
property.ShouldSerialize = instance => !((VersionOptions)instance).NuGetPackageVersionOrDefault.IsDefault;
}
if (property.DeclaringType == typeof(VersionOptions) && member.Name == nameof(VersionOptions.CloudBuild))
{
property.ShouldSerialize = instance => !((VersionOptions)instance).CloudBuildOrDefault.IsDefault;
}
if (property.DeclaringType == typeof(VersionOptions.CloudBuildOptions) && member.Name == nameof(VersionOptions.CloudBuildOptions.SetAllVariables))
{
property.ShouldSerialize = instance => ((VersionOptions.CloudBuildOptions)instance).SetAllVariablesOrDefault != VersionOptions.CloudBuildOptions.DefaultInstance.SetAllVariables.Value;
}
if (property.DeclaringType == typeof(VersionOptions.CloudBuildOptions) && member.Name == nameof(VersionOptions.CloudBuildOptions.SetVersionVariables))
{
property.ShouldSerialize = instance => ((VersionOptions.CloudBuildOptions)instance).SetVersionVariablesOrDefault != VersionOptions.CloudBuildOptions.DefaultInstance.SetVersionVariables.Value;
}
if (property.DeclaringType == typeof(VersionOptions.CloudBuildNumberOptions) && member.Name == nameof(VersionOptions.CloudBuildNumberOptions.IncludeCommitId))
{
property.ShouldSerialize = instance => !((VersionOptions.CloudBuildNumberOptions)instance).IncludeCommitIdOrDefault.IsDefault;
}
if (property.DeclaringType == typeof(VersionOptions.CloudBuildNumberCommitIdOptions) && member.Name == nameof(VersionOptions.CloudBuildNumberCommitIdOptions.When))
{
property.ShouldSerialize = instance => ((VersionOptions.CloudBuildNumberCommitIdOptions)instance).WhenOrDefault != VersionOptions.CloudBuildNumberCommitIdOptions.DefaultInstance.When.Value;
}
if (property.DeclaringType == typeof(VersionOptions.CloudBuildNumberCommitIdOptions) && member.Name == nameof(VersionOptions.CloudBuildNumberCommitIdOptions.Where))
{
property.ShouldSerialize = instance => ((VersionOptions.CloudBuildNumberCommitIdOptions)instance).WhereOrDefault != VersionOptions.CloudBuildNumberCommitIdOptions.DefaultInstance.Where.Value;
}
if (property.DeclaringType == typeof(VersionOptions) && member.Name == nameof(VersionOptions.Release))
{
property.ShouldSerialize = instance => !((VersionOptions)instance).ReleaseOrDefault.IsDefault;
}
if (property.DeclaringType == typeof(VersionOptions.ReleaseOptions) && member.Name == nameof(VersionOptions.ReleaseOptions.BranchName))
{
property.ShouldSerialize = instance => ((VersionOptions.ReleaseOptions)instance).BranchNameOrDefault != VersionOptions.ReleaseOptions.DefaultInstance.BranchName;
}
if (property.DeclaringType == typeof(VersionOptions.ReleaseOptions) && member.Name == nameof(VersionOptions.ReleaseOptions.VersionIncrement))
{
property.ShouldSerialize = instance => ((VersionOptions.ReleaseOptions)instance).VersionIncrementOrDefault != VersionOptions.ReleaseOptions.DefaultInstance.VersionIncrement.Value;
}
if (property.DeclaringType == typeof(VersionOptions.ReleaseOptions) && member.Name == nameof(VersionOptions.ReleaseOptions.FirstUnstableTag))
{
property.ShouldSerialize = instance => ((VersionOptions.ReleaseOptions)instance).FirstUnstableTagOrDefault != VersionOptions.ReleaseOptions.DefaultInstance.FirstUnstableTag;
}
}
return property;
}
}
| 49.094595 | 207 | 0.686072 | [
"MIT"
] | AArnott/Nerdbank.GitVersioning | src/NerdBank.GitVersioning/VersionOptionsContractResolver.cs | 7,268 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Animation.DoubleAnimation.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Animation
{
public partial class DoubleAnimation : DoubleAnimationBase
{
#region Methods and constructors
public System.Windows.Media.Animation.DoubleAnimation Clone()
{
return default(System.Windows.Media.Animation.DoubleAnimation);
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
public DoubleAnimation()
{
}
public DoubleAnimation(double toValue, System.Windows.Duration duration, FillBehavior fillBehavior)
{
}
public DoubleAnimation(double toValue, System.Windows.Duration duration)
{
}
public DoubleAnimation(double fromValue, double toValue, System.Windows.Duration duration, FillBehavior fillBehavior)
{
}
public DoubleAnimation(double fromValue, double toValue, System.Windows.Duration duration)
{
}
protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue, AnimationClock animationClock)
{
return default(double);
}
#endregion
#region Properties and indexers
public Nullable<double> By
{
get
{
return default(Nullable<double>);
}
set
{
}
}
public IEasingFunction EasingFunction
{
get
{
return default(IEasingFunction);
}
set
{
}
}
public Nullable<double> From
{
get
{
return default(Nullable<double>);
}
set
{
}
}
public bool IsAdditive
{
get
{
return default(bool);
}
set
{
}
}
public bool IsCumulative
{
get
{
return default(bool);
}
set
{
}
}
public Nullable<double> To
{
get
{
return default(Nullable<double>);
}
set
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty ByProperty;
public readonly static System.Windows.DependencyProperty EasingFunctionProperty;
public readonly static System.Windows.DependencyProperty FromProperty;
public readonly static System.Windows.DependencyProperty ToProperty;
#endregion
}
}
| 27.660256 | 463 | 0.698494 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/PresentationCore/Sources/System.Windows.Media.Animation.DoubleAnimation.cs | 4,315 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour
{
Asteroid asteroidConfigure;
Asteroid asteroidRequest;
Asteroid asteroidPlay;
Asteroid asteroidAdViewRequest;
Asteroid asteroidAdViewDestroy; //DestroyAdView
AdColony.AdColonyAdView adView;
AdColony.InterstitialAd Ad = null;
ArrayList arrayList = new ArrayList();
static int counter = 0;
float currencyPopupTimer = 0.0f;
void Start()
{
GameObject configureObj = GameObject.FindGameObjectWithTag(Constants.AsteroidConfigureTag);
asteroidConfigure = configureObj.GetComponent<Asteroid>();
GameObject requestObj = GameObject.FindGameObjectWithTag(Constants.AsteroidRequestTag);
asteroidRequest = requestObj.GetComponent<Asteroid>();
GameObject playObj = GameObject.FindGameObjectWithTag(Constants.AsteroidPlayTag);
asteroidPlay = playObj.GetComponent<Asteroid>();
GameObject adViewRequstObj = GameObject.FindGameObjectWithTag(Constants.AsteroidAdViewRequest);
asteroidAdViewRequest = adViewRequstObj.GetComponent<Asteroid>();
GameObject adViewDestroyObj = GameObject.FindGameObjectWithTag(Constants.AsteroidAdViewDestroy);
asteroidAdViewDestroy = adViewDestroyObj.GetComponent<Asteroid>();
// Only configure asteroid is available at start.
asteroidConfigure.Show();
asteroidRequest.Hide();
asteroidPlay.Hide();
asteroidAdViewRequest.Hide();
asteroidAdViewDestroy.Hide();
// ----- AdColony Ads -----
AdColony.Ads.OnConfigurationCompleted += (List<AdColony.Zone> zones_) =>
{
Debug.Log("AdColony.Ads.OnConfigurationCompleted called");
if (zones_ == null || zones_.Count <= 0)
{
// Show the configure asteroid again.
asteroidConfigure.Show();
}
else
{
// Successfully configured... show the request ad asteroid.
asteroidRequest.Show();
asteroidAdViewRequest.Show();
}
};
AdColony.Ads.OnRequestInterstitial += (AdColony.InterstitialAd ad_) =>
{
Debug.Log("AdColony.Ads.OnRequestInterstitial called");
Ad = ad_;
// Successfully requested ad... show the play ad asteroid.
asteroidPlay.Show();
};
AdColony.Ads.OnRequestInterstitialFailedWithZone += (string zoneId) =>
{
Debug.Log("AdColony.Ads.OnRequestInterstitialFailedWithZone called, zone: " + zoneId);
// Request Ad failed... show the request ad asteroid.
asteroidRequest.Show();
};
AdColony.Ads.OnOpened += (AdColony.InterstitialAd ad_) =>
{
Debug.Log("AdColony.Ads.OnOpened called");
// Ad started playing... show the request ad asteroid for the next ad.
asteroidRequest.Show();
};
AdColony.Ads.OnClosed += (AdColony.InterstitialAd ad_) =>
{
Debug.Log("AdColony.Ads.OnClosed called, expired: " + ad_.Expired);
ad_.DestroyAd();
};
AdColony.Ads.OnExpiring += (AdColony.InterstitialAd ad_) =>
{
Debug.Log("AdColony.Ads.OnExpiring called");
Ad = null;
// Current ad expired... show the request ad asteroid.
asteroidRequest.Show();
asteroidPlay.Hide();
};
AdColony.Ads.OnIAPOpportunity += (AdColony.InterstitialAd ad_, string iapProductId_, AdColony.AdsIAPEngagementType engagement_) =>
{
Debug.Log("AdColony.Ads.OnIAPOpportunity called");
};
AdColony.Ads.OnRewardGranted += (string zoneId, bool success, string name, int amount) =>
{
Debug.Log(string.Format("AdColony.Ads.OnRewardGranted called\n\tzoneId: {0}\n\tsuccess: {1}\n\tname: {2}\n\tamount: {3}", zoneId, success, name, amount));
};
AdColony.Ads.OnCustomMessageReceived += (string type, string message) =>
{
Debug.Log(string.Format("AdColony.Ads.OnCustomMessageReceived called\n\ttype: {0}\n\tmessage: {1}", type, message));
};
//Banner events.
AdColony.Ads.OnAdViewOpened += (AdColony.AdColonyAdView ad_) =>
{
Debug.Log("AdColony.SampleApps.OnAdViewOpened called");
};
AdColony.Ads.OnAdViewLoaded += (AdColony.AdColonyAdView ad_) =>
{
Debug.Log("AdColony.SampleApps.OnAdViewLoaded called");
asteroidAdViewDestroy.Show();
arrayList.Add(ad_);
adView = ad_;
// Show or hide the ad view(this is optional; the banner is shown by default)
/* Setting 2 timers of 5 and 10 seconds, after 5 sec calling
* the ad view's hide method that is defined below and after 10 sec calling the ad view's show method that is defined below.*/
Invoke("HideAdView", 5.0f);
Invoke("ShowAdView", 10.0f);
};
AdColony.Ads.OnAdViewFailedToLoad += (AdColony.AdColonyAdView ad_) =>
{
Debug.Log("AdColony.SampleApps.OnAdViewFailedToLoad called with Zone id:" + ad_.ZoneId + " " + ad_.adPosition);
asteroidAdViewRequest.Show();
};
AdColony.Ads.OnAdViewClosed += (AdColony.AdColonyAdView ad_) =>
{
Debug.Log("AdColony.SampleApps.OnAdViewClosed called");
};
AdColony.Ads.OnAdViewClicked += (AdColony.AdColonyAdView ad_) =>
{
Debug.Log("AdColony.SampleApps.OnAdViewClicked called");
};
AdColony.Ads.OnAdViewLeftApplication += (AdColony.AdColonyAdView ad_) =>
{
Debug.Log("AdColony.SampleApps.OnAdViewLeftApplication called");
};
}
void Update()
{
if (currencyPopupTimer > 0.0f)
{
// This is a temporary hack to make sure we can re-show the requasteroidAdViewRequest.Show();est asteroid
// if we are playing a currency ad and the user click "NO" on the popup dialog.
currencyPopupTimer -= Time.deltaTime;
if (currencyPopupTimer <= 0.0f)
{
asteroidRequest.Show();
asteroidPlay.Hide();
}
}
}
void ConfigureAds()
{
// Configure the AdColony SDK
Debug.Log("**** Configure ADC SDK ****");
// Set some test app options with metadata.
AdColony.AppOptions appOptions = new AdColony.AppOptions();
appOptions.UserId = "foo";
appOptions.SetOption("test_key", "Happy Fun Time!");
appOptions.SetPrivacyConsentString(AdColony.AppOptions.GDPR, "1");
appOptions.SetPrivacyFrameworkRequired(AdColony.AppOptions.GDPR, true);
appOptions.SetPrivacyConsentString(AdColony.AppOptions.CCPA, "0");
appOptions.SetPrivacyFrameworkRequired(AdColony.AppOptions.CCPA, false);
appOptions.SetPrivacyFrameworkRequired(AdColony.AppOptions.COPPA, true);
string[] zoneIDs = new string[] { Constants.InterstitialZoneID, Constants.AdViewZoneID, Constants.CurrencyZoneID };
AdColony.Ads.Configure(Constants.AppID, appOptions, zoneIDs);
}
void RequestAd()
{
// Request an ad.
Debug.Log("**** Request Ad ****");
AdColony.AdOptions adOptions = new AdColony.AdOptions();
adOptions.ShowPrePopup = true;
adOptions.ShowPostPopup = true;
AdColony.Ads.RequestInterstitialAd(Constants.CurrencyZoneID, adOptions);
}
void RequestBannerAd()
{
AdColony.AdOptions adOptions = new AdColony.AdOptions();
if (counter == 1)
{
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.Bottom, adOptions);
counter = 2;
}
else if (counter == 2)
{
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.TopLeft, adOptions);
counter = 3;
}
else if (counter == 3)
{
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.TopRight, adOptions);
counter = 4;
}
else if (counter == 4)
{
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.BottomLeft, adOptions);
counter = 5;
}
else if (counter == 5)
{
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.BottomRight, adOptions);
counter = 6;
}
else if (counter == 6)
{
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.Center, adOptions);
counter = 7;
}
else
{
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.Top, adOptions);
counter = 1;
}
}
void RequestBannerAd2()
{
AdColony.AdOptions adOptions = new AdColony.AdOptions();
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.Center, adOptions);
AdColony.Ads.RequestAdView(Constants.AdViewZoneID, AdColony.AdSize.Banner, AdColony.AdPosition.Bottom, adOptions);
}
void PlayAd()
{
if (Ad != null)
{
AdColony.Ads.ShowAd(Ad);
if (Ad.ZoneId == Constants.CurrencyZoneID)
{
currencyPopupTimer = 5.0f;
}
}
}
// Show or hide the ad view(this is optional; the banner is shown by default)
void HideAdView()
{
//Hide the ad view.
adView.HideAdView();
}
void ShowAdView()
{
//Show the ad view.
adView.ShowAdView();
}
public void PerformAdColonyAction(Asteroid asteroid)
{
if (asteroid == asteroidConfigure)
{
ConfigureAds();
}
else if (asteroid == asteroidRequest)
{
RequestAd();
}
else if (asteroid == asteroidPlay)
{
PlayAd();
}
else if (asteroid == asteroidAdViewRequest)
{
RequestBannerAd();
asteroidAdViewRequest.Show();
}
else if (asteroid == asteroidAdViewDestroy)
{
if (arrayList.Count != 0)
{
AdColony.AdColonyAdView adView = (AdColony.AdColonyAdView)arrayList[0];
adView.DestroyAdView();
arrayList.Remove(adView);
if (arrayList.Count != 0)
{
asteroidAdViewDestroy.Show();
}
}
}
}
} | 34.11215 | 166 | 0.60347 | [
"Apache-2.0"
] | isabella232/AdColony-Unity-Plugin | Sample/Assets/Scripts/GameController.cs | 10,952 | C# |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id$")]
namespace Elmah.Assertions
{
using System;
internal delegate object ContextExpressionEvaluationHandler(object context);
internal sealed class DelegatedContextExpression : IContextExpression
{
private readonly ContextExpressionEvaluationHandler _handler;
public DelegatedContextExpression(ContextExpressionEvaluationHandler handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
_handler = handler;
}
public ContextExpressionEvaluationHandler Handler
{
get { return _handler; }
}
public object Evaluate(object context)
{
return _handler(context);
}
public override string ToString()
{
return Handler.ToString();
}
}
} | 29.389831 | 86 | 0.642445 | [
"Apache-2.0"
] | AdamBenoit/elmah.1x | src/Elmah/Assertions/DelegatedContextExpression.cs | 1,734 | C# |
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2021 DigiDNA - www.imazing.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
using System;
using System.Windows.Data;
using System.Windows.Markup;
namespace ValueTransformers
{
[ MarkupExtensionReturnType( typeof( IValueConverter ) ) ]
[ ValueConversion( typeof( object ), typeof( bool ) ) ]
public class StringIsNotEmpty: MarkupExtension, IValueConverter
{
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
return value is string s && s.Length > 0;
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
throw new NotSupportedException();
}
private static StringIsNotEmpty Converter
{
get;
set;
}
public override object ProvideValue( IServiceProvider serviceProvider )
{
if( Converter == null )
{
Converter = new StringIsNotEmpty();
}
return Converter;
}
}
}
| 37.419355 | 127 | 0.653879 | [
"MIT"
] | DigiDNA/ValueTransformers-WPF | ValueTransformers/Converters/StringIsNotEmpty.cs | 2,322 | C# |
// <copyright file="MetricsInfluxDbReporterBuilder.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using App.Metrics.Builder;
using App.Metrics.Formatters;
using App.Metrics.Formatters.InfluxDB;
using App.Metrics.Reporting.InfluxDB;
using App.Metrics.Reporting.InfluxDB.Client;
// ReSharper disable CheckNamespace
namespace App.Metrics
// ReSharper restore CheckNamespace
{
/// <summary>
/// Builder for configuring metrics InfluxDB reporting using an
/// <see cref="IMetricsReportingBuilder" />.
/// </summary>
public static class MetricsInfluxDbReporterBuilder
{
/// <summary>
/// Add the <see cref="InfluxDbMetricsReporter" /> allowing metrics to be reported to InfluxDB.
/// </summary>
/// <param name="metricReporterProviderBuilder">
/// The <see cref="IMetricsReportingBuilder" /> used to configure metrics reporters.
/// </param>
/// <param name="options">The InfluxDB reporting options to use.</param>
/// <returns>
/// An <see cref="IMetricsBuilder" /> that can be used to further configure App Metrics.
/// </returns>
public static IMetricsBuilder ToInfluxDb(
this IMetricsReportingBuilder metricReporterProviderBuilder,
MetricsReportingInfluxDbOptions options)
{
if (metricReporterProviderBuilder == null)
{
throw new ArgumentNullException(nameof(metricReporterProviderBuilder));
}
var httpClient = CreateClient(options.InfluxDb, options.HttpPolicy);
var reporter = new InfluxDbMetricsReporter(options, httpClient);
return metricReporterProviderBuilder.Using(reporter);
}
/// <summary>
/// Add the <see cref="InfluxDbMetricsReporter" /> allowing metrics to be reported to InfluxDB.
/// </summary>
/// <param name="metricReporterProviderBuilder">
/// The <see cref="IMetricsReportingBuilder" /> used to configure metrics reporters.
/// </param>
/// <param name="setupAction">The InfluxDB reporting options to use.</param>
/// <returns>
/// An <see cref="IMetricsBuilder" /> that can be used to further configure App Metrics.
/// </returns>
public static IMetricsBuilder ToInfluxDb(
this IMetricsReportingBuilder metricReporterProviderBuilder,
Action<MetricsReportingInfluxDbOptions> setupAction)
{
if (metricReporterProviderBuilder == null)
{
throw new ArgumentNullException(nameof(metricReporterProviderBuilder));
}
var options = new MetricsReportingInfluxDbOptions();
setupAction?.Invoke(options);
var httpClient = CreateClient(options.InfluxDb, options.HttpPolicy);
var reporter = new InfluxDbMetricsReporter(options, httpClient);
return metricReporterProviderBuilder.Using(reporter);
}
/// <summary>
/// Add the <see cref="InfluxDbMetricsReporter" /> allowing metrics to be reported to InfluxDB.
/// </summary>
/// <param name="metricReporterProviderBuilder">
/// The <see cref="IMetricsReportingBuilder" /> used to configure metrics reporters.
/// </param>
/// <param name="url">The base url where InfluxDB is hosted.</param>
/// <param name="database">The InfluxDB where metrics should be flushed.</param>
/// <param name="fieldsSetup">The metric fields to report as well as thier names.</param>
/// <param name="lineProtocolOptionsSetup">The setup action to configure the <see cref="MetricsInfluxDbLineProtocolOptions"/> to use.</param>
/// <returns>
/// An <see cref="IMetricsBuilder" /> that can be used to further configure App Metrics.
/// </returns>
public static IMetricsBuilder ToInfluxDb(
this IMetricsReportingBuilder metricReporterProviderBuilder,
string url,
string database,
Action<MetricFields> fieldsSetup = null,
Action<MetricsInfluxDbLineProtocolOptions> lineProtocolOptionsSetup = null)
{
if (metricReporterProviderBuilder == null)
{
throw new ArgumentNullException(nameof(metricReporterProviderBuilder));
}
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
throw new InvalidOperationException($"{nameof(url)} must be a valid absolute URI");
}
var lineProtocolOptions = new MetricsInfluxDbLineProtocolOptions();
lineProtocolOptionsSetup?.Invoke(lineProtocolOptions);
IMetricsOutputFormatter formatter;
MetricFields fields = null;
if (fieldsSetup == null)
{
formatter = new MetricsInfluxDbLineProtocolOutputFormatter(lineProtocolOptions);
}
else
{
fields = new MetricFields();
fieldsSetup.Invoke(fields);
formatter = new MetricsInfluxDbLineProtocolOutputFormatter(lineProtocolOptions, fields);
}
var options = new MetricsReportingInfluxDbOptions
{
InfluxDb =
{
BaseUri = uri,
Database = database
},
MetricsOutputFormatter = formatter
};
var httpClient = CreateClient(options.InfluxDb, options.HttpPolicy);
var reporter = new InfluxDbMetricsReporter(options, httpClient);
var builder = metricReporterProviderBuilder.Using(reporter);
builder.OutputMetrics.AsInfluxDbLineProtocol(lineProtocolOptions, fields);
return builder;
}
/// <summary>
/// Add the <see cref="InfluxDbMetricsReporter" /> allowing metrics to be reported to InfluxDB.
/// </summary>
/// <param name="metricReporterProviderBuilder">
/// The <see cref="IMetricsReportingBuilder" /> used to configure metrics reporters.
/// </param>
/// <param name="url">The base url where InfluxDB is hosted.</param>
/// <param name="database">The InfluxDB where metrics should be flushed.</param>
/// <param name="flushInterval">
/// The <see cref="T:System.TimeSpan" /> interval used if intended to schedule metrics
/// reporting.
/// </param>
/// <param name="fieldsSetup">The metric fields to report as well as thier names.</param>
/// <param name="lineProtocolOptionsSetup">The setup action to configure the <see cref="MetricsInfluxDbLineProtocolOptions"/> to use.</param>
/// <returns>
/// An <see cref="IMetricsBuilder" /> that can be used to further configure App Metrics.
/// </returns>
public static IMetricsBuilder ToInfluxDb(
this IMetricsReportingBuilder metricReporterProviderBuilder,
string url,
string database,
TimeSpan flushInterval,
Action<MetricFields> fieldsSetup = null,
Action<MetricsInfluxDbLineProtocolOptions> lineProtocolOptionsSetup = null)
{
if (metricReporterProviderBuilder == null)
{
throw new ArgumentNullException(nameof(metricReporterProviderBuilder));
}
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
throw new InvalidOperationException($"{nameof(url)} must be a valid absolute URI");
}
var lineProtocolOptions = new MetricsInfluxDbLineProtocolOptions();
lineProtocolOptionsSetup?.Invoke(lineProtocolOptions);
IMetricsOutputFormatter formatter;
MetricFields fields = null;
if (fieldsSetup == null)
{
formatter = new MetricsInfluxDbLineProtocolOutputFormatter(lineProtocolOptions);
}
else
{
fields = new MetricFields();
fieldsSetup.Invoke(fields);
formatter = new MetricsInfluxDbLineProtocolOutputFormatter(lineProtocolOptions, fields);
}
var options = new MetricsReportingInfluxDbOptions
{
FlushInterval = flushInterval,
InfluxDb =
{
BaseUri = uri,
Database = database
},
MetricsOutputFormatter = formatter
};
var httpClient = CreateClient(options.InfluxDb, options.HttpPolicy);
var reporter = new InfluxDbMetricsReporter(options, httpClient);
var builder = metricReporterProviderBuilder.Using(reporter);
builder.OutputMetrics.AsInfluxDbLineProtocol(lineProtocolOptions, fields);
return builder;
}
internal static ILineProtocolClient CreateClient(
InfluxDbOptions influxDbOptions,
HttpPolicy httpPolicy,
HttpMessageHandler httpMessageHandler = null)
{
var httpClient = httpMessageHandler == null
? new HttpClient()
: new HttpClient(httpMessageHandler);
httpClient.BaseAddress = influxDbOptions.BaseUri;
httpClient.Timeout = httpPolicy.Timeout;
if (string.IsNullOrWhiteSpace(influxDbOptions.UserName) || string.IsNullOrWhiteSpace(influxDbOptions.Password))
{
return new DefaultLineProtocolClient(
influxDbOptions,
httpPolicy,
httpClient);
}
var byteArray = Encoding.ASCII.GetBytes($"{influxDbOptions.UserName}:{influxDbOptions.Password}");
httpClient.BaseAddress = influxDbOptions.BaseUri;
httpClient.Timeout = httpPolicy.Timeout;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
return new DefaultLineProtocolClient(
influxDbOptions,
httpPolicy,
httpClient);
}
}
} | 41.942529 | 149 | 0.598063 | [
"Apache-2.0"
] | 8adre/AppMetrics | src/Reporting/src/App.Metrics.Reporting.InfluxDB/Builder/MetricsInfluxDbReporterBuilder.cs | 10,949 | C# |
using System;
using System.Collections.Generic;
namespace Builder
{
public class Program
{
public static void Main()
{
var superBuilder = new SuperCarBuilder();
var notSuperBuilder = new NotSoSuperCarBuilder();
var factory = new CarFactory();
var builders = new List<CarBuilder> { superBuilder, notSuperBuilder };
foreach (var b in builders)
{
var c = factory.Build(b);
Console.WriteLine($"The Car requested by " +
$"{b.GetType().Name}: " +
$"\n--------------------------------------" +
$"\nHorse Power: {c.HorsePower}" +
$"\nImpressive Feature: {c.MostImpressiveFeature}" +
$"\nTop Speed: {c.TopSpeedMPH} mph\n");
}
}
}
} | 31.357143 | 82 | 0.474943 | [
"MIT"
] | pirocorp/ASP.NET-Core | 10. DESIGN PATTERNS/DesignPatternsDemo/CreationalPatternsDemo/05Builder/Program.cs | 880 | C# |
using Lucene.Net.Linq.Clauses.Expressions;
using Lucene.Net.Linq.Search;
using Lucene.Net.Linq.Transformation.TreeVisitors;
using Lucene.Net.Search;
using NUnit.Framework;
using System.Linq.Expressions;
namespace Lucene.Net.Linq.Tests.Transformation.TreeVisitors
{
[TestFixture]
public class BooleanBinaryToQueryPredicateExpressionTreeVisitorTests
{
private BooleanBinaryToQueryPredicateExpressionTreeVisitor visitor;
// Query(Name:foo*)
private static readonly LuceneQueryPredicateExpression predicate = new LuceneQueryPredicateExpression(
new LuceneQueryFieldExpression(typeof(string), "Name"),
Expression.Constant("foo"),
Occur.MUST,
QueryType.Prefix);
[SetUp]
public void SetUp()
{
visitor = new BooleanBinaryToQueryPredicateExpressionTreeVisitor();
}
[Test]
public void EqualFalse()
{
var call = CreateBinaryExpression(ExpressionType.Equal, false);
var result = visitor.VisitExpression(call) as LuceneQueryPredicateExpression;
AssertResult(result, Occur.MUST_NOT);
}
[Test]
public void NotEqualTrue()
{
var call = CreateBinaryExpression(ExpressionType.NotEqual, true);
var result = visitor.VisitExpression(call) as LuceneQueryPredicateExpression;
AssertResult(result, Occur.MUST_NOT);
}
[Test]
public void EqualTrue()
{
var call = CreateBinaryExpression(ExpressionType.Equal, true);
var result = visitor.VisitExpression(call);
Assert.That(result, Is.SameAs(predicate));
}
[Test]
public void NotEqualFalse()
{
var call = CreateBinaryExpression(ExpressionType.NotEqual, false);
var result = visitor.VisitExpression(call);
Assert.That(result, Is.SameAs(predicate));
}
[Test]
public void RetainsBoostAndAllowSpecialCharacters()
{
var call = CreateBinaryExpression(ExpressionType.Equal, false);
predicate.AllowSpecialCharacters = true;
predicate.Boost = 1234f;
var result = visitor.VisitExpression(call) as LuceneQueryPredicateExpression;
AssertResult(result, Occur.MUST_NOT);
}
private static void AssertResult(LuceneQueryPredicateExpression result, Occur expectedOccur)
{
Assert.That(result, Is.Not.Null, "Expected LuceneQueryPredicateExpression to be returned.");
Assert.That(result, Is.Not.SameAs(predicate));
Assert.That(result.QueryField, Is.SameAs(predicate.QueryField));
Assert.That(result.QueryPattern, Is.SameAs(predicate.QueryPattern));
Assert.That(result.QueryType, Is.EqualTo(predicate.QueryType));
Assert.That(result.Occur, Is.EqualTo(expectedOccur));
Assert.That(result.Boost, Is.EqualTo(predicate.Boost));
Assert.That(result.AllowSpecialCharacters, Is.EqualTo(predicate.AllowSpecialCharacters));
}
private static BinaryExpression CreateBinaryExpression(ExpressionType expressionType, bool value)
{
return Expression.MakeBinary(
expressionType,
predicate,
Expression.Constant(value));
}
}
} | 34.910891 | 111 | 0.630459 | [
"Apache-2.0"
] | mattbab/Lucene.Net.Linq | source/Lucene.Net.Linq.Tests/Transformation/TreeVisitors/BooleanBinaryToQueryPredicateExpressionTreeVisitorTests.cs | 3,526 | C# |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace FontDialog
{
internal class FontFamilyListItem : TextBlock, IComparable
{
private readonly string _displayName;
public FontFamilyListItem(FontFamily fontFamily)
{
_displayName = GetDisplayName(fontFamily);
FontFamily = fontFamily;
Text = _displayName;
ToolTip = _displayName;
// In the case of symbol font, apply the default message font to the text so it can be read.
if (IsSymbolFont(fontFamily))
{
var range = new TextRange(ContentStart, ContentEnd);
range.ApplyPropertyValue(FontFamilyProperty, SystemFonts.MessageFontFamily);
}
}
int IComparable.CompareTo(object obj) => string.Compare(_displayName, obj.ToString(), true, CultureInfo.CurrentCulture);
public override string ToString() => _displayName;
internal static bool IsSymbolFont(FontFamily fontFamily)
{
foreach (var typeface in fontFamily.GetTypefaces())
{
GlyphTypeface face;
if (typeface.TryGetGlyphTypeface(out face))
{
return face.Symbol;
}
}
return false;
}
internal static string GetDisplayName(FontFamily family) => NameDictionaryHelper.GetDisplayName(family.FamilyNames);
}
} | 33.25 | 128 | 0.635049 | [
"MIT"
] | 21pages/WPF-Samples | Sample Applications/FontDialog/FontFamilyListItem.cs | 1,729 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.Adapters.Facebook.FacebookEvents.Templates
{
/// <summary>
/// Facebook button object.
/// </summary>
[Obsolete("The Bot Framework Adapters will be deprecated in the next version of the Bot Framework SDK and moved to https://github.com/BotBuilderCommunity/botbuilder-community-dotnet. Please refer to their new location for all future work.")]
public class Button
{
/// <summary>
/// Gets or sets the type of button.
/// </summary>
/// <value>The type of the button.</value>
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
/// <summary>
/// Gets or sets the URL of the button.
/// </summary>
/// <value>The URL of the button.</value>
[JsonProperty(PropertyName = "url")]
public Uri Url { get; set; }
/// <summary>
/// Gets or sets the title of the button.
/// </summary>
/// <value>The title of the button.</value>
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
/// <summary>
/// Gets or sets the string sent to webhook.
/// </summary>
/// <value>The string sent to webhook.</value>
[JsonProperty(PropertyName = "payload")]
public string Payload { get; set; }
}
}
| 34.181818 | 245 | 0.601729 | [
"MIT"
] | Arsh-Kashyap/botbuilder-dotnet | libraries/Adapters/Microsoft.Bot.Builder.Adapters.Facebook/FacebookEvents/Templates/Button.cs | 1,506 | C# |
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.Ubigia.Api.Functional.Traversal.Tests
{
using System;
using System.Threading.Tasks;
public class TestFunctionHandler : IFunctionHandler
{
public ParameterSet[] ParameterSets { get; }
public string Name { get; }
public TestFunctionHandler()
{
ParameterSets = new []
{
new ParameterSet(false),
new ParameterSet(true),
new ParameterSet(false, new Parameter("var", typeof(object))),
new ParameterSet(true, new Parameter("var", typeof(string))),
new ParameterSet(false, new Parameter("var1", typeof(object)), new Parameter("var2", typeof(object))),
new ParameterSet(false, new Parameter("var1", typeof(string)), new Parameter("var2", typeof(string)), new Parameter("var3", typeof(string))),
new ParameterSet(true, new Parameter("var1", typeof(string)), new Parameter("var2", typeof(string)), new Parameter("var3", typeof(string))),
};
Name = "Function";
}
public Task Process(IFunctionContext context, ParameterSet parameterSet, ArgumentSet argumentSet, IObservable<object> input, ExecutionScope scope, IObserver<object> output, bool processAsSubject)
{
throw new NotImplementedException();
}
}
}
| 42.4 | 203 | 0.631402 | [
"MIT"
] | vrenken/EtAlii.Ubigia | Source/Api/EtAlii.Ubigia.Api.Functional.Tests/Traversal/TestFunctionHandler.cs | 1,486 | C# |
namespace Compos.Coreforce.Models.Description
{
public class UrlsDescription
{
public string compactLayouts { get; set; }
public string rowTemplate { get; set; }
public string approvalLayouts { get; set; }
public string uiDetailTemplate { get; set; }
public string uiEditTemplate { get; set; }
public string defaultValues { get; set; }
public string listviews { get; set; }
public string describe { get; set; }
public string uiNewRecord { get; set; }
public string quickActions { get; set; }
public string layouts { get; set; }
public string sobject { get; set; }
}
}
| 35.631579 | 52 | 0.620384 | [
"MIT"
] | COMPEON/Compos.Coreforce | Compos.Coreforce/Models/Description/UrlsDescription.cs | 679 | C# |
namespace TekConf.Tests.UI
{
public static class ScreenNames
{
public static string AddTask = "AddTaskScreen";
public static string ConferencesList = "ConferencesList";
}
} | 22.5 | 59 | 0.761111 | [
"MIT"
] | tekconf/TekConf.Forms | Tests/TekConf.Tests.UI/Screens/ScreenNames.cs | 182 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Modules.Journal.Components
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Users.Social;
public class Utilities
{
private static readonly Regex PageRegex = new Regex(
"<(title)[^>]*?>((?:.|\\n)*?)</\\s*\\1\\s*>",
RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex MetaRegex = new Regex(
"<meta\\s*(?:(?:\\b(\\w|-)+\\b\\s*(?:=\\s*(?:\"[^\"]*\"|'[^']*'|[^\"'<> ]+)\\s*)?)*)/?\\s*>",
RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex MetaSubRegex = new Regex(
"<meta[\\s]+[^>]*?(((name|property)*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?)|(content*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?))((content*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?>)|(name*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?>)|>)",
RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex MetaSubRegex2 = new Regex(
"<img[\\s]+[^>]*?((alt*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?)|(src*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?))((src*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?>)|(alt*?[\\s]?=[\\s\\x27\\x22]+(.*?)[\\x27\\x22]+.*?>)|>)",
RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex ResexRegex = new Regex("(\\{resx:.+?\\})", RegexOptions.Compiled);
private static readonly Regex HtmlTextRegex = new Regex("<(.|\\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static string LocalizeControl(string controlText)
{
string sKey = string.Empty;
string sReplace = string.Empty;
MatchCollection matches = default(MatchCollection);
matches = ResexRegex.Matches(controlText);
foreach (Match match in matches)
{
sKey = match.Value;
sReplace = GetSharedResource(sKey);
string newValue = match.Value;
if (!string.IsNullOrEmpty(sReplace))
{
newValue = sReplace;
}
controlText = controlText.Replace(sKey, newValue);
}
return controlText;
}
public static string GetSharedResource(string key)
{
string sValue = key;
sValue = DotNetNuke.Services.Localization.Localization.GetString(key, Constants.SharedResourcesPath);
if (sValue == string.Empty)
{
return key;
}
else
{
return sValue;
}
}
public static string RemoveHTML(string sText)
{
if (string.IsNullOrEmpty(sText))
{
return string.Empty;
}
sText = HttpUtility.HtmlDecode(sText);
sText = HttpUtility.UrlDecode(sText);
sText = sText.Trim();
if (string.IsNullOrEmpty(sText))
{
return string.Empty;
}
sText = HtmlTextRegex.Replace(sText, string.Empty);
sText = HttpUtility.HtmlEncode(sText);
return sText;
}
public static bool AreFriends(UserInfo profileUser, UserInfo currentUser)
{
var friendsRelationShip = RelationshipController.Instance.GetFriendRelationship(profileUser, currentUser);
return friendsRelationShip != null && friendsRelationShip.Status == RelationshipStatus.Accepted;
}
internal static Bitmap GetImageFromURL(string url)
{
string sImgName = string.Empty;
System.Net.WebRequest myRequest = default(System.Net.WebRequest);
Bitmap bmp = null;
try
{
myRequest = System.Net.WebRequest.Create(url);
myRequest.Proxy = null;
using (WebResponse myResponse = myRequest.GetResponse())
{
using (Stream myStream = myResponse.GetResponseStream())
{
string sContentType = myResponse.ContentType;
string sExt = string.Empty;
if (sContentType.Contains("png"))
{
sExt = ".png";
}
else if (sContentType.Contains("jpg"))
{
sExt = ".jpg";
}
else if (sContentType.Contains("jpeg"))
{
sExt = ".jpg";
}
else if (sContentType.Contains("gif"))
{
sExt = ".gif";
}
if (!string.IsNullOrEmpty(sExt))
{
bmp = new Bitmap(myStream);
}
}
}
return bmp;
}
catch
{
return null;
}
}
internal static string PrepareURL(string url)
{
url = url.Trim();
if (!url.StartsWith("http"))
{
url = "http://" + url;
}
if (url.Contains("https://"))
{
url = url.Replace("https://", "http://");
}
if (url.Contains("http://http://"))
{
url = url.Replace("http://http://", "http://");
}
if (!(url.IndexOf("http://") == 0))
{
url = "http://" + url;
}
Uri objURI = null;
objURI = new Uri(url);
return url;
}
internal static LinkInfo GetLinkData(string URL)
{
string sPage = GetPageFromURL(ref URL, string.Empty, string.Empty);
LinkInfo link = new LinkInfo();
if (string.IsNullOrEmpty(sPage))
{
return link;
}
string sTitle = string.Empty;
string sDescription = string.Empty;
string sImage = string.Empty;
link.URL = URL;
link.Images = new List<ImageInfo>();
Match m = PageRegex.Match(sPage);
if (m.Success)
{
link.Title = m.Groups[2].ToString().Trim();
}
MatchCollection matches = default(MatchCollection);
matches = MetaRegex.Matches(sPage);
int i = 0;
foreach (Match match in matches)
{
string sTempDesc = match.Groups[0].Value;
foreach (Match subM in MetaSubRegex.Matches(sTempDesc))
{
if (subM.Groups[4].Value.Equals("OG:DESCRIPTION", StringComparison.InvariantCultureIgnoreCase))
{
link.Description = subM.Groups[9].Value;
}
else if (subM.Groups[4].Value.Equals("DESCRIPTION", StringComparison.InvariantCultureIgnoreCase))
{
link.Description = subM.Groups[9].Value;
}
if (subM.Groups[4].Value.Equals("OG:TITLE", StringComparison.InvariantCultureIgnoreCase))
{
link.Title = subM.Groups[9].Value;
}
if (subM.Groups[4].Value.Equals("OG:IMAGE", StringComparison.InvariantCultureIgnoreCase))
{
sImage = subM.Groups[9].Value;
ImageInfo img = new ImageInfo();
img.URL = sImage;
link.Images.Add(img);
i += 1;
}
}
}
if (!string.IsNullOrEmpty(link.Description))
{
link.Description = HttpUtility.HtmlDecode(link.Description);
link.Description = HttpUtility.UrlDecode(link.Description);
link.Description = RemoveHTML(link.Description);
}
if (!string.IsNullOrEmpty(link.Title))
{
link.Title = link.Title.Replace("&", "&");
}
matches = MetaSubRegex2.Matches(sPage);
string imgList = string.Empty;
string hostUrl = string.Empty;
if (!URL.Contains("http"))
{
URL = "http://" + URL;
}
Uri uri = new Uri(URL);
hostUrl = uri.Host;
if (URL.Contains("https:"))
{
hostUrl = "https://" + hostUrl;
}
else
{
hostUrl = "http://" + hostUrl;
}
foreach (Match match in matches)
{
string sImg = match.Groups[5].Value;
if (string.IsNullOrEmpty(sImg))
{
sImg = match.Groups[8].Value;
}
if (!string.IsNullOrEmpty(sImg))
{
if (!sImg.Contains("http"))
{
sImg = hostUrl + sImg;
}
ImageInfo img = new ImageInfo();
img.URL = sImg;
if (!imgList.Contains(sImg))
{
Bitmap bmp = Utilities.GetImageFromURL(sImg);
if (bmp != null)
{
if (bmp.Height > 25 & bmp.Height < 500 & bmp.Width > 25 & bmp.Width < 500)
{
link.Images.Add(img);
imgList += sImg;
i += 1;
}
}
}
if (i == 10)
{
break;
}
}
}
return link;
}
internal static string GetPageFromURL(ref string url, string username, string password)
{
url = PrepareURL(url);
HttpWebRequest objWebRequest = default(HttpWebRequest);
HttpWebResponse objWebResponse = default(HttpWebResponse);
CookieContainer cookies = new CookieContainer();
Uri objURI = new Uri(url);
objWebRequest = (HttpWebRequest)HttpWebRequest.Create(objURI);
objWebRequest.KeepAlive = false;
objWebRequest.Proxy = null;
objWebRequest.CookieContainer = cookies;
if (!string.IsNullOrEmpty(username) & !string.IsNullOrEmpty(password))
{
NetworkCredential nc = new NetworkCredential(username, password);
objWebRequest.Credentials = nc;
}
string sHTML = string.Empty;
try
{
objWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
Encoding enc = Encoding.UTF8;
string contentType = objWebResponse.ContentType;
if ((objWebRequest.HaveResponse == true) & objWebResponse.StatusCode == HttpStatusCode.OK)
{
objWebResponse.Cookies = objWebRequest.CookieContainer.GetCookies(objWebRequest.RequestUri);
using (Stream objStream = objWebResponse.GetResponseStream())
using (StreamReader objStreamReader = new StreamReader(objStream, enc))
{
sHTML = objStreamReader.ReadToEnd();
objStreamReader.Close();
objStream.Close();
}
}
objWebResponse.Close();
}
catch (Exception ex)
{
Services.Exceptions.Exceptions.LogException(ex);
}
return sHTML;
}
}
}
| 36.047753 | 267 | 0.465051 | [
"MIT"
] | Acidburn0zzz/Dnn.Platform | DNN Platform/Modules/Journal/Components/Utilities.cs | 12,835 | C# |
using System;
using System.Collections.Generic;
using Ical.Net.DataTypes;
using Ical.Net.Interfaces.DataTypes;
namespace Ical.Net.Interfaces.Components
{
public interface ITimeZone : ICalendarComponent
{
string TzId { get; set; }
IDateTime LastModified { get; set; }
Uri Url { get; set; }
HashSet<ITimeZoneInfo> TimeZoneInfos { get; set; }
}
} | 24.375 | 58 | 0.676923 | [
"MIT"
] | Clarity-Informatics/ical.net | v2/ical.NET/Interfaces/Components/ITimeZone.cs | 392 | C# |
using System.Diagnostics.CodeAnalysis;
// ReSharper disable once CheckNamespace
namespace System
{
public static class VersionExtensions
{
/// <summary>
/// Is 'version' greater then the 'otherVersion', where the significantParts is the stop part.
/// Example significantParts=2, then only Major and Minor wil be taken into consideration.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="otherVersion">The other version.</param>
/// <param name="significantParts">The significant parts.</param>
/// <returns>-1, 0 or 1.</returns>
/// <exception cref="ArgumentNullException">version.</exception>
[SuppressMessage("Critical Code Smell", "S3776:Cognitive Complexity of methods should not be too high", Justification = "OK.")]
public static int CompareTo(this Version version, Version otherVersion, int significantParts)
{
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
if (otherVersion == null)
{
return 1;
}
if (version.Major != otherVersion.Major && significantParts >= 1)
{
return version.Major > otherVersion.Major ? 1 : -1;
}
if (version.Minor != otherVersion.Minor && significantParts >= 2)
{
return version.Minor > otherVersion.Minor ? 1 : -1;
}
if (version.Build != otherVersion.Build && significantParts >= 3)
{
return version.Build > otherVersion.Build ? 1 : -1;
}
if (version.Revision != otherVersion.Revision && significantParts >= 4)
{
return version.Revision > otherVersion.Revision ? 1 : -1;
}
return 0;
}
/// <summary>
/// Is 'version' greater then the 'otherVersion'.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="otherVersion">The other version.</param>
/// <returns>
/// <c>true</c> if 'otherVersion' is greater then the current 'version'; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">version.</exception>
public static bool GreaterThan(this Version version, Version otherVersion)
{
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
if (otherVersion == null)
{
return true;
}
return version.CompareTo(otherVersion, 4) > 0;
}
}
} | 35.896104 | 135 | 0.54848 | [
"MIT"
] | TomMalow/atc | src/Atc/Extensions/VersionExtensions.cs | 2,766 | C# |
namespace ExtensionMethods
{
public static class WindowExtensions
{
public static bool? ShowDialogCenteredToMouse(this Window window)
{
ComputeTopLeft(ref window);
return window.ShowDialog();
}
public static Task<bool?> ShowDialogAsync(this Window self)
{
if (self == null)
throw new ArgumentNullException("self");
var completion = new TaskCompletionSource<bool?>();
self.Dispatcher.BeginInvoke(new Action(() => completion.SetResult(self.ShowDialog())));
return completion.Task;
}
private static void ComputeTopLeft(ref Window window)
{
W32Point pt = new();
if (!GetCursorPos(ref pt))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
// .net 4.6.2
//var dpi = System.Windows.Media.VisualTreeHelper.GetDpi(window);
window.Top = pt.Y / 1.25f; // dpi.DpiScaleY;
window.Left = pt.X / 1.25f; // dpi.DpiScaleX;
}
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(ref W32Point pt);
[StructLayout(LayoutKind.Sequential)]
public struct W32Point
{
public int X;
public int Y;
}
}
} | 30.673913 | 99 | 0.576187 | [
"Unlicense"
] | BAndysc/WoWDatabaseEditor | WDE.QuestChainEditor/Utils/WindowExtensions.cs | 1,413 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SageMaker.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SageMaker.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListPipelineExecutions Request Marshaller
/// </summary>
public class ListPipelineExecutionsRequestMarshaller : IMarshaller<IRequest, ListPipelineExecutionsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListPipelineExecutionsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListPipelineExecutionsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SageMaker");
string target = "SageMaker.ListPipelineExecutions";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-24";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetCreatedAfter())
{
context.Writer.WritePropertyName("CreatedAfter");
context.Writer.Write(publicRequest.CreatedAfter);
}
if(publicRequest.IsSetCreatedBefore())
{
context.Writer.WritePropertyName("CreatedBefore");
context.Writer.Write(publicRequest.CreatedBefore);
}
if(publicRequest.IsSetMaxResults())
{
context.Writer.WritePropertyName("MaxResults");
context.Writer.Write(publicRequest.MaxResults);
}
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("NextToken");
context.Writer.Write(publicRequest.NextToken);
}
if(publicRequest.IsSetPipelineName())
{
context.Writer.WritePropertyName("PipelineName");
context.Writer.Write(publicRequest.PipelineName);
}
if(publicRequest.IsSetSortBy())
{
context.Writer.WritePropertyName("SortBy");
context.Writer.Write(publicRequest.SortBy);
}
if(publicRequest.IsSetSortOrder())
{
context.Writer.WritePropertyName("SortOrder");
context.Writer.Write(publicRequest.SortOrder);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static ListPipelineExecutionsRequestMarshaller _instance = new ListPipelineExecutionsRequestMarshaller();
internal static ListPipelineExecutionsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListPipelineExecutionsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.266187 | 159 | 0.60127 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/ListPipelineExecutionsRequestMarshaller.cs | 5,041 | C# |
namespace SKIT.FlurlHttpClient.Upyun.Console.Models
{
/// <summary>
/// <para>表示 [POST] /v2/buckets/cdn/source 接口的响应。</para>
/// </summary>
public class SetBucketCDNSourceV2Response : UpyunConsoleResponse
{
public static class Types
{
public class Data : GetBucketCDNSourceV2Response.Types.Data
{
}
}
/// <summary>
/// 获取或设置操作结果。
/// </summary>
[Newtonsoft.Json.JsonProperty("result")]
[System.Text.Json.Serialization.JsonPropertyName("result")]
public bool Result { get; set; }
/// <summary>
/// 获取或设置返回数据。
/// </summary>
[Newtonsoft.Json.JsonProperty("data")]
[System.Text.Json.Serialization.JsonPropertyName("data")]
public Types.Data Data { get; set; } = default!;
}
}
| 28.533333 | 71 | 0.570093 | [
"MIT"
] | fudiwei/DotNetCore.SKIT.FlurlHttpClient.Upyun | src/SKIT.FlurlHttpClient.Upyun.Console/Models/Buckets/CDN/SetBucketCDNSourceV2Response.cs | 914 | C# |
using System.IO;
using NuGet.Versioning;
using Xunit;
namespace NuGet.Packaging.Test
{
public class VersionFolderPathResolverTests
{
[Fact]
public void VersionFolderPathResolver_GetInstallPath()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetInstallPath(tc.Id, tc.Version);
// Assert
Assert.Equal(Path.Combine(tc.PackagesPath, "nuget.packaging", "3.4.3-beta"), actual);
}
[Fact]
public void VersionFolderPathResolver_GetPackageFilePath()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetPackageFilePath(tc.Id, tc.Version);
// Assert
Assert.Equal(
Path.Combine(
tc.PackagesPath,
"nuget.packaging",
"3.4.3-beta",
"nuget.packaging.3.4.3-beta.nupkg"),
actual);
}
[Fact]
public void VersionFolderPathResolver_GetManifestFilePath()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetManifestFilePath(tc.Id, tc.Version);
// Assert
Assert.Equal(
Path.Combine(
tc.PackagesPath, "nuget.packaging", "3.4.3-beta", "nuget.packaging.nuspec"),
actual);
}
[Fact]
public void VersionFolderPathResolver_GetHashPath()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetHashPath(tc.Id, tc.Version);
// Assert
Assert.Equal(
Path.Combine(
tc.PackagesPath,
"nuget.packaging",
"3.4.3-beta",
"nuget.packaging.3.4.3-beta.nupkg.sha512"),
actual);
}
[Fact]
public void VersionFolderPathResolver_GetPackageDirectory()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetPackageDirectory(tc.Id, tc.Version);
// Assert
Assert.Equal(Path.Combine("nuget.packaging", "3.4.3-beta"), actual);
}
[Fact]
public void VersionFolderPathResolver_GetPackageFileName()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetPackageFileName(tc.Id, tc.Version);
// Assert
Assert.Equal("nuget.packaging.3.4.3-beta.nupkg", actual);
}
[Fact]
public void VersionFolderPathResolver_GetManifestFileName()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetManifestFileName(tc.Id, tc.Version);
// Assert
Assert.Equal("nuget.packaging.nuspec", actual);
}
[Fact]
public void VersionFolderPathResolver_GetVersionListPath()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetVersionListPath(tc.Id);
// Assert
Assert.Equal(
Path.Combine(
tc.PackagesPath,
"nuget.packaging"),
actual);
}
[Fact]
public void VersionFolderPathResolver_GetVersionListDirectory()
{
// Arrange
var tc = new TestContext();
// Act
var actual = tc.Target.GetVersionListDirectory(tc.Id);
// Assert
Assert.Equal("nuget.packaging", actual);
}
private class TestContext
{
public TestContext()
{
// data
PackagesPath = "prefix";
Id = "NuGet.Packaging";
Version = new NuGetVersion("3.04.3-Beta");
}
public string Id { get; private set; }
public string PackagesPath { get; set; }
public NuGetVersion Version { get; set; }
public VersionFolderPathResolver Target
{
get { return new VersionFolderPathResolver(PackagesPath); }
}
}
}
}
| 27.048485 | 97 | 0.489357 | [
"Apache-2.0"
] | OctopusDeploy/NuGet.Client | test/NuGet.Core.Tests/NuGet.Packaging.Test/VersionFolderPathResolverTests.cs | 4,465 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoAll
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // P/Invoke to Win32 function
public void TestAllCultures()
{
Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed");
Assert.All(cultures, Validate);
}
private void Validate(CultureInfo ci)
{
Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME));
// si-LK has some special case when running on Win7 so we just ignore this one
if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase))
{
Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName);
}
// zh-Hans and zh-Hant has different behavior on different platform
Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase);
Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME));
ValidateDTFI(ci);
ValidateNFI(ci);
ValidateRegionInfo(ci);
}
private void ValidateDTFI(CultureInfo ci)
{
DateTimeFormatInfo dtfi = ci.DateTimeFormat;
Calendar cal = dtfi.Calendar;
int calId = GetCalendarId(cal);
Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(calId, GetDefaultcalendar(ci));
Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK)));
Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR));
Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true));
Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern);
Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern);
Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern);
string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0];
string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE));
string longTimePattern1 = GetTimeFormats(ci, 0)[0];
string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT));
string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1;
string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2;
Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 });
Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 });
Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 });
Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) });
Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) });
Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) });
int eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
}
private void ValidateNFI(CultureInfo ci)
{
NumberFormatInfo nfi = ci.NumberFormat;
Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol);
}
private void ValidateRegionInfo(CultureInfo ci)
{
if (ci.Name.Length == 0) // no region for invariant
return;
RegionInfo ri = new RegionInfo(ci.Name);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol);
Assert.True(ci.Name.Equals(ri.Name, StringComparison.OrdinalIgnoreCase) || // Desktop usese culture name as region name
ri.Name.Equals(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), StringComparison.OrdinalIgnoreCase)); // netcore uses 2 letter ISO for region name
Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase);
}
private int[] ConvertWin32GroupString(String win32Str)
{
// None of these cases make any sense
if (win32Str == null || win32Str.Length == 0)
{
return (new int[] { 3 });
}
if (win32Str[0] == '0')
{
return (new int[] { 0 });
}
// Since its in n;n;n;n;n format, we can always get the length quickly
int[] values;
if (win32Str[win32Str.Length - 1] == '0')
{
// Trailing 0 gets dropped. 1;0 -> 1
values = new int[(win32Str.Length / 2)];
}
else
{
// Need extra space for trailing zero 1 -> 1;0
values = new int[(win32Str.Length / 2) + 2];
values[values.Length - 1] = 0;
}
int i;
int j;
for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
{
// Note that this # shouldn't ever be zero, 'cause 0 is only at end
// But we'll test because its registry that could be anything
if (win32Str[i] < '1' || win32Str[i] > '9')
return new int[] { 3 };
values[j] = (int)(win32Str[i] - '0');
}
return (values);
}
private List<string> _timePatterns;
private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam)
{
_timePatterns.Add(ReescapeWin32String(lpTimeFormatString));
return true;
}
private string[] GetTimeFormats(CultureInfo ci, uint flags)
{
_timePatterns = new List<string>();
Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), String.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags));
return _timePatterns.ToArray();
}
internal String ReescapeWin32String(String str)
{
// If we don't have data, then don't try anything
if (str == null)
return null;
StringBuilder result = null;
bool inQuote = false;
for (int i = 0; i < str.Length; i++)
{
// Look for quote
if (str[i] == '\'')
{
// Already in quote?
if (inQuote)
{
// See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
if (i + 1 < str.Length && str[i + 1] == '\'')
{
// Found another ', so we have ''. Need to add \' instead.
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append a \' and keep going (so we don't turn off quote mode)
result.Append("\\'");
i++;
continue;
}
// Turning off quote mode, fall through to add it
inQuote = false;
}
else
{
// Found beginning quote, fall through to add it
inQuote = true;
}
}
// Is there a single \ character?
else if (str[i] == '\\')
{
// Found a \, need to change it to \\
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append our \\ to the string & continue
result.Append("\\\\");
continue;
}
// If we have a builder we need to add our character
if (result != null)
result.Append(str[i]);
}
// Unchanged string? , just return input string
if (result == null)
return str;
// String changed, need to use the builder
return result.ToString();
}
private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[13];
for (uint i = 0; i < 13; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i, false);
}
return names;
}
private int ConvertFirstDayOfWeekMonToSun(int iTemp)
{
// Convert Mon-Sun to Sun-Sat format
iTemp++;
if (iTemp > 6)
{
// Wrap Sunday and convert invalid data to Sunday
iTemp = 0;
}
return iTemp;
}
private string[] GetDayNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[7];
for (uint i = 1; i < 7; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true);
}
names[0] = GetCalendarInfo(ci, calendar, calType + 6, true);
return names;
}
private int GetCalendarId(Calendar cal)
{
int calId = 0;
if (cal is System.Globalization.GregorianCalendar)
{
calId = (int)(cal as GregorianCalendar).CalendarType;
}
else if (cal is System.Globalization.JapaneseCalendar)
{
calId = CAL_JAPAN;
}
else if (cal is System.Globalization.TaiwanCalendar)
{
calId = CAL_TAIWAN;
}
else if (cal is System.Globalization.KoreanCalendar)
{
calId = CAL_KOREA;
}
else if (cal is System.Globalization.HijriCalendar)
{
calId = CAL_HIJRI;
}
else if (cal is System.Globalization.ThaiBuddhistCalendar)
{
calId = CAL_THAI;
}
else if (cal is System.Globalization.HebrewCalendar)
{
calId = CAL_HEBREW;
}
else if (cal is System.Globalization.UmAlQuraCalendar)
{
calId = CAL_UMALQURA;
}
else if (cal is System.Globalization.PersianCalendar)
{
calId = CAL_PERSIAN;
}
else
{
throw new KeyNotFoundException(String.Format("Got a calendar {0} which we cannot map its Id", cal));
}
return calId;
}
internal bool EnumLocales(string name, uint dwFlags, IntPtr param)
{
CultureInfo ci = new CultureInfo(name);
if (!ci.IsNeutralCulture)
cultures.Add(ci);
return true;
}
private string GetLocaleInfo(CultureInfo ci, uint lctype)
{
Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, String.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci));
return sb.ToString();
}
private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail)
{
if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0)
{
Assert.False(throwInFail, String.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar));
return "";
}
return ReescapeWin32String(sb.ToString());
}
private List<int> _optionalCals = new List<int>();
private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_optionalCals.Add(calendar);
return true;
}
private int[] GetOptionalCalendars(CultureInfo ci)
{
_optionalCals = new List<int>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed.");
return _optionalCals.ToArray();
}
private List<string> _calPatterns;
private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_calPatterns.Add(ReescapeWin32String(lpCalendarInfoString));
return true;
}
private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType)
{
_calPatterns = new List<string>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo.");
return _calPatterns.ToArray();
}
private int GetDefaultcalendar(CultureInfo ci)
{
int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE);
if (calId != 0)
return calId;
int[] cals = GetOptionalCalendars(ci);
Assert.True(cals.Length > 0);
return cals[0];
}
private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType)
{
int data = 0;
Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, String.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType));
return data;
}
internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param);
internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam);
internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam);
internal static StringBuilder sb = new StringBuilder(400);
internal static List<CultureInfo> cultures = new List<CultureInfo>();
internal const uint LOCALE_WINDOWS = 0x00000001;
internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072;
internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073;
internal const uint LOCALE_SPARENT = 0x0000006d;
internal const uint LOCALE_SISO639LANGNAME = 0x00000059;
internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM"
internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM"
internal const uint LOCALE_ICALENDARTYPE = 0x00001009;
internal const uint LOCALE_RETURN_NUMBER = 0x20000000;
internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D;
internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
internal const uint LOCALE_SLONGDATE = 0x00000020;
internal const uint LOCALE_STIMEFORMAT = 0x00001003;
internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000;
internal const uint LOCALE_SSHORTDATE = 0x0000001F;
internal const uint LOCALE_SSHORTTIME = 0x00000079;
internal const uint LOCALE_SYEARMONTH = 0x00001006;
internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign
internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign
internal const uint LOCALE_SDECIMAL = 0x0000000E;
internal const uint LOCALE_STHOUSAND = 0x0000000F;
internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017;
internal const uint LOCALE_SMONDECIMALSEP = 0x00000016;
internal const uint LOCALE_SCURRENCY = 0x00000014;
internal const uint LOCALE_IDIGITS = 0x00000011;
internal const uint LOCALE_ICURRDIGITS = 0x00000019;
internal const uint LOCALE_ICURRENCY = 0x0000001B;
internal const uint LOCALE_INEGCURR = 0x0000001C;
internal const uint LOCALE_INEGNUMBER = 0x00001010;
internal const uint LOCALE_SMONGROUPING = 0x00000018;
internal const uint LOCALE_SNAN = 0x00000069;
internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity
internal const uint LOCALE_SGROUPING = 0x00000010;
internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074;
internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075;
internal const uint LOCALE_SPERCENT = 0x00000076;
internal const uint LOCALE_SPERMILLE = 0x00000077;
internal const uint LOCALE_SPOSINFINITY = 0x0000006a;
internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002;
internal const uint LOCALE_IMEASURE = 0x0000000D;
internal const uint LOCALE_SINTLSYMBOL = 0x00000015;
internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008;
internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e;
internal const uint CAL_SMONTHNAME1 = 0x00000015;
internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022;
internal const uint CAL_ICALINTVALUE = 0x00000001;
internal const uint CAL_SDAYNAME1 = 0x00000007;
internal const uint CAL_SLONGDATE = 0x00000006;
internal const uint CAL_SMONTHDAY = 0x00000038;
internal const uint CAL_SSHORTDATE = 0x00000005;
internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031;
internal const uint CAL_SYEARMONTH = 0x0000002f;
internal const uint CAL_SERASTRING = 0x00000004;
internal const uint CAL_SABBREVERASTRING = 0x00000039;
internal const uint ENUM_ALL_CALENDARS = 0xffffffff;
internal const uint TIME_NOSECONDS = 0x00000002;
internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar
internal const int CAL_TAIWAN = 4; // Taiwan Era calendar
internal const int CAL_KOREA = 5; // Korean Tangun Era calendar
internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar
internal const int CAL_THAI = 7; // Thai calendar
internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar
internal const int CAL_PERSIAN = 22;
internal const int CAL_UMALQURA = 23;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam);
public static IEnumerable<object[]> CultureInfo_TestData()
{
yield return new object[] { "en" , 0x0009, "en-US", "eng", "ENU", "en" , "en-US" };
yield return new object[] { "ar" , 0x0001, "ar-SA", "ara", "ARA", "ar" , "en-US" };
yield return new object[] { "en-US" , 0x0409, "en-US", "eng", "ENU", "en-US" , "en-US" };
yield return new object[] { "ar-SA" , 0x0401, "ar-SA", "ara", "ARA", "ar-SA" , "en-US" };
yield return new object[] { "ja-JP" , 0x0411, "ja-JP", "jpn", "JPN", "ja-JP" , "ja-JP" };
yield return new object[] { "zh-CN" , 0x0804, "zh-CN", "zho", "CHS", "zh-Hans-CN" , "zh-CN" };
yield return new object[] { "en-GB" , 0x0809, "en-GB", "eng", "ENG", "en-GB" , "en-GB" };
yield return new object[] { "tr-TR" , 0x041f, "tr-TR", "tur", "TRK", "tr-TR" , "tr-TR" };
}
[Theory]
[MemberData(nameof(CultureInfo_TestData))]
public void LcidTest(string cultureName, int lcid, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName)
{
CultureInfo ci = new CultureInfo(lcid);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.True(ci.UseUserOverride, "UseUserOverride for lcid created culture expected to be true");
Assert.False(ci.IsReadOnly, "IsReadOnly for lcid created culture expected to be false");
Assert.Equal(threeLetterISOLanguageName, ci.ThreeLetterISOLanguageName);
Assert.Equal(threeLetterWindowsLanguageName, ci.ThreeLetterWindowsLanguageName);
ci = new CultureInfo(cultureName);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.True(ci.UseUserOverride, "UseUserOverride for named created culture expected to be true");
Assert.False(ci.IsReadOnly, "IsReadOnly for named created culture expected to be false");
ci = new CultureInfo(lcid, false);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with false user override culture expected to be false");
Assert.False(ci.IsReadOnly, "IsReadOnly with false user override culture expected to be false");
ci = CultureInfo.GetCultureInfo(lcid);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and lcid expected to be false");
Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and lcid expected to be true");
ci = CultureInfo.GetCultureInfo(cultureName);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and name expected to be false");
Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and name expected to be true");
ci = CultureInfo.GetCultureInfo(cultureName, "");
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and sort name expected to be false");
Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and sort name expected to be true");
Assert.Equal(CultureInfo.InvariantCulture.TextInfo, ci.TextInfo);
Assert.Equal(CultureInfo.InvariantCulture.CompareInfo, ci.CompareInfo);
ci = CultureInfo.CreateSpecificCulture(cultureName);
Assert.Equal(specificCultureName, ci.Name);
ci = CultureInfo.GetCultureInfoByIetfLanguageTag(cultureName);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(ci.Name, ci.IetfLanguageTag);
Assert.Equal(lcid, ci.KeyboardLayoutId);
Assert.Equal(consoleUICultureName, ci.GetConsoleFallbackUICulture().Name);
}
[Fact]
public void InstalledUICultureTest()
{
var c1 = CultureInfo.InstalledUICulture;
var c2 = CultureInfo.InstalledUICulture;
// we cannot expect the value we get for InstalledUICulture without reading the OS.
// instead we test ensuring the value doesn't change if we requested it multiple times.
Assert.Equal(c1.Name, c2.Name);
}
[Theory]
[MemberData(nameof(CultureInfo_TestData))]
public void GetCulturesTest(string cultureName, int lcid, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName)
{
bool found = false;
Assert.All(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
c => Assert.True( (c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.NeutralCultures) != 0)) || c.Equals(CultureInfo.InvariantCulture)));
found = CultureInfo.GetCultures(CultureTypes.NeutralCultures).Any(c => c.Name.Equals(cultureName, StringComparison.OrdinalIgnoreCase) ||
c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase));
Assert.All(CultureInfo.GetCultures(CultureTypes.SpecificCultures), c => Assert.True(!c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.SpecificCultures) != 0)));
if (!found)
{
found = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Any(c => c.Name.Equals(cultureName, StringComparison.OrdinalIgnoreCase) ||
c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase));
}
Assert.True(found, $"Expected to find the culture {cultureName} in the enumerated list");
}
[Fact]
public void ClearCachedDataTest()
{
CultureInfo ci = CultureInfo.GetCultureInfo("ja-JP");
Assert.True((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "Expected getting same object reference");
ci.ClearCachedData();
Assert.False((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "expected to get a new object reference");
}
[Fact]
[ActiveIssue("TFS 444333 - Should ExceptionMiniaturizer exempt CultureNotFoundException.InvalidCultureName from being optimized away?", TargetFrameworkMonikers.UapAot)]
public void CultureNotFoundExceptionTest()
{
AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("!@#$%^&*()"));
AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture"));
AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("longCulture" + new string('a', 100)));
AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000));
CultureNotFoundException e = AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture"));
Assert.Equal("This is invalid culture", e.InvalidCultureName);
e = AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000));
Assert.Equal(0x1000, e.InvalidCultureId);
}
}
}
| 50.979938 | 227 | 0.627123 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Globalization/tests/CultureInfo/CultureInfoAll.cs | 33,035 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
namespace LazuriteUI.Windows.Main.Statistics.Views.DiagramViewImplementation
{
public class LowGraphicsVisualHost : FrameworkElement
{
private VisualCollection children;
public LowGraphicsVisualHost()
{
children = new VisualCollection(this);
}
public void DrawLines(List<Line> lines, Brush brush)
{
children.Clear();
var visual = new DrawingVisual();
children.Add(visual);
Optimize(lines);
var pen = new Pen(brush, 1);
using (var dc = visual.RenderOpen())
foreach (var line in lines)
dc.DrawLine(pen, line.Point1, line.Point2);
}
public void DrawLines(List<ColoredLine> coloredLines)
{
children.Clear();
var visual = new DrawingVisual();
children.Add(visual);
var lines = coloredLines.Cast<Line>().ToList();
Optimize(lines);
using (var dc = visual.RenderOpen())
foreach (var line in lines)
dc.DrawLine(new Pen(((ColoredLine)line).Brush, 4), line.Point1, line.Point2);
}
public void DrawPoints(Point[] points, Brush brush)
{
points = points.Distinct().ToArray();
children.Clear();
var visual = new DrawingVisual();
children.Add(visual);
var pen = new Pen(brush, 1);
using (var dc = visual.RenderOpen())
foreach (var point in points)
dc.DrawEllipse(brush, pen, point, 3, 3);
}
private void Optimize(List<Line> lines)
{
var changesCnt = 1;
while (changesCnt != 0)
{
changesCnt = 0;
for (int i = 1; i < lines.Count; i++)
{
var line1 = lines[i - 1];
var line2 = lines[i];
if (line1.IsOneLine(line2))
{
line1.Merge(line2);
lines.Remove(line2);
changesCnt++;
}
}
}
}
protected override int VisualChildrenCount
{
get => children.Count;
}
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= children.Count)
throw new ArgumentOutOfRangeException();
return children[index];
}
}
public class Line
{
public Point Point1 { get; set; }
public Point Point2 { get; set; }
public bool IsOneLine(Line line)
{
if (Point2.Equals(line.Point1))
{
if (Point1.Equals(Point2))
return true;
else
return Math.Abs((Point1.X - Point2.X) / (Point1.Y - Point2.Y))
== Math.Abs((Point2.X * line.Point2.X) / (Point2.Y - line.Point2.Y));
}
return false;
}
public void Merge(Line line)
{
Point2 = line.Point2;
}
}
public class ColoredLine : Line
{
public Brush Brush { get; set; }
}
}
| 28.07377 | 97 | 0.488467 | [
"Apache-2.0"
] | noant/Lazurite | Lazurite/LazuriteUI.Windows.Main/Statistics/Views/DiagramViewImplementation/LowGraphicsVisualHost.cs | 3,427 | C# |
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
namespace Sample.Core
{
/// <summary>
/// 使用 [MetadataViewImplementation(typeof(CustomExportMetadata))],则需要修改下面对应的相应不应该使用相应形象
/// </summary>
public interface IMetadata
{
[DefaultValue(0)]
int Priority { get; }
string Name { get; }
string Description { get; }
string Author { get; }
string Version { get; }
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class CustomExportMetadata : ExportAttribute, IMetadata
{
public int Priority { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public string Author { get; private set; }
public string Version { get; private set; }
public CustomExportMetadata() : base(typeof(IMetadata))
{
}
public CustomExportMetadata(int priority) : this()
{
this.Priority = priority;
}
public CustomExportMetadata(int priority, string name) : this(priority)
{
this.Name = name;
}
public CustomExportMetadata(int priority, string name, string description) : this(priority, name)
{
this.Description = description;
}
public CustomExportMetadata(int priority, string name, string description, string author) : this(priority, name, description)
{
this.Author = author;
}
public CustomExportMetadata(int priority, string name, string description, string author, string version) : this(priority, name, description, author)
{
this.Version = version;
}
}
} | 30.433333 | 157 | 0.62103 | [
"MIT"
] | hippieZhou/MEF.Sample | src/mvvmlight/Sample.Core/IMetadata.cs | 1,876 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using Neurotoxin.Roentgen.Data.Extensions;
namespace Neurotoxin.Roentgen.Data.Entities
{
public abstract class EntityBase : IEntityBase
{
[Key]
public int RowId { get; set; }
[Index]
public Guid EntityId { get; set; }
[Index]
[StringLength(1700)]
public string Name { get; set; }
[Index]
public int VersionNumber { get; set; }
[Index]
public bool LatestVersion { get; set; }
public string Description { get; set; }
/// <summary>
/// Manual or automatic comments related to the given version.
/// </summary>
public string Comment { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public string LockedBy { get; set; }
public int Loc { get; set; }
public int Length { get; set; }
protected EntityBase()
{
CreatedOn = DateTime.Now;
EntityId = Guid.NewGuid();
LatestVersion = true;
CreatedBy = EnvironmentExtensions.GetCurrentUserName();
}
/// <summary>
/// Entity base table configuration.
/// </summary>
/// <returns>Configuration class/</returns>
public static EntityTypeConfiguration<EntityBase> BaseConfig()
{
var config = new EntityTypeConfiguration<EntityBase>();
config.ToTable("Entities");
return config;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((EntityBase) obj);
}
protected bool Equals(EntityBase other)
{
return string.Equals(Name, other.Name) && string.Equals(Description, other.Description);
}
public override int GetHashCode()
{
unchecked
{
return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ (Description != null ? Description.GetHashCode() : 0);
}
}
protected bool StringEquals(string a, string b)
{
return string.IsNullOrEmpty(a) && string.IsNullOrEmpty(b) || string.Equals(a, b);
}
}
} | 32.487179 | 127 | 0.573796 | [
"MIT"
] | mercenaryntx/roentgen | Neurotoxin.Roentgen.Data/Entities/EntityBase.cs | 2,536 | C# |
using UnityEngine;
using System.Collections;
// correspond with protocol.vehicle_parts_id
public enum CarStat
{
HP = 1,
Power,
Speed,
Acceleration,
};
public class Calculator : MonoBehaviour
{
public const float BASE_IN_GAME_SPEED = 8f;
public const float BASE_IN_GAME_ACCELERATION = 3f;
public const float BASE_IN_GAME_POWER = 5f;
public const int BASE_IN_GAME_HP = 100;
public const int BASE_UI_UNIT_SPEED = 20;
public const int BASE_UI_UNIT_ACCELERATION = 30;
public const int BASE_UI_UNIT_POWER = 20;
public const int BASE_UI_UNIT_HP = 100;
public const float UI_SPEED_UNIT_TO_IN_GAME = 0.02f;
public const float UI_ACCELERATION_UNIT_TO_IN_GAME = 0.025f;
public const float UI_POWER_UNIT_TO_IN_GAME = 0.05f;
public const int UI_HP_UNIT_TO_IN_GAME = 2;
public const int UI_HP_UPGRADE_UNIT_TO_IN_GAME = 1;
public const short CAR_PARTS_MAX_LEVEL = 5;
internal static int CurrentUIUnit(Constants.VehicleLevel aCarLevel, short aBasicUnit, int aBaseUnit, short aPartsLevel)
{
int carUpgrade = aBasicUnit * CarUpgradePercentage(aCarLevel) / 100;
int baseIncrease = aBasicUnit - aBaseUnit;
int partsUpgrade = baseIncrease * PartsUpgradePercentage(aPartsLevel) / 100;
return aBasicUnit + carUpgrade + partsUpgrade;
}
internal static int MaxUIUnit(short aBasicUnit, int aBaseUnit)
{
int carUpgrade = aBasicUnit * CarUpgradePercentage(Constants.VehicleLevel.S_CLASS) / 100;
int baseIncrease = aBasicUnit - aBaseUnit;
int partsUpgrade = baseIncrease * PartsUpgradePercentage(CAR_PARTS_MAX_LEVEL) / 100;
return aBasicUnit + carUpgrade + partsUpgrade;
}
internal static int CarUpgradePercentage(Constants.VehicleLevel aCarLevel)
{
switch (aCarLevel)
{
case Constants.VehicleLevel.D_CLASS: return 0;
case Constants.VehicleLevel.C_CLASS: return 10;
case Constants.VehicleLevel.B_CLASS: return 20;
case Constants.VehicleLevel.A_CLASS: return 35;
case Constants.VehicleLevel.S_CLASS: return 50;
}
return 0;
}
internal static int PartsUpgradePercentage(short aPartsLevel)
{
switch (aPartsLevel)
{
case 1: return 100;
case 2: return 150;
case 3: return 200;
case 4: return 250;
case 5: return 300;
}
return 100;
}
internal static float InGameStat(CarStat aType, short aBasicUIStat, Constants.VehicleLevel aCarLevel, short aPartsLevel)
{
int carUpgrade = 0;
int baseIncrease = 0;
int partsUpgrade = 0;
Debug.Log("[InGameStat] type = " + aType + ", basic = " + aBasicUIStat + ", carLevel = " + aCarLevel + ", partsLevel = " + aPartsLevel);
switch (aType)
{
case CarStat.Speed:
carUpgrade = aBasicUIStat * CarUpgradePercentage(aCarLevel) / 100;
baseIncrease = aBasicUIStat - BASE_UI_UNIT_SPEED;
partsUpgrade = baseIncrease * PartsUpgradePercentage(aPartsLevel) / 100;
return BASE_IN_GAME_SPEED + ((float)(carUpgrade + baseIncrease + partsUpgrade) * UI_SPEED_UNIT_TO_IN_GAME);
case CarStat.Acceleration:
carUpgrade = aBasicUIStat * CarUpgradePercentage(aCarLevel) / 100;
baseIncrease = aBasicUIStat - BASE_UI_UNIT_ACCELERATION;
partsUpgrade = baseIncrease * PartsUpgradePercentage(aPartsLevel) / 100;
return BASE_IN_GAME_ACCELERATION + ((float)(carUpgrade + baseIncrease + partsUpgrade) * UI_ACCELERATION_UNIT_TO_IN_GAME);
case CarStat.Power:
carUpgrade = aBasicUIStat * CarUpgradePercentage(aCarLevel) / 100;
baseIncrease = aBasicUIStat - BASE_UI_UNIT_POWER;
partsUpgrade = baseIncrease * PartsUpgradePercentage(aPartsLevel) / 100;
return BASE_IN_GAME_POWER + ((float)(carUpgrade + baseIncrease + partsUpgrade) * UI_POWER_UNIT_TO_IN_GAME);
case CarStat.HP:
carUpgrade = aBasicUIStat * CarUpgradePercentage(aCarLevel) / 100;
baseIncrease = aBasicUIStat - BASE_UI_UNIT_HP;
partsUpgrade = baseIncrease * PartsUpgradePercentage(aPartsLevel) / 100;
return (float)BASE_IN_GAME_HP + ((float)baseIncrease * UI_HP_UNIT_TO_IN_GAME) + ((float)(carUpgrade + partsUpgrade) * UI_HP_UPGRADE_UNIT_TO_IN_GAME);
}
return 0f;
}
} | 39.445378 | 166 | 0.647635 | [
"MIT"
] | showstop98/gtb-client | Assets/Script/Util/Calculator.cs | 4,696 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Final_Project_Khouloud_Nasrallah_Tarek_Tarshishi
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 25.5 | 65 | 0.647059 | [
"MIT"
] | tarektarshishi/Covid19-Vaccination | Final_Project_Khouloud_Nasrallah_Tarek_Tarshishi/Program.cs | 612 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Moto Path Z")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("0.0.0.1")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Moto Path Z")]
[assembly: System.Reflection.AssemblyTitleAttribute("MPZ")]
[assembly: System.Reflection.AssemblyVersionAttribute("0.0.0.1")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.625 | 80 | 0.641026 | [
"MIT"
] | MotoPathZ/Public-SDK | MPZ/MPZ/obj/Debug/netstandard2.0/MPZ.AssemblyInfo.cs | 975 | C# |
public class Solution {
public int IsPrefixOfWord(string sentence, string searchWord) {
var arr = sentence.Split(' ');
for(var i = 0; i < arr.Length; ++i){
if(arr[i].StartsWith(searchWord))
return i+1;
}
return -1;
}
} | 28.6 | 67 | 0.527972 | [
"MIT"
] | webigboss/Leetcode | 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence/1455_Original_string.cs | 286 | C# |
using System;
using System.Collections.Generic;
using Xunit;
using LanguageExt;
using static LanguageExt.Prelude;
using static Echo.Process;
using static Echo.ProcessConfig;
using static Echo.Strategy;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Echo.Tests
{
public class LifeTimeTests
{
public class ProcessFixture : IDisposable
{
public ProcessFixture()
{
initialise();
subscribe<Exception>(Errors(), e => raise<Unit>(e));
}
public void Dispose() => shutdownAll();
}
[Collection("no-parallelism")]
public class LifeTimeIssues : IClassFixture<ProcessFixture>
{
static Unit WaitForKill(ProcessId pid, int timeOutSeconds = 3)
{
var total = timeOutSeconds * 1000;
var span = 200;
while (total > 0)
{
if (!Process.exists(pid)) return unit;
Task.Delay(span).Wait();
total -= span;
}
throw new TimeoutException($"Process still exists after {timeOutSeconds}s: {pid}");
}
[Fact(Timeout = 5000)]
// make sure that the state is not re-initialized after kill
// issue 48 (race condition resulted in inboxFn called after DisposeState)
public void NoZombieState()
{
var events = new List<string>();
var actor = spawn<IDisposable, string>(nameof(NoZombieState),
() =>
{
events.Add("setup");
return Disposable.Create(() => events.Add("dispose"));
},
(state, msg) =>
{
events.Add(msg);
Task.Delay(100 * milliseconds).Wait();
kill();
return state; // will never get here
});
tell(actor, "inbox1"); // inbox1 might arrive before StartUp-System-Message (but doesn't matter)
tell(actor, "inbox2"); // msg inbox2 may or may not arrive before kill is executed, either way, it shouldn't be processed
WaitForKill(actor);
Assert.Equal(List("setup", "inbox1", "dispose"), events.Freeze());
}
[Fact(Timeout = 5000)]
// make sure that the state is not re-initialized after kill and that ask is processed cleanly (sync) until kill
public void NoZombieStateWhenAsked()
{
var events = new List<string>();
var actor = spawn<IDisposable, string>(nameof(NoZombieStateWhenAsked),
() =>
{
events.Add("setup");
return Disposable.Create(() => events.Add("dispose"));
},
(state, msg) =>
{
events.Add(msg);
reply($"{msg}answer");
events.Add($"{msg}answer");
return state;
});
var answer1Task = Task.Run(() => ask<string>(actor, "request1")); // request will arrive before kill is executed
Task.Delay(50).Wait();
kill(actor);
Task.Delay(50).Wait();
var answer2task = Task.Run(() => ask<string>(actor, "request2")); // request will arrive after kill is executed
Task.Delay(50).Wait();
WaitForKill(actor);
Assert.Equal("request1answer", answer1Task.Result);
Assert.Equal(List("setup", "request1", "request1answer", "dispose"), events.Freeze());
Assert.Throws<AggregateException>(() => answer2task.Result);
}
[Fact(Timeout = 5000)]
// issue 47 / pr 49
public void ActorWithoutCancellationToken()
{
int inboxResult = 0;
var actor = spawn(nameof(ActorWithoutCancellationToken), (string msg) =>
{
inboxResult++;
});
tell(actor, "test");
Task.Delay(50).Wait();
kill(actor);
Assert.Equal(1, inboxResult);
}
[Fact(Timeout = 5000)]
public void KillAndStart()
{
static ProcessId start(int state) =>
spawn<int, Unit>(
nameof(KillAndStart),
() => state,
(int state, Unit _) =>
{
reply(state);
return state;
});
// start and check it is running with a correct startup number
var actor = start(1);
Assert.Equal(1, ask<int>(actor, unit));
Assert.True(children(User()).Contains(actor));
// kill and make sure it is gone
kill(actor);
WaitForKill(actor);
Assert.False(children(User()).Contains(actor));
// start and check it is running with a correct startup number
actor = start(2);
Assert.Equal(2, ask<int>(actor, unit));
Assert.True(children(User()).Contains(actor));
kill(actor);
}
[Fact(Timeout = 5000)]
public void KillAndStartChild()
{
var actor = spawn(nameof(KillAndStartChild), (string msg) =>
{
if (msg == "count")
{
reply(Children.Count.ToString());
return;
}
else
{
var child = Children.Find("child")
.IfNone(() => spawn("child", (string msg) => reply(msg)));
if (msg == "kill")
{
kill(child);
WaitForKill(child);
}
else
{
fwd(child);
}
}
});
Assert.Equal("0", ask<string>(actor, "count"));
Assert.Equal("test1", ask<string>(actor, "test1"));
Assert.Equal("1", ask<string>(actor, "count"));
tell(actor, "kill");
Assert.Equal("0", ask<string>(actor, "count"));
Assert.Equal("test2", ask<string>(actor, "test2"));
Assert.Equal("1", ask<string>(actor, "count"));
kill(actor);
}
[Theory]
[InlineData(false, 1)]
[InlineData(true, 3)]
public void CrashAndManageState(bool resume, int expectedState)
{
ProcessId spawnKidIfNotExists() =>
spawn<int, int>(
"child",
() => 0,
(state, msg) => {
if (msg == 2) throw new Exception();
reply(state + msg);
return state + msg;
});
var actor = spawn<int>(
nameof(CrashAndManageState),
(int msg) => {
fwd(Children.Find("child").IfNone(spawnKidIfNotExists));
},
Strategy: OneForOne(Always(resume ? Directive.Resume : Directive.Restart)));
Assert.Equal(1, ask<int>(actor, 1));
Assert.Equal(2, ask<int>(actor, 1));
tell(actor, 2); // crash + resume/restart
Task.Delay(100).Wait();
Assert.Equal(expectedState, ask<int>(actor, 1));
kill(actor);
}
}
}
}
| 37.808036 | 137 | 0.428504 | [
"MIT"
] | ProductiveRage/echo-process | Echo.Tests/LifeTimeTests.cs | 8,471 | C# |
using System;
using System.Linq;
namespace BlazorLeaflet.Utils
{
public class StringHelper
{
private static readonly Random _random = new Random();
public static string GetRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[_random.Next(s.Length)]).ToArray());
}
}
}
| 20.6 | 79 | 0.737864 | [
"MIT"
] | hse-electronics/BlazorLeaflet | BlazorLeaflet/BlazorLeaflet/Utils/StringHelper.cs | 414 | C# |
using System.Linq;
using TT.Domain.Abstract;
using TT.Domain.Models;
namespace TT.Domain.Concrete
{
public class EFPlayerLogRepository : IPlayerLogRepository
{
private StatsContext context = new StatsContext();
public IQueryable<PlayerLog> PlayerLogs
{
get { return context.PlayerLogs; }
}
public void SavePlayerLog(PlayerLog PlayerLog)
{
if (PlayerLog.Id == 0)
{
context.PlayerLogs.Add(PlayerLog);
}
else
{
var editMe = context.PlayerLogs.Find(PlayerLog.Id);
if (editMe != null)
{
// dbEntry.Name = PlayerLog.Name;
// dbEntry.Message = PlayerLog.Message;
// dbEntry.TimeStamp = PlayerLog.TimeStamp;
}
}
context.SaveChanges();
}
public void DeletePlayerLog(int id)
{
var dbEntry = context.PlayerLogs.Find(id);
if (dbEntry != null)
{
context.PlayerLogs.Remove(dbEntry);
context.SaveChanges();
}
}
}
} | 25.3125 | 67 | 0.497942 | [
"MIT"
] | transformania/tt-game | src/TT.Domain/Legacy/Concrete/EFPlayerLogRepository.cs | 1,217 | C# |
using System;
using System.IO;
// csharp: hina/io/extensions/memorystreamextensions.cs [snipped]
namespace Hina.IO
{
public static class MemoryStreamExtensions
{
public static ArraySegment<byte> GetBuffer(this MemoryStream stream)
{
if (stream.TryGetBuffer(out var buffer))
return buffer;
throw new ArgumentException("failed to extract underlying buffer from memory stream");
}
}
}
| 25.611111 | 98 | 0.663774 | [
"MIT"
] | NebulaSleuth/bnc.rtmpsharp | src/_Sky/Hina/IO/Extensions/MemoryStreamExtensions.cs | 463 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace MovingPlatformDemo.GumRuntimes.DefaultForms
{
public partial class TreeViewRuntime
{
partial void CustomInitialize ()
{
}
}
}
| 17.214286 | 53 | 0.684647 | [
"MIT"
] | coldacid/FlatRedBall | Samples/Platformer/MovingPlatformDemo/MovingPlatformDemo/GumRuntimes/DefaultForms/TreeViewRuntime.cs | 241 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Runtime;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SP_Taxonomy_client_test.Infrastructure;
namespace SP_Taxonomy_client_test
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ITermSet, SharePointTermsService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddMvc().AddNewtonsoftJson().SetCompatibilityVersion(CompatibilityVersion.Latest);
services.AddMvcCore().AddNewtonsoftJson();
services.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//app.UseHttpsRedirection();
//app.UseMvc();
}
}
}
| 33.876923 | 143 | 0.644868 | [
"Apache-2.0"
] | JonasAls89/termstore | SP_Taxonomy_client_test/Startup.cs | 2,204 | C# |
namespace ApproximateOptimization
{
public interface IOptimizer
{
/// <summary>
/// Runs the actual solving algorithm. This may take considerable time.
/// </summary>
void FindMaximum();
/// <summary>
/// After running the search, the best found solution can be found in this property.
/// </summary>
double[] BestSolutionSoFar { get; }
/// <summary>
/// A score of the best found solution.
/// You may need to check this property to establish how good is the solution found in "BestSolutionSoFar".
/// </summary>
double SolutionValue { get; }
/// <summary>
/// A flag indicating if any solution was found (even one with a bad SolutionValue).
/// </summary>
bool SolutionFound { get; }
}
}
| 30.142857 | 115 | 0.584123 | [
"MIT"
] | krzyszsz/ApproximateOptimization | ApproximateOptimization/Optimizers/IOptimizer.cs | 846 | C# |
using System;
using System.Linq;
using System.Threading;
using Datadog.Trace.RuntimeMetrics;
using Datadog.Trace.Vendors.StatsdClient;
using Moq;
using Xunit;
namespace Datadog.Trace.Tests.RuntimeMetrics
{
[CollectionDefinition(nameof(RuntimeMetricsWriterTests), DisableParallelization = true)]
[Collection(nameof(RuntimeMetricsWriterTests))]
public class RuntimeMetricsWriterTests
{
[Fact]
public void PushEvents()
{
var listener = new Mock<IRuntimeMetricsListener>();
var mutex = new ManualResetEventSlim();
listener.Setup(l => l.Refresh())
.Callback(() => mutex.Set());
using (new RuntimeMetricsWriter(Mock.Of<IDogStatsd>(), TimeSpan.FromMilliseconds(10), (_, d) => listener.Object))
{
Assert.True(mutex.Wait(10000), "Method Refresh() wasn't called on the listener");
}
}
[Fact]
public void ShouldSwallowFactoryExceptions()
{
Func<IDogStatsd, TimeSpan, IRuntimeMetricsListener> factory = (_, d) => throw new InvalidOperationException("This exception should be caught");
var writer = new RuntimeMetricsWriter(Mock.Of<IDogStatsd>(), TimeSpan.FromMilliseconds(10), factory);
writer.Dispose();
}
[Fact]
public void ShouldCaptureFirstChanceExceptions()
{
var statsd = new Mock<IDogStatsd>();
using (var writer = new RuntimeMetricsWriter(statsd.Object, TimeSpan.FromMilliseconds(Timeout.Infinite), (_, d) => Mock.Of<IRuntimeMetricsListener>()))
{
for (int i = 0; i < 10; i++)
{
try
{
throw new CustomException1();
}
catch
{
// ignored
}
if (i % 2 == 0)
{
try
{
throw new CustomException2();
}
catch
{
// ignored
}
}
}
statsd.Verify(
s => s.Increment(MetricsNames.ExceptionsCount, It.IsAny<int>(), It.IsAny<double>(), It.IsAny<string[]>()),
Times.Never);
writer.PushEvents();
statsd.Verify(
s => s.Increment(MetricsNames.ExceptionsCount, 10, It.IsAny<double>(), new[] { "exception_type:CustomException1" }),
Times.Once);
statsd.Verify(
s => s.Increment(MetricsNames.ExceptionsCount, 5, It.IsAny<double>(), new[] { "exception_type:CustomException2" }),
Times.Once);
statsd.Invocations.Clear();
// Make sure stats are reset when pushed
writer.PushEvents();
statsd.Verify(
s => s.Increment(MetricsNames.ExceptionsCount, It.IsAny<int>(), It.IsAny<double>(), new[] { "exception_type:CustomException1" }),
Times.Never);
statsd.Verify(
s => s.Increment(MetricsNames.ExceptionsCount, It.IsAny<int>(), It.IsAny<double>(), new[] { "exception_type:CustomException2" }),
Times.Never);
}
}
[Fact]
public void CleanupResources()
{
var statsd = new Mock<IDogStatsd>();
var runtimeListener = new Mock<IRuntimeMetricsListener>();
var writer = new RuntimeMetricsWriter(statsd.Object, TimeSpan.FromMilliseconds(Timeout.Infinite), (_, d) => runtimeListener.Object);
writer.Dispose();
runtimeListener.Verify(l => l.Dispose(), Times.Once);
// Make sure that the writer unsubscribed from the global exception handler
try
{
throw new CustomException1();
}
catch
{
// ignored
}
writer.ExceptionCounts.TryGetValue(nameof(CustomException1), out var count);
Assert.Equal(0, count);
}
private class CustomException1 : Exception
{
}
private class CustomException2 : Exception
{
}
}
}
| 33.177778 | 163 | 0.511498 | [
"Apache-2.0"
] | alirezavafi/dd-trace-dotnet-splunk | test/Datadog.Trace.Tests/RuntimeMetrics/RuntimeMetricsWriterTests.cs | 4,479 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601
{
using Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Runtime.PowerShell;
/// <summary>The common properties of the export.</summary>
[System.ComponentModel.TypeConverter(typeof(CommonExportPropertiesTypeConverter))]
public partial class CommonExportProperties
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.CommonExportProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal CommonExportProperties(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Definition = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDefinition) content.GetValueForProperty("Definition",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Definition, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDefinitionTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfo = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDeliveryInfo) content.GetValueForProperty("DeliveryInfo",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfo, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDeliveryInfoTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistory = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportExecutionListResult) content.GetValueForProperty("RunHistory",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistory, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportExecutionListResultTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Format = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.FormatType?) content.GetValueForProperty("Format",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Format, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.FormatType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).NextRunTimeEstimate = (global::System.DateTime?) content.GetValueForProperty("NextRunTimeEstimate",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).NextRunTimeEstimate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionDataSet = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDataset) content.GetValueForProperty("DefinitionDataSet",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionDataSet, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDatasetTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistoryValue = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportExecution[]) content.GetValueForProperty("RunHistoryValue",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistoryValue, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportExecution>(__y, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportExecutionTypeConverter.ConvertFrom));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionType = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.ExportType) content.GetValueForProperty("DefinitionType",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionType, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.ExportType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimeframe = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.TimeframeType) content.GetValueForProperty("DefinitionTimeframe",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimeframe, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.TimeframeType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfoDestination = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDeliveryDestination) content.GetValueForProperty("DeliveryInfoDestination",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfoDestination, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDeliveryDestinationTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimePeriod = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportTimePeriod) content.GetValueForProperty("DefinitionTimePeriod",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimePeriod, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportTimePeriodTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodFrom = (global::System.DateTime) content.GetValueForProperty("TimePeriodFrom",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodFrom, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetGranularity = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.GranularityType?) content.GetValueForProperty("DataSetGranularity",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetGranularity, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.GranularityType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDatasetConfiguration) content.GetValueForProperty("DataSetConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetConfiguration, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDatasetConfigurationTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationContainer = (string) content.GetValueForProperty("DestinationContainer",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationContainer, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationResourceId = (string) content.GetValueForProperty("DestinationResourceId",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationResourceId, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationRootFolderPath = (string) content.GetValueForProperty("DestinationRootFolderPath",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationRootFolderPath, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodTo = (global::System.DateTime) content.GetValueForProperty("TimePeriodTo",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodTo, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).ConfigurationColumn = (string[]) content.GetValueForProperty("ConfigurationColumn",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).ConfigurationColumn, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.CommonExportProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal CommonExportProperties(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Definition = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDefinition) content.GetValueForProperty("Definition",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Definition, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDefinitionTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfo = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDeliveryInfo) content.GetValueForProperty("DeliveryInfo",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfo, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDeliveryInfoTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistory = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportExecutionListResult) content.GetValueForProperty("RunHistory",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistory, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportExecutionListResultTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Format = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.FormatType?) content.GetValueForProperty("Format",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).Format, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.FormatType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).NextRunTimeEstimate = (global::System.DateTime?) content.GetValueForProperty("NextRunTimeEstimate",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).NextRunTimeEstimate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionDataSet = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDataset) content.GetValueForProperty("DefinitionDataSet",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionDataSet, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDatasetTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistoryValue = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportExecution[]) content.GetValueForProperty("RunHistoryValue",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).RunHistoryValue, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportExecution>(__y, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportExecutionTypeConverter.ConvertFrom));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionType = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.ExportType) content.GetValueForProperty("DefinitionType",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionType, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.ExportType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimeframe = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.TimeframeType) content.GetValueForProperty("DefinitionTimeframe",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimeframe, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.TimeframeType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfoDestination = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDeliveryDestination) content.GetValueForProperty("DeliveryInfoDestination",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DeliveryInfoDestination, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDeliveryDestinationTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimePeriod = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportTimePeriod) content.GetValueForProperty("DefinitionTimePeriod",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DefinitionTimePeriod, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportTimePeriodTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodFrom = (global::System.DateTime) content.GetValueForProperty("TimePeriodFrom",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodFrom, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetGranularity = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.GranularityType?) content.GetValueForProperty("DataSetGranularity",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetGranularity, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Support.GranularityType.CreateFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetConfiguration = (Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.IExportDatasetConfiguration) content.GetValueForProperty("DataSetConfiguration",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DataSetConfiguration, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ExportDatasetConfigurationTypeConverter.ConvertFrom);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationContainer = (string) content.GetValueForProperty("DestinationContainer",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationContainer, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationResourceId = (string) content.GetValueForProperty("DestinationResourceId",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationResourceId, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationRootFolderPath = (string) content.GetValueForProperty("DestinationRootFolderPath",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).DestinationRootFolderPath, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodTo = (global::System.DateTime) content.GetValueForProperty("TimePeriodTo",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).TimePeriodTo, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).ConfigurationColumn = (string[]) content.GetValueForProperty("ConfigurationColumn",((Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportPropertiesInternal)this).ConfigurationColumn, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
AfterDeserializePSObject(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.CommonExportProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportProperties"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportProperties DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new CommonExportProperties(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.CommonExportProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportProperties"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new CommonExportProperties(content);
}
/// <summary>
/// Creates a new instance of <see cref="CommonExportProperties" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Models.Api20200601.ICommonExportProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CostManagement.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// The common properties of the export.
[System.ComponentModel.TypeConverter(typeof(CommonExportPropertiesTypeConverter))]
public partial interface ICommonExportProperties
{
}
} | 154.502959 | 651 | 0.80242 | [
"MIT"
] | 3quanfeng/azure-powershell | src/CostManagement/generated/api/Models/Api20200601/CommonExportProperties.PowerShell.cs | 25,943 | C# |
using Microsoft.EntityFrameworkCore;
namespace AMT.Data.Entities
{
public partial class ODSContext : DbContext
{
public ODSContext()
{
}
public ODSContext(DbContextOptions<ODSContext> options)
: base(options)
{
Database.SetCommandTimeout(300);
}
public virtual DbSet<SchoolMinMaxDateDim> SchoolMinMaxDateDims { get; set; }
public virtual DbSet<CurrentSchoolYearDim> CurrentSchoolYearDims { get; set; }
public virtual DbSet<SchoolCalendarDim> SchoolCalendarDims { get; set; }
public virtual DbSet<StudentSectionAttendanceEventFact> StudentSectionAttendanceEventFacts { get; set; }
public virtual DbSet<StudentSchoolAttendanceEventFact> StudentSchoolAttendanceEventFacts { get; set; }
public virtual DbSet<GradingPeriodDim> GradingPeriodDims { get; set; }
public virtual DbSet<StudentSectionDim> StudentSectionDims { get; set; }
public virtual DbSet<StudentSchoolDim> StudentSchoolDims { get; set; }
public virtual DbSet<StudentDim> StudentDims { get; set; }
public virtual DbSet<StudentLanguageDim> StudentLanguageDims { get; set; }
public virtual DbSet<WarehouseStudentUSIMappingDim> WarehouseStudentUSIMappingDims { get; set; }
public virtual DbSet<ProgramDim> ProgramDims { get; set; }
public virtual DbSet<StudentProgramAssociationDim> StudentProgramAssociationDims { get; set; }
public virtual DbSet<ContactPersonDim> ContactPersonDims { get; set; }
public virtual DbSet<UserDim> UserDims { get; set; }
public virtual DbSet<UserAuthorizationDim> UserAuthorizationDims { get; set; }
public virtual DbSet<UserStudentDataAuthorizationDim> UserStudentDataAuthorizationDims { get; set; }
public virtual DbSet<StudentDataAuthorizationDim> StudentDataAuthorizationDims { get; set; }
public virtual DbSet<StudentDisciplineDim> StudentDisciplineDims { get; set; }
public virtual DbSet<StudentAssessmentDim> StudentAssessmentDims { get; set; }
public virtual DbSet<StudentAssessmentScoreResultDim> StudentAssessmentScoreResultDims { get; set; }
public virtual DbSet<StudentGradeDim> StudentGradeDims { get; set; }
public virtual DbSet<GradingScaleDim> GradingScaleDims { get; set; }
public virtual DbSet<GradingScaleGradeDim> GradingScaleGradeDims { get; set; }
public virtual DbSet<GradingScaleGradeLevelDim> GradingScaleGradeLevelDims { get; set; }
public virtual DbSet<GradingScaleMetricThresholdDim> GradingScaleMetricThresholdDims { get; set; }
public virtual DbSet<GradeLevelTypeDim> GradeLevelTypeDims { get; set; }
public virtual DbSet<StudentAssessmentItemDim> StudentAssessmentItemDims { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(System.Reflection.Assembly.GetExecutingAssembly());
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
| 56.345455 | 112 | 0.731849 | [
"Apache-2.0"
] | ESPSG/Dashboard-Replacement-POC | API/AMT.Data/Entities/ODSContext.cs | 3,101 | C# |
using McMaster.Extensions.CommandLineUtils;
namespace DocumentFramework.Tool.CommandLineApplications
{
public static class Root
{
public static CommandLineApplication BuildApplication()
{
var app = new CommandLineApplication();
app.HelpOption("-h|--help", true);
app.AddSubcommand(Migrations.BuildApplication());
app.AddSubcommand(MongoContext.BuildApplication());
return app;
}
}
} | 27.444444 | 64 | 0.629555 | [
"MIT"
] | stormmuller/document-framework | Tool/CommandLineApplications/Root.cs | 494 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainModel.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Runtime.Serialization;
namespace PicklesDoc.Pickles.UserInterface.Settings
{
[DataContract(Name = "pickles", Namespace = "")]
public class MainModel
{
[DataMember(Name = "featureDirectory")]
public string FeatureDirectory { get; set; }
[DataMember(Name = "outputDirectory")]
public string OutputDirectory { get; set; }
[DataMember(Name = "projectName")]
public string ProjectName { get; set; }
[DataMember(Name = "projectVersion")]
public string ProjectVersion { get; set; }
[DataMember(Name = "includeTestResults")]
public bool IncludeTestResults { get; set; }
[DataMember(Name = "testResultsFile")]
public string TestResultsFile { get; set; }
[DataMember(Name = "testResultsFormat")]
public TestResultsFormat TestResultsFormat { get; set; }
[DataMember(Name = "documentationFormats")]
public DocumentationFormat[] DocumentationFormats { get; set; }
[DataMember(Name = "selectedLanguageLcid")]
public int SelectedLanguageLcid { get; set; }
[DataMember(Name = "createDirectoryForEachOutputFormat", IsRequired = false)]
public bool CreateDirectoryForEachOutputFormat { get; set; }
[DataMember(Name = "includeExperimentalFeatures", IsRequired = false)]
public bool IncludeExperimentalFeatures { get; set; }
[DataMember(Name = "enableComments", IsRequired = false)]
public bool EnableComments { get; set; }
[DataMember(Name = "excludeTags", IsRequired = false)]
public string ExcludeTags { get; set; }
[DataMember(Name = "HideTags", IsRequired = false)]
public string HideTags { get; set; }
}
}
| 38.013699 | 121 | 0.615495 | [
"Apache-2.0"
] | NicksonT/pickles | src/Pickles/Pickles.UserInterface/Settings/MainModel.cs | 2,777 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer4.Quickstart.UI
{
/// <summary>
/// This sample controller implements a typical login/logout/provision workflow for local and external accounts.
/// The login service encapsulates the interactions with the user data store. This data store is in-memory only and cannot be used for production!
/// The interaction service provides a way for the UI to communicate with identityserver for validation and context retrieval
/// </summary>
[SecurityHeaders]
[AllowAnonymous]
public class AccountController : Controller
{
private readonly TestUserStore _users;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IAuthenticationSchemeProvider _schemeProvider;
private readonly IEventService _events;
public AccountController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IAuthenticationSchemeProvider schemeProvider,
IEventService events,
TestUserStore users = null)
{
// if the TestUserStore is not in DI, then we'll just use the global users collection
// this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
_users = users ?? new TestUserStore(TestUsers.Users);
_interaction = interaction;
_clientStore = clientStore;
_schemeProvider = schemeProvider;
_events = events;
}
/// <summary>
/// Entry point into the login workflow
/// </summary>
[HttpGet]
public async Task<IActionResult> Login(string returnUrl)
{
// build a model so we know what to show on the login page
var vm = await BuildLoginViewModelAsync(returnUrl);
if (vm.IsExternalLoginOnly)
{
// we only have one option for logging in and it's an external provider
return RedirectToAction("Challenge", "External", new { provider = vm.ExternalLoginScheme, returnUrl });
}
return View(vm);
}
/// <summary>
/// Handle postback from username/password login
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string button)
{
// check if we are in the context of an authorization request
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
// the user clicked the "cancel" button
if (button != "login")
{
if (context != null)
{
// if the user cancels, send a result back into IdentityServer as if they
// denied the consent (even if this client does not require consent).
// this will send back an access denied OIDC error response to the client.
await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
}
return Redirect(model.ReturnUrl);
}
else
{
// since we don't have a valid context, then we just go back to the home page
return Redirect("~/");
}
}
if (ModelState.IsValid)
{
// validate username/password against in-memory store
if (_users.ValidateCredentials(model.Username, model.Password))
{
var user = _users.FindByUsername(model.Username);
await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId: context?.ClientId));
// only set explicit expiration here if user chooses "remember me".
// otherwise we rely upon expiration configured in cookie middleware.
AuthenticationProperties props = null;
if (AccountOptions.AllowRememberLogin && model.RememberLogin)
{
props = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
};
};
// issue authentication cookie with subject ID and username
await HttpContext.SignInAsync(user.SubjectId, user.Username, props);
if (context != null)
{
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
}
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}
// request for a local page
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
else if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect("~/");
}
else
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId:context?.ClientId));
ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
var vm = await BuildLoginViewModelAsync(model);
return View(vm);
}
/// <summary>
/// Show logout page
/// </summary>
[HttpGet]
public async Task<IActionResult> Logout(string logoutId)
{
// build a model so the logout page knows what to display
var vm = await BuildLogoutViewModelAsync(logoutId);
if (vm.ShowLogoutPrompt == false)
{
// if the request for logout was properly authenticated from IdentityServer, then
// we don't need to show the prompt and can just log the user out directly.
return await Logout(vm);
}
return View(vm);
}
/// <summary>
/// Handle logout page postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout(LogoutInputModel model)
{
// build a model so the logged out page knows what to display
var vm = await BuildLoggedOutViewModelAsync(model.LogoutId);
if (User?.Identity.IsAuthenticated == true)
{
// delete local authentication cookie
await HttpContext.SignOutAsync();
// raise the logout event
await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));
}
// check if we need to trigger sign-out at an upstream identity provider
if (vm.TriggerExternalSignout)
{
// build a return URL so the upstream provider will redirect back
// to us after the user has logged out. this allows us to then
// complete our single sign-out processing.
string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
// this triggers a redirect to the external provider for sign-out
return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
}
return View("LoggedOut", vm);
}
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
/*****************************************/
/* helper APIs for the AccountController */
/*****************************************/
private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
{
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null)
{
var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;
// this is meant to short circuit the UI and only trigger the one external IdP
var vm = new LoginViewModel
{
EnableLocalLogin = local,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
};
if (!local)
{
vm.ExternalProviders = new[] { new ExternalProvider { AuthenticationScheme = context.IdP } };
}
return vm;
}
var schemes = await _schemeProvider.GetAllSchemesAsync();
var providers = schemes
.Where(x => x.DisplayName != null ||
(x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
)
.Select(x => new ExternalProvider
{
DisplayName = x.DisplayName,
AuthenticationScheme = x.Name
}).ToList();
var allowLocal = true;
if (context?.ClientId != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);
if (client != null)
{
allowLocal = client.EnableLocalLogin;
if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
{
providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
}
}
}
return new LoginViewModel
{
AllowRememberLogin = AccountOptions.AllowRememberLogin,
EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
ExternalProviders = providers.ToArray()
};
}
private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model)
{
var vm = await BuildLoginViewModelAsync(model.ReturnUrl);
vm.Username = model.Username;
vm.RememberLogin = model.RememberLogin;
return vm;
}
private async Task<LogoutViewModel> BuildLogoutViewModelAsync(string logoutId)
{
var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt };
if (User?.Identity.IsAuthenticated != true)
{
// if the user is not authenticated, then just show logged out page
vm.ShowLogoutPrompt = false;
return vm;
}
var context = await _interaction.GetLogoutContextAsync(logoutId);
if (context?.ShowSignoutPrompt == false)
{
// it's safe to automatically sign-out
vm.ShowLogoutPrompt = false;
return vm;
}
// show the logout prompt. this prevents attacks where the user
// is automatically signed out by another malicious web page.
return vm;
}
private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId)
{
// get context information (client name, post logout redirect URI and iframe for federated signout)
var logout = await _interaction.GetLogoutContextAsync(logoutId);
var vm = new LoggedOutViewModel
{
AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut,
PostLogoutRedirectUri = logout?.PostLogoutRedirectUri,
ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName,
SignOutIframeUrl = logout?.SignOutIFrameUrl,
LogoutId = logoutId
};
if (User?.Identity.IsAuthenticated == true)
{
var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value;
if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider)
{
var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp);
if (providerSupportsSignout)
{
if (vm.LogoutId == null)
{
// if there's no current logout context, we need to create one
// this captures necessary info from the current logged in user
// before we signout and redirect away to the external IdP for signout
vm.LogoutId = await _interaction.CreateLogoutContextAsync();
}
vm.ExternalAuthenticationScheme = idp;
}
}
}
return vm;
}
}
} | 42.10989 | 150 | 0.561913 | [
"Apache-2.0"
] | 48355746/IdentityServer4 | src/EntityFramework/host/Quickstart/Account/AccountController.cs | 15,328 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Backups_aka_Lab4
{
public class FullCreationPolicy : ICreationPolicy
{
private const string FullBackupsDirectory = @"C:\backups\full";
public RestorePoint CreateRestorePoint(List<RestorePoint> restorePoints, List<BackupFile> files)
{
var restorePointId = Guid.NewGuid();
var destinationDirectory = Path.Combine(FullBackupsDirectory, restorePointId.ToString());
foreach (var file in files)
{
CopyFile(file, destinationDirectory);
}
return new RestorePoint(
restorePointId,
files.ToArray(),
DateTime.Now,
RestorePointType.Full,
destinationDirectory);
}
private void CopyFile(BackupFile file, string destinationDirectory)
{
// File.Copy(file.FullPath, Path.Combine(destinationDirectory, file.Name));
}
}
}
| 24.083333 | 98 | 0.742791 | [
"MIT"
] | richiurb/OOP-labs | lab4/Backups_aka_Lab4/Creation/FullCreationPolicy.cs | 869 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PSAToSE")]
[assembly: AssemblyDescription("Converts PSA files to SEAnim animations")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DTZxPorter")]
[assembly: AssemblyProduct("PSAToSE")]
[assembly: AssemblyCopyright("Copyright © 2018 DTZxPorter")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bbabb149-099f-4e89-8bfe-fb60937edc4e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.108108 | 84 | 0.749827 | [
"MIT"
] | dtzxporter/PSAToSE | src/PSAToSE/Properties/AssemblyInfo.cs | 1,450 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("01 Variable types")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01 Variable types")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3530bf92-d36a-4943-9dd7-7d5d9ac5bea5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.744136 | [
"MIT"
] | PetarMetodiev/Telerik-Homeworks | C# Part 1/02 Primitive-data-types-and-variables/Primitive-data-types-and-variables/01 Variable types/Properties/AssemblyInfo.cs | 1,410 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CrudTcp.Core.Http.Action
{
public class Created : IHttpAction
{
public int Code { get; set; }
public object Object { get; set; }
public Created(object obj)
{
Code = 201;
Object = obj;
}
}
}
| 18.809524 | 42 | 0.594937 | [
"Apache-2.0"
] | ilyacoding/bsuir | KSiS/Lab_4/CrudTcp/CrudTcp/Core/Http/Action/Created.cs | 397 | C# |
using System;
using Nethereum.ABI.Decoders;
using Nethereum.ABI.Encoders;
namespace Nethereum.ABI
{
/// <summary>
/// Generic ABI type
/// </summary>
public abstract class ABIType
{
public ABIType(string name)
{
Name = name;
}
protected ITypeDecoder Decoder { get; set; }
protected ITypeEncoder Encoder { get; set; }
/// <summary>
/// The type name as it was specified in the interface description
/// </summary>
public virtual string Name { get; }
/// <summary>
/// The canonical type name (used for the method signature creation)
/// E.g. 'int' - canonical 'int256'
/// </summary>
public virtual string CanonicalName => Name;
/// <returns> fixed size in bytes or negative value if the type is dynamic </returns>
public virtual int FixedSize => 32;
public static ABIType CreateABIType(string typeName)
{
if (typeName.Contains("["))
return ArrayType.CreateABIType(typeName);
if ("bool".Equals(typeName))
return new BoolType();
if (typeName.StartsWith("int", StringComparison.Ordinal) ||
typeName.StartsWith("uint", StringComparison.Ordinal))
return new IntType(typeName);
if ("address".Equals(typeName))
return new AddressType();
if ("string".Equals(typeName))
return new StringType();
if ("bytes".Equals(typeName))
return new BytesType();
if (typeName.StartsWith("bytes", StringComparison.Ordinal))
{
var size = Convert.ToInt32(typeName.Substring(5));
if (size == 32)
return new Bytes32Type(typeName);
else
return new BytesElementaryType(typeName, size);
}
throw new ArgumentException("Unknown type: " + typeName);
}
public object Decode(byte[] encoded, Type type)
{
return Decoder.Decode(encoded, type);
}
public object Decode(string encoded, Type type)
{
return Decoder.Decode(encoded, type);
}
public T Decode<T>(string encoded)
{
return Decoder.Decode<T>(encoded);
}
public T Decode<T>(byte[] encoded)
{
return Decoder.Decode<T>(encoded);
}
/// <summary>
/// Encodes the value according to specific type rules
/// </summary>
/// <param name="value"> </param>
public byte[] Encode(object value)
{
return Encoder.Encode(value);
}
public Type GetDefaultDecodingType()
{
return Decoder.GetDefaultDecodingType();
}
public bool IsDynamic()
{
return FixedSize < 0;
}
public override string ToString()
{
return Name;
}
}
} | 29.625 | 93 | 0.530672 | [
"MIT"
] | F1nZeR/Nethereum | src/Nethereum.ABI/ABIType.cs | 3,081 | C# |
// Copyright (c) 2018, Rene Lergner - wpinternals.net - @Heathcliff74xda
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Threading;
namespace WPinternals
{
// Create this class on the UI thread, after the main-window of the application is initialized.
// It is necessary to create the object on the UI thread, because notification events to the View need to be fired on that thread.
// The Model for this ViewModel communicates over USB and for that it uses the hWnd of the main window.
// Therefore the main window must be created before the ViewModel is created.
internal class NokiaFlashViewModel : ContextViewModel
{
private NokiaFlashModel CurrentModel;
private Action<PhoneInterfaces> RequestModeSwitch;
internal Action SwitchToGettingStarted;
private object LockDeviceInfo = new object();
bool DeviceInfoLoaded = false;
internal NokiaFlashViewModel(NokiaPhoneModel CurrentModel, Action<PhoneInterfaces> RequestModeSwitch, Action SwitchToGettingStarted)
: base()
{
this.CurrentModel = (NokiaFlashModel)CurrentModel;
this.RequestModeSwitch = RequestModeSwitch;
this.SwitchToGettingStarted = SwitchToGettingStarted;
}
// Device info should be loaded only one time and only when the ViewModel is active
internal override void EvaluateViewState()
{
if (IsActive)
new Thread(() => StartLoadDeviceInfo()).Start();
}
private void StartLoadDeviceInfo()
{
lock (LockDeviceInfo)
{
if (!DeviceInfoLoaded)
{
try
{
//byte[] Imsi = CurrentModel.ExecuteJsonMethodAsBytes("ReadImsi", "Imsi"); // 9 bytes: 08 29 40 40 ...
//string BatteryLevel = CurrentModel.ExecuteJsonMethodAsString("ReadBatteryLevel", "BatteryLevel");
//string SystemAsicVersion = CurrentModel.ExecuteJsonMethodAsString("ReadSystemAsicVersion", "SystemAsicVersion"); // 8960 -> Chip SOC version
//string OperatorName = CurrentModel.ExecuteJsonMethodAsString("ReadOperatorName", "OperatorName"); // 000-DK
//string ManufacturerModelName = CurrentModel.ExecuteJsonMethodAsString("ReadManufacturerModelName", "ManufacturerModelName"); // RM-821_eu_denmark_251
//string AkVersion = CurrentModel.ExecuteJsonMethodAsString("ReadAkVersion", "AkVersion"); // 9200.10521
//string BspVersion = CurrentModel.ExecuteJsonMethodAsString("ReadBspVersion", "BspVersion"); // 3051.40000
//string ProductCode = CurrentModel.ExecuteJsonMethodAsString("ReadProductCode", "ProductCode"); // 059Q9D7
//string SecurityMode = CurrentModel.ExecuteJsonMethodAsString("GetSecurityMode", "SecMode"); // Restricted
//string SerialNumber = CurrentModel.ExecuteJsonMethodAsString("ReadSerialNumber", "SerialNumber"); // 356355051883955 = IMEI
//string SwVersion = CurrentModel.ExecuteJsonMethodAsString("ReadSwVersion", "SwVersion"); // 3051.40000.1349.0007
//string ModuleCode = CurrentModel.ExecuteJsonMethodAsString("ReadModuleCode", "ModuleCode"); // 0205137
//byte[] PublicId = CurrentModel.ExecuteJsonMethodAsBytes("ReadPublicId", "PublicId"); // 0x14 bytes: a5 e5 ...
//string Psn = CurrentModel.ExecuteJsonMethodAsString("ReadPsn", "Psn"); // CEP737370
//string HwVersion = CurrentModel.ExecuteJsonMethodAsString("ReadHwVersion", "HWVersion"); // 6504 = 6.5.0.4
//byte[] BtId = CurrentModel.ExecuteJsonMethodAsBytes("ReadBtId", "BtId"); // 6 bytes: bc c6 ...
//byte[] WlanMacAddress1 = CurrentModel.ExecuteJsonMethodAsBytes("ReadWlanMacAddress", "WlanMacAddress1"); // 6 bytes
//byte[] WlanMacAddress2 = CurrentModel.ExecuteJsonMethodAsBytes("ReadWlanMacAddress", "WlanMacAddress2"); // same
//byte[] WlanMacAddress3 = CurrentModel.ExecuteJsonMethodAsBytes("ReadWlanMacAddress", "WlanMacAddress3"); // same
//bool SimlockActive = CurrentModel.ExecuteJsonMethodAsBoolean("ReadSimlockActive", "SimLockActive"); // false
//string ServiceTag = CurrentModel.ExecuteJsonMethodAsString("ReadServiceTag", "ServiceTag"); // error
//byte[] RfChipsetVersion = CurrentModel.ExecuteJsonMethodAsBytes("ReadRfChipsetVersion", "RfChipsetVersion"); // error
//byte[] Meid = CurrentModel.ExecuteJsonMethodAsBytes("ReadMeid", "Meid"); // error
//string Test = CurrentModel.ExecuteJsonMethodAsString("ReadManufacturingData", ""); -> This method is only possible in Label-mode.
UefiSecurityStatusResponse SecurityStatus = CurrentModel.ReadSecurityStatus();
UInt32? FlagsResult = CurrentModel.ReadSecurityFlags();
UInt32 SecurityFlags = 0;
if (FlagsResult != null)
{
SecurityFlags = (UInt32)CurrentModel.ReadSecurityFlags();
LogFile.Log("Security flags: 0x" + SecurityFlags.ToString("X8"));
FinalConfigDakStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.Dak);
FinalConfigFastBootStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.FastBoot);
FinalConfigFfuVerifyStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.FfuVerify);
FinalConfigJtagStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.Jtag);
FinalConfigOemIdStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.OemId);
FinalConfigProductionDoneStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.ProductionDone);
FinalConfigPublicIdStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.PublicId);
FinalConfigRkhStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.Rkh);
FinalConfigRpmWdogStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.RpmWdog);
FinalConfigSecGenStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.SecGen);
FinalConfigSecureBootStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.SecureBoot);
FinalConfigShkStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.Shk);
FinalConfigSimlockStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.Simlock);
FinalConfigSpdmSecModeStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.SpdmSecMode);
FinalConfigSsmStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.Ssm);
}
else
LogFile.Log("Security flags could not be read");
PlatformName = CurrentModel.ReadStringParam("DPI");
LogFile.Log("Platform Name: " + PlatformName);
// Some phones do not support the Terminal interface! (928 verizon)
// Instead read param RRKH to get the RKH.
PublicID = null;
byte[] RawPublicID = CurrentModel.ReadParam("PID");
if ((RawPublicID != null) && (RawPublicID.Length > 4))
{
PublicID = new byte[RawPublicID.Length - 4];
Array.Copy(RawPublicID, 4, PublicID, 0, RawPublicID.Length - 4);
LogFile.Log("Public ID: " + Converter.ConvertHexToString(PublicID, " "));
}
else
{
PublicID = new byte[20];
LogFile.Log("Public ID: " + Converter.ConvertHexToString(PublicID, " "));
}
RootKeyHash = CurrentModel.ReadParam("RRKH");
if (RootKeyHash != null)
LogFile.Log("Root Key Hash: " + Converter.ConvertHexToString(RootKeyHash, " "));
if (SecurityStatus != null)
{
PlatformSecureBootStatus = SecurityStatus.PlatformSecureBootStatus;
LogFile.Log("Platform Secure Boot Status: " + PlatformSecureBootStatus.ToString());
UefiSecureBootStatus = SecurityStatus.UefiSecureBootStatus;
LogFile.Log("Uefi Secure Boot Status: " + UefiSecureBootStatus.ToString());
EffectiveSecureBootStatus = SecurityStatus.PlatformSecureBootStatus && SecurityStatus.UefiSecureBootStatus;
LogFile.Log("Effective Secure Boot Status: " + EffectiveSecureBootStatus.ToString());
BootloaderSecurityQfuseStatus = SecurityStatus.SecureFfuEfuseStatus;
LogFile.Log("Bootloader Security Qfuse Status: " + BootloaderSecurityQfuseStatus.ToString());
BootloaderSecurityAuthenticationStatus = SecurityStatus.AuthenticationStatus;
LogFile.Log("Bootloader Security Authentication Status: " + BootloaderSecurityAuthenticationStatus.ToString());
BootloaderSecurityRdcStatus = SecurityStatus.RdcStatus;
LogFile.Log("Bootloader Security Rdc Status: " + BootloaderSecurityRdcStatus.ToString());
EffectiveBootloaderSecurityStatus = SecurityStatus.SecureFfuEfuseStatus && !SecurityStatus.AuthenticationStatus && !SecurityStatus.RdcStatus;
LogFile.Log("Effective Bootloader Security Status: " + EffectiveBootloaderSecurityStatus.ToString());
NativeDebugStatus = !SecurityStatus.DebugStatus;
LogFile.Log("Native Debug Status: " + NativeDebugStatus.ToString());
}
byte[] CID = CurrentModel.ReadParam("CID");
byte[] EMS = CurrentModel.ReadParam("EMS");
if (CID != null && EMS != null)
{
UInt16 MID = (UInt16)(((UInt16)CID[0] << 8) + CID[1]);
UInt64 MemSize = (UInt64)(((UInt32)EMS[0] << 24) + ((UInt32)EMS[1] << 16) + ((UInt32)EMS[2] << 8) + EMS[3]) * 0x200;
double MemSizeDouble = (double)MemSize / 1024 / 1024 / 1024;
MemSizeDouble = (double)(int)(MemSizeDouble * 10) / 10;
string Manufacturer = null;
switch (MID)
{
case 0x0002:
case 0x0045:
Manufacturer = "SanDisk";
break;
case 0x0011:
Manufacturer = "Toshiba";
break;
case 0x0013:
Manufacturer = "Micron";
break;
case 0x0015:
Manufacturer = "Samsung";
break;
case 0x0090:
Manufacturer = "Hynix";
break;
case 0x0070:
Manufacturer = "Kingston";
break;
case 0x00EC:
Manufacturer = "GigaDevice";
break;
}
if (Manufacturer == null)
eMMC = MemSizeDouble.ToString() + " GB";
else
eMMC = Manufacturer + " " + MemSizeDouble.ToString() + " GB";
SamsungWarningVisible = (MID == 0x0015);
}
else
{
eMMC = "Unknown";
SamsungWarningVisible = true;
}
int? chargecurrent = CurrentModel.ReadCurrentChargeCurrent();
if (chargecurrent.HasValue)
{
if (chargecurrent < 0)
ChargingStatus = CurrentModel.ReadCurrentChargeLevel() + "% - " + ((-1) * CurrentModel.ReadCurrentChargeCurrent()) + " mA (discharging)";
else
ChargingStatus = CurrentModel.ReadCurrentChargeLevel() + "% - " + CurrentModel.ReadCurrentChargeCurrent() + " mA (charging)";
LogFile.Log("Charging status: " + ChargingStatus);
}
else
{
ChargingStatus = "Unknown";
LogFile.Log("Charging status: " + ChargingStatus);
}
PhoneInfo Info = CurrentModel.ReadPhoneInfo(true);
if (Info.FlashAppProtocolVersionMajor < 2)
BootloaderDescription = "Lumia Bootloader Spec A";
else
BootloaderDescription = "Lumia Bootloader Spec B";
LogFile.Log("Bootloader: " + BootloaderDescription);
ProductCode = Info.ProductCode;
LogFile.Log("ProductCode: " + ProductCode);
ProductType = Info.Type;
LogFile.Log("ProductType: " + ProductType);
if (RootKeyHash == null)
{
LogFile.Log("Root Key Hash was null. Gathering information from an alternative source.");
RootKeyHash = Info.RKH;
if (RootKeyHash != null)
LogFile.Log("Root Key Hash: " + Converter.ConvertHexToString(RootKeyHash, " "));
else
{
RootKeyHash = new byte[32];
LogFile.Log("Root Key Hash: " + Converter.ConvertHexToString(RootKeyHash, " "));
}
}
if (PlatformName == null)
{
LogFile.Log("Platform Name was null. Gathering information from an alternative source.");
PlatformName = Info.PlatformID;
LogFile.Log("Platform Name: " + PlatformName);
}
if (SecurityStatus == null)
{
LogFile.Log("Security Status was null. Gathering information from an alternative source.");
PlatformSecureBootStatus = Info.PlatformSecureBootEnabled;
LogFile.Log("Platform Secure Boot Status: " + PlatformSecureBootStatus.ToString());
UefiSecureBootStatus = Info.UefiSecureBootEnabled;
LogFile.Log("Uefi Secure Boot Status: " + UefiSecureBootStatus.ToString());
EffectiveSecureBootStatus = Info.PlatformSecureBootEnabled && Info.UefiSecureBootEnabled;
LogFile.Log("Effective Secure Boot Status: " + EffectiveSecureBootStatus.ToString());
BootloaderSecurityQfuseStatus = Info.SecureFfuEnabled;
LogFile.Log("Bootloader Security Qfuse Status: " + BootloaderSecurityQfuseStatus.ToString());
BootloaderSecurityAuthenticationStatus = Info.Authenticated;
LogFile.Log("Bootloader Security Authentication Status: " + BootloaderSecurityAuthenticationStatus.ToString());
BootloaderSecurityRdcStatus = Info.RdcPresent;
LogFile.Log("Bootloader Security Rdc Status: " + BootloaderSecurityRdcStatus.ToString());
EffectiveBootloaderSecurityStatus = !Info.IsBootloaderSecure;
LogFile.Log("Effective Bootloader Security Status: " + EffectiveBootloaderSecurityStatus.ToString());
NativeDebugStatus = !Info.JtagDisabled;
LogFile.Log("Native Debug Status: " + NativeDebugStatus.ToString());
}
}
catch
{
LogFile.Log("Reading status from Flash interface was aborted.");
}
DeviceInfoLoaded = true;
}
}
}
private byte[] _PublicID = null;
public byte[] PublicID
{
get
{
return _PublicID;
}
set
{
_PublicID = value;
OnPropertyChanged("PublicID");
}
}
private byte[] _RootKeyHash = null;
public byte[] RootKeyHash
{
get
{
return _RootKeyHash;
}
set
{
_RootKeyHash = value;
OnPropertyChanged("RootKeyHash");
}
}
private string _PlatformName = null;
public string PlatformName
{
get
{
return _PlatformName;
}
set
{
_PlatformName = value;
OnPropertyChanged("PlatformName");
}
}
private string _ProductType = null;
public string ProductType
{
get
{
return _ProductType;
}
set
{
_ProductType = value;
OnPropertyChanged("ProductType");
}
}
private string _ProductCode = null;
public string ProductCode
{
get
{
return _ProductCode;
}
set
{
_ProductCode = value;
OnPropertyChanged("ProductCode");
}
}
private string _eMMC = null;
public string eMMC
{
get
{
return _eMMC;
}
set
{
_eMMC = value;
OnPropertyChanged("eMMC");
}
}
private string _BootloaderDescription = null;
public string BootloaderDescription
{
get
{
return _BootloaderDescription;
}
set
{
_BootloaderDescription = value;
OnPropertyChanged("BootloaderDescription");
}
}
private string _ChargingStatus = null;
public string ChargingStatus
{
get
{
return _ChargingStatus;
}
set
{
_ChargingStatus = value;
OnPropertyChanged("ChargingStatus");
}
}
private bool _SamsungWarningVisible = false;
public bool SamsungWarningVisible
{
get
{
return _SamsungWarningVisible;
}
set
{
_SamsungWarningVisible = value;
OnPropertyChanged("SamsungWarningVisible");
}
}
private bool? _PlatformSecureBootStatus = null;
public bool? PlatformSecureBootStatus
{
get
{
return _PlatformSecureBootStatus;
}
set
{
_PlatformSecureBootStatus = value;
OnPropertyChanged("PlatformSecureBootStatus");
}
}
private bool? _BootloaderSecurityQfuseStatus = null;
public bool? BootloaderSecurityQfuseStatus
{
get
{
return _BootloaderSecurityQfuseStatus;
}
set
{
_BootloaderSecurityQfuseStatus = value;
OnPropertyChanged("BootloaderSecurityQfuseStatus");
}
}
private bool? _BootloaderSecurityRdcStatus = null;
public bool? BootloaderSecurityRdcStatus
{
get
{
return _BootloaderSecurityRdcStatus;
}
set
{
_BootloaderSecurityRdcStatus = value;
OnPropertyChanged("BootloaderSecurityRdcStatus");
}
}
private bool? _BootloaderSecurityAuthenticationStatus = null;
public bool? BootloaderSecurityAuthenticationStatus
{
get
{
return _BootloaderSecurityAuthenticationStatus;
}
set
{
_BootloaderSecurityAuthenticationStatus = value;
OnPropertyChanged("BootloaderSecurityAuthenticationStatus");
}
}
private bool? _UefiSecureBootStatus = null;
public bool? UefiSecureBootStatus
{
get
{
return _UefiSecureBootStatus;
}
set
{
_UefiSecureBootStatus = value;
OnPropertyChanged("UefiSecureBootStatus");
}
}
private bool? _EffectiveSecureBootStatus = null;
public bool? EffectiveSecureBootStatus
{
get
{
return _EffectiveSecureBootStatus;
}
set
{
_EffectiveSecureBootStatus = value;
OnPropertyChanged("EffectiveSecureBootStatus");
}
}
private bool? _EffectiveBootloaderSecurityStatus = null;
public bool? EffectiveBootloaderSecurityStatus
{
get
{
return _EffectiveBootloaderSecurityStatus;
}
set
{
_EffectiveBootloaderSecurityStatus = value;
OnPropertyChanged("EffectiveBootloaderSecurityStatus");
}
}
private bool? _NativeDebugStatus = null;
public bool? NativeDebugStatus
{
get
{
return _NativeDebugStatus;
}
set
{
_NativeDebugStatus = value;
OnPropertyChanged("NativeDebugStatus");
}
}
#region Final Config
private bool? _FinalConfigSecureBootStatus = null;
public bool? FinalConfigSecureBootStatus
{
get
{
return _FinalConfigSecureBootStatus;
}
set
{
_FinalConfigSecureBootStatus = value;
OnPropertyChanged("FinalConfigSecureBootStatus");
}
}
private bool? _FinalConfigFfuVerifyStatus = null;
public bool? FinalConfigFfuVerifyStatus
{
get
{
return _FinalConfigFfuVerifyStatus;
}
set
{
_FinalConfigFfuVerifyStatus = value;
OnPropertyChanged("FinalConfigFfuVerifyStatus");
}
}
private bool? _FinalConfigJtagStatus = null;
public bool? FinalConfigJtagStatus
{
get
{
return _FinalConfigJtagStatus;
}
set
{
_FinalConfigJtagStatus = value;
OnPropertyChanged("FinalConfigJtagStatus");
}
}
private bool? _FinalConfigShkStatus = null;
public bool? FinalConfigShkStatus
{
get
{
return _FinalConfigShkStatus;
}
set
{
_FinalConfigShkStatus = value;
OnPropertyChanged("FinalConfigShkStatus");
}
}
private bool? _FinalConfigSimlockStatus = null;
public bool? FinalConfigSimlockStatus
{
get
{
return _FinalConfigSimlockStatus;
}
set
{
_FinalConfigSimlockStatus = value;
OnPropertyChanged("FinalConfigSimlockStatus");
}
}
private bool? _FinalConfigProductionDoneStatus = null;
public bool? FinalConfigProductionDoneStatus
{
get
{
return _FinalConfigProductionDoneStatus;
}
set
{
_FinalConfigProductionDoneStatus = value;
OnPropertyChanged("FinalConfigProductionDoneStatus");
}
}
private bool? _FinalConfigRkhStatus = null;
public bool? FinalConfigRkhStatus
{
get
{
return _FinalConfigRkhStatus;
}
set
{
_FinalConfigRkhStatus = value;
OnPropertyChanged("FinalConfigRkhStatus");
}
}
private bool? _FinalConfigPublicIdStatus = null;
public bool? FinalConfigPublicIdStatus
{
get
{
return _FinalConfigPublicIdStatus;
}
set
{
_FinalConfigPublicIdStatus = value;
OnPropertyChanged("FinalConfigPublicIdStatus");
}
}
private bool? _FinalConfigDakStatus = null;
public bool? FinalConfigDakStatus
{
get
{
return _FinalConfigDakStatus;
}
set
{
_FinalConfigDakStatus = value;
OnPropertyChanged("FinalConfigDakStatus");
}
}
private bool? _FinalConfigSecGenStatus = null;
public bool? FinalConfigSecGenStatus
{
get
{
return _FinalConfigSecGenStatus;
}
set
{
_FinalConfigSecGenStatus = value;
OnPropertyChanged("FinalConfigSecGenStatus");
}
}
private bool? _FinalConfigOemIdStatus = null;
public bool? FinalConfigOemIdStatus
{
get
{
return _FinalConfigOemIdStatus;
}
set
{
_FinalConfigOemIdStatus = value;
OnPropertyChanged("FinalConfigOemIdStatus");
}
}
private bool? _FinalConfigFastBootStatus = null;
public bool? FinalConfigFastBootStatus
{
get
{
return _FinalConfigFastBootStatus;
}
set
{
_FinalConfigFastBootStatus = value;
OnPropertyChanged("FinalConfigFastBootStatus");
}
}
private bool? _FinalConfigSpdmSecModeStatus = null;
public bool? FinalConfigSpdmSecModeStatus
{
get
{
return _FinalConfigSpdmSecModeStatus;
}
set
{
_FinalConfigSpdmSecModeStatus = value;
OnPropertyChanged("FinalConfigSpdmSecModeStatus");
}
}
private bool? _FinalConfigRpmWdogStatus = null;
public bool? FinalConfigRpmWdogStatus
{
get
{
return _FinalConfigRpmWdogStatus;
}
set
{
_FinalConfigRpmWdogStatus = value;
OnPropertyChanged("FinalConfigRpmWdogStatus");
}
}
private bool? _FinalConfigSsmStatus = null;
public bool? FinalConfigSsmStatus
{
get
{
return _FinalConfigSsmStatus;
}
set
{
_FinalConfigSsmStatus = value;
OnPropertyChanged("FinalConfigSsmStatus");
}
}
#endregion
internal void RebootTo(string Mode)
{
switch (Mode)
{
case "Normal":
RequestModeSwitch(PhoneInterfaces.Lumia_Normal);
break;
case "Label":
RequestModeSwitch(PhoneInterfaces.Lumia_Label);
break;
case "MassStorage":
RequestModeSwitch(PhoneInterfaces.Lumia_MassStorage);
break;
default:
return;
}
}
}
}
| 41.647368 | 176 | 0.500348 | [
"MIT"
] | Niktendo/WPinternals | ViewModels/NokiaFlashViewModel.cs | 31,654 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Shapes")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shapes")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("08245ca8-c4b3-487a-bc2f-582a3f4df1a9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.297297 | 84 | 0.745652 | [
"MIT"
] | zrusev/SoftUni_2016 | 06. C# OOP Advanced - July 2017/01. Interfaces And Abstraction/01. Interfaces And Abstraction - Lab/Lab Interfaces and Abstraction/Shapes/Properties/AssemblyInfo.cs | 1,383 | C# |
using System;
using Spring.Collection.Reference;
using UnityEngine;
namespace Summer.Debugger.Window.Model.VO
{
/// <summary>
/// 日志记录结点。
/// </summary>
public sealed class LogNode : IReference
{
private DateTime logTime;
private int logFrameCount;
private LogType logType;
private string logMessage;
private string stackTrack;
/// <summary>
/// 初始化日志记录结点的新实例。
/// </summary>
public LogNode()
{
logTime = default(DateTime);
logFrameCount = 0;
logType = LogType.Error;
logMessage = null;
stackTrack = null;
}
/// <summary>
/// 获取日志时间。
/// </summary>
public DateTime LogTime
{
get { return logTime; }
}
/// <summary>
/// 获取日志帧计数。
/// </summary>
public int LogFrameCount
{
get { return logFrameCount; }
}
/// <summary>
/// 获取日志类型。
/// </summary>
public LogType LogType
{
get { return logType; }
}
/// <summary>
/// 获取日志内容。
/// </summary>
public string LogMessage
{
get { return logMessage; }
}
/// <summary>
/// 获取日志堆栈信息。
/// </summary>
public string StackTrack
{
get { return stackTrack; }
}
/// <summary>
/// 创建日志记录结点。
/// </summary>
/// <param name="logType">日志类型。</param>
/// <param name="logMessage">日志内容。</param>
/// <param name="stackTrack">日志堆栈信息。</param>
/// <returns>创建的日志记录结点。</returns>
public static LogNode Create(LogType logType, string logMessage, string stackTrack)
{
LogNode logNode = ReferenceCache.Acquire<LogNode>();
logNode.logTime = DateTime.UtcNow;
logNode.logFrameCount = Time.frameCount;
logNode.logType = logType;
logNode.logMessage = logMessage;
logNode.stackTrack = stackTrack;
return logNode;
}
/// <summary>
/// 清理日志记录结点。
/// </summary>
public void Clear()
{
logTime = default(DateTime);
logFrameCount = 0;
logType = LogType.Error;
logMessage = null;
stackTrack = null;
}
}
} | 24.56 | 91 | 0.486564 | [
"MIT"
] | Mu-L/Tank | Assets/Summer/Debugger/Window/Model/VO/LogNode.cs | 2,666 | C# |
using System.Collections.Generic;
namespace edu.tum.cs.conqat.dotnet {
public class Target {
}
public class SomeClass
{
public List<Target> someMethod()
{
return new List<Target>();
}
}
public class Source {
public void Caller() {
SomeClass x = new SomeClass();
List<Target> y = x.someMethod();
}
}
} | 18.041667 | 45 | 0.501155 | [
"Apache-2.0"
] | assessorgeneral/ConQAT | org.conqat.engine.dotnet/test-data/org.conqat.engine.dotnet.ila.scenario/genericReturnType.cs | 433 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.ROS20150901.Models
{
public class DescribeResourceDetailResponse : TeaModel {
[NameInMap("headers")]
[Validation(Required=true)]
public Dictionary<string, string> Headers { get; set; }
}
}
| 20.210526 | 63 | 0.700521 | [
"Apache-2.0"
] | alibabacloud-sdk-swift/alibabacloud-sdk | ros-20150901/csharp/core/Models/DescribeResourceDetailResponse.cs | 384 | C# |
using EnterpriseServerless.FunctionApp.Abstractions.Interfaces;
using EnterpriseServerless.FunctionApp.Abstractions.Models;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using static EnterpriseServerless.FunctionApp.Abstractions.Constants.Constants;
namespace EnterpriseServerless.FunctionApp.Services
{
public class CallLoggingService : ICallLoggingService
{
private CosmosClient _cosmosClient;
private readonly ILogger<CallLoggingService> _logger;
private readonly IConfigurationRoot _configuration;
private static readonly JsonSerializer Serializer = new JsonSerializer();
private readonly int _checkMinuteInterval;
private readonly int _callLogDayRetension;
public CallLoggingService(
CosmosClient cosmosClient,
ILogger<CallLoggingService> log,
IConfigurationRoot configuration)
{
_cosmosClient = cosmosClient;
_logger = log;
_configuration = configuration;
_checkMinuteInterval = int.Parse(_configuration["Twilio-CheckMinuteInterval"] ?? "90");
_callLogDayRetension = int.Parse(_configuration["Twilio-CallLogDayRetension"] ?? "15");
}
public async Task CreateCallLogAsync(CallLog item)
{
_logger.LogInformation($"Creating CallLog for callSid: '{item.callSid}'");
var container = _cosmosClient.GetContainer(CosmosDb.DatabaseId, CosmosDb.CallLogCollection);
using (Stream stream = ToStream<CallLog>(item))
{
using (ResponseMessage responseMessage = await container.CreateItemStreamAsync(stream, new PartitionKey(item.callSid)))
{
// Item stream operations do not throw exceptions for better performance
if (responseMessage.IsSuccessStatusCode)
{
CallLog streamResponse = FromStream<CallLog>(responseMessage.Content);
_logger.LogInformation($"CallLog id: '{streamResponse.id}' created successfully");
#if DEBUG
_logger.LogDebug($"INSERT Diagnostics for CreateCallLogAsync: {responseMessage.Diagnostics}");
#endif
}
else
{
_logger.LogError($"Failed to create CallLog for callSid: '{item.id}' from stream. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}");
}
}
}
}
public async Task UpdateCallLogAsync(string callSid)
{
_logger.LogInformation($"Updating CallLog for callSid: '{callSid}'");
try
{
var container = _cosmosClient.GetContainer(CosmosDb.DatabaseId, CosmosDb.CallLogCollection);
// Read the item to see if it exists. Note ReadItemAsync will not throw an exception if an item does not exist. Instead, we check the StatusCode property off the response object.
ItemResponse<CallLog> response = await container.ReadItemAsync<CallLog>(
id: callSid,
partitionKey: new PartitionKey(callSid));
#if DEBUG
if (response.Diagnostics != null)
{
_logger.LogDebug($"READ Diagnostics for UpdateCallLogAsync for callSid: '{callSid}': {response.Diagnostics}");
}
#endif
if (response.StatusCode == HttpStatusCode.NotFound)
{
_logger.LogDebug("CallLog details for '{0}' not found", callSid);
return;
}
var callLog = (CallLog)response;
callLog.endTime = DateTime.UtcNow;
callLog.lastUpdateDate = DateTime.UtcNow;
// Save document
response = await container.UpsertItemAsync(partitionKey: new PartitionKey(callLog.callSid), item: callLog);
callLog = response.Resource;
_logger.LogInformation($"Updated CallLog for callSid: '{callLog.callSid}'. StatusCode of this operation: {response.StatusCode}");
#if DEBUG
_logger.LogDebug($"UPSERT Diagnostics for UpdateCallLogAsync for callSid: '{callSid}': {response.Diagnostics}");
#endif
}
catch (CosmosException ex)
{
_logger.LogError(ex, $"UpdateCallLogAsync error for callSid: '{callSid}'");
throw;
}
}
public async Task<ICollection<CallLog>> GetCallLogsAsync()
{
try
{
var container = _cosmosClient.GetContainer(CosmosDb.DatabaseId, CosmosDb.CallLogCollection);
// Cosmos DB queries are case sensitive.
var query = @$"
SELECT TOP 100 *
FROM c
WHERE c.ttl = -1
AND c.startTime < @dateInterval
";
var dateInterval = $"{DateTime.UtcNow.AddMinutes(-_checkMinuteInterval)}";
QueryDefinition queryDefinition = new QueryDefinition(query)
.WithParameter("@dateInterval", dateInterval);
List<CallLog> results = new List<CallLog>();
FeedIterator<CallLog> resultSetIterator = container.GetItemQueryIterator<CallLog>(queryDefinition);
while (resultSetIterator.HasMoreResults)
{
FeedResponse<CallLog> response = await resultSetIterator.ReadNextAsync();
results.AddRange(response);
#if DEBUG
if (response.Diagnostics != null)
{
Console.WriteLine($"\nQueryWithSqlParameters diagnostics: {response.Diagnostics}");
}
#endif
}
if (results.Any())
{
_logger.LogInformation($"Call logs to process: {results.Count}");
}
return results;
}
catch (CosmosException ex)
{
_logger.LogError(ex, $"GetCallLogsAsync error");
throw;
}
}
public async Task DeleteCallLogAsync(string callSid)
{
_logger.LogInformation($"Deleting callSid: '{callSid}'");
try
{
var container = _cosmosClient.GetContainer(CosmosDb.DatabaseId, CosmosDb.CallLogCollection);
// Read the item to see if it exists. Note ReadItemAsync will not throw an exception if an item does not exist. Instead, we check the StatusCode property off the response object.
ItemResponse<CallLog> response = await container.ReadItemAsync<CallLog>(
id: callSid,
partitionKey: new PartitionKey(callSid));
#if DEBUG
if (response.Diagnostics != null)
{
_logger.LogDebug($"READ Diagnostics for DeleteCallLogAsync for callSid: '{callSid}': {response.Diagnostics}");
}
#endif
var callLog = (CallLog)response;
callLog.lastUpdateDate = DateTime.UtcNow;
callLog.ttl = 60 * 60 * 24 * _callLogDayRetension;
// Save document
response = await container.UpsertItemAsync(partitionKey: new PartitionKey(callLog.callSid), item: callLog);
callLog = response.Resource;
_logger.LogInformation($"Updated CallLog for callSid: '{callLog.callSid}', enabled TTL for {_callLogDayRetension} days. StatusCode of this operation: {response.StatusCode}");
}
catch (CosmosException ex)
{
_logger.LogError(ex, $"DeleteCallLogAsync error for callSid: '{callSid}'");
throw;
}
}
private static T FromStream<T>(Stream stream)
{
using (stream)
{
if (typeof(Stream).IsAssignableFrom(typeof(T)))
{
return (T)(object)stream;
}
using (StreamReader sr = new StreamReader(stream))
{
using (JsonTextReader jsonTextReader = new JsonTextReader(sr))
{
return Serializer.Deserialize<T>(jsonTextReader);
}
}
}
}
private static Stream ToStream<T>(T input)
{
MemoryStream streamPayload = new MemoryStream();
using (StreamWriter streamWriter = new StreamWriter(streamPayload, encoding: Encoding.Default, bufferSize: 1024, leaveOpen: true))
{
using (JsonWriter writer = new JsonTextWriter(streamWriter))
{
writer.Formatting = Newtonsoft.Json.Formatting.None;
Serializer.Serialize(writer, input);
writer.Flush();
streamWriter.Flush();
}
}
streamPayload.Position = 0;
return streamPayload;
}
}
}
| 40.383621 | 198 | 0.581812 | [
"MIT"
] | calloncampbell/Enterprise-Serverless-Demo | EnterpriseServerless.FunctionApp/Services/CallLoggingService.cs | 9,371 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LayoutTool.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LayoutTool.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon LayoutTool {
get {
object obj = ResourceManager.GetObject("LayoutTool", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
}
}
| 42.797297 | 176 | 0.602779 | [
"MIT"
] | jackobo/jackobs-code | LayoutTool/src/LayoutTool.DEV/Properties/Resources.Designer.cs | 3,169 | C# |
using MikuMikuWorld.Assets;
using OpenTK;
using OpenTK.Graphics;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MikuMikuWorld
{
class BGDrawer
{
public Texture2D Texture { get; set; }
public TransitColor Color { get; private set; }
public Vector2 Speed { get; set; } = Vector2.One;
private Vector2 offset;
public BGDrawer(Texture2D tex)
{
Texture = tex;
Color = new TransitColor(Color4.White);
}
public void Update(double deltaTime)
{
Color.Update(deltaTime);
offset += Speed * (float)deltaTime;
offset.X = MMWMath.Repeat(offset.X, 0.0f, Texture.Size.Width);
offset.Y = MMWMath.Repeat(offset.Y, 0.0f, Texture.Size.Height);
}
public void Draw(double deltaTime)
{
for (var y = -1; y < MMW.ClientSize.Height / Texture.Size.Height + 2; y++)
{
for (var x = -1; x < MMW.ClientSize.Width / Texture.Size.Width + 2; x++)
{
//Drawer.DrawTexturePixeled(Texture, offset.X + (Texture.Size.Width * x), offset.Y + (Texture.Size.Height * y), Color.Now);
Drawer.DrawTexturePixeledAlignment(Texture, ContentAlignment.TopLeft, offset.X + (Texture.Size.Width * x), offset.Y + (Texture.Size.Height * y), Color.Now);
/*
Drawer.DrawTexture(
Texture,
new RectangleF(0, 0, 1, 1),
new RectangleF(offset.X + (Texture.Size.Width * x), offset.Y + (Texture.Size.Height * y), Texture.Size.Width, Texture.Size.Height),
Color.Now,
Vector3.Zero,
Vector2.One,
Vector2.One * 0.5f);
*/
}
}
}
}
}
| 33.533333 | 176 | 0.52833 | [
"BSD-3-Clause"
] | yoship1639/MikuMikuWorld | MikuMikuWorld_Walker/BGDrawer.cs | 2,014 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
namespace ICSharpCode.CodeQualityAnalysis
{
public interface INode
{
string Name { get; }
IDependency Dependency { get; }
string GetInfo();
Relationship GetRelationship(INode node);
BitmapSource Icon { get; }
}
}
| 25.857143 | 103 | 0.760589 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | src/AddIns/Analysis/CodeQuality/Old/Src/INode.cs | 545 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatement), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementNotStatementStatementSqliMatchStatement")]
public interface IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatement
{
/// <summary>text_transformation block.</summary>
[JsiiProperty(name: "textTransformation", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformation\"},\"kind\":\"array\"}}")]
aws.IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformation[] TextTransformation
{
get;
}
/// <summary>field_to_match block.</summary>
[JsiiProperty(name: "fieldToMatch", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementFieldToMatch\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementFieldToMatch[]? FieldToMatch
{
get
{
return null;
}
}
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatement), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementNotStatementStatementSqliMatchStatement")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatement
{
private _Proxy(ByRefValue reference): base(reference)
{
}
/// <summary>text_transformation block.</summary>
[JsiiProperty(name: "textTransformation", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformation\"},\"kind\":\"array\"}}")]
public aws.IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformation[] TextTransformation
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformation[]>()!;
}
/// <summary>field_to_match block.</summary>
[JsiiOptional]
[JsiiProperty(name: "fieldToMatch", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementFieldToMatch\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementFieldToMatch[]? FieldToMatch
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatementFieldToMatch[]?>();
}
}
}
}
| 56.730769 | 227 | 0.715593 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2WebAclRuleStatementNotStatementStatementSqliMatchStatement.cs | 2,950 | C# |
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(HPSettings))]
public class HPSettingsInspector : Editor
{
private HPSettings settings;
public void OnEnable()
{
settings = (HPSettings)target;
}
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField("General", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Respawn HP Cost: ");
settings.respawnHPCost = EditorGUILayout.FloatField(settings.respawnHPCost);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Max Speed Reduction: ");
settings.maxSpeedReduction = EditorGUILayout.FloatField(settings.maxSpeedReduction);
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Collision", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Minimum Impact Force: ");
settings.minImpactForce = EditorGUILayout.FloatField(settings.minImpactForce);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Impact Damage Multiplier: ");
settings.impactDamageMultiplier = EditorGUILayout.FloatField(settings.impactDamageMultiplier);
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Items", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Missile Damage: ");
settings.missileDamage = EditorGUILayout.FloatField(settings.missileDamage);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Poison Damage (Per Second): ");
settings.poisonDamage = EditorGUILayout.FloatField(settings.poisonDamage);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Health Regeneration: ");
settings.healthRegeneration = EditorGUILayout.FloatField(settings.healthRegeneration);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Shield Regeneration (Per Second): ");
settings.shieldRegeneration = EditorGUILayout.FloatField(settings.shieldRegeneration);
EditorGUILayout.EndHorizontal();
}
}
| 37.734375 | 102 | 0.724224 | [
"MIT"
] | kidshenlong/warpspeed | Project Files/Assets/Scripts/Editor/HPSettingsInspector.cs | 2,415 | C# |
using System;
namespace EdnaExcelConfigUtils
{
public class VariableTime
{
public int? YearsOffset { get; set; }
public int? MonthsOffset { get; set; }
public int? DaysOffset { get; set; }
public int? HoursOffset { get; set; }
public int? MinutesOffset { get; set; }
public int? SecondsOffset { get; set; }
public DateTime AbsoluteTime { get; set; } = DateTime.Now;
public VariableTime()
{
}
public VariableTime(int? yearsOffset, int? monthsOffset, int? daysOffset, int? hoursOffset, int? minutesOffset, int? secondsOffset, DateTime absoluteTime)
{
YearsOffset = yearsOffset;
MonthsOffset = monthsOffset;
DaysOffset = daysOffset;
HoursOffset = hoursOffset;
MinutesOffset = minutesOffset;
SecondsOffset = secondsOffset;
AbsoluteTime = absoluteTime;
}
internal VariableTime Clone()
{
VariableTime variableTime = new VariableTime
{
YearsOffset = YearsOffset,
MonthsOffset = MonthsOffset,
DaysOffset = DaysOffset,
HoursOffset = HoursOffset,
MinutesOffset = MinutesOffset,
SecondsOffset = SecondsOffset,
AbsoluteTime = AbsoluteTime
};
return variableTime;
}
public DateTime GetTime()
{
DateTime absTime = AbsoluteTime;
DateTime nowTime = DateTime.Now;
// Make millisecond component as zero for the absolute time and now time
absTime = absTime.AddMilliseconds(-1 * absTime.Millisecond);
nowTime = nowTime.AddMilliseconds(-1 * nowTime.Millisecond);
DateTime resultTime = nowTime;
// Add offsets to current time as per the settings
if (YearsOffset.HasValue)
{
resultTime = resultTime.AddYears(YearsOffset.Value);
}
if (MonthsOffset.HasValue)
{
resultTime = resultTime.AddMonths(MonthsOffset.Value);
}
if (DaysOffset.HasValue)
{
resultTime = resultTime.AddDays(DaysOffset.Value);
}
if (HoursOffset.HasValue)
{
resultTime = resultTime.AddHours(HoursOffset.Value);
}
if (MinutesOffset.HasValue)
{
resultTime = resultTime.AddMinutes(MinutesOffset.Value);
}
if (SecondsOffset.HasValue)
{
resultTime = resultTime.AddSeconds(SecondsOffset.Value);
}
// Set absolute time settings to the result time
if (!YearsOffset.HasValue)
{
resultTime = resultTime.AddYears(absTime.Year - resultTime.Year);
}
if (!MonthsOffset.HasValue)
{
resultTime = resultTime.AddMonths(absTime.Month - resultTime.Month);
}
if (!DaysOffset.HasValue)
{
resultTime = resultTime.AddDays(absTime.Day - resultTime.Day);
}
if (!HoursOffset.HasValue)
{
resultTime = resultTime.AddHours(absTime.Hour - resultTime.Hour);
}
if (!MinutesOffset.HasValue)
{
resultTime = resultTime.AddMinutes(absTime.Minute - resultTime.Minute);
}
if (!SecondsOffset.HasValue)
{
resultTime = resultTime.AddSeconds(absTime.Second - resultTime.Second);
}
return resultTime;
}
}
}
| 33.837838 | 162 | 0.539936 | [
"MIT"
] | nagasudhirpulla/edna_chunks_dump_script | src/EdnaExcelConfigUtils/VariableTime.cs | 3,758 | C# |
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DncZeus.Api.Entities
{
public class SystemLog
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]//添加时自动增长
public int Id { get; set; }
public string Application { get; set; }
public string Levels { get; set; }
public string Operatingtime { get; set; }
public string Operatingaddress { get; set; }
public string Logger { get; set; }
public string Callsite { get; set; }
public string Requesturl { get; set; }
public string Referrerurl { get; set; }
public string Action { get; set; }
public string Message { get; set; }
public string Exception { get; set; }
}
}
| 32.2 | 70 | 0.632298 | [
"MIT"
] | zhangbao138208/financeAndpersonnel | DncZeus.Api/Entities/SystemLog.cs | 821 | C# |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
/**
* Test whether block ciphers implement reset contract on init, encrypt/decrypt and reset.
*/
[TestFixture]
public class StreamCipherResetTest
: SimpleTest
{
public override string Name
{
get { return "Stream Cipher Reset"; }
}
public override void PerformTest()
{
TestReset(typeof(Salsa20Engine), 32, 8);
TestReset(typeof(Salsa20Engine), 16, 8);
TestReset(typeof(XSalsa20Engine), 32, 24);
TestReset(typeof(ChaChaEngine), 32, 8);
TestReset(typeof(ChaChaEngine), 16, 8);
TestReset(typeof(RC4Engine), 16);
TestReset(typeof(IsaacEngine), 16);
TestReset(typeof(HC128Engine), 16, 16);
TestReset(typeof(HC256Engine), 16, 16);
//TestReset(typeof(Grainv1Engine), 16, 8);
//TestReset(typeof(Grain128Engine), 16, 12);
}
private static readonly SecureRandom RAND = new SecureRandom();
private static byte[] Random(int size)
{
return SecureRandom.GetNextBytes(RAND, size);
}
private IStreamCipher Make(Type sct)
{
return (IStreamCipher)Activator.CreateInstance(sct);
}
private void TestReset(Type sct, int keyLen)
{
TestReset(Make(sct), Make(sct), new KeyParameter(Random(keyLen)));
}
private void TestReset(Type sct, int keyLen, int ivLen)
{
TestReset(Make(sct), Make(sct), new ParametersWithIV(new KeyParameter(Random(keyLen)), Random(ivLen)));
}
private void TestReset(IStreamCipher cipher1, IStreamCipher cipher2, ICipherParameters cipherParams)
{
cipher1.Init(true, cipherParams);
byte[] plaintext = new byte[1023];
byte[] ciphertext = new byte[plaintext.Length];
// Establish baseline answer
cipher1.ProcessBytes(plaintext, 0, plaintext.Length, ciphertext, 0);
// Test encryption resets
CheckReset(cipher1, cipherParams, true, plaintext, ciphertext);
// Test decryption resets with fresh instance
cipher2.Init(false, cipherParams);
CheckReset(cipher2, cipherParams, false, ciphertext, plaintext);
}
private void CheckReset(IStreamCipher cipher, ICipherParameters cipherParams,
bool encrypt, byte[] pretext, byte[] posttext)
{
// Do initial run
byte[] output = new byte[posttext.Length];
cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0);
// Check encrypt resets cipher
cipher.Init(encrypt, cipherParams);
try
{
cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0);
}
catch (Exception e)
{
Fail(cipher.AlgorithmName + " init did not reset: " + e.Message);
}
if (!Arrays.AreEqual(output, posttext))
{
Fail(cipher.AlgorithmName + " init did not reset.", Hex.ToHexString(posttext), Hex.ToHexString(output));
}
// Check reset resets data
cipher.Reset();
try
{
cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0);
}
catch (Exception e)
{
Fail(cipher.AlgorithmName + " reset did not reset: " + e.Message);
}
if (!Arrays.AreEqual(output, posttext))
{
Fail(cipher.AlgorithmName + " reset did not reset.");
}
}
public static void Main(string[] args)
{
RunTest(new StreamCipherResetTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| 31.962963 | 120 | 0.573581 | [
"MIT"
] | 63l06ri5/bc-csharp | crypto/test/src/crypto/test/StreamCipherResetTest.cs | 4,317 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
// [START dialogflow_v3_generated_TransitionRouteGroups_DeleteTransitionRouteGroup_sync_flattened_resourceNames]
using Google.Cloud.Dialogflow.Cx.V3;
public sealed partial class GeneratedTransitionRouteGroupsClientSnippets
{
/// <summary>Snippet for DeleteTransitionRouteGroup</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void DeleteTransitionRouteGroupResourceNames()
{
// Create client
TransitionRouteGroupsClient transitionRouteGroupsClient = TransitionRouteGroupsClient.Create();
// Initialize request argument(s)
TransitionRouteGroupName name = TransitionRouteGroupName.FromProjectLocationAgentFlowTransitionRouteGroup("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[TRANSITION_ROUTE_GROUP]");
// Make the request
transitionRouteGroupsClient.DeleteTransitionRouteGroup(name);
}
}
// [END dialogflow_v3_generated_TransitionRouteGroups_DeleteTransitionRouteGroup_sync_flattened_resourceNames]
}
| 45.829268 | 194 | 0.734965 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Dialogflow.Cx.V3/Google.Cloud.Dialogflow.Cx.V3.GeneratedSnippets/TransitionRouteGroupsClient.DeleteTransitionRouteGroupResourceNamesSnippet.g.cs | 1,879 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal partial class Matcher<T>
{
private class SingleMatcher : Matcher<T>
{
private readonly Func<T, bool> _predicate;
private readonly string _description;
public SingleMatcher(Func<T, bool> predicate, string description)
{
_predicate = predicate;
_description = description;
}
public override bool TryMatch(IList<T> sequence, ref int index)
{
if (index < sequence.Count && _predicate(sequence[index]))
{
index++;
return true;
}
return false;
}
public override string ToString() => _description;
}
}
}
| 28.842105 | 77 | 0.570255 | [
"MIT"
] | belav/roslyn | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SingleMatcher.cs | 1,098 | C# |
namespace Lab_17_Northwind_Tests_Code_First
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class NorthwindModel : DbContext
{
public NorthwindModel()
: base("name=NorthwindModel2")
{
}
public virtual DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.Property(e => e.CustomerID)
.IsFixedLength();
}
}
}
| 24.8 | 76 | 0.614516 | [
"MIT"
] | philanderson888/2019-11-c-sharp-labs | Labs/Lab_17_Northwind_Tests_Code_First/NorthwindModel.cs | 620 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using GSF.Diagnostics;
using GSF.IO;
using GSF.Security.Authentication;
using GSF.Snap.Services;
using NUnit.Framework;
namespace GSF.Security
{
[TestFixture]
public class SecureStream_Test
{
public NullToken T;
Stopwatch m_sw = new Stopwatch();
//[Test]
//public void Test1()
//{
// m_sw.Reset();
// var net = new NetworkStreamSimulator();
// var sa = new SecureStreamServer<NullToken>();
// sa.Srp.Users.AddUser("user1","password");
// ThreadPool.QueueUserWorkItem(Client1, net.ClientStream);
// SecureStream stream;
// sa.TryAuthenticateAsServer(net.ServerStream, out stream, out T);
// sa.TryAuthenticateAsServer(net.ServerStream, out stream, out T);
// Thread.Sleep(100);
//}
//void Client1(object state)
//{
// Stream client = (Stream)state;
// var sa = new SecureStreamClientSrp("user1", "password");
// m_sw.Start();
// sa.TryAuthenticate(client);
// m_sw.Stop();
// System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
// m_sw.Restart();
// sa.TryAuthenticate(client);
// m_sw.Stop();
// System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
//}
//[Test]
//public void TestRepeat()
//{
// for (int x = 0; x < 5; x++)
// Test1();
//}
//[Test]
//public void Default()
//{
// for (int x = 0; x < 5; x++)
// TestDefault();
//}
[Test]
public void TestDefault()
{
Logger.Console.Verbose = VerboseLevel.All;
m_sw.Reset();
var net = new NetworkStreamSimulator();
var sa = new SecureStreamServer<NullToken>();
sa.SetDefaultUser(true, new NullToken());
ThreadPool.QueueUserWorkItem(ClientDefault, net.ClientStream);
Stream stream;
if (!sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T))
{
throw new Exception();
}
stream.Write("Message");
stream.Flush();
if (stream.ReadString() != "Response")
throw new Exception();
stream.Dispose();
Thread.Sleep(100);
}
void ClientDefault(object state)
{
Stream client = (Stream)state;
var sa = new SecureStreamClientDefault();
Stream stream;
if (!sa.TryAuthenticate(client, true, out stream))
{
throw new Exception();
}
if (stream.ReadString() != "Message")
throw new Exception();
stream.Write("Response");
stream.Flush();
stream.Dispose();
}
[Test]
public void BenchmarkDefault()
{
for (int x = 0; x < 5; x++)
TestBenchmarkDefault();
}
[Test]
public void TestBenchmarkDefault()
{
Logger.Console.Verbose = VerboseLevel.All;
m_sw.Reset();
var net = new NetworkStreamSimulator();
var sa = new SecureStreamServer<NullToken>();
sa.SetDefaultUser(true, new NullToken());
ThreadPool.QueueUserWorkItem(ClientBenchmarkDefault, net.ClientStream);
Stream stream;
sa.TryAuthenticateAsServer(net.ServerStream, false, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, false, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, false, out stream, out T);
Thread.Sleep(100);
}
void ClientBenchmarkDefault(object state)
{
Stream client = (Stream)state;
var sa = new SecureStreamClientDefault();
m_sw.Start();
sa.TryAuthenticate(client, false);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client, false);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client, false);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
}
[Test]
public void TestBenchmarkIntegrated()
{
return;
Logger.Console.Verbose = VerboseLevel.All;
m_sw.Reset();
var net = new NetworkStreamSimulator();
var sa = new SecureStreamServer<NullToken>();
sa.AddUserIntegratedSecurity("Zthe\\steven", new NullToken());
ThreadPool.QueueUserWorkItem(ClientBenchmarkIntegrated, net.ClientStream);
Stream stream;
sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T);
sa.TryAuthenticateAsServer(net.ServerStream, true, out stream, out T);
Thread.Sleep(100);
}
void ClientBenchmarkIntegrated(object state)
{
Stream client = (Stream)state;
var sa = new SecureStreamClientIntegratedSecurity();
m_sw.Start();
sa.TryAuthenticate(client);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
m_sw.Restart();
sa.TryAuthenticate(client);
m_sw.Stop();
System.Console.WriteLine(m_sw.Elapsed.TotalMilliseconds);
}
[Test]
public void TestRepeatIntegrated()
{
for (int x = 0; x < 5; x++)
TestBenchmarkIntegrated();
}
}
}
| 30.833333 | 87 | 0.549688 | [
"MIT"
] | BarkingCactii/OpenHistorian_Noja | Source/Libraries/Tests/GSF.SortedTreeStore.Test/Security/SecureStream_Test.cs | 7,217 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 4.0.1
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace QuantLib {
public class FloatingRateBond : Bond {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
private bool swigCMemOwnDerived;
internal FloatingRateBond(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.FloatingRateBond_SWIGSmartPtrUpcast(cPtr), true) {
swigCMemOwnDerived = cMemoryOwn;
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(FloatingRateBond obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
protected override void Dispose(bool disposing) {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwnDerived) {
swigCMemOwnDerived = false;
NQuantLibcPINVOKE.delete_FloatingRateBond(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
base.Dispose(disposing);
}
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays, DoubleVector gearings, DoubleVector spreads, DoubleVector caps, DoubleVector floors, bool inArrears, double redemption, Date issueDate) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_0(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays, DoubleVector.getCPtr(gearings), DoubleVector.getCPtr(spreads), DoubleVector.getCPtr(caps), DoubleVector.getCPtr(floors), inArrears, redemption, Date.getCPtr(issueDate)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays, DoubleVector gearings, DoubleVector spreads, DoubleVector caps, DoubleVector floors, bool inArrears, double redemption) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_1(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays, DoubleVector.getCPtr(gearings), DoubleVector.getCPtr(spreads), DoubleVector.getCPtr(caps), DoubleVector.getCPtr(floors), inArrears, redemption), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays, DoubleVector gearings, DoubleVector spreads, DoubleVector caps, DoubleVector floors, bool inArrears) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_2(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays, DoubleVector.getCPtr(gearings), DoubleVector.getCPtr(spreads), DoubleVector.getCPtr(caps), DoubleVector.getCPtr(floors), inArrears), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays, DoubleVector gearings, DoubleVector spreads, DoubleVector caps, DoubleVector floors) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_3(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays, DoubleVector.getCPtr(gearings), DoubleVector.getCPtr(spreads), DoubleVector.getCPtr(caps), DoubleVector.getCPtr(floors)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays, DoubleVector gearings, DoubleVector spreads, DoubleVector caps) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_4(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays, DoubleVector.getCPtr(gearings), DoubleVector.getCPtr(spreads), DoubleVector.getCPtr(caps)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays, DoubleVector gearings, DoubleVector spreads) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_5(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays, DoubleVector.getCPtr(gearings), DoubleVector.getCPtr(spreads)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays, DoubleVector gearings) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_6(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays, DoubleVector.getCPtr(gearings)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, uint fixingDays) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_7(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, fixingDays), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_8(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public FloatingRateBond(uint settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter) : this(NQuantLibcPINVOKE.new_FloatingRateBond__SWIG_9(settlementDays, faceAmount, Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
}
}
| 98.365854 | 715 | 0.798413 | [
"Apache-2.0"
] | andrew-stakiwicz-r3/financial_derivatives_demo | quantlib_swig_bindings/CSharp/csharp/FloatingRateBond.cs | 8,066 | C# |
using Jaeger.Samplers;
using Jaeger.Senders;
using Jaeger.Senders.Thrift;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenTracing;
using OpenTracing.Util;
namespace Jaeger.Example.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// Use "OpenTracing.Contrib.NetCore" to automatically generate spans for ASP.NET Core, Entity Framework Core, ...
// See https://github.com/opentracing-contrib/csharp-netcore for details.
services.AddOpenTracing();
// Adds the Jaeger Tracer.
services.AddSingleton<ITracer>(serviceProvider =>
{
var serviceName = serviceProvider.GetRequiredService<IWebHostEnvironment>().ApplicationName;
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
// This is necessary to pick the correct sender, otherwise a NoopSender is used!
Jaeger.Configuration.SenderConfiguration.DefaultSenderResolver = new SenderResolver(loggerFactory)
.RegisterSenderFactory<ThriftSenderFactory>();
// This will log to a default localhost installation of Jaeger.
var tracer = new Tracer.Builder(serviceName)
.WithLoggerFactory(loggerFactory)
.WithSampler(new ConstSampler(true))
.Build();
// Allows code that can't use DI to also access the tracer.
GlobalTracer.Register(tracer);
return tracer;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
} | 37.8 | 143 | 0.631041 | [
"Apache-2.0"
] | Chatham/LetsTrace | examples/Jaeger.Example.WebApi/Startup.cs | 2,837 | C# |
using System;
using System.Runtime.Serialization;
using System.Security.Cryptography;
namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration
{
/// <summary>
/// Manages an RSA key for the agent using the most appropriate store for the target platform.
/// </summary>
[ServiceLocator(
PreferredOnWindows = typeof(RSAEncryptedFileKeyManager),
Default = typeof(RSAFileKeyManager)
)]
public interface IRSAKeyManager : IAgentService
{
/// <summary>
/// Creates a new <c>RSACryptoServiceProvider</c> instance for the current agent. If a key file is found then the current
/// key is returned to the caller.
/// </summary>
/// <returns>An <c>RSACryptoServiceProvider</c> instance representing the key for the agent</returns>
RSACryptoServiceProvider CreateKey();
/// <summary>
/// Deletes the RSA key managed by the key manager.
/// </summary>
void DeleteKey();
/// <summary>
/// Gets the <c>RSACryptoServiceProvider</c> instance currently stored by the key manager.
/// </summary>
/// <returns>An <c>RSACryptoServiceProvider</c> instance representing the key for the agent</returns>
/// <exception cref="CryptographicException">No key exists in the store</exception>
RSACryptoServiceProvider GetKey();
}
// Newtonsoft 10 is not working properly with dotnet RSAParameters class
// RSAParameters has fields marked as [NonSerialized] which cause we loss those fields after serialize to JSON
// https://github.com/JamesNK/Newtonsoft.Json/issues/1517
// https://github.com/dotnet/corefx/issues/23847
// As workaround, we create our own RSAParameters class without any [NonSerialized] attributes.
[Serializable]
internal class RSAParametersSerializable : ISerializable
{
private RSAParameters _rsaParameters;
public RSAParameters RSAParameters
{
get
{
return _rsaParameters;
}
}
public RSAParametersSerializable(RSAParameters rsaParameters)
{
_rsaParameters = rsaParameters;
}
private RSAParametersSerializable()
{
}
public byte[] D { get { return _rsaParameters.D; } set { _rsaParameters.D = value; } }
public byte[] DP { get { return _rsaParameters.DP; } set { _rsaParameters.DP = value; } }
public byte[] DQ { get { return _rsaParameters.DQ; } set { _rsaParameters.DQ = value; } }
public byte[] Exponent { get { return _rsaParameters.Exponent; } set { _rsaParameters.Exponent = value; } }
public byte[] InverseQ { get { return _rsaParameters.InverseQ; } set { _rsaParameters.InverseQ = value; } }
public byte[] Modulus { get { return _rsaParameters.Modulus; } set { _rsaParameters.Modulus = value; } }
public byte[] P { get { return _rsaParameters.P; } set { _rsaParameters.P = value; } }
public byte[] Q { get { return _rsaParameters.Q; } set { _rsaParameters.Q = value; } }
public RSAParametersSerializable(SerializationInfo information, StreamingContext context)
{
_rsaParameters = new RSAParameters()
{
D = (byte[])information.GetValue("d", typeof(byte[])),
DP = (byte[])information.GetValue("dp", typeof(byte[])),
DQ = (byte[])information.GetValue("dq", typeof(byte[])),
Exponent = (byte[])information.GetValue("exponent", typeof(byte[])),
InverseQ = (byte[])information.GetValue("inverseQ", typeof(byte[])),
Modulus = (byte[])information.GetValue("modulus", typeof(byte[])),
P = (byte[])information.GetValue("p", typeof(byte[])),
Q = (byte[])information.GetValue("q", typeof(byte[]))
};
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("d", _rsaParameters.D);
info.AddValue("dp", _rsaParameters.DP);
info.AddValue("dq", _rsaParameters.DQ);
info.AddValue("exponent", _rsaParameters.Exponent);
info.AddValue("inverseQ", _rsaParameters.InverseQ);
info.AddValue("modulus", _rsaParameters.Modulus);
info.AddValue("p", _rsaParameters.P);
info.AddValue("q", _rsaParameters.Q);
}
}
}
| 41.878505 | 129 | 0.626423 | [
"MIT"
] | Loovax/azure-pipelines-agent | src/Agent.Listener/Configuration/IRSAKeyManager.cs | 4,483 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using JetBrains.Annotations;
using PornSearch.Tests.Enums;
using Xunit;
namespace PornSearch.Tests.Asserts
{
public static class PornVideoThumbAssert
{
[AssertionMethod]
public static void Check_NbVideo_ByPage(int nbVideo, PornSearchFilter searchFilter, PageSearch pageSearch) {
PornWebsite website = searchFilter.Website;
string filter = searchFilter.Filter;
int page = searchFilter.Page;
string description = $"{website}, '{filter}', {page}, {searchFilter.SexOrientation}";
int[] nbVideoMax = GetNbVideoMaxByPage(website, filter, page, pageSearch);
switch (pageSearch) {
case PageSearch.Empty:
Assert.True(0 == nbVideo, $"Value = 0, Value: {nbVideo} - {description}");
break;
case PageSearch.Complete:
// If for Pornhub the search filter is empty, Channel Id may be empty if the video is not available in your country
int tolerance = website == PornWebsite.Pornhub && string.IsNullOrWhiteSpace(filter) ? 2 : 0;
Assert.True(nbVideo >= nbVideoMax[0] - tolerance,
$"Value >= {nbVideoMax[0] - tolerance}, Value: {nbVideo} - {description}");
Assert.True(nbVideo <= nbVideoMax[1], $"Value <= {nbVideoMax[1]}, Value: {nbVideo} - {description}");
break;
case PageSearch.Channel:
Assert.True(nbVideo >= 0, $"Value >= 0, Value: {nbVideo} - {description}");
Assert.True(nbVideo <= nbVideoMax[1], $"Value <= {nbVideoMax[1]}, Value: {nbVideo} - {description}");
break;
case PageSearch.Partial:
Assert.True(nbVideo > 0, $"Value > 0, Value: {nbVideo} - {description}");
Assert.True(nbVideo <= nbVideoMax[1], $"Value <= {nbVideoMax[1]}, Value: {nbVideo} - {description}");
break;
default: throw new ArgumentOutOfRangeException(nameof(pageSearch), pageSearch, null);
}
}
public static int[] GetNbVideoMaxByPage(PornWebsite website, string filter, int page, PageSearch pageSearch) {
if (website == PornWebsite.Pornhub) {
if (string.IsNullOrWhiteSpace(filter))
return page == 1 ? new[] { 32, 32 } : new[] { 44, 44 };
if (pageSearch == PageSearch.Channel && page == 1)
return new[] { 22, 22 };
return new[] { 20, 20 };
}
if (website == PornWebsite.XVideos)
return string.IsNullOrWhiteSpace(filter) && page == 1 ? new[] { 46, 48 } : new[] { 25, 27 };
throw new NotImplementedException();
}
[AssertionMethod]
public static void CheckAll(List<PornVideoThumb> videosThumbs, PornWebsite website, string filter,
PornSexOrientation sexOrientation) {
Assert.NotNull(videosThumbs);
foreach (PornVideoThumb videoThumb in videosThumbs)
Assert_VideoThumb(videoThumb, website, sexOrientation);
Assert_All_Unique_Value(videosThumbs, website, filter, sexOrientation);
Assert_All_Not_Same_Value(videosThumbs);
}
[AssertionMethod]
private static void Assert_VideoThumb(PornVideoThumb videoThumb, PornWebsite website, PornSexOrientation sexOrientation) {
Assert.NotNull(videoThumb);
Assert.Equal(website, videoThumb.Website);
Assert.Equal(sexOrientation, videoThumb.SexOrientation);
Assert_VideoThumb_Id(videoThumb.Id, website);
Assert_VideoThumb_Title(videoThumb.Title);
Assert.NotNull(videoThumb.Channel);
Assert_VideoThumb_Channel_Id(videoThumb.Channel.Id, website);
Assert_VideoThumb_Channel_Name(videoThumb.Channel.Name);
Assert_VideoThumb_ThumbnailUrl(videoThumb.ThumbnailUrl, website);
Assert_VideoThumb_PageUrl(videoThumb.PageUrl, website);
Assert_VideoThumb_Link_Id_PageUrl(videoThumb.Id, videoThumb.PageUrl, website);
Assert_VideoThumb_Not_Same_Value(videoThumb);
}
[AssertionMethod]
private static void Assert_VideoThumb_Id(string id, PornWebsite website) {
Assert.NotNull(id);
switch (website) {
case PornWebsite.Pornhub:
Assert.Matches("^(ph[0-9a-f]{13}|[0-9]{5,10}|[a-f0-9]{20})$", id);
break;
case PornWebsite.XVideos:
Assert.Matches("^[0-9]{4,8}$", id);
break;
default: throw new ArgumentOutOfRangeException(nameof(website), website, null);
}
}
private static void Assert_VideoThumb_Title(string title) {
Assert.NotNull(title);
Assert.NotEqual("", title.Trim());
Assert.Equal(HttpUtility.HtmlDecode(title), title);
Assert.DoesNotContain("\u00A0", title);
}
[AssertionMethod]
private static void Assert_VideoThumb_Channel_Id(string channelId, PornWebsite website) {
Assert.NotNull(channelId);
switch (website) {
case PornWebsite.Pornhub:
Assert.Matches("^/(channels|model|pornstar|users)/[^/\\s]*$", channelId);
break;
case PornWebsite.XVideos:
Assert.Matches("^/[^/\\s]*$", channelId);
break;
default: throw new ArgumentOutOfRangeException(nameof(website), website, null);
}
}
private static void Assert_VideoThumb_Channel_Name(string channelName) {
Assert.NotNull(channelName);
Assert.NotEqual("", channelName.Trim());
Assert.Equal(HttpUtility.HtmlDecode(channelName), channelName);
}
[AssertionMethod]
private static void Assert_VideoThumb_ThumbnailUrl(string thumbnailUrl, PornWebsite website) {
Assert.NotNull(thumbnailUrl);
switch (website) {
case PornWebsite.Pornhub:
Assert.Matches("^https://[bcde]i[.]phncdn[.]com/videos[^\\s]*[.]jpg$", thumbnailUrl);
break;
case PornWebsite.XVideos:
Assert.Matches("^http(s)?://(cdn77-pic|img-l3|img-hw)[.]xvideos-cdn[.]com/videos(_new)*/thumbs[^\\s.]*?[.][0-9]+[.]jpg$",
thumbnailUrl);
break;
default: throw new ArgumentOutOfRangeException(nameof(website), website, null);
}
}
[AssertionMethod]
private static void Assert_VideoThumb_PageUrl(string pageUrl, PornWebsite website) {
Assert.NotNull(pageUrl);
switch (website) {
case PornWebsite.Pornhub:
Assert.Matches("^https://www[.]pornhub[.]com/view_video[.]php[?]viewkey=(ph[0-9a-f]{13}|[0-9]{5,10}|[a-f0-9]{20})$",
pageUrl);
break;
case PornWebsite.XVideos:
Assert.Matches("^https://www[.]xvideos[.]com/video[0-9]{4,8}/[^\\s]+$", pageUrl);
break;
default: throw new ArgumentOutOfRangeException(nameof(website), website, null);
}
}
[AssertionMethod]
private static void Assert_VideoThumb_Link_Id_PageUrl(string id, string pageUrl, PornWebsite website) {
switch (website) {
case PornWebsite.Pornhub:
Assert.Equal($"https://www.pornhub.com/view_video.php?viewkey={id}", pageUrl);
break;
case PornWebsite.XVideos:
Assert.StartsWith($"https://www.xvideos.com/video{id}/", pageUrl);
break;
default: throw new ArgumentOutOfRangeException(nameof(website), website, null);
}
}
private static void Assert_VideoThumb_Not_Same_Value(PornVideoThumb videoThumb) {
Assert_All_Not_Same_Value(new List<PornVideoThumb> { videoThumb });
}
private static void Assert_All_Not_Same_Value(List<PornVideoThumb> videoThumbs) {
foreach (PornVideoThumb videoThumb in videoThumbs) {
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Id == i.Title));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Id == i.Channel.Id));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Id == i.Channel.Name));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Id == i.ThumbnailUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Id == i.PageUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Title == i.Channel.Id));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Title == i.ThumbnailUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Title == i.PageUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Channel.Id == i.Channel.Name));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Channel.Id == i.ThumbnailUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Channel.Id == i.PageUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Channel.Name == i.ThumbnailUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.Channel.Name == i.PageUrl));
Assert.Equal(0, videoThumbs.Count(i => videoThumb.ThumbnailUrl == i.PageUrl));
}
}
public static void Check_All_Unique_Value_ByPage(List<PornVideoThumb> videoThumbs) {
Assert.NotNull(videoThumbs);
Assert_All_Unique_Value(videoThumbs, true);
}
private static void Assert_All_Unique_Value(List<PornVideoThumb> videoThumbs, PornWebsite website, string filter,
PornSexOrientation sexOrientation) {
bool uniqueValue = true;
if (website == PornWebsite.Pornhub) {
// If you search for gay videos with the empty search filter, too many videos can be on multiple pages (e.g. on pages 1 and 2)
bool notGay = sexOrientation != PornSexOrientation.Gay;
bool gaySearchNotEmpty = sexOrientation == PornSexOrientation.Gay && !string.IsNullOrWhiteSpace(filter);
uniqueValue = notGay || gaySearchNotEmpty;
}
Assert_All_Unique_Value(videoThumbs, uniqueValue);
}
private static void Assert_All_Unique_Value(List<PornVideoThumb> videoThumbs, bool uniqueValue) {
if (uniqueValue) {
const int tolerance = 2;
Assert.True(videoThumbs.Count - videoThumbs.Select(i => i.Id).Distinct().Count() <= tolerance);
Assert.True(videoThumbs.Count - videoThumbs.Select(i => i.ThumbnailUrl).Distinct().Count() <= tolerance);
Assert.True(videoThumbs.Count - videoThumbs.Select(i => i.PageUrl).Distinct().Count() <= tolerance);
}
Assert.Equal(videoThumbs.Select(i => i.Channel.Id).Distinct().Count(),
videoThumbs.Select(i => $"{i.Channel.Id} {i.Channel.Name}").Distinct().Count());
}
public static void Equal(PornVideoThumb videoThumb1, PornVideoThumb videoThumb2) {
Assert.NotNull(videoThumb1);
Assert.NotNull(videoThumb2);
Assert.Equal(videoThumb1.Website, videoThumb2.Website);
Assert.Equal(videoThumb1.SexOrientation, videoThumb2.SexOrientation);
Assert.Equal(videoThumb1.Id, videoThumb2.Id);
Assert.Equal(videoThumb1.Title, videoThumb2.Title);
Assert.Equal(videoThumb1.Channel.Id, videoThumb2.Channel.Id);
Assert.Equal(videoThumb1.Channel.Name, videoThumb2.Channel.Name);
switch (videoThumb1.Website) {
case PornWebsite.Pornhub: {
// The 9th character can change value
const string pattern = "^https://.(.*)$";
Assert.Equal(Regex.Replace(videoThumb1.ThumbnailUrl, pattern, "$1"),
Regex.Replace(videoThumb2.ThumbnailUrl, pattern, "$1"));
break;
}
case PornWebsite.XVideos: {
// The first subdomain and end of url can change value
const string pattern = "^http(s)?://[^.]*[.](.*?)[.][0-9]+[.]jpg$";
Assert.Equal(Regex.Replace(videoThumb1.ThumbnailUrl, pattern, "$2").Replace("-1", ""),
Regex.Replace(videoThumb2.ThumbnailUrl, pattern, "$2").Replace("-1", ""));
break;
}
default:
Assert.Equal(videoThumb1.ThumbnailUrl, videoThumb2.ThumbnailUrl);
break;
}
Assert.Equal(videoThumb1.PageUrl, videoThumb2.PageUrl);
}
}
}
| 52.562992 | 142 | 0.579282 | [
"MIT"
] | Crash8/PornSearch | src/PornSearch.Tests/Asserts/PornVideoThumbAssert.cs | 13,351 | C# |
using System.IO;
namespace BeatSaberMarkupLanguage.Animations.APNG.Chunks
{
/// <summary>
/// Animation Control chunk.
/// </summary>
internal class acTLChunk : Chunk
{
private uint frameCount;
private uint playCount;
/// <summary>
/// Initializes a new instance of the <see cref="acTLChunk"/> class.
/// </summary>
internal acTLChunk()
{
Length = 8;
ChunkType = "acTL";
ChunkData = new byte[Length];
}
/// <summary>
/// Initializes a new instance of the <see cref="acTLChunk"/> class.
/// </summary>
/// <param name="bytes">Byte array of chunk data.</param>
public acTLChunk(byte[] bytes)
: base(bytes)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="acTLChunk"/> class.
/// </summary>
/// <param name="ms">Memory stream of chunk data.</param>
public acTLChunk(MemoryStream ms)
: base(ms)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="acTLChunk"/> class.
/// </summary>
/// <param name="chunk">Chunk object.</param>
public acTLChunk(Chunk chunk)
: base(chunk)
{
}
/// <summary>
/// Gets the number frames.
/// </summary>
/// <value>The number frames.</value>
public uint FrameCount
{
get => frameCount;
internal set
{
frameCount = value;
ModifyChunkData(0, Helper.ConvertEndian(value));
}
}
/// <summary>
/// Gets the number plays.
/// </summary>
/// <value>The number plays.</value>
public uint PlayCount
{
get => playCount;
internal set
{
playCount = value;
ModifyChunkData(4, Helper.ConvertEndian(value));
}
}
/// <summary>
/// Parses the data.
/// </summary>
/// <param name="ms">Memory stream to parse.</param>
protected override void ParseData(MemoryStream ms)
{
frameCount = Helper.ConvertEndian(ms.ReadUInt32());
playCount = Helper.ConvertEndian(ms.ReadUInt32());
}
}
} | 27.409091 | 76 | 0.491294 | [
"MIT"
] | Auros/BeatSaberMarkupLanguage | BeatSaberMarkupLanguage/Animations/APNG/Chunks/acTLChunk.cs | 2,414 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
// [START compute_v1_generated_MachineImages_List_sync]
using Google.Api.Gax;
using Google.Cloud.Compute.V1;
using System;
public sealed partial class GeneratedMachineImagesClientSnippets
{
/// <summary>Snippet for List</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListRequestObject()
{
// Create client
MachineImagesClient machineImagesClient = MachineImagesClient.Create();
// Initialize request argument(s)
ListMachineImagesRequest request = new ListMachineImagesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<MachineImageList, MachineImage> response = machineImagesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (MachineImage item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (MachineImageList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MachineImage item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MachineImage> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MachineImage item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
// [END compute_v1_generated_MachineImages_List_sync]
}
| 39.679012 | 120 | 0.611388 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/MachineImagesClient.ListRequestObjectSnippet.g.cs | 3,214 | C# |
namespace MySharpSupport
{
using System;
using System.Reflection;
using LeagueSharp;
using LeagueSharp.Common;
using MySharpSupport.Util;
using Version = System.Version;
internal class Program
{
public static Version Version;
private static void Main(string[] args)
{
Version = Assembly.GetExecutingAssembly().GetName().Version;
CustomEvents.Game.OnGameLoad += a =>
{
try
{
//Load AI
AI.Init.DoInitWithDelay();
var type = Type.GetType("MySharpSupport.Plugins." + ObjectManager.Player.ChampionName);
if (type != null)
{
Protector.Init();
//SpellDetector.Init();
DynamicInitializer.NewInstance(type);
return;
}
Helpers.PrintMessage(ObjectManager.Player.ChampionName + " not supported");
}
catch (Exception e)
{
Console.WriteLine(e);
}
};
//Utils.EnableConsoleEditMode();
//Drawing.OnDraw += a =>
//{
// var offset = 0;
// foreach (var buff in ObjectManager.Player.Buffs)
// {
// Drawing.DrawText(100, 100 + offset, Color.Tomato,
// string.Format("{0} | {1} | {2} | {3} | {4} | {5} | {6}", buff.Name, buff.DisplayName,
// buff.Type.ToString(), buff.Count, buff.IsActive, buff.StartTime, buff.EndTime));
// offset += 15;
// }
//};
//Obj_AI_Base.OnProcessSpellCast += (sender, spell) =>
//{
// if (!sender.IsValid<Obj_AI_Hero>())
// {
// return;
// }
// try
// {
// if (!Orbwalking.IsAutoAttack(spell.SData.Name))
// {
// var text = string.Format(
// "{0};{1};{2};{3};{4};{5};{6};{7};{8}{9}\n", Environment.TickCount, sender.BaseSkinName,
// spell.SData.Name, spell.SData.CastRadius[0], spell.SData.CastRange[0],
// spell.SData.CastRangeDisplayOverride[0], spell.SData.LineWidth, spell.SData.MissileSpeed,
// spell.SData.SpellCastTime, spell.SData.SpellTotalTime);
// File.AppendAllText("D:/OnProcessSpellCast-" + Game.Id + ".csv", text);
// }
// }
// catch (Exception e)
// {
// Console.WriteLine(e);
// }
//};
//GameObject.OnCreate += (sender, eventArgs) =>
//{
// if (!sender.IsValid<Obj_SpellMissile>())
// {
// return;
// }
// try
// {
// var miss = (Obj_SpellMissile) sender;
// if (!miss.SpellCaster.IsValid<Obj_AI_Hero>())
// {
// return;
// }
// var text = string.Format(
// "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};{10}\n", Environment.TickCount, miss.Type, miss.Name,
// miss.SData.Name, miss.SData.CastRadius[0], miss.SData.CastRange[0],
// miss.SData.CastRangeDisplayOverride[0], miss.SData.LineWidth, miss.SData.MissileSpeed,
// miss.SData.SpellCastTime, miss.SData.SpellTotalTime);
// File.AppendAllText("D:/Obj_SpellMissile-" + Game.Id + ".csv", text);
// }
// catch (Exception e)
// {
// Console.WriteLine(e);
// }
//};
}
}
} | 36.147826 | 120 | 0.410392 | [
"MIT"
] | toannatkm0/LOZ | MySharpSupport/Program.cs | 4,159 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d10misc.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.DirectX;
namespace TerraFX.Interop.Windows;
public static partial class GUID
{
[NativeTypeName("const GUID")]
public static ref readonly Guid GUID_DeviceType
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ReadOnlySpan<byte> data = new byte[] {
0x4D, 0xFB, 0x22, 0xD7,
0x68, 0x7A,
0x7A, 0x43,
0xB2,
0x0C,
0x58,
0x04,
0xEE,
0x24,
0x94,
0xA6
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
}
| 28.926829 | 145 | 0.593592 | [
"MIT"
] | FalsePattern/jwin32 | cs_guid_definitions/sources/Interop/Windows/DirectX/um/d3d10misc/GUID.cs | 1,188 | C# |
using UnityEngine;
public class SVGGEllipse : ISVGPathSegment {
private readonly Vector2 p;
private readonly float r1;
private readonly float r2;
private readonly float angle;
public SVGGEllipse(Vector2 p, float r1, float r2, float angle) {
this.p = p;
this.r1 = r1;
this.r2 = r2;
this.angle = angle;
}
public void ExpandBounds(SVGGraphicsPath path) {
path.ExpandBounds(p, r1, r2);
}
public bool Render(SVGGraphicsPath path, ISVGPathDraw pathDraw) {
pathDraw.EllipseTo(path.matrixTransform.Transform(p), r1, r2, path.transformAngle + angle);
return true;
}
}
| 24.44 | 95 | 0.703764 | [
"BSD-3-Clause"
] | MrJoy/UnitySVG | Assets/UnitySVG/Implementation/RenderingEngine/BasicType/SVGGEllipse.cs | 611 | C# |
using System;
using CoreBluetooth;
namespace Shiny.BluetoothLE.Peripherals
{
public class Peripheral : IPeripheral
{
public Peripheral(CBCentral central)
{
this.Central = central;
this.Uuid = new Guid(central.Identifier.ToString());
}
public Guid Uuid { get; }
public CBCentral Central { get; }
public object Context { get; set; }
}
} | 21.15 | 64 | 0.600473 | [
"MIT"
] | DanielCauser/shiny | src/Shiny.BluetoothLE/Peripherals/Platforms/ios+macos/Peripheral.cs | 425 | C# |
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace UnityGLTF.Loader
{
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}
public class FileDownloader : IDataLoader
{
private readonly string filesroot;
private readonly Uri baseAddress;
public string query;
public FileDownloader(string uri, string downloadedFilesroot)
{
filesroot = downloadedFilesroot;
baseAddress = new Uri(uri);
}
public async Task<Stream> LoadStreamAsync(string gltfFilePath)
{
MyWebClient client = new MyWebClient();
Uri uri = new Uri(baseAddress, gltfFilePath + query);
string file = Path.Combine(filesroot, URIHelper.GetFileFromUri(uri));
client.DownloadFileAsync(uri, file);
return File.OpenRead(file);
}
}
}
| 29.7 | 102 | 0.642256 | [
"Apache-2.0"
] | Gfi-Innovation/UMI3D-Desktop-Browser | UMI3D-Browser-Desktop/Assets/UMI3D SDK/Dependencies/Runtime/IntegrationGltf/FileDownloader.cs | 1,190 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayCommerceOperationTimescardRefundApplyModel Data Structure.
/// </summary>
[Serializable]
public class AlipayCommerceOperationTimescardRefundApplyModel : AopObject
{
/// <summary>
/// 次卡id
/// </summary>
[XmlElement("card_id")]
public string CardId { get; set; }
/// <summary>
/// 场景码
/// </summary>
[XmlElement("scene_code")]
public string SceneCode { get; set; }
/// <summary>
/// 用户id
/// </summary>
[XmlElement("user_id")]
public string UserId { get; set; }
}
}
| 23 | 77 | 0.5554 | [
"Apache-2.0"
] | alipay/alipay-sdk-net | AlipaySDKNet.Standard/Domain/AlipayCommerceOperationTimescardRefundApplyModel.cs | 727 | C# |
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Octolamp.Frontend.Hubs
{
public class NotificationHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
| 20.315789 | 73 | 0.69171 | [
"MIT"
] | MoimHossain/linkerd-demo | src/Octolamp.Frontend/Hubs/NotificationHub.cs | 388 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Diagnostics;
namespace System.Xml.Xsl.Qil
{
/// <summary>
/// View over a Qil StrConcat operator.
/// </summary>
/// <remarks>
/// Don't construct QIL nodes directly; instead, use the <see cref="QilFactory">QilFactory</see>.
/// </remarks>
internal class QilStrConcat : QilBinary
{
//-----------------------------------------------
// Constructor
//-----------------------------------------------
/// <summary>
/// Construct a new node
/// </summary>
public QilStrConcat(QilNodeType nodeType, QilNode delimiter, QilNode values) : base(nodeType, delimiter, values)
{
}
//-----------------------------------------------
// QilStrConcat methods
//-----------------------------------------------
/// <summary>
/// A string delimiter to insert between successive values of the concatenation
/// </summary>
public QilNode Delimiter
{
get { return Left; }
set { Left = value; }
}
/// <summary>
/// List of values to concatenate
/// </summary>
public QilNode Values
{
get { return Right; }
set { Right = value; }
}
}
}
| 27.830189 | 120 | 0.477288 | [
"MIT"
] | IEvangelist/runtime | src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilStrConcat.cs | 1,475 | C# |
using System;
using System.Collections.Generic;
using Bit.Client.Web.BlazorUI.Playground.Web.Pages.Components.ComponentDemoBase;
namespace Bit.Client.Web.BlazorUI.Playground.Web.Pages.Components.Modal
{
public partial class BitModalDemo
{
private bool IsOpen = false;
private readonly List<ComponentParameter> componentParameters = new()
{
new ComponentParameter()
{
Name = "ChildContent",
Type = "RenderFragment",
DefaultValue = "",
Description = "The content of Modal, It can be Any custom tag or a text.",
},
new ComponentParameter()
{
Name = "IsAlert",
Type = "bool?",
DefaultValue = "",
Description = "Determines the ARIA role of the dialog (alertdialog/dialog). If this is set, it will override the ARIA role determined by IsBlocking and IsModeless.",
},
new ComponentParameter()
{
Name = "IsBlocking",
Type = "bool",
DefaultValue = "false",
Description = "Whether the dialog can be light dismissed by clicking outside the dialog (on the overlay).",
},
new ComponentParameter()
{
Name = "IsModeless",
Type = "bool",
DefaultValue = "false",
Description = "Whether the dialog should be modeless (e.g. not dismiss when focusing/clicking outside of the dialog). if true: IsBlocking is ignored, there will be no overlay.",
},
new ComponentParameter()
{
Name = "IsOpen",
Type = "bool",
DefaultValue = "false",
Description = "Whether the dialog is displayed.",
},
new ComponentParameter()
{
Name = "OnDismiss",
Type = "EventCallback<MouseEventArgs>",
DefaultValue = "",
Description = "A callback function for when the Modal is dismissed light dismiss, before the animation completes.",
},
new ComponentParameter()
{
Name = "SubtitleAriaId",
Type = "string",
DefaultValue = "",
Description = "ARIA id for the subtitle of the Modal, if any.",
},
new ComponentParameter()
{
Name = "TitleAriaId",
Type = "string",
DefaultValue = "",
Description = "ARIA id for the title of the Modal, if any.",
},
};
private readonly string modalSampleCode = $"<BitButton OnClick=@(()=>IsOpen=true)>Open Modal</BitButton>{Environment.NewLine}" +
$"<BitModal @bind-IsOpen=IsOpen>{Environment.NewLine}" +
$"<div class='modal-header'>{Environment.NewLine}" +
$"<span>Lorem Ipsum</span>{Environment.NewLine}" +
$"<BitIconButton OnClick=@(()=>IsOpen=false) IconName='BitIcon.ChromeClose' Title='Close' />{Environment.NewLine}" +
$"</div>{Environment.NewLine}" +
$"<div class='modal-body'>{Environment.NewLine}" +
$"<p>{Environment.NewLine}" +
$"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas lorem nulla, malesuada ut sagittis sitamet, vulputate in leo.Maecenas vulputate congue sapien eu tincidunt.Etiam eu sem turpis.Fusce temporsagittis nunc, ut interdum ipsum vestibulum non." +
$"Proin dolor elit, aliquam eget tincidunt non, vestibulum ut turpis.In hac habitasse platea dictumst.In a odio eget enim porttitor maximus.Aliquam nulla nibh,ullamcorper aliquam placerat eu, viverra et dui.Phasellus ex lectus, maximus in mollis ac, luctus vel eros." +
$"Vivamus ultrices, turpis sed malesuada gravida, eros ipsum venenatis elit, et volutpat eros dui et ante. Quisque ultricies mi nec leo ultricies mollis.Vivamus egestas volutpat lacinia. Quisque pharetra eleifend fficitur.{ Environment.NewLine}" +
$"</p>{Environment.NewLine}" +
$"<p>{Environment.NewLine}" +
$"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas lorem nulla, malesuada ut sagittis sitamet, vulputate in leo.Maecenas vulputate congue sapien eu tincidunt.Etiam eu sem turpis.Fusce temporsagittis nunc, ut interdum ipsum vestibulum non." +
$"Proin dolor elit, aliquam eget tincidunt non, vestibulum ut turpis.In hac habitasse platea dictumst.In a odio eget enim porttitor maximus.Aliquam nulla nibh,ullamcorper aliquam placerat eu, viverra et dui.Phasellus ex lectus, maximus in mollis ac, luctus vel eros." +
$"Vivamus ultrices, turpis sed malesuada gravida, eros ipsum venenatis elit, et volutpat eros dui et ante. Quisque ultricies mi nec leo ultricies mollis.Vivamus egestas volutpat lacinia. Quisque pharetra eleifend fficitur.{ Environment.NewLine}" +
$"</p>{Environment.NewLine}" +
$"<p>{Environment.NewLine}" +
$"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas lorem nulla, malesuada ut sagittis sitamet, vulputate in leo.Maecenas vulputate congue sapien eu tincidunt.Etiam eu sem turpis.Fusce temporsagittis nunc, ut interdum ipsum vestibulum non." +
$"Proin dolor elit, aliquam eget tincidunt non, vestibulum ut turpis.In hac habitasse platea dictumst.In a odio eget enim porttitor maximus.Aliquam nulla nibh,ullamcorper aliquam placerat eu, viverra et dui.Phasellus ex lectus, maximus in mollis ac, luctus vel eros." +
$"Vivamus ultrices, turpis sed malesuada gravida, eros ipsum venenatis elit, et volutpat eros dui et ante. Quisque ultricies mi nec leo ultricies mollis.Vivamus egestas volutpat lacinia. Quisque pharetra eleifend fficitur.{ Environment.NewLine}" +
$"</p>{Environment.NewLine}" +
$"<p>{Environment.NewLine}" +
$"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas lorem nulla, malesuada ut sagittis sitamet, vulputate in leo.Maecenas vulputate congue sapien eu tincidunt.Etiam eu sem turpis.Fusce temporsagittis nunc, ut interdum ipsum vestibulum non." +
$"Proin dolor elit, aliquam eget tincidunt non, vestibulum ut turpis.In hac habitasse platea dictumst.In a odio eget enim porttitor maximus.Aliquam nulla nibh,ullamcorper aliquam placerat eu, viverra et dui.Phasellus ex lectus, maximus in mollis ac, luctus vel eros." +
$"Vivamus ultrices, turpis sed malesuada gravida, eros ipsum venenatis elit, et volutpat eros dui et ante. Quisque ultricies mi nec leo ultricies mollis.Vivamus egestas volutpat lacinia. Quisque pharetra eleifend fficitur.{ Environment.NewLine}" +
$"</p>{Environment.NewLine}" +
$"<p>{Environment.NewLine}" +
$"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas lorem nulla, malesuada ut sagittis sitamet, vulputate in leo.Maecenas vulputate congue sapien eu tincidunt.Etiam eu sem turpis.Fusce temporsagittis nunc, ut interdum ipsum vestibulum non." +
$"Proin dolor elit, aliquam eget tincidunt non, vestibulum ut turpis.In hac habitasse platea dictumst.In a odio eget enim porttitor maximus.Aliquam nulla nibh,ullamcorper aliquam placerat eu, viverra et dui.Phasellus ex lectus, maximus in mollis ac, luctus vel eros." +
$"Vivamus ultrices, turpis sed malesuada gravida, eros ipsum venenatis elit, et volutpat eros dui et ante. Quisque ultricies mi nec leo ultricies mollis.Vivamus egestas volutpat lacinia. Quisque pharetra eleifend fficitur.{ Environment.NewLine}" +
$"</p>{Environment.NewLine}" +
$"</div>{Environment.NewLine}" +
$"</BitModal>{Environment.NewLine}" +
$"<style>{Environment.NewLine}" +
$".modal-header {{ {Environment.NewLine}" +
$"display: flex;{Environment.NewLine}" +
$"align-items: center;{Environment.NewLine}" +
$"font-size: 24px;{Environment.NewLine}" +
$"font-weight: 600;{Environment.NewLine}" +
$"border-top: 4px solid #5C2D91;{Environment.NewLine}" +
$"justify-content: space-between;{Environment.NewLine}" +
$"padding: 12px 12px 14px 24px;{Environment.NewLine}" +
$"}} {Environment.NewLine}" +
$".modal-body {{ {Environment.NewLine}" +
$"overflow-y: hidden;{Environment.NewLine}" +
$"line-height: 20px;{Environment.NewLine}" +
$"padding: 0 24px 24px;{Environment.NewLine}" +
$"}} {Environment.NewLine}" +
$"</style>{Environment.NewLine}";
}
}
| 72.292683 | 283 | 0.633603 | [
"MIT"
] | Md23Mh/bitframework | src/Client/Web/Playground/Bit.Client.Web.BlazorUI.Playground/Web/Pages/Components/Modal/BitModalDemo.razor.cs | 8,894 | C# |
// MIT License
//
// Copyright(c) 2021 ICARUS Consulting GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System.Collections.Generic;
namespace Yaapii.Atoms.Func
{
/// <summary>
/// Chains functions together.
/// </summary>
/// <typeparam name="In"></typeparam>
/// <typeparam name="Between"></typeparam>
/// <typeparam name="Out"></typeparam>
public sealed class ChainedFunc<In, Between, Out> : IFunc<In, Out>
{
/// <summary>
/// first function
/// </summary>
private readonly IFunc<In, Between> _before;
/// <summary>
/// chained functions
/// </summary>
private readonly IEnumerable<IFunc<Between, Between>> _funcs;
/// <summary>
/// last function
/// </summary>
private readonly IFunc<Between, Out> _after;
/// <summary>
/// Chains functions together.
/// </summary>
/// <param name="before">first function</param>
/// <param name="after">last function</param>
public ChainedFunc(System.Func<In, Between> before, System.Func<Between, Out> after) : this(
new FuncOf<In, Between>(input => before(input)),
new List<IFunc<Between, Between>>(),
new FuncOf<Between, Out>((bet) => after(bet)))
{ }
/// <summary>
/// ctor
/// </summary>
/// <param name="before">first function</param>
/// <param name="after">last function</param>
public ChainedFunc(IFunc<In, Between> before, IFunc<Between, Out> after) : this(
before,
new List<IFunc<Between, Between>>(),
after)
{ }
/// <summary>
/// ctor
/// </summary>
/// <param name="before">first function</param>
/// <param name="funcs">functions to chain</param>
/// <param name="after">last function</param>
public ChainedFunc(System.Func<In, Between> before, IEnumerable<IFunc<Between, Between>> funcs, System.Func<Between, Out> after) : this(
new FuncOf<In, Between>(before),
funcs,
new FuncOf<Between, Out>(after))
{ }
/// <summary>
/// ctor
/// </summary>
/// <param name="before">first function</param>
/// <param name="funcs">functions to chain</param>
/// <param name="after">last function</param>
public ChainedFunc(System.Func<In, Between> before, IEnumerable<System.Func<Between, Between>> funcs, System.Func<Between, Out> after
) : this(
new FuncOf<In, Between>(before),
new Enumerable.Mapped<System.Func<Between, Between>, IFunc<Between, Between>>(
f => new FuncOf<Between, Between>(f),
funcs),
new FuncOf<Between, Out>(after))
{ }
/// <summary>
/// ctor
/// </summary>
/// <param name="before">first function</param>
/// <param name="funcs">functions to chain</param>
/// <param name="after">last function</param>
public ChainedFunc(
IFunc<In, Between> before,
IEnumerable<IFunc<Between, Between>> funcs,
IFunc<Between, Out> after
)
{
this._before = before;
this._funcs = funcs;
this._after = after;
}
/// <summary>
/// applys input to the chain
/// </summary>
/// <param name="input">input to apply</param>
/// <returns>output</returns>
public Out Invoke(In input)
{
Between temp = this._before.Invoke(input);
foreach (IFunc<Between, Between> func in this._funcs)
{
temp = func.Invoke(temp);
}
return this._after.Invoke(temp);
}
}
}
| 36.977444 | 144 | 0.582147 | [
"MIT"
] | icarus-consulting/Yaapii.Atoms | src/Yaapii.Atoms/Func/ChainedFunc.cs | 4,918 | C# |
using SkiaSharp;
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using TDNPGL.Core.Debug;
using TDNPGL.Core.Gameplay;
using TDNPGL.Core.Gameplay.Assets;
using TDNPGL.Core.Gameplay.Interfaces;
using TDNPGL.Core.Graphics;
using TDNPGL.Core.Graphics.Renderers;
namespace TDNPGL.Core
{
public class Game : IUpdateable
{
internal GameProvider provider;
public EntryPoint CurrentEntry;
public Level CurrentLevel { get; protected set; }
public GraphicsOutput GraphicsOutput { get; protected set; }
private Game(GameProvider provider, Assembly assetsAssembly, string gameName, bool enableCustomLogger) : this(
provider
,AssetLoader.GetEntry(assetsAssembly)
,gameName
,enableCustomLogger) { }
private Game(GameProvider provider, EntryPoint entry, string gameName, bool enableCustomLogger)
{
this.provider = provider;
CurrentPlatform = Environment.OSVersion.Platform;
this.GraphicsOutput = new GraphicsOutput(this);
if (enableCustomLogger)
Logging.SetCustomLogger();
GameName = gameName;
AssetsAssembly = entry.CurrentAssembly;
CurrentEntry = entry;
}
public string GameName{ get; set; } = "Unnamed";
public IParentable Parent { get => null; set {} }
public PlatformID CurrentPlatform;
public Assembly AssetsAssembly;
public void SetLevel(Level level)
{
CurrentLevel = level;
CurrentLevel.BeginUpdate();
CurrentLevel.ReloadObjectsIDs();
Logging.MessageAction("LEVEL", "Level setted: {0}", ConsoleColor.Green, ConsoleColor.Gray,CurrentLevel.Name);
}
public void Run()
{
GraphicsOutput.AddOutputGameRenderer(provider.Renderer);
Sprite.LoadSprites();
CurrentEntry.RunMainLevel();
Logging.MessageAction("RUN", "Loading objects...", ConsoleColor.Green, ConsoleColor.Gray);
while (true)
{
if (CurrentLevel.IsObjectsLoaded())
break;
Thread.Sleep(10);
}
GraphicsOutput.AddOutputGameRenderer(this.provider.Renderer);
Logging.MessageAction("RUN", "{0} is running platform", ConsoleColor.Green, ConsoleColor.Gray, Environment.OSVersion.ToString());
Logging.MessageAction("RUN", "{0} is game renderer size", ConsoleColor.Green, ConsoleColor.Gray, GetGameRendererSize(0));
GraphicsOutput.BeginRender();
current = this;
}
#region Static
private static Game current;
public SKSize GetGameRendererSize(int id)
{
SKSize size;
IGameRenderer renderer = GraphicsOutput.GetGameRenderers().ToArray()[id];
double height=renderer.RenderHeight;
double width= renderer.RenderWidth;
size = new SKSize((float)width, (float)height);
return size;
}
public static Game GetInstance()
{
return current;
}
#region Create
public static Game Create(GameProvider provider,Assembly assetsAssembly,string gameName,bool enableCustomLogger)
=> new Game(provider,assetsAssembly,gameName,enableCustomLogger);
public static Game Create(GameProvider provider, EntryPoint entry, string gameName, bool enableCustomLogger)
=> new Game(provider, entry, gameName, enableCustomLogger);
public static Game Create<EntryType>(GameProvider provider, string GameName, bool EnableCustomLogger) where EntryType : EntryPoint
=> Create(provider, Assembly.GetAssembly(typeof(EntryType)), GameName, EnableCustomLogger);
#endregion Create
#endregion Static
#region Events
public void OnTick() { }
public void OnStart() { }
public void OnFirstTick() { }
public void OnMouseReleasedOver(int button, SKPoint point) { }
void IUpdateable.OnKeyDown(ConsoleKeyInfo key)
{
try
{
foreach (GameObject obj in CurrentLevel.Objects)
{
obj.OnKeyDown(key);
}
}
catch (Exception ex)
{
Exceptions.Call(ex);
}
}
public void OnMouseReleased(int button, SKPoint point)
{
try
{
foreach (GameObject obj in CurrentLevel.Objects)
{
obj.OnMouseReleased(button, point);
}
}
catch (Exception ex)
{
Exceptions.Call(ex);
}
}
public void OnMouseMove(int button, SKPoint point)
{
try
{
foreach (GameObject obj in CurrentLevel.Objects)
{
obj.OnMouseMove(button, point);
}
}
catch (Exception ex)
{
Exceptions.Call(ex);
}
}
public void OnMouseDown(int button, SKPoint point)
{
try
{
foreach (GameObject obj in CurrentLevel.Objects)
{
obj.OnMouseDown(button, point);
}
}
catch (Exception ex)
{
Exceptions.Call(ex);
}
}
#endregion
}
}
| 34.088235 | 142 | 0.554098 | [
"Apache-2.0"
] | TDNPGL/TDNPGL | src/TDNPGL.Core/Game.cs | 5,797 | C# |
/*
swfOP is an open source library for manipulation and examination of
Macromedia Flash (SWF) ActionScript bytecode.
Copyright (C) 2004 Florian Krüsch.
see Licence.cs for LGPL full text!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System.IO;
using System;
namespace SwfOp.ByteCode.Actions
{
/// <summary>
/// bytecode instruction object
/// </summary>
public class ActionStringEquals : BaseAction {
/// <summary>
/// constructor
/// </summary>
public ActionStringEquals():base(ActionCode.StringEquals)
{
}
/// <see cref="SwfOp.ByteCode.Actions.BaseAction.PopCount"/>
public override int PopCount { get { return 2; } }
/// <see cref="SwfOp.ByteCode.Actions.BaseAction.PushCount"/>
public override int PushCount { get { return 1; } }
/// <summary>overriden ToString method</summary>
public override string ToString() {
return "string equals";
}
}
}
| 34.169811 | 78 | 0.638874 | [
"MIT"
] | Acidburn0zzz/flashdevelop | External/Tools/SwfOp/ByteCode/Actions/ActionStringEquals.cs | 1,762 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ColouredCoinVendingMachine.Models
{
public class ListingViewModel : Listing
{
public Int64 AmountForSale { get; set; }
}
} | 19.916667 | 48 | 0.728033 | [
"MIT"
] | bitcoinbrisbane/coloredcoinvendingmachine | src/ColouredCoinVendingMachine/Models/ListingViewModel.cs | 241 | C# |
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu (fileName = "New Unit", menuName = "Cards/Create New Unit"), System.Serializable]
public class UnitCard : Card
{
[Space (20)]
[SerializeField] int power;
[SerializeField] int health;
[SerializeField] int movementSpeed;
[SerializeField] int attackRange;
[Space (20)]
//Card Effects
[SerializeField] CardEffectTrigger[] cardEffects;
[SerializeField] CardEffectListener[] cardEffectListeners;
[Space (20)]
//Play Effect
[SerializeField] PlayAbility onPlayEffect;
[Space (20)]
//Actions
[SerializeField] List<ActionAbility> actions;
public int Power {get {return power;}}
public int Health {get {return health;}}
public int MovementSpeed {get {return movementSpeed;}}
public int AttackRange {get {return attackRange;}}
public CardEffectTrigger[] CardEffects {get {return cardEffects;}}
public CardEffectListener[] CardEffectListeners {get {return cardEffectListeners;}}
public PlayAbility OnPlayEffect {get {return onPlayEffect;}}
public List<ActionAbility> Actions {get {return actions;}}
}
| 35.631579 | 98 | 0.638848 | [
"MIT"
] | SKhorozian/TCG | TCG/Assets/_Scripts/Cards/CardTypes/UnitCard.cs | 1,354 | C# |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace Alphaleonis.Win32.Network
{
/// <summary>A set of bit flags that describe the permissions for the shared resource's on servers running with share-level security.</summary>
/// <remarks>Note that Windows does not support share-level security. This member is ignored on a server running user-level security.</remarks>
[Flags]
public enum AccessPermissions
{
/// <summary>No permissions.</summary>
None = 0,
/// <summary>ACCESS_READ
/// <para>Permission to read data from a resource and, by default, to execute the resource.</para>
/// </summary>
Read = 1,
/// <summary>ACCESS_WRITE
/// <para>Permission to write data to the resource.</para>
/// </summary>
Write = 2,
/// <summary>ACCESS_CREATE
/// <para>Permission to create an instance of the resource (such as a file); data can be written to the resource as the resource is created.</para>
/// </summary>
Create = 4,
/// <summary>ACCESS_EXEC
/// <para>Permission to execute the resource.</para>
/// </summary>
Execute = 8,
/// <summary>ACCESS_DELETE
/// <para>Permission to delete the resource.</para>
/// </summary>
Delete = 16,
/// <summary>ACCESS_ATRIB
/// <para>Permission to modify the resource's attributes, such as the date and time when a file was last modified.</para>
/// </summary>
Attributes = 32,
/// <summary>ACCESS_PERM
/// <para>Permission to modify the permissions (read, write, create, execute, and delete) assigned to a resource for a user or application.</para>
/// </summary>
Permissions = 64,
/// <summary>ACCESS_ALL
/// <para>Permission to read, write, create, execute, and delete resources, and to modify their attributes and permissions.</para>
/// </summary>
All = 32768
}
} | 41.864865 | 153 | 0.676566 | [
"MIT"
] | OpenDataSpace/AlphaFS | AlphaFS/Network/Enumerations/AccessPermissions.cs | 3,098 | C# |
using System;
namespace FontAwesome
{
/// <summary>
/// The unicode values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Unicode
{
/// <summary>
/// fa-layer-group unicode value ("\uf5fd").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/layer-group
/// </summary>
public const string LayerGroup = "\uf5fd";
}
/// <summary>
/// The Css values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Css
{
/// <summary>
/// LayerGroup unicode value ("fa-layer-group").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/layer-group
/// </summary>
public const string LayerGroup = "fa-layer-group";
}
/// <summary>
/// The Icon names for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Icon
{
/// <summary>
/// fa-layer-group unicode value ("\uf5fd").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/layer-group
/// </summary>
public const string LayerGroup = "LayerGroup";
}
} | 36.409836 | 154 | 0.594327 | [
"MIT"
] | michaelswells/FontAwesomeAttribute | FontAwesome/FontAwesome.LayerGroup.cs | 2,221 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodCollectionResponse.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type DirectoryObjectCheckMemberObjectsCollectionResponse.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class DirectoryObjectCheckMemberObjectsCollectionResponse
{
/// <summary>
/// Gets or sets the <see cref="IDirectoryObjectCheckMemberObjectsCollectionPage"/> value.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Required.Default)]
public IDirectoryObjectCheckMemberObjectsCollectionPage Value { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData(ReadData = true)]
public IDictionary<string, object> AdditionalData { get; set; }
}
}
| 40.8 | 153 | 0.619748 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/DirectoryObjectCheckMemberObjectsCollectionResponse.cs | 1,428 | C# |
using System.Linq;
using BotEngine.Motor;
using Sanderling.ABot.Bot.Task;
using Sanderling.Motor;
namespace Sanderling.ABot.Bot.Strategies
{
internal class ShipCheckingState : IStragegyState
{
private CheckShipTask task;
public IBotTask GetStateActions(Bot bot)
{
task = new CheckShipTask(bot.MemoryMeasurementAtTime?.Value, "Puller");
return task;
}
public IBotTask GetStateExitActions(Bot bot)
{
var fittingWindow = bot.MemoryMeasurementAtTime?.Value?.WindowShipFitting?.FirstOrDefault();
if (fittingWindow != null)
return bot.MemoryMeasurementAtTime?.Value?.Neocom?.FittingButton?.ClickTask();
return null;
}
public bool MoveToNext => task?.ShipNameFound ?? false;
}
} | 24.827586 | 95 | 0.748611 | [
"Apache-2.0"
] | Fulborg/A-Bot | src/Sanderling.ABot/Bot/Strategies/ShipCheckingState.cs | 722 | C# |
namespace MrCoto.BeanDiscoveryExample.Commands
{
public class TodoObject
{
}
}
| 13.142857 | 47 | 0.695652 | [
"MIT"
] | mrcoto/BeanDiscovery | BeanDiscoveryExample/Commands/TodoObject.cs | 94 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RateMap : MonoBehaviour
{
public static float Reward(HMapGen input, HMapGen wanted) {;
float actStep = 1f / ConstParameters.stepSqrt;
float ans = 0f;
for(int i = 0; i < ConstParameters.stepSqrt; i++) {
for(int j = 0; j < ConstParameters.stepSqrt; j++) {
float inputVal = input.GetValue(i * actStep, j * actStep);
float wantedVal = wanted.GetValue(i * actStep, j * actStep);
ans += Mathf.Abs(inputVal - wantedVal);
}
}
ans /= (float) ConstParameters.stepSqrt;
return ans;
}
public static float MSE(HMapGen input, HMapGen wanted) {
float actStep = 1f / ConstParameters.stepSqrt;
float ans = 0f;
for(int i = 0; i < ConstParameters.stepSqrt; i++) {
for(int j = 0; j < ConstParameters.stepSqrt; j++) {
float inputVal = Mathf.Max(0, input.GetValue(i * actStep, j *actStep));
float wantedVal = Mathf.Max(0, wanted.GetValue(i * actStep, j * actStep));
float diff = inputVal - wantedVal;
ans += diff * diff;
}
}
ans /= ConstParameters.stepSqrt * ConstParameters.stepSqrt;
return ans;
}
public static float MCReward(HMapGen input, HMapGen wanted) {
float end = Time.realtimeSinceStartup + ConstParameters.mcRewardDuration;
float ans = 0f;
int probNum = 0;
float current = Time.realtimeSinceStartup;
while(current < end) {
float randI = Random.Range(0f, 1f);
float randJ = Random.Range(0f, 1f);
float inputVal = input.GetValue(randI, randJ);
float wantedVal = wanted.GetValue(randI, randJ);
ans += Mathf.Abs(inputVal - wantedVal);
probNum++;
current = Time.realtimeSinceStartup;
}
ans /= (float) probNum;
return ans;
}
public static float DSSIM(HMapGen input, HMapGen wanted) {
float meanInput = 0f, meanWanted = 0f, varianceInput = 0f, varianceWanted = 0f, covariance = 0f;
float k1 = 0.01f, k2 = 0.03f, max = 150f;
float c1 = (max * k1) * (max * k1), c2 = (max * k2) * (max * k2);
float actStep = 1f / ConstParameters.stepSqrt;
meanInput = CountMean(input);
meanWanted = CountMean(wanted);
varianceInput = CountVariance(input, meanInput);
varianceWanted = CountVariance(wanted, meanWanted);
covariance = CountCoVariance(input, wanted, meanInput, meanWanted);
float nom = (2f * meanInput * meanWanted + c1) * (2f * covariance + c2);
float den = (meanInput * meanInput + meanWanted * meanWanted + c1) * (varianceInput * varianceInput + varianceWanted * varianceWanted + c2);
return (float) (1f - (nom / den)) / 2f;
}
private static float CountMean(HMapGen map) {
float actStep = 1f / ConstParameters.stepSqrt;
float mean = 0f;
for(int i = 0; i < ConstParameters.stepSqrt; i++) {
for(int j = 0; j < ConstParameters.stepSqrt; j++) {
float val = Mathf.Max(0,map.GetValue(i * actStep, j * actStep));
mean += val;
}
}
mean /= (float) ConstParameters.stepSqrt;
return mean;
}
private static float CountVariance(HMapGen map, float mean) {
float len = ConstParameters.stepSqrt - 1f;
float actStep = 1f / ConstParameters.stepSqrt;
float variance = 0f;
for(int i = 0; i < ConstParameters.stepSqrt; i++) {
for(int j = 0; j < ConstParameters.stepSqrt; j++) {
float val = Mathf.Max(0, map.GetValue(i * actStep, j *actStep));
variance += (val - mean) * (val - mean);
}
}
variance /= len;
return variance;
}
private static float CountCoVariance(HMapGen map1, HMapGen map2, float mean1, float mean2) {
float len = ConstParameters.stepSqrt - 1f;
float actStep = 1f / (float) ConstParameters.stepSqrt;
float covariance = 0f;
for(int i = 0; i < ConstParameters.stepSqrt-1; i++) {
for(int j = i+1; j < ConstParameters.stepSqrt; j++) {
float val1 = map1.GetValue(i * actStep, j *actStep);
float val2 = map2.GetValue(i * actStep, j * actStep);
covariance += (val1 - mean1) * (val2 - mean2);
}
}
covariance /= len;
return covariance;
}
public static float FitnessFunc(HMapGen input, HMapGen wanted) {
if(ConstParameters.useABS)
return Reward(input, wanted) * TreeDepthPenalty(input);
else if(ConstParameters.useMSE)
return MSE(input, wanted) * TreeDepthPenalty(input);
else if(ConstParameters.useMC)
return MCReward(input, wanted) * TreeDepthPenalty(input);
else if(ConstParameters.useDSSIM)
return DSSIM(input, wanted) * TreeDepthPenalty(input);
else //sanity check
return MSE(input, wanted) * TreeDepthPenalty(input);
}
public static float TreeDepthPenalty(HMapGen tree)
{
return 1 + TreeStructure.TreeDepth(tree) * ConstParameters.depthPenalty;
}
void Start() {
BinOpHMap map1 = TreeStructure.MakeRandomNode(2) as BinOpHMap;
BinOpHMap map3 = TreeStructure.MakeRandomNode(3) as BinOpHMap;
map1.SetRandomGenes();
map3.SetRandomGenes();
ElipseHMap el = new ElipseHMap();
el.SetRandomGenes();
/*
string ans1 = "", ans2 = "";
float[] gen1 = map1.GetGenes();
float[] gen2 = map2.GetGenes();
for(int i = 0; i < 3; i++) {
ans1 += gen1[i].ToString() + " ";
ans2 += gen2[i].ToString() + " ";
}
Debug.Log(ans1);
Debug.Log(ans2);
*/
Debug.Log("MSE: " + MSE(map1, map3));
Debug.Log("Reward: " + Reward(map1, map3));
Debug.Log("MC Reward: " + MCReward(map1, map3));
Debug.Log("DSSIM: " + DSSIM(map1, map3));
Debug.Log("DSSIM 0: " + DSSIM(map1, map1));
Debug.Log(map3.ToString());
// Debug.Log(map3.PrintGenes());
Debug.Log(map1.ToString());
// Debug.Log(map1.PrintGenes());
Debug.Log(map3.GetValue(0f, 0f));
Debug.Log(map1.GetValue(0f, 0f));
// float[] t = el.GetGenes();
// t[0] = 0f;
// t[1] = 0f;
// el.SetGenes(t);
// Debug.Log(el.PrintGenes());
// Debug.Log(el.GetValue(0f, 0f));
}
}
| 38.210227 | 148 | 0.562974 | [
"MIT"
] | KrzysiekSlawik/evolutionary-height-map-approximation | Assets/Scripts/AI/RateMap.cs | 6,727 | C# |
// Copyright © 2017-2020 Chromely Projects. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Chromely.Core.Network
{
public static class UrlSchemeCollectionExtension
{
public static bool IsUrlRegisteredExternalBrowserScheme(this List<UrlScheme> urlSchemes, string url)
{
if (urlSchemes == null ||
!urlSchemes.Any() ||
string.IsNullOrWhiteSpace(url))
return false;
return urlSchemes.Any((x => x.IsUrlOfSameScheme(url) && (x.UrlSchemeType == UrlSchemeType.ExternalBrowser)));
}
public static bool IsUrlRegisteredCommandScheme(this List<UrlScheme> urlSchemes, string url)
{
if (urlSchemes == null ||
!urlSchemes.Any() ||
string.IsNullOrWhiteSpace(url))
return false;
return urlSchemes.Any((x => x.IsUrlOfSameScheme(url) && (x.UrlSchemeType == UrlSchemeType.Command)));
}
public static bool IsUrlRegisteredLocalRequestScheme(this List<UrlScheme> urlSchemes, string url)
{
if (urlSchemes == null ||
!urlSchemes.Any() ||
string.IsNullOrWhiteSpace(url))
return false;
return urlSchemes.Any((x => x.IsUrlOfSameScheme(url) && (x.UrlSchemeType == UrlSchemeType.LocalRequest)));
}
public static bool IsUrlRegisteredExternalRequestScheme(this List<UrlScheme> urlSchemes, string url)
{
if (urlSchemes == null ||
!urlSchemes.Any() ||
string.IsNullOrWhiteSpace(url))
return false;
return urlSchemes.Any((x => x.IsUrlOfSameScheme(url) && (x.UrlSchemeType == UrlSchemeType.LocalRequest)));
}
public static IEnumerable<UrlScheme> GetSchemesByType(this List<UrlScheme> urlSchemes, UrlSchemeType type)
{
if (urlSchemes == null || !urlSchemes.Any())
return new List<UrlScheme>();
return urlSchemes.Where((x => (x.UrlSchemeType == type))).ToList();
}
public static IEnumerable<UrlScheme> GetSchemesByType(this List<UrlScheme> urlSchemes, string url, UrlSchemeType type)
{
if (urlSchemes == null ||
urlSchemes.Count == 0 ||
string.IsNullOrWhiteSpace(url))
return null;
return urlSchemes.Where((x => x.IsUrlOfSameScheme(url) && (x.UrlSchemeType == type))).ToList();
}
public static UrlScheme GetScheme(this List<UrlScheme> urlSchemes, string url, UrlSchemeType type)
{
if (urlSchemes == null ||
urlSchemes.Count == 0 ||
string.IsNullOrWhiteSpace(url) )
return null;
var uri = new Uri(url);
var scheme = string.IsNullOrWhiteSpace(uri.Scheme) ? string.Empty : uri.Scheme;
var host = string.IsNullOrWhiteSpace(uri.Host) ? string.Empty : uri.Host;
var itemList = urlSchemes.Where((x => x.IsUrlOfSameScheme(url) &&
(!string.IsNullOrWhiteSpace(x.Scheme) && x.Scheme.Equals(scheme, StringComparison.InvariantCultureIgnoreCase)) &&
(!string.IsNullOrWhiteSpace(x.Host) && x.Scheme.Equals(host, StringComparison.InvariantCultureIgnoreCase)) &&
(x.UrlSchemeType == type)));
if (itemList != null && itemList.Any())
{
return itemList.FirstOrDefault();
}
itemList = urlSchemes.Where((x => x.IsUrlOfSameScheme(url) &&
(!string.IsNullOrWhiteSpace(x.Scheme) && x.Scheme.Equals(scheme, StringComparison.InvariantCultureIgnoreCase)) &&
(x.UrlSchemeType == type)));
if (itemList != null && itemList.Any())
{
return itemList.FirstOrDefault();
}
return null;
}
}
}
| 40.132075 | 162 | 0.565115 | [
"MIT",
"BSD-3-Clause"
] | GerHobbelt/Chromely | src/Chromely.Core/Network/UrlSchemeCollectionExtension.cs | 4,257 | C# |
// Stationeers.Addons (c) 2018-2021 Damian 'Erdroy' Korczowski & Contributors
using System.Collections;
namespace Stationeers.Addons.Modules
{
/// <summary>
/// Basic module interface.
/// </summary>
internal interface IModule
{
/// <summary>
/// Initializes the module.
/// Similar to <see cref="Load"/> but it should not take long time to execute.
/// Heavier operations should be executed in the <see cref="Load"/> coroutine,
/// to track it's progress.
/// </summary>
void Initialize();
/// <summary>
/// Coroutine that loads this module.
/// Called always only once.
/// </summary>
/// <returns>Coroutine handle.</returns>
IEnumerator Load();
/// <summary>
/// Shutdowns the module.
/// </summary>
void Shutdown();
/// <summary>
/// The loading string that is being shown when this module is loading.
/// </summary>
string LoadingCaption { get; }
}
}
| 28.894737 | 90 | 0.540984 | [
"MIT"
] | Erdroy/Stationeers.Addons | Source/Stationeers.Addons/Modules/IModule.cs | 1,100 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.