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.VisualStudio.TemplateWizard;
namespace Ezfx.Csv.ItemWizards
{
public class VBClassWizard : ClassWizard, IWizard
{
protected override string GetPropertyCode(CsvColumn col)
{
return col.ToVBCode();
}
}
}
| 20.615385 | 64 | 0.656716 | [
"Apache-2.0"
] | EricWebsmith/csv2entity | Templates/Ezfx.Csv.Templates/Wizard/VBClassWizard.cs | 270 | C# |
using System.Collections.Generic;
namespace SIS.HTTP.Sessions
{
using Common;
public class HttpSession : IHttpSession
{
private readonly Dictionary<string, object> sessionParameters;
public HttpSession(string id)
{
CoreValidator.ThrowIfNull(id, nameof(id));
this.Id = id;
this.sessionParameters = new Dictionary<string, object>();
}
public string Id { get; }
public object GetParameter(string name)
{
CoreValidator.ThrowIfNullOrEmpty(name, nameof(name));
return this.sessionParameters.GetValueOrDefault(name, null);
}
public bool ContainsParameter(string name)
{
CoreValidator.ThrowIfNullOrEmpty(name, nameof(name));
return this.sessionParameters.ContainsKey(name);
}
public void AddParameter(string name, object parameter)
{
CoreValidator.ThrowIfNullOrEmpty(name, nameof(name));
CoreValidator.ThrowIfNull(parameter, nameof(parameter));
this.sessionParameters.Add(name, parameter);
}
public void ClearParameters()
{
this.sessionParameters.Clear();
}
}
}
| 28.181818 | 72 | 0.616935 | [
"MIT"
] | sapphire119/Musaca-Exam-SoftUni | Exam/SIS.HTTP/Sessions/HttpSession.cs | 1,242 | C# |
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using BootstrapBlazor.Components;
using BootstrapBlazor.DataAcces.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// BootstrapBlazor 服务扩展类
/// </summary>
public static class EFCoreServiceCollectionExtensions
{
/// <summary>
/// 增加 Entity Framework 数据库操作服务
/// </summary>
/// <param name="services"></param>
/// <param name="optionsAction"></param>
/// <param name="contextLifetime"></param>
/// <param name="optionsLifetime"></param>
/// <returns></returns>
public static IServiceCollection AddEntityFrameworkCore<TContext>(this IServiceCollection services, Action<DbContextOptionsBuilder>? optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContext : DbContext
{
services.AddDbContext<TContext>(optionsAction, contextLifetime, optionsLifetime);
services.TryAdd(new ServiceDescriptor(typeof(IDataService<>), typeof(DefaultDataService<>), contextLifetime));
services.TryAddSingleton(provider =>
{
DbContext DbContextResolve(IEntityFrameworkCoreDataService server)
{
return provider.GetRequiredService<TContext>();
}
return (Func<IEntityFrameworkCoreDataService, DbContext>)DbContextResolve;
});
return services;
}
}
}
| 43.953488 | 278 | 0.678836 | [
"Apache-2.0"
] | Witchie/BootstrapBlazor | src/Extensions/DataServices/BootstrapBlazor.DataAcces.EntityFrameworkCore/EFCoreServiceCollectionExtensions.cs | 1,920 | C# |
// Copyright 2018 yinyue200.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.
namespace LottieSharp.Model
{
public class Font
{
public Font(string family, string name, SkiaSharp.SKTypefaceStyle style, float ascent)
{
Family = family;
Name = name;
Style = style;
Ascent = ascent;
}
public string Family { get; }
public string Name { get; }
public SkiaSharp.SKTypefaceStyle Style { get; }
internal readonly float Ascent;
}
}
| 30.571429 | 94 | 0.654206 | [
"Apache-2.0"
] | alex-harper/LottieSkiaSharp | LottieSkiaSharp/Model/Font.cs | 1,072 | 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("03ExceptionDotNetFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03ExceptionDotNetFramework")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("3ac2a18c-ac0b-47b9-8a02-a13dd3ccee2b")]
// 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.378378 | 84 | 0.752817 | [
"Unlicense"
] | rusky65/HowToCSharp | 07Day/03ExceptionDotNetFramework/Properties/AssemblyInfo.cs | 1,423 | C# |
namespace LocalizationDemo;
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
| 19.461538 | 65 | 0.671937 | [
"MIT"
] | NimblePros/ApiLocalizationDemo | LocalizationDemo/WeatherForecast.cs | 253 | C# |
// <copyright file="AccountUpdateErpFigures.cs" company="">
// Copyright (c) 2015 All Rights Reserved
// </copyright>
// <author></author>
// <date>1/26/2015 1:55:15 PM</date>
// <summary>Implements the AccountUpdateErpFigures Plugin.</summary>
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
// </auto-generated>
using System;
using System.Collections.Generic;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using DG.XrmFramework.BusinessDomain.ServiceContext;
namespace DG.Some.Namespace {
/// <summary>
/// AccountUpdateErpFigures Plugin.
/// Fires when the following attributes are updated:
/// All Attributes
/// </summary>
public class AccountPostImagePlugin : Plugin {
/// <summary>
/// Initializes a new instance of the <see cref="AccountPostImagePlugin"/> class.
/// </summary>
public AccountPostImagePlugin() : base(typeof(AccountPostImagePlugin)) {
RegisterPluginStep<Account>(
EventOperation.Delete,
ExecutionStage.PostOperation,
ExecuteAccountUpdateErpFigures)
.SetExecutionMode(ExecutionMode.Synchronous)
.AddImage(ImageType.PostImage,
a => a.ParentAccountId);
}
/// <summary>
/// Executes the plug-in.
/// </summary>
/// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
/// <see cref="IPluginExecutionContext"/>,
/// <see cref="IOrganizationService"/>
/// and <see cref="ITracingService"/>
/// </param>
/// <remarks>
/// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
/// The plug-in's Execute method should be written to be stateless as the constructor
/// is not called for every invocation of the plug-in. Also, multiple system threads
/// could execute the plug-in at the same time. All per invocation state information
/// is stored in the context. This means that you should not use global variables in plug-ins.
/// </remarks>
protected void ExecuteAccountUpdateErpFigures(LocalPluginContext localContext) {
}
}
}
| 37.606557 | 102 | 0.638187 | [
"MIT"
] | doodlleus/XrmMockup | tests/SharedPluginsAndCodeactivites/AccountPostImagePlugin.cs | 2,296 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace GrillMaster.Domain.Entities
{
public class GrillMenu
{
public GrillMenu()
{
Items = new List<GrillMenuItem>();
}
public int sId { get; set; }
public string Id { get; set; }
public string Menu { get; set; }
public IList<GrillMenuItem> Items { get; set; }
}
}
| 19.454545 | 55 | 0.570093 | [
"MIT"
] | Changelling/GrillMaster | src/Domain/Entities/GrillMenu.cs | 430 | C# |
using Hangfire;
using Hangfire.PostgreSql;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
using TibiaApi.Comum;
namespace TibiaApi.Web.Config
{
public static class HangfireStartStatic
{
public static void StartHangfire(this IApplicationBuilder app, bool apenasDashboard, IServiceProvider serviceProvider)
{
var workersCount = Environment.ProcessorCount * 10;
//if (apenasDashboard)
// workersCount = 1;
//var filas = apenasDashboard
// ? new[] { Constantes.FilasHangfire.DEFAULT }
// :
var filas = new[] {
Constantes.FilasHangfire.WORLD_SERVICE,
Constantes.FilasHangfire.PLAYER_SERVICE,
Constantes.FilasHangfire.DEFAULT,
Constantes.FilasHangfire.WORLD_SCRAPY,
Constantes.FilasHangfire.PLAYER_SCRAPY,
};
var nome = apenasDashboard ? "TIBIA_DASHBOARD_API_" : "TIBIA_FULL_";
BackgroundJobServerOptions options = CreateOptionsBackgroundServer(serviceProvider, filas, nome, workersCount);
app.UseHangfireServer(options);
}
public static void StartDashboardHangfire(this IApplicationBuilder app)
{
var optionsDashboard = new DashboardOptions()
{
Authorization = new[] { new Auth.HangfireAutorizationFilter() },
};
app.UseHangfireDashboard("/hangfire", optionsDashboard);
}
private static BackgroundJobServerOptions CreateOptionsBackgroundServer(IServiceProvider serviceProvider, string[] filas, string nome, int workersCount)
{
return new BackgroundJobServerOptions()
{
//Activator = new HangfireActivator(serviceProvider),
Queues = filas,
WorkerCount = workersCount,
ServerName = $"{nome}{Environment.MachineName}_{Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6)}",
};
}
public static void StartServiceHangfire(this IServiceCollection services, ConnectionMultiplexer redis)
{
services
.AddHangfire(x =>
x.UseRedisStorage(redis)
);
}
private static Action<BackgroundJobServerOptions> BackgroundServerHangfire(IServiceProvider serviceProvider, string[] filas, string nome, int workersCount)
{
return x =>
{
x.Queues = filas;
x.WorkerCount = workersCount;
x.ServerName = $"{nome}{Environment.MachineName}_{Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6)}";
};
}
public static JobStorage GenerateJobStorage(string connectionString) => new PostgreSqlStorage(connectionString);
public static BackgroundJobServer CreateBackgroundJobServer(IServiceProvider serviceProvider, string connectionString)
{
var filas = new[] {
Constantes.FilasHangfire.WORLD_SCRAPY,
Constantes.FilasHangfire.PLAYER_SCRAPY,
Constantes.FilasHangfire.WORLD_SERVICE,
Constantes.FilasHangfire.PLAYER_SERVICE,
Constantes.FilasHangfire.DEFAULT,
};
var options = CreateOptionsBackgroundServer(serviceProvider, filas, "MAQUINA_JOB_", 10);
return new BackgroundJobServer(options, GenerateJobStorage(connectionString));
}
}
}
| 37.212121 | 163 | 0.613735 | [
"Apache-2.0"
] | guigolabs/ScrapyTibiaCSharp | TibiaApi.Comum.DependecysStart/Config/HangfireStartStatic.cs | 3,686 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Rebus.AdoNet.Dialects
{
/// <summary>
/// This class maps a DbType to names.
/// </summary>
/// <remarks>
/// Associations may be marked with a capacity. Calling the <c>Get()</c>
/// method with a type and actual size n will return the associated
/// name with smallest capacity >= n, if available and an unmarked
/// default type otherwise.
/// Eg, setting
/// <code>
/// Names.Put(DbType, "TEXT" );
/// Names.Put(DbType, 255, "VARCHAR($l)" );
/// Names.Put(DbType, 65534, "LONGVARCHAR($l)" );
/// </code>
/// will give you back the following:
/// <code>
/// Names.Get(DbType) // --> "TEXT" (default)
/// Names.Get(DbType,100) // --> "VARCHAR(100)" (100 is in [0:255])
/// Names.Get(DbType,1000) // --> "LONGVARCHAR(1000)" (100 is in [256:65534])
/// Names.Get(DbType,100000) // --> "TEXT" (default)
/// </code>
/// On the other hand, simply putting
/// <code>
/// Names.Put(DbType, "VARCHAR($l)" );
/// </code>
/// would result in
/// <code>
/// Names.Get(DbType) // --> "VARCHAR($l)" (will cause trouble)
/// Names.Get(DbType,100) // --> "VARCHAR(100)"
/// Names.Get(DbType,1000) // --> "VARCHAR(1000)"
/// Names.Get(DbType,10000) // --> "VARCHAR(10000)"
/// </code>
/// </remarks>
public class TypeNames
{
public const string LengthPlaceHolder = "$l";
public const string PrecisionPlaceHolder = "$p";
public const string ScalePlaceHolder = "$s";
private readonly Dictionary<DbType, SortedList<uint, string>> weighted = new Dictionary<DbType, SortedList<uint, string>>();
private readonly Dictionary<DbType, string> defaults = new Dictionary<DbType, string>();
/// <summary>
///
/// </summary>
/// <param name="template"></param>
/// <param name="placeholder"></param>
/// <param name="replacement"></param>
/// <returns></returns>
private static string ReplaceOnce(string template, string placeholder, string replacement)
{
int loc = template.IndexOf(placeholder, StringComparison.Ordinal);
if (loc < 0)
{
return template;
}
else
{
return new StringBuilder(template.Substring(0, loc))
.Append(replacement)
.Append(template.Substring(loc + placeholder.Length))
.ToString();
}
}
/// <summary>
/// Replaces the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="size">The size.</param>
/// <param name="precision">The precision.</param>
/// <param name="scale">The scale.</param>
/// <returns></returns>
private static string Replace(string type, uint size, uint precision, uint scale)
{
type = ReplaceOnce(type, LengthPlaceHolder, size.ToString());
type = ReplaceOnce(type, ScalePlaceHolder, scale.ToString());
return ReplaceOnce(type, PrecisionPlaceHolder, precision.ToString());
}
/// <summary>
/// Get default type name for specified type
/// </summary>
/// <param name="typecode">the type key</param>
/// <returns>the default type name associated with the specified key</returns>
public string Get(DbType typecode)
{
string result;
if (!defaults.TryGetValue(typecode, out result))
{
throw new ArgumentException("Dialect does not support DbType." + typecode, "typecode");
}
return result;
}
/// <summary>
/// Get the type name specified type and size
/// </summary>
/// <param name="typecode">the type key</param>
/// <param name="size">the SQL length </param>
/// <param name="scale">the SQL scale </param>
/// <param name="precision">the SQL precision </param>
/// <returns>
/// The associated name with smallest capacity >= size if available and the
/// default type name otherwise
/// </returns>
public string Get(DbType typecode, uint size, uint precision, uint scale)
{
SortedList<uint, string> map;
weighted.TryGetValue(typecode, out map);
if (map != null && map.Count > 0)
{
foreach (KeyValuePair<uint, string> entry in map)
{
if (size <= entry.Key)
{
return Replace(entry.Value, size, precision, scale);
}
}
}
//Could not find a specific type for the size, using the default
return Replace(Get(typecode), size, precision, scale);
}
/// <summary>
/// For types with a simple length, this method returns the definition
/// for the longest registered type.
/// </summary>
/// <param name="typecode"></param>
/// <returns></returns>
public string GetLongest(DbType typecode)
{
SortedList<uint, string> map;
weighted.TryGetValue(typecode, out map);
if (map != null && map.Count > 0)
return Replace(map.Values[map.Count - 1], map.Keys[map.Count - 1], 0, 0);
return Get(typecode);
}
/// <summary>
/// Set a type name for specified type key and capacity
/// </summary>
/// <param name="typecode">the type key</param>
/// <param name="capacity">the (maximum) type size/length</param>
/// <param name="value">The associated name</param>
public void Put(DbType typecode, uint capacity, string value)
{
SortedList<uint, string> map;
if (!weighted.TryGetValue(typecode, out map))
{
// add new ordered map
weighted[typecode] = map = new SortedList<uint, string>();
}
map[capacity] = value;
}
/// <summary>
///
/// </summary>
/// <param name="typecode"></param>
/// <param name="value"></param>
public void Put(DbType typecode, string value)
{
defaults[typecode] = value;
}
}
} | 32.698864 | 127 | 0.609904 | [
"MIT"
] | DiegoVeraEvicertia/Rebus.AdoNet | Rebus.AdoNet/Dialects/TypeNames.cs | 5,860 | C# |
// ======================================================================
//
// Copyright (C) 2018-2068 湖南心莱信息科技有限公司
// All rights reserved
//
// filename : FromImageMessage.cs
// description :
//
// created by codelove1314@live.cn at 2021-02-09 10:48:26
// Blog:http://www.cnblogs.com/codelove/
// GitHub : https://github.com/xin-lai
// Home:http://xin-lai.com
//
// =======================================================================
namespace Magicodes.Wx.PublicAccount.Sdk.AspNet.ServerMessages.From
{
using System.Xml.Serialization;
/// <summary>
/// 图片消息
/// </summary>
public class FromImageMessage : FromMessageBase
{
/// <summary>
/// Gets or sets the ImageUrl
/// 图片链接
/// </summary>
[XmlElement("PicUrl")]
public string ImageUrl { get; set; }
/// <summary>
/// Gets or sets the MediaId
/// 图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
/// </summary>
[XmlElement("MediaId")]
public string MediaId { get; set; }
}
}
| 28.125 | 74 | 0.469333 | [
"MIT"
] | CacoCode/Magicodes.Wx.Sdk | src/Magicodes.Wx.PublicAccount.Sdk.AspNet/ServerMessages/From/FromImageMessage.cs | 1,223 | C# |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace MekSweeper.UI.App
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
private MainWindowViewModel ViewModel => (MainWindowViewModel) DataContext;
private void OnRightClick(object sender, MouseButtonEventArgs e)
{
var button = (Button) sender;
ViewModel.FlagCellCommand.Execute(button.DataContext);
}
private void OnClick(object sender, RoutedEventArgs e)
{
var button = (Button) sender;
ViewModel.UncoverCellCommand.Execute(button.DataContext);
}
private void UIElement_OnMouseUp(object sender, MouseButtonEventArgs e)
{
if (e.ButtonState != MouseButtonState.Released)
{
return;
}
var button = (Button) sender;
switch (e.ChangedButton)
{
case MouseButton.Left:
ViewModel.UncoverCellCommand.Execute(button.DataContext);
break;
case MouseButton.Right:
ViewModel.FlagCellCommand.Execute(button.DataContext);
break;
case MouseButton.Middle:
ViewModel.RevealKnownCommand.Execute(button.DataContext);
break;
}
}
}
}
| 29.232143 | 83 | 0.562615 | [
"Apache-2.0"
] | mekmak/MekSweeper | MekSweeper.UI.App/MainWindow.xaml.cs | 1,639 | C# |
/*----------------------------------------------------------------
Copyright (C) 2018 Senparc
文件名:SsoApi.cs
文件功能描述:OA数据开放接口(Work中新增)
创建标识:Senparc - 20170617
修改标识:Senparc - 20170709
修改描述:v0.3.1 修复OaDataOpenApi接口AccessToken传递问题
修改标识:Senparc - 20170712
修改描述:v14.5.1 AccessToken HandlerWaper改造
----------------------------------------------------------------*/
using Senparc.CO2NET.Helpers;
using Senparc.NeuChar;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen.OaDataOpenJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen
{
/// <summary>
/// OA数据开放接口
/// </summary>
public class OaDataOpenApi
{
/// <summary>
/// 打卡类型
/// </summary>
public enum OpenCheckinDataType
{
上下班打卡 = 1,
外出打卡 = 2,
全部打卡 = 3
}
#region 同步方法
/// <summary>
/// 获取打卡数据【QY移植新增】
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="openCheckinDataType">打卡类型</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="userIdList">需要获取打卡记录的用户列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetCheckinData", true)]
public static GetCheckinDataJsonResult GetCheckinData(string accessTokenOrAppKey, OpenCheckinDataType openCheckinDataType, DateTime startTime, DateTime endTime, string[] userIdList, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/checkin/getcheckindata?access_token={0}";
var data = new
{
opencheckindatatype = (int)openCheckinDataType,
starttime = DateTimeHelper.GetUnixDateTime(startTime),
endtime = DateTimeHelper.GetUnixDateTime(endTime),
useridlist = userIdList
};
return Senparc.Weixin.CommonAPIs.CommonJsonSend.Send<GetCheckinDataJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取打卡规则
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="datetime">需要获取规则的日期当天0点的Unix时间戳</param>
/// <param name="userIdList">需要获取打卡规则的用户列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetCheckinOption", true)]
public static GetCheckinOptionJsonResult GetCheckinOption(string accessTokenOrAppKey, DateTime datetime, string[] userIdList, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/checkin/getcheckinoption?access_token={0}";
var data = new
{
datetime = DateTimeHelper.GetUnixDateTime(datetime),
useridlist = userIdList
};
return Weixin.CommonAPIs.CommonJsonSend.Send<GetCheckinOptionJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取审批数据【QY移植新增】
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetApprovalData", true)]
public static GetApprovalDataJsonResult GetApprovalData(string accessTokenOrAppKey, DateTime startTime, DateTime endTime, long next_spnum, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/corp/getapprovaldata?access_token={0}";
var data = new
{
starttime = DateTimeHelper.GetUnixDateTime(startTime),
endtime = DateTimeHelper.GetUnixDateTime(endTime),
next_spnum = next_spnum
};
return Senparc.Weixin.CommonAPIs.CommonJsonSend.Send<GetApprovalDataJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取公费电话拨打记录
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetDialRecord", true)]
public static GetDialRecordJsonResult GetDialRecord(string accessTokenOrAppKey, DateTime startTime, DateTime endTime, int offset, int limit, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/dial/get_dial_record?access_token={0}";
var data = new
{
starttime = DateTimeHelper.GetUnixDateTime(startTime),
endtime = DateTimeHelper.GetUnixDateTime(endTime),
offset = offset,
limit = limit
};
return Weixin.CommonAPIs.CommonJsonSend.Send<GetDialRecordJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 查询自建应用审批单当前状态
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetOpenApprovalData", true)]
public static GetOpenApprovalDataJsonResult GetOpenApprovalData(string accessTokenOrAppKey, string thirdId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/corp/getopenapprovaldata?access_token={0}";
var data = new
{
thirdId
};
return Weixin.CommonAPIs.CommonJsonSend.Send<GetOpenApprovalDataJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#if !NET35 && !NET40
#region 异步方法
/// <summary>
/// 【异步方法】获取打卡规则
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="datetime">需要获取规则的日期当天0点的Unix时间戳</param>
/// <param name="userIdList">需要获取打卡规则的用户列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetCheckinOptionAsync", true)]
public static async Task<GetCheckinOptionJsonResult> GetCheckinOptionAsync(string accessTokenOrAppKey, DateTime datetime, string[] userIdList, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/checkin/getcheckinoption?access_token={0}";
var data = new
{
datetime = DateTimeHelper.GetUnixDateTime(datetime),
useridlist = userIdList
};
return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetCheckinOptionJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】获取打卡数据【QY移植新增】
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="openCheckinDataType">打卡类型</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="userIdList">需要获取打卡记录的用户列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetCheckinDataAsync", true)]
public static async Task<GetCheckinDataJsonResult> GetCheckinDataAsync(string accessTokenOrAppKey, OpenCheckinDataType openCheckinDataType, DateTime startTime, DateTime endTime, string[] userIdList, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/checkin/getcheckindata?access_token={0}";
var data = new
{
opencheckindatatype = (int)openCheckinDataType,
starttime = DateTimeHelper.GetUnixDateTime(startTime),
endtime = DateTimeHelper.GetUnixDateTime(endTime),
useridlist = userIdList
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetCheckinDataJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】获取审批数据【QY移植新增】
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="openCheckinDataType">打卡类型</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="userIdList">需要获取打卡记录的用户列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetApprovalDataAsync", true)]
public static async Task<GetApprovalDataJsonResult> GetApprovalDataAsync(string accessTokenOrAppKey, DateTime startTime, DateTime endTime, long next_spnum, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/corp/getapprovaldata?access_token={0}";
var data = new
{
starttime = DateTimeHelper.GetUnixDateTime(startTime),
endtime = DateTimeHelper.GetUnixDateTime(endTime),
next_spnum = next_spnum
};
return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetApprovalDataJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】获取公费电话拨打记录
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetDialRecordAsync", true)]
public static async Task<GetDialRecordJsonResult> GetDialRecordAsync(string accessTokenOrAppKey, DateTime startTime, DateTime endTime, int offset, int limit, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/dial/get_dial_record?access_token={0}";
var data = new
{
starttime = DateTimeHelper.GetUnixDateTime(startTime),
endtime = DateTimeHelper.GetUnixDateTime(endTime),
offset = offset,
limit = limit
};
return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetDialRecordJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】查询自建应用审批单当前状态
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证(AccessToken)或AppKey(根据AccessTokenContainer.BuildingKey(corpId, corpSecret)方法获得)</param>
/// <param name="startTime">获取打卡记录的开始时间</param>
/// <param name="endTime">获取打卡记录的结束时间</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[ApiBind(NeuChar.PlatformType.WeChat_Work, "OaDataOpenApi.GetOpenApprovalDataAsync", true)]
public static async Task<GetOpenApprovalDataJsonResult> GetOpenApprovalDataAsync(string accessTokenOrAppKey, string thirdId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/corp/getopenapprovaldata?access_token={0}";
var data = new
{
thirdId
};
return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetOpenApprovalDataJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#endif
}
}
| 44.636086 | 237 | 0.617635 | [
"Apache-2.0"
] | 253437873/WeiXinMPSDK | src/Senparc.Weixin.Work/Senparc.Weixin.Work/AdvancedAPIs/OaDataOpen/OaDataOpenApi.cs | 15,956 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletEnemy : MonoBehaviour
{
[SerializeField, Range(0.1f, 100f)]
public float speed = 0f;
public int damage = 50;
public Rigidbody2D rb;
public GameObject impactEffect;
void Start ()
{
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D (Collider2D hitInfo)
{
Player enemy = hitInfo.GetComponent<Player>();
if (enemy != null)
{
enemy.TakeDamage(damage);
Instantiate(impactEffect, transform.position, transform.rotation);
Destroy(gameObject);
}
}
}
| 22.516129 | 78 | 0.611748 | [
"MIT"
] | BunnyHop99/Mafia2D | Assets/Scripts/BulletEnemy.cs | 698 | C# |
using System.Diagnostics.Contracts;
namespace Examples.Zoppi
{
public class ATM
{
public bool cardInserted;
public bool authenticated;
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(!authenticated || cardInserted);
}
public ATM()
{
cardInserted = false;
authenticated = false;
}
public void InsertCard(int number)
{
Contract.Requires(!cardInserted);
cardInserted = true;
}
public void RemoveCard()
{
Contract.Requires(cardInserted);
cardInserted = false;
authenticated = false;
}
public void Authenticate(int pin)
{
Contract.Requires(cardInserted);
Contract.Requires(!authenticated);
authenticated = true;
}
public void PrintTicket()
{
Contract.Requires(authenticated);
}
public void Extract(int amount)
{
Contract.Requires(authenticated);
}
public void Deposit(int amount)
{
Contract.Requires(authenticated);
}
public void ChangePin(int pin)
{
Contract.Requires(authenticated);
}
}
}
| 20.545455 | 63 | 0.525811 | [
"MIT"
] | lleraromero/contractor-net | Examples.Zoppi/ATM.cs | 1,358 | C# |
using Xunit;
namespace Marten.Testing.Bugs
{
public class Bug_416_cannot_create_index_on_datetime_field: IntegratedFixture
{
[Fact]
public void should_throw_a_defensive_check_telling_you_that_you_cannot_index_a_date_time_field()
{
StoreOptions(_ => _.Schema.For<Target>().Index(x => x.Date));
theStore.Tenancy.Default.EnsureStorageExists(typeof(Target));
}
}
}
| 26.9375 | 104 | 0.691415 | [
"MIT"
] | Crown0815/marten | src/Marten.Testing/Bugs/Bug_416_cannot_create_index_on_datetime_field.cs | 431 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using ModularMonolith.Modules.Conferences.Core.DTO;
using ModularMonolith.Modules.Conferences.Core.Entities;
using ModularMonolith.Modules.Conferences.Core.Exceptions;
using ModularMonolith.Modules.Conferences.Core.Repositories;
namespace ModularMonolith.Modules.Conferences.Core.Services
{
internal class ConferenceService : IConferenceService
{
private readonly IConferenceRepository _conferenceRepository;
private readonly IHostRepository _hostRepository;
private readonly ILogger<ConferenceService> _logger;
public ConferenceService(IConferenceRepository conferenceRepository,
IHostRepository hostRepository, ILogger<ConferenceService> logger)
{
_conferenceRepository = conferenceRepository;
_hostRepository = hostRepository;
_logger = logger;
}
public async Task AddAsync(ConferenceDetailsDto dto)
{
await ValidateHostExistsAsync(dto.HostId);
dto.Id = Guid.NewGuid();
var conference = new Conference();
Map(conference, dto);
await _conferenceRepository.AddAsync(conference);
_logger.LogInformation("Created a conference: '{Name}' with ID: '{Id}'", dto.Name, dto.Id);
}
public async Task<ConferenceDetailsDto> GetAsync(Guid id)
{
var conference = await _conferenceRepository.GetAsync(id);
return conference is not null ? MapDetails(conference) : null;
}
public async Task<IReadOnlyList<ConferenceDto>> BrowseAsync()
{
var conferences = await _conferenceRepository.BrowseAsync();
return conferences.Select(Map<ConferenceDto>).ToList();
}
public async Task UpdateAsync(ConferenceDetailsDto dto)
{
var conference = await GetConferenceAsync(dto.Id);
var hostId = conference.HostId;
if (conference is null)
{
throw new ConferenceNotFoundException(dto.Id);
}
Map(conference, dto);
conference.HostId = hostId; // Host cannot be updated
await _conferenceRepository.UpdateAsync(conference);
_logger.LogInformation("Updated a conference: '{Name}' with ID: '{Id}'", dto.Name, dto.Id);
}
public async Task DeleteAsync(Guid id)
{
// Can we delete a conference with tickets being already sold?
var conference = await GetConferenceAsync(id);
await _conferenceRepository.DeleteAsync(conference);
_logger.LogInformation("Deleted a conference: '{Name}' with ID: '{Id}'", conference.Name, conference.Id);
}
private async Task ValidateHostExistsAsync(Guid hostId)
{
var host = await _hostRepository.GetAsync(hostId);
if (host is null)
{
throw new HostNotFoundException(hostId);
}
}
private async Task<Conference> GetConferenceAsync(Guid id)
{
var conference = await _conferenceRepository.GetAsync(id);
if (conference is null)
{
throw new ConferenceNotFoundException(id);
}
return conference;
}
private static void Map(Conference conference, ConferenceDetailsDto dto)
{
conference.Id = dto.Id;
conference.HostId = dto.HostId;
conference.Name = dto.Name;
conference.Description = dto.Description;
conference.Location = dto.Location;
conference.From = dto.From;
conference.To = dto.To;
}
private static T Map<T>(Conference conference) where T : ConferenceDto, new()
=> new()
{
Id = conference.Id,
HostId = conference.HostId,
Name = conference.Name,
Location = conference.Location,
From = conference.From,
To = conference.To
};
private static ConferenceDetailsDto MapDetails(Conference conference)
{
var dto = Map<ConferenceDetailsDto>(conference);
dto.Description = conference.Description;
return dto;
}
}
} | 36.080645 | 117 | 0.614662 | [
"MIT"
] | davidhenley/ModularMonolith | src/Modules/Conferences/ModularMonolith.Modules.Conferences.Core/Services/ConferenceService.cs | 4,474 | C# |
//===============================================================================
// Microsoft patterns & practices Enterprise Library
// Policy Injection Application Block
//===============================================================================
// Copyright © Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Design;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Design.Validation;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using FakeRules = Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules;
using PropertyMatchingOption = Microsoft.Practices.Unity.InterceptionExtension.PropertyMatchingOption;
namespace Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration
{
/// <summary>
/// A configuration element class that stores configuration information for instances
/// of <see cref="PropertyMatchingRule"/>.
/// </summary>
[ResourceDescription(typeof(DesignResources), "PropertyMatchingRuleDataDescription")]
[ResourceDisplayName(typeof(DesignResources), "PropertyMatchingRuleDataDisplayName")]
public class PropertyMatchingRuleData : MatchingRuleData
{
private const string MatchesPropertyName = "matches";
/// <summary>
/// Constructs a new <see cref="PropertyMatchingRuleData"/> instance.
/// </summary>
public PropertyMatchingRuleData()
{
Type = typeof(FakeRules.PropertyMatchingRule);
}
/// <summary>
/// Constructs a new <see cref="PropertyMatchingRuleData"/> instance.
/// </summary>
/// <param name="matchingRuleName">Matching rule instance name in configuration.</param>
public PropertyMatchingRuleData(string matchingRuleName)
: this(matchingRuleName, new List<PropertyMatchData>())
{
}
/// <summary>
/// Constructs a new <see cref="PropertyMatchingRuleData"/> instance.
/// </summary>
/// <param name="matchingRuleName">Matching rule instance name in configuration.</param>
/// <param name="matches">Collection of <see cref="PropertyMatchData"/> containing
/// property patterns to match.</param>
public PropertyMatchingRuleData(string matchingRuleName, IEnumerable<PropertyMatchData> matches)
: base(matchingRuleName, typeof(FakeRules.PropertyMatchingRule))
{
foreach (PropertyMatchData match in matches)
{
Matches.Add(match);
}
}
/// <summary>
/// The collection of <see cref="PropertyMatchData"/> containing property names to match.
/// </summary>
/// <value>The "matches" config subelement.</value>
[ConfigurationProperty(MatchesPropertyName)]
[ConfigurationCollection(typeof(PropertyMatchData))]
[ResourceDescription(typeof(DesignResources), "PropertyMatchingRuleDataMatchesDescription")]
[ResourceDisplayName(typeof(DesignResources), "PropertyMatchingRuleDataMatchesDisplayName")]
[Editor(CommonDesignTime.EditorTypes.CollectionEditor, CommonDesignTime.EditorTypes.FrameworkElement)]
[Validation(PolicyInjectionDesignTime.Validators.MatchCollectionPopulatedValidationType)]
public MatchDataCollection<PropertyMatchData> Matches
{
get { return (MatchDataCollection<PropertyMatchData>)base[MatchesPropertyName]; }
set { base[MatchesPropertyName] = value; }
}
/// <summary>
/// Configures an <see cref="IUnityContainer"/> to resolve the represented matching rule by using the specified name.
/// </summary>
/// <param name="container">The container to configure.</param>
/// <param name="registrationName">The name of the registration.</param>
protected override void DoConfigureContainer(IUnityContainer container, string registrationName)
{
container.RegisterType<IMatchingRule, PropertyMatchingRule>(
registrationName,
new InjectionConstructor(new InjectionParameter(this.Matches.Select(match => new PropertyMatchingInfo(match.Match, match.MatchOption, match.IgnoreCase)).ToArray())));
}
}
/// <summary>
/// A derived <see cref="MatchData"/> which adds storage for which methods
/// on the property to match.
/// </summary>
[ResourceDescription(typeof(DesignResources), "PropertyMatchDataDescription")]
[ResourceDisplayName(typeof(DesignResources), "PropertyMatchDataDisplayName")]
public class PropertyMatchData : MatchData
{
private const string OptionPropertyName = "matchOption";
/// <summary>
/// Initializes a new instance of the <see cref="PropertyMatchData"/> class.
/// </summary>
public PropertyMatchData()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PropertyMatchData"/> class by using the specified pattern.
/// </summary>
/// <param name="match">The property name pattern to match. The rule will match both getter and setter methods of a property.</param>
public PropertyMatchData(string match)
: base(match)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PropertyMatchData"/> class by using the specified pattern and options.
/// </summary>
/// <param name="match">The property name pattern to match.</param>
/// <param name="option">Which of the property methods to match. See <see cref="PropertyMatchingOption"/>
/// for the valid options.</param>
public PropertyMatchData(string match, PropertyMatchingOption option)
: base(match)
{
MatchOption = option;
}
/// <summary>
/// Initializes a new instance of the <see cref="PropertyMatchData"/> class by using the specified pattern and options.
/// </summary>
/// <param name="match">The property name pattern to match.</param>
/// <param name="option">Which of the property methods to match. See <see cref="PropertyMatchingOption"/>
/// for the valid options.</param>
/// <param name="ignoreCase">If false, type name comparisons are case sensitive. If true,
/// comparisons are case insensitive.</param>
public PropertyMatchData(string match, PropertyMatchingOption option, bool ignoreCase)
: base(match, ignoreCase)
{
MatchOption = option;
}
/// <summary>
/// Which methods of the property to match. Default is to match both getters and setters.
/// </summary>
/// <value>The "matchOption" config attribute.</value>
[ConfigurationProperty(OptionPropertyName, DefaultValue = PropertyMatchingOption.GetOrSet, IsRequired = false)]
[ResourceDescription(typeof(DesignResources), "PropertyMatchDataMatchOptionDescription")]
[ResourceDisplayName(typeof(DesignResources), "PropertyMatchDataMatchOptionDisplayName")]
[ViewModel(CommonDesignTime.ViewModelTypeNames.CollectionEditorContainedElementProperty)]
public PropertyMatchingOption MatchOption
{
get { return (PropertyMatchingOption)base[OptionPropertyName]; }
set { base[OptionPropertyName] = value; }
}
}
}
| 48.189024 | 182 | 0.661647 | [
"MIT"
] | talley/EnterpriseLibraryNetCore | Source/Policy Injection Application Block/PolicyInjection/Configuration/PropertyMatchingRuleData.cs | 7,906 | C# |
//
// assign.cs: Assignments.
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
// Martin Baulig (martin@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001, 2002, 2003 Ximian, Inc.
// Copyright 2004-2008 Novell, Inc
// Copyright 2011 Xamarin Inc
//
using System;
#if STATIC
using IKVM.Reflection.Emit;
#else
using System.Reflection.Emit;
#endif
namespace Mono.CSharp {
/// <summary>
/// This interface is implemented by expressions that can be assigned to.
/// </summary>
/// <remarks>
/// This interface is implemented by Expressions whose values can not
/// store the result on the top of the stack.
///
/// Expressions implementing this (Properties, Indexers and Arrays) would
/// perform an assignment of the Expression "source" into its final
/// location.
///
/// No values on the top of the stack are expected to be left by
/// invoking this method.
/// </remarks>
public interface IAssignMethod {
//
// This is an extra version of Emit. If leave_copy is `true'
// A copy of the expression will be left on the stack at the
// end of the code generated for EmitAssign
//
void Emit (EmitContext ec, bool leave_copy);
//
// This method does the assignment
// `source' will be stored into the location specified by `this'
// if `leave_copy' is true, a copy of `source' will be left on the stack
// if `prepare_for_load' is true, when `source' is emitted, there will
// be data on the stack that it can use to compuatate its value. This is
// for expressions like a [f ()] ++, where you can't call `f ()' twice.
//
void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound);
/*
For simple assignments, this interface is very simple, EmitAssign is called with source
as the source expression and leave_copy and prepare_for_load false.
For compound assignments it gets complicated.
EmitAssign will be called as before, however, prepare_for_load will be
true. The @source expression will contain an expression
which calls Emit. So, the calls look like:
this.EmitAssign (ec, source, false, true) ->
source.Emit (ec); ->
[...] ->
this.Emit (ec, false); ->
end this.Emit (ec, false); ->
end [...]
end source.Emit (ec);
end this.EmitAssign (ec, source, false, true)
When prepare_for_load is true, EmitAssign emits a `token' on the stack that
Emit will use for its state.
Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
Here is the call tree again. This time, each call is annotated with the IL
it produces:
this.EmitAssign (ec, source, false, true)
call f
dup
Binary.Emit ()
this.Emit (ec, false);
ldfld y
end this.Emit (ec, false);
IntConstant.Emit ()
ldc.i4.1
end IntConstant.Emit
add
end Binary.Emit ()
stfld
end this.EmitAssign (ec, source, false, true)
Observe two things:
1) EmitAssign left a token on the stack. It was the result of f ().
2) This token was used by Emit
leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
of the expression at that point in evaluation. This is used for pre/post inc/dec
and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
this.EmitAssign (ec, source, true, true)
call f
dup
Binary.Emit ()
this.Emit (ec, false);
ldfld y
end this.Emit (ec, false);
IntConstant.Emit ()
ldc.i4.1
end IntConstant.Emit
add
end Binary.Emit ()
dup
stloc temp
stfld
ldloc temp
end this.EmitAssign (ec, source, true, true)
And with it true in Emit
this.EmitAssign (ec, source, false, true)
call f
dup
Binary.Emit ()
this.Emit (ec, true);
ldfld y
dup
stloc temp
end this.Emit (ec, true);
IntConstant.Emit ()
ldc.i4.1
end IntConstant.Emit
add
end Binary.Emit ()
stfld
ldloc temp
end this.EmitAssign (ec, source, false, true)
Note that these two examples are what happens for ++x and x++, respectively.
*/
}
/// <summary>
/// An Expression to hold a temporary value.
/// </summary>
/// <remarks>
/// The LocalTemporary class is used to hold temporary values of a given
/// type to "simulate" the expression semantics. The local variable is
/// never captured.
///
/// The local temporary is used to alter the normal flow of code generation
/// basically it creates a local variable, and its emit instruction generates
/// code to access this value, return its address or save its value.
///
/// If `is_address' is true, then the value that we store is the address to the
/// real value, and not the value itself.
///
/// This is needed for a value type, because otherwise you just end up making a
/// copy of the value on the stack and modifying it. You really need a pointer
/// to the origional value so that you can modify it in that location. This
/// Does not happen with a class because a class is a pointer -- so you always
/// get the indirection.
///
/// </remarks>
public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod {
LocalBuilder builder;
public LocalTemporary (TypeSpec t)
{
type = t;
eclass = ExprClass.Value;
}
public LocalTemporary (LocalBuilder b, TypeSpec t)
: this (t)
{
builder = b;
}
public void Release (EmitContext ec)
{
ec.FreeTemporaryLocal (builder, type);
builder = null;
}
public override bool ContainsEmitWithAwait ()
{
return false;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
Arguments args = new Arguments (1);
args.Add (new Argument (this));
return CreateExpressionFactoryCall (ec, "Constant", args);
}
protected override Expression DoResolve (ResolveContext ec)
{
return this;
}
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
return this;
}
public override void Emit (EmitContext ec)
{
if (builder == null)
throw new InternalErrorException ("Emit without Store, or after Release");
ec.Emit (OpCodes.Ldloc, builder);
}
#region IAssignMethod Members
public void Emit (EmitContext ec, bool leave_copy)
{
Emit (ec);
if (leave_copy)
Emit (ec);
}
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
{
if (isCompound)
throw new NotImplementedException ();
source.Emit (ec);
Store (ec);
if (leave_copy)
Emit (ec);
}
#endregion
public LocalBuilder Builder {
get { return builder; }
}
public void Store (EmitContext ec)
{
if (builder == null)
builder = ec.GetTemporaryLocal (type);
ec.Emit (OpCodes.Stloc, builder);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
if (builder == null)
builder = ec.GetTemporaryLocal (type);
if (builder.LocalType.IsByRef) {
//
// if is_address, than this is just the address anyways,
// so we just return this.
//
ec.Emit (OpCodes.Ldloc, builder);
} else {
ec.Emit (OpCodes.Ldloca, builder);
}
}
}
/// <summary>
/// The Assign node takes care of assigning the value of source into
/// the expression represented by target.
/// </summary>
public abstract class Assign : ExpressionStatement {
protected Expression target, source;
protected Assign (Expression target, Expression source, Location loc)
{
this.target = target;
this.source = source;
this.loc = loc;
}
public Expression Target {
get { return target; }
}
public Expression Source {
get {
return source;
}
}
public override Location StartLocation {
get {
return target.StartLocation;
}
}
public override bool ContainsEmitWithAwait ()
{
return target.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ();
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
return null;
}
protected override Expression DoResolve (ResolveContext ec)
{
bool ok = true;
source = source.Resolve (ec);
if (source == null) {
ok = false;
source = EmptyExpression.Null;
}
target = target.ResolveLValue (ec, source);
if (target == null || !ok)
return null;
TypeSpec target_type = target.Type;
TypeSpec source_type = source.Type;
eclass = ExprClass.Value;
type = target_type;
if (!(target is IAssignMethod)) {
target.Error_ValueAssignment (ec, source);
return null;
}
if (target_type != source_type) {
Expression resolved = ResolveConversions (ec);
if (resolved != this)
return resolved;
}
return this;
}
#if NET_4_0 || MONODROID
public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
{
var tassign = target as IDynamicAssign;
if (tassign == null)
throw new InternalErrorException (target.GetType () + " does not support dynamic assignment");
var target_object = tassign.MakeAssignExpression (ctx, source);
//
// Some hacking is needed as DLR does not support void type and requires
// always have object convertible return type to support caching and chaining
//
// We do this by introducing an explicit block which returns RHS value when
// available or null
//
if (target_object.NodeType == System.Linq.Expressions.ExpressionType.Block)
return target_object;
System.Linq.Expressions.UnaryExpression source_object;
if (ctx.HasSet (BuilderContext.Options.CheckedScope)) {
source_object = System.Linq.Expressions.Expression.ConvertChecked (source.MakeExpression (ctx), target_object.Type);
} else {
source_object = System.Linq.Expressions.Expression.Convert (source.MakeExpression (ctx), target_object.Type);
}
return System.Linq.Expressions.Expression.Assign (target_object, source_object);
}
#endif
protected virtual Expression ResolveConversions (ResolveContext ec)
{
source = Convert.ImplicitConversionRequired (ec, source, target.Type, source.Location);
if (source == null)
return null;
return this;
}
void Emit (EmitContext ec, bool is_statement)
{
IAssignMethod t = (IAssignMethod) target;
t.EmitAssign (ec, source, !is_statement, this is CompoundAssign);
}
public override void Emit (EmitContext ec)
{
Emit (ec, false);
}
public override void EmitStatement (EmitContext ec)
{
Emit (ec, true);
}
protected override void CloneTo (CloneContext clonectx, Expression t)
{
Assign _target = (Assign) t;
_target.target = target.Clone (clonectx);
_target.source = source.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class SimpleAssign : Assign
{
public SimpleAssign (Expression target, Expression source)
: this (target, source, target.Location)
{
}
public SimpleAssign (Expression target, Expression source, Location loc)
: base (target, source, loc)
{
}
bool CheckEqualAssign (Expression t)
{
if (source is Assign) {
Assign a = (Assign) source;
if (t.Equals (a.Target))
return true;
return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t);
}
return t.Equals (source);
}
protected override Expression DoResolve (ResolveContext ec)
{
Expression e = base.DoResolve (ec);
if (e == null || e != this)
return e;
if (CheckEqualAssign (target))
ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
return this;
}
}
public class RuntimeExplicitAssign : Assign
{
public RuntimeExplicitAssign (Expression target, Expression source)
: base (target, source, target.Location)
{
}
protected override Expression ResolveConversions (ResolveContext ec)
{
source = EmptyCast.Create (source, target.Type);
return this;
}
}
//
// Compiler generated assign
//
class CompilerAssign : Assign
{
public CompilerAssign (Expression target, Expression source, Location loc)
: base (target, source, loc)
{
if (target.Type != null) {
type = target.Type;
eclass = ExprClass.Value;
}
}
protected override Expression DoResolve (ResolveContext ec)
{
var expr = base.DoResolve (ec);
var vr = target as VariableReference;
if (vr != null && vr.VariableInfo != null)
vr.VariableInfo.IsEverAssigned = false;
return expr;
}
public void UpdateSource (Expression source)
{
base.source = source;
}
}
//
// Implements fields and events class initializers
//
public class FieldInitializer : Assign
{
//
// Field initializers are tricky for partial classes. They have to
// share same constructor (block) for expression trees resolve but
// they have they own resolve scope
//
sealed class FieldInitializerContext : ResolveContext
{
ExplicitBlock ctor_block;
public FieldInitializerContext (IMemberContext mc, ResolveContext constructorContext)
: base (mc, Options.FieldInitializerScope | Options.ConstructorScope)
{
this.ctor_block = constructorContext.CurrentBlock.Explicit;
}
public override ExplicitBlock ConstructorBlock {
get {
return ctor_block;
}
}
}
//
// Keep resolved value because field initializers have their own rules
//
ExpressionStatement resolved;
FieldBase mc;
public FieldInitializer (FieldBase mc, Expression expression, Location loc)
: base (new FieldExpr (mc.Spec, expression.Location), expression, loc)
{
this.mc = mc;
if (!mc.IsStatic)
((FieldExpr)target).InstanceExpression = new CompilerGeneratedThis (mc.CurrentType, expression.Location);
}
public override Location StartLocation {
get {
return loc;
}
}
protected override Expression DoResolve (ResolveContext ec)
{
// Field initializer can be resolved (fail) many times
if (source == null)
return null;
if (resolved == null) {
var ctx = new FieldInitializerContext (mc, ec);
resolved = base.DoResolve (ctx) as ExpressionStatement;
}
return resolved;
}
public override void EmitStatement (EmitContext ec)
{
if (resolved == null)
return;
//
// Emit sequence symbol info even if we are in compiler generated
// block to allow debugging field initializers when constructor is
// compiler generated
//
if (ec.HasSet (BuilderContext.Options.OmitDebugInfo) && ec.HasMethodSymbolBuilder) {
using (ec.With (BuilderContext.Options.OmitDebugInfo, false)) {
ec.Mark (loc);
}
}
if (resolved != this)
resolved.EmitStatement (ec);
else
base.EmitStatement (ec);
}
public bool IsDefaultInitializer {
get {
Constant c = source as Constant;
if (c == null)
return false;
FieldExpr fe = (FieldExpr)target;
return c.IsDefaultInitializer (fe.Type);
}
}
public override bool IsSideEffectFree {
get {
return source.IsSideEffectFree;
}
}
}
//
// This class is used for compound assignments.
//
public class CompoundAssign : Assign
{
// This is just a hack implemented for arrays only
public sealed class TargetExpression : Expression
{
readonly Expression child;
public TargetExpression (Expression child)
{
this.child = child;
this.loc = child.Location;
}
public override bool ContainsEmitWithAwait ()
{
return child.ContainsEmitWithAwait ();
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
protected override Expression DoResolve (ResolveContext ec)
{
type = child.Type;
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
child.Emit (ec);
}
public override Expression EmitToField (EmitContext ec)
{
return child.EmitToField (ec);
}
}
// Used for underlying binary operator
readonly Binary.Operator op;
Expression right;
Expression left;
public CompoundAssign (Binary.Operator op, Expression target, Expression source)
: base (target, source, target.Location)
{
right = source;
this.op = op;
}
public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left)
: this (op, target, source)
{
this.left = left;
}
public Binary.Operator Operator {
get {
return op;
}
}
protected override Expression DoResolve (ResolveContext ec)
{
right = right.Resolve (ec);
if (right == null)
return null;
MemberAccess ma = target as MemberAccess;
using (ec.Set (ResolveContext.Options.CompoundAssignmentScope)) {
target = target.Resolve (ec);
}
if (target == null)
return null;
if (target is MethodGroupExpr){
ec.Report.Error (1656, loc,
"Cannot assign to `{0}' because it is a `{1}'",
((MethodGroupExpr)target).Name, target.ExprClassName);
return null;
}
var event_expr = target as EventExpr;
if (event_expr != null) {
source = Convert.ImplicitConversionRequired (ec, right, target.Type, loc);
if (source == null)
return null;
Expression rside;
if (op == Binary.Operator.Addition)
rside = EmptyExpression.EventAddition;
else if (op == Binary.Operator.Subtraction)
rside = EmptyExpression.EventSubtraction;
else
rside = null;
target = target.ResolveLValue (ec, rside);
if (target == null)
return null;
eclass = ExprClass.Value;
type = event_expr.Operator.ReturnType;
return this;
}
//
// Only now we can decouple the original source/target
// into a tree, to guarantee that we do not have side
// effects.
//
if (left == null)
left = new TargetExpression (target);
source = new Binary (op, left, right, true);
if (target is DynamicMemberAssignable) {
Arguments targs = ((DynamicMemberAssignable) target).Arguments;
source = source.Resolve (ec);
Arguments args = new Arguments (targs.Count + 1);
args.AddRange (targs);
args.Add (new Argument (source));
var binder_flags = CSharpBinderFlags.ValueFromCompoundAssignment;
//
// Compound assignment does target conversion using additional method
// call, set checked context as the binary operation can overflow
//
if (ec.HasSet (ResolveContext.Options.CheckedScope))
binder_flags |= CSharpBinderFlags.CheckedContext;
if (target is DynamicMemberBinder) {
source = new DynamicMemberBinder (ma.Name, binder_flags, args, loc).Resolve (ec);
// Handles possible event addition/subtraction
if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction) {
args = new Arguments (targs.Count + 1);
args.AddRange (targs);
args.Add (new Argument (right));
string method_prefix = op == Binary.Operator.Addition ?
Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix;
var invoke = DynamicInvocation.CreateSpecialNameInvoke (
new MemberAccess (right, method_prefix + ma.Name, loc), args, loc).Resolve (ec);
args = new Arguments (targs.Count);
args.AddRange (targs);
source = new DynamicEventCompoundAssign (ma.Name, args,
(ExpressionStatement) source, (ExpressionStatement) invoke, loc).Resolve (ec);
}
} else {
source = new DynamicIndexBinder (binder_flags, args, loc).Resolve (ec);
}
return source;
}
return base.DoResolve (ec);
}
protected override Expression ResolveConversions (ResolveContext ec)
{
//
// LAMESPEC: Under dynamic context no target conversion is happening
// This allows more natual dynamic behaviour but breaks compatibility
// with static binding
//
if (target is RuntimeValueExpression)
return this;
TypeSpec target_type = target.Type;
//
// 1. the return type is implicitly convertible to the type of target
//
if (Convert.ImplicitConversionExists (ec, source, target_type)) {
source = Convert.ImplicitConversion (ec, source, target_type, loc);
return this;
}
//
// Otherwise, if the selected operator is a predefined operator
//
Binary b = source as Binary;
if (b == null) {
if (source is ReducedExpression)
b = ((ReducedExpression) source).OriginalExpression as Binary;
else if (source is ReducedExpression.ReducedConstantExpression) {
b = ((ReducedExpression.ReducedConstantExpression) source).OriginalExpression as Binary;
} else if (source is Nullable.LiftedBinaryOperator) {
var po = ((Nullable.LiftedBinaryOperator) source);
if (po.UserOperator == null)
b = po.Binary;
} else if (source is TypeCast) {
b = ((TypeCast) source).Child as Binary;
}
}
if (b != null) {
//
// 2a. the operator is a shift operator
//
// 2b. the return type is explicitly convertible to the type of x, and
// y is implicitly convertible to the type of x
//
if ((b.Oper & Binary.Operator.ShiftMask) != 0 ||
Convert.ImplicitConversionExists (ec, right, target_type)) {
source = Convert.ExplicitConversion (ec, source, target_type, loc);
return this;
}
}
if (source.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
Arguments arg = new Arguments (1);
arg.Add (new Argument (source));
return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec);
}
right.Error_ValueCannotBeConverted (ec, target_type, false);
return null;
}
protected override void CloneTo (CloneContext clonectx, Expression t)
{
CompoundAssign ctarget = (CompoundAssign) t;
ctarget.right = ctarget.source = source.Clone (clonectx);
ctarget.target = target.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
}
| 25.692666 | 137 | 0.680517 | [
"Apache-2.0"
] | alistair/mono | mcs/mcs/assign.cs | 22,070 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from shared/dxgi1_2.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
namespace TerraFX.Interop.DirectX;
/// <include file='IDXGIDevice2.xml' path='doc/member[@name="IDXGIDevice2"]/*' />
[Guid("05008617-FBFD-4051-A790-144884B4F6A9")]
[NativeTypeName("struct IDXGIDevice2 : IDXGIDevice1")]
[NativeInheritance("IDXGIDevice1")]
public unsafe partial struct IDXGIDevice2 : IDXGIDevice2.Interface
{
public void** lpVtbl;
/// <inheritdoc cref="IUnknown.QueryInterface" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IDXGIDevice2*, Guid*, void**, int>)(lpVtbl[0]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
/// <inheritdoc cref="IUnknown.AddRef" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IDXGIDevice2*, uint>)(lpVtbl[1]))((IDXGIDevice2*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IUnknown.Release" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IDXGIDevice2*, uint>)(lpVtbl[2]))((IDXGIDevice2*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IDXGIObject.SetPrivateData" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public HRESULT SetPrivateData([NativeTypeName("const GUID &")] Guid* Name, uint DataSize, [NativeTypeName("const void *")] void* pData)
{
return ((delegate* unmanaged<IDXGIDevice2*, Guid*, uint, void*, int>)(lpVtbl[3]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), Name, DataSize, pData);
}
/// <inheritdoc cref="IDXGIObject.SetPrivateDataInterface" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
public HRESULT SetPrivateDataInterface([NativeTypeName("const GUID &")] Guid* Name, [NativeTypeName("const IUnknown *")] IUnknown* pUnknown)
{
return ((delegate* unmanaged<IDXGIDevice2*, Guid*, IUnknown*, int>)(lpVtbl[4]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), Name, pUnknown);
}
/// <inheritdoc cref="IDXGIObject.GetPrivateData" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public HRESULT GetPrivateData([NativeTypeName("const GUID &")] Guid* Name, uint* pDataSize, void* pData)
{
return ((delegate* unmanaged<IDXGIDevice2*, Guid*, uint*, void*, int>)(lpVtbl[5]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), Name, pDataSize, pData);
}
/// <inheritdoc cref="IDXGIObject.GetParent" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
public HRESULT GetParent([NativeTypeName("const IID &")] Guid* riid, void** ppParent)
{
return ((delegate* unmanaged<IDXGIDevice2*, Guid*, void**, int>)(lpVtbl[6]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), riid, ppParent);
}
/// <inheritdoc cref="IDXGIDevice.GetAdapter" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
public HRESULT GetAdapter(IDXGIAdapter** pAdapter)
{
return ((delegate* unmanaged<IDXGIDevice2*, IDXGIAdapter**, int>)(lpVtbl[7]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), pAdapter);
}
/// <inheritdoc cref="IDXGIDevice.CreateSurface" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
public HRESULT CreateSurface([NativeTypeName("const DXGI_SURFACE_DESC *")] DXGI_SURFACE_DESC* pDesc, uint NumSurfaces, [NativeTypeName("DXGI_USAGE")] uint Usage, [NativeTypeName("const DXGI_SHARED_RESOURCE *")] DXGI_SHARED_RESOURCE* pSharedResource, IDXGISurface** ppSurface)
{
return ((delegate* unmanaged<IDXGIDevice2*, DXGI_SURFACE_DESC*, uint, uint, DXGI_SHARED_RESOURCE*, IDXGISurface**, int>)(lpVtbl[8]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), pDesc, NumSurfaces, Usage, pSharedResource, ppSurface);
}
/// <inheritdoc cref="IDXGIDevice.QueryResourceResidency" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(9)]
public HRESULT QueryResourceResidency([NativeTypeName("IUnknown *const *")] IUnknown** ppResources, DXGI_RESIDENCY* pResidencyStatus, uint NumResources)
{
return ((delegate* unmanaged<IDXGIDevice2*, IUnknown**, DXGI_RESIDENCY*, uint, int>)(lpVtbl[9]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), ppResources, pResidencyStatus, NumResources);
}
/// <inheritdoc cref="IDXGIDevice.SetGPUThreadPriority" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(10)]
public HRESULT SetGPUThreadPriority(int Priority)
{
return ((delegate* unmanaged<IDXGIDevice2*, int, int>)(lpVtbl[10]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), Priority);
}
/// <inheritdoc cref="IDXGIDevice.GetGPUThreadPriority" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(11)]
public HRESULT GetGPUThreadPriority(int* pPriority)
{
return ((delegate* unmanaged<IDXGIDevice2*, int*, int>)(lpVtbl[11]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), pPriority);
}
/// <inheritdoc cref="IDXGIDevice1.SetMaximumFrameLatency" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(12)]
public HRESULT SetMaximumFrameLatency(uint MaxLatency)
{
return ((delegate* unmanaged<IDXGIDevice2*, uint, int>)(lpVtbl[12]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), MaxLatency);
}
/// <inheritdoc cref="IDXGIDevice1.GetMaximumFrameLatency" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(13)]
public HRESULT GetMaximumFrameLatency(uint* pMaxLatency)
{
return ((delegate* unmanaged<IDXGIDevice2*, uint*, int>)(lpVtbl[13]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), pMaxLatency);
}
/// <include file='IDXGIDevice2.xml' path='doc/member[@name="IDXGIDevice2.OfferResources"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(14)]
public HRESULT OfferResources(uint NumResources, [NativeTypeName("IDXGIResource *const *")] IDXGIResource** ppResources, DXGI_OFFER_RESOURCE_PRIORITY Priority)
{
return ((delegate* unmanaged<IDXGIDevice2*, uint, IDXGIResource**, DXGI_OFFER_RESOURCE_PRIORITY, int>)(lpVtbl[14]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), NumResources, ppResources, Priority);
}
/// <include file='IDXGIDevice2.xml' path='doc/member[@name="IDXGIDevice2.ReclaimResources"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(15)]
public HRESULT ReclaimResources(uint NumResources, [NativeTypeName("IDXGIResource *const *")] IDXGIResource** ppResources, BOOL* pDiscarded)
{
return ((delegate* unmanaged<IDXGIDevice2*, uint, IDXGIResource**, BOOL*, int>)(lpVtbl[15]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), NumResources, ppResources, pDiscarded);
}
/// <include file='IDXGIDevice2.xml' path='doc/member[@name="IDXGIDevice2.EnqueueSetEvent"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(16)]
public HRESULT EnqueueSetEvent(HANDLE hEvent)
{
return ((delegate* unmanaged<IDXGIDevice2*, HANDLE, int>)(lpVtbl[16]))((IDXGIDevice2*)Unsafe.AsPointer(ref this), hEvent);
}
public interface Interface : IDXGIDevice1.Interface
{
[VtblIndex(14)]
HRESULT OfferResources(uint NumResources, [NativeTypeName("IDXGIResource *const *")] IDXGIResource** ppResources, DXGI_OFFER_RESOURCE_PRIORITY Priority);
[VtblIndex(15)]
HRESULT ReclaimResources(uint NumResources, [NativeTypeName("IDXGIResource *const *")] IDXGIResource** ppResources, BOOL* pDiscarded);
[VtblIndex(16)]
HRESULT EnqueueSetEvent(HANDLE hEvent);
}
public partial struct Vtbl<TSelf>
where TSelf : unmanaged, Interface
{
[NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> AddRef;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> Release;
[NativeTypeName("HRESULT (const GUID &, UINT, const void *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, uint, void*, int> SetPrivateData;
[NativeTypeName("HRESULT (const GUID &, const IUnknown *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, IUnknown*, int> SetPrivateDataInterface;
[NativeTypeName("HRESULT (const GUID &, UINT *, void *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, uint*, void*, int> GetPrivateData;
[NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, void**, int> GetParent;
[NativeTypeName("HRESULT (IDXGIAdapter **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IDXGIAdapter**, int> GetAdapter;
[NativeTypeName("HRESULT (const DXGI_SURFACE_DESC *, UINT, DXGI_USAGE, const DXGI_SHARED_RESOURCE *, IDXGISurface **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, DXGI_SURFACE_DESC*, uint, uint, DXGI_SHARED_RESOURCE*, IDXGISurface**, int> CreateSurface;
[NativeTypeName("HRESULT (IUnknown *const *, DXGI_RESIDENCY *, UINT) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IUnknown**, DXGI_RESIDENCY*, uint, int> QueryResourceResidency;
[NativeTypeName("HRESULT (INT) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int, int> SetGPUThreadPriority;
[NativeTypeName("HRESULT (INT *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int*, int> GetGPUThreadPriority;
[NativeTypeName("HRESULT (UINT) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint, int> SetMaximumFrameLatency;
[NativeTypeName("HRESULT (UINT *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint*, int> GetMaximumFrameLatency;
[NativeTypeName("HRESULT (UINT, IDXGIResource *const *, DXGI_OFFER_RESOURCE_PRIORITY) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint, IDXGIResource**, DXGI_OFFER_RESOURCE_PRIORITY, int> OfferResources;
[NativeTypeName("HRESULT (UINT, IDXGIResource *const *, BOOL *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint, IDXGIResource**, BOOL*, int> ReclaimResources;
[NativeTypeName("HRESULT (HANDLE) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, HANDLE, int> EnqueueSetEvent;
}
}
| 49.951327 | 279 | 0.705731 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/DirectX/shared/dxgi1_2/IDXGIDevice2.cs | 11,291 | C# |
////////////////////////////////////////////////////////////////////////////////
//
// @module Assets Common Lib
// @author Osipov Stanislav (Stan's Assets)
// @support support@stansassets.com
// @website https://stansassets.com
//
////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System;
using System.Collections;
namespace SA.Common.Animation {
public class ValuesTween : MonoBehaviour {
public event Action OnComplete = delegate {};
public event Action<float> OnValueChanged = delegate {};
public event Action<Vector3> OnVectorValueChanged = delegate {};
public bool DestoryGameObjectOnComplete = true;
private float FinalFloatValue;
private Vector3 FinalVectorValue;
//--------------------------------------
// INITIALIZE
//--------------------------------------
public static ValuesTween Create() {
return new GameObject("SA.Common.Animation.ValuesTween").AddComponent<ValuesTween>();
}
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
void Update() {
OnValueChanged(transform.position.x);
OnVectorValueChanged(transform.position);
}
public void ValueTo(float from, float to, float time, EaseType easeType = EaseType.linear) {
Vector3 pos = transform.position;
pos.x = from;
transform.position = pos;
FinalFloatValue = to;
SA_iTween.MoveTo(gameObject, SA_iTween.Hash("x", to, "time", time, "easeType", easeType.ToString(), "oncomplete", "onTweenComplete", "oncompletetarget", gameObject));
}
public void VectorTo(Vector3 from, Vector3 to, float time, EaseType easeType = EaseType.linear) {
transform.position = from;
FinalVectorValue = to;
SA_iTween.MoveTo(gameObject, SA_iTween.Hash("position", to, "time", time, "easeType", easeType.ToString(), "oncomplete", "onTweenComplete", "oncompletetarget", gameObject));
}
public void ScaleTo(Vector3 from, Vector3 to, float time, EaseType easeType = EaseType.linear) {
transform.localScale = from;
FinalVectorValue = to;
SA_iTween.ScaleTo(gameObject, SA_iTween.Hash("scale", to, "time", time, "easeType", easeType.ToString(), "oncomplete", "onTweenComplete", "oncompletetarget", gameObject));
}
public void VectorToS(Vector3 from, Vector3 to, float speed, EaseType easeType = EaseType.linear) {
transform.position = from;
FinalVectorValue = to;
SA_iTween.MoveTo(gameObject, SA_iTween.Hash("position", to, "speed", speed, "easeType", easeType.ToString(), "oncomplete", "onTweenComplete", "oncompletetarget", gameObject));
}
public void Stop() {
SA_iTween.Stop(gameObject);
Destroy(gameObject);
}
//--------------------------------------
// PRIVATE METHODS
//--------------------------------------
private void onTweenComplete() {
OnValueChanged(FinalFloatValue);
OnVectorValueChanged(FinalVectorValue);
OnComplete();
if(DestoryGameObjectOnComplete) {
Destroy(gameObject);
} else {
Destroy(this);
}
}
}
}
| 27.535714 | 179 | 0.612516 | [
"MIT"
] | KingOfFawns/Special_Course | Special Course/Assets/Plugins/StansAssets/Support/Common/Effetcs/Animations/Tween/Methods/SA_ValuesTween.cs | 3,084 | C# |
using System;
using System.Collections.Generic;
using Chloe.Server.Data.Contracts;
using Chloe.Server.Dtos;
using Chloe.Server.Services.Contracts;
using System.Data.Entity;
using System.Linq;
using Chloe.Server.Models;
namespace Chloe.Server.Services
{
public class ProjectService : IProjectService
{
public ProjectService(IChloeUow uow, ICacheProvider cacheProvider)
{
this.uow = uow;
this.repository = uow.Projects;
this.cache = cacheProvider.GetCache();
}
public ProjectAddOrUpdateResponseDto AddOrUpdate(ProjectAddOrUpdateRequestDto request)
{
var entity = repository.GetAll()
.Where(x => x.Id == request.Id && x.IsDeleted == false)
.FirstOrDefault();
if (entity == null) repository.Add(entity = new Project());
entity.Name = request.Name;
uow.SaveChanges();
return new ProjectAddOrUpdateResponseDto(entity);
}
public dynamic Remove(int id)
{
var entity = repository.GetById(id);
entity.IsDeleted = true;
uow.SaveChanges();
return id;
}
public ICollection<ProjectDto> Get()
{
ICollection<ProjectDto> response = new HashSet<ProjectDto>();
var entities = repository.GetAll().Where(x => x.IsDeleted == false).ToList();
foreach(var entity in entities) { response.Add(new ProjectDto(entity)); }
return response;
}
public ProjectDto GetById(int id)
{
return new ProjectDto(repository.GetAll().Where(x => x.Id == id && x.IsDeleted == false).FirstOrDefault());
}
protected readonly IChloeUow uow;
protected readonly IRepository<Project> repository;
protected readonly ICache cache;
}
}
| 31.949153 | 119 | 0.607958 | [
"MIT"
] | QuinntyneBrown/dynamic-scheduling | Server/Services/ProjectService.cs | 1,885 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Tests
{
/// <summary>
/// Contains tests that ensure the correctness of the Queue class.
/// </summary>
public abstract class Queue_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
{
#region Queue<T> Helper Methods
protected Queue<T> GenericQueueFactory()
{
return new Queue<T>();
}
protected Queue<T> GenericQueueFactory(int count)
{
Queue<T> queue = new Queue<T>(count);
int seed = count * 34;
for (int i = 0; i < count; i++)
queue.Enqueue(CreateT(seed++));
return queue;
}
#endregion
#region IGenericSharedAPI<T> Helper Methods
protected override IEnumerable<T> GenericIEnumerableFactory()
{
return GenericQueueFactory();
}
protected override IEnumerable<T> GenericIEnumerableFactory(int count)
{
return GenericQueueFactory(count);
}
protected override int Count(IEnumerable<T> enumerable) => ((Queue<T>)enumerable).Count;
protected override void Add(IEnumerable<T> enumerable, T value) =>
((Queue<T>)enumerable).Enqueue(value);
protected override void Clear(IEnumerable<T> enumerable) => ((Queue<T>)enumerable).Clear();
protected override bool Contains(IEnumerable<T> enumerable, T value) =>
((Queue<T>)enumerable).Contains(value);
protected override void CopyTo(IEnumerable<T> enumerable, T[] array, int index) =>
((Queue<T>)enumerable).CopyTo(array, index);
protected override bool Remove(IEnumerable<T> enumerable) =>
((Queue<T>)enumerable).TryDequeue(out _);
protected override bool Enumerator_Current_UndefinedOperation_Throws => true;
protected override Type IGenericSharedAPI_CopyTo_IndexLargerThanArrayCount_ThrowType =>
typeof(ArgumentOutOfRangeException);
#endregion
#region Constructor_IEnumerable
[Theory]
[MemberData(nameof(EnumerableTestData))]
public void Queue_Generic_Constructor_IEnumerable(
EnumerableType enumerableType,
int setLength,
int enumerableLength,
int numberOfMatchingElements,
int numberOfDuplicateElements
)
{
_ = setLength;
_ = numberOfMatchingElements;
IEnumerable<T> enumerable = CreateEnumerable(
enumerableType,
null,
enumerableLength,
0,
numberOfDuplicateElements
);
Queue<T> queue = new Queue<T>(enumerable);
Assert.Equal(enumerable, queue);
}
[Fact]
public void Queue_Generic_Constructor_IEnumerable_Null_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("collection", () => new Queue<T>(null));
}
#endregion
#region Constructor_Capacity
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_Constructor_int(int count)
{
Queue<T> queue = new Queue<T>(count);
Assert.Equal(Array.Empty<T>(), queue.ToArray());
queue.Clear();
Assert.Equal(Array.Empty<T>(), queue.ToArray());
}
[Fact]
public void Queue_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"capacity",
() => new Queue<T>(-1)
);
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"capacity",
() => new Queue<T>(int.MinValue)
);
}
#endregion
#region Dequeue
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_Dequeue_AllElements(int count)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> elements = queue.ToList();
foreach (T element in elements)
Assert.Equal(element, queue.Dequeue());
}
[Fact]
public void Queue_Generic_Dequeue_OnEmptyQueue_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => new Queue<T>().Dequeue());
}
[Theory]
[InlineData(0, 5)]
[InlineData(1, 1)]
[InlineData(3, 100)]
public void Queue_Generic_EnqueueAndDequeue(int capacity, int items)
{
int seed = 53134;
var q = new Queue<T>(capacity);
Assert.Equal(0, q.Count);
// Enqueue some values and make sure the count is correct
List<T> source = (List<T>)CreateEnumerable(EnumerableType.List, null, items, 0, 0);
foreach (T val in source)
{
q.Enqueue(val);
}
Assert.Equal(source, q);
// Dequeue to make sure the values are removed in the right order and the count is updated
for (int i = 0; i < items; i++)
{
T itemToRemove = source[0];
source.RemoveAt(0);
Assert.Equal(itemToRemove, q.Dequeue());
Assert.Equal(items - i - 1, q.Count);
}
// Can't dequeue when empty
Assert.Throws<InvalidOperationException>(() => q.Dequeue());
// But can still be used after a failure and after bouncing at empty
T itemToAdd = CreateT(seed++);
q.Enqueue(itemToAdd);
Assert.Equal(itemToAdd, q.Dequeue());
}
#endregion
#region ToArray
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_ToArray(int count)
{
Queue<T> queue = GenericQueueFactory(count);
Assert.True(queue.ToArray().SequenceEqual(queue.ToArray<T>()));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_ToArray_NonWrappedQueue(int count)
{
Queue<T> collection = new Queue<T>(count + 1);
AddToCollection(collection, count);
T[] elements = collection.ToArray();
elements.Reverse();
Assert.True(Enumerable.SequenceEqual(elements, collection.ToArray<T>()));
}
#endregion
#region Peek
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_Peek_AllElements(int count)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> elements = queue.ToList();
foreach (T element in elements)
{
Assert.Equal(element, queue.Peek());
queue.Dequeue();
}
}
[Fact]
public void Queue_Generic_Peek_OnEmptyQueue_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => new Queue<T>().Peek());
}
#endregion
#region TrimExcess
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_OnValidQueueThatHasntBeenRemovedFrom(int count)
{
Queue<T> queue = GenericQueueFactory(count);
queue.TrimExcess();
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_Repeatedly(int count)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> expected = queue.ToList();
queue.TrimExcess();
queue.TrimExcess();
queue.TrimExcess();
Assert.True(queue.SequenceEqual(expected));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_AfterRemovingOneElement(int count)
{
if (count > 0)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> expected = queue.ToList();
queue.TrimExcess();
T removed = queue.Dequeue();
expected.Remove(removed);
queue.TrimExcess();
Assert.True(queue.SequenceEqual(expected));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_AfterClearingAndAddingSomeElementsBack(int count)
{
if (count > 0)
{
Queue<T> queue = GenericQueueFactory(count);
queue.TrimExcess();
queue.Clear();
queue.TrimExcess();
Assert.Equal(0, queue.Count);
AddToCollection(queue, count / 10);
queue.TrimExcess();
Assert.Equal(count / 10, queue.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_AfterClearingAndAddingAllElementsBack(int count)
{
if (count > 0)
{
Queue<T> queue = GenericQueueFactory(count);
queue.TrimExcess();
queue.Clear();
queue.TrimExcess();
Assert.Equal(0, queue.Count);
AddToCollection(queue, count);
queue.TrimExcess();
Assert.Equal(count, queue.Count);
}
}
#endregion
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TryDequeue_AllElements(int count)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> elements = queue.ToList();
foreach (T element in elements)
{
T result;
Assert.True(queue.TryDequeue(out result));
Assert.Equal(element, result);
}
}
[Fact]
public void Queue_Generic_TryDequeue_EmptyQueue_ReturnsFalse()
{
T result;
Assert.False(new Queue<T>().TryDequeue(out result));
Assert.Equal(default(T), result);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TryPeek_AllElements(int count)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> elements = queue.ToList();
foreach (T element in elements)
{
T result;
Assert.True(queue.TryPeek(out result));
Assert.Equal(element, result);
queue.Dequeue();
}
}
[Fact]
public void Queue_Generic_TryPeek_EmptyQueue_ReturnsFalse()
{
T result;
Assert.False(new Queue<T>().TryPeek(out result));
Assert.Equal(default(T), result);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_EnsureCapacity_RequestingLargerCapacity_DoesInvalidateEnumeration(
int count
)
{
Queue<T> queue = GenericQueueFactory(count);
IEnumerator<T> copiedEnumerator = new List<T>(queue).GetEnumerator();
IEnumerator<T> enumerator = queue.GetEnumerator();
queue.EnsureCapacity(count + 1);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
[Fact]
public void Queue_Generic_EnsureCapacity_NotInitialized_RequestedZero_ReturnsZero()
{
var queue = GenericQueueFactory();
Assert.Equal(0, queue.EnsureCapacity(0));
}
[Fact]
public void Queue_Generic_EnsureCapacity_NegativeCapacityRequested_Throws()
{
var queue = GenericQueueFactory();
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"capacity",
() => queue.EnsureCapacity(-1)
);
}
public static IEnumerable<object[]> Queue_Generic_EnsureCapacity_LargeCapacityRequested_Throws_MemberData()
{
yield return new object[] { Array.MaxLength + 1 };
yield return new object[] { int.MaxValue };
}
[Theory]
[MemberData(nameof(Queue_Generic_EnsureCapacity_LargeCapacityRequested_Throws_MemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51411", TestRuntimes.Mono)]
public void Queue_Generic_EnsureCapacity_LargeCapacityRequested_Throws(
int requestedCapacity
)
{
var queue = GenericQueueFactory();
AssertExtensions.Throws<OutOfMemoryException>(
() => queue.EnsureCapacity(requestedCapacity)
);
}
[Theory]
[InlineData(5)]
public void Queue_Generic_EnsureCapacity_RequestedCapacitySmallerThanOrEqualToCurrent_CapacityUnchanged(
int currentCapacity
)
{
var queue = new Queue<T>(currentCapacity);
for (int requestCapacity = 0; requestCapacity <= currentCapacity; requestCapacity++)
{
Assert.Equal(currentCapacity, queue.EnsureCapacity(requestCapacity));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_EnsureCapacity_RequestedCapacitySmallerThanOrEqualToCount_CapacityUnchanged(
int count
)
{
Queue<T> queue = GenericQueueFactory(count);
for (int requestCapacity = 0; requestCapacity <= count; requestCapacity++)
{
Assert.Equal(count, queue.EnsureCapacity(requestCapacity));
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(5)]
public void Queue_Generic_EnsureCapacity_CapacityIsAtLeastTheRequested(int count)
{
Queue<T> queue = GenericQueueFactory(count);
int requestCapacity = count + 1;
int newCapacity = queue.EnsureCapacity(requestCapacity);
Assert.InRange(newCapacity, requestCapacity, int.MaxValue);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_EnsureCapacity_RequestingLargerCapacity_DoesNotImpactQueueContent(
int count
)
{
Queue<T> queue = GenericQueueFactory(count);
var copiedList = new List<T>(queue);
queue.EnsureCapacity(count + 1);
Assert.Equal(copiedList, queue);
for (int i = 0; i < count; i++)
{
Assert.Equal(copiedList[i], queue.Dequeue());
}
}
}
}
| 32.670259 | 115 | 0.572465 | [
"MIT"
] | belav/runtime | src/libraries/System.Collections/tests/Generic/Queue/Queue.Generic.Tests.cs | 15,159 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*===============================================================
Project: Core Library
Developer: Marci San Diego
Company: Personal - marcisandiego@gmail.com
Date: 06/11/2018 16:03
===============================================================*/
namespace MSD
{
public abstract class RuntimeDictionary<TKey, TValue> : ScriptableObject,
IDictionary<TKey, TValue>
{
protected Dictionary<TKey, TValue> itemPair = new Dictionary<TKey, TValue>();
public TValue this[TKey key] {
get => itemPair[key];
set => itemPair[key] = value;
}
public ICollection<TKey> Keys => itemPair.Keys;
public ICollection<TValue> Values => itemPair.Values;
public int Count => itemPair.Count;
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => ((IDictionary<TKey, TValue>)itemPair).IsReadOnly;
public void Add(TKey key, TValue value)
{
itemPair.Add(key, value);
}
public void Clear()
{
itemPair.Clear();
}
public bool ContainsKey(TKey key)
{
return itemPair.ContainsKey(key);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return itemPair.GetEnumerator();
}
public bool Remove(TKey key)
{
return itemPair.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
return itemPair.TryGetValue(key, out value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
((IDictionary<TKey, TValue>)itemPair).Add(item);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return ((IDictionary<TKey, TValue>)itemPair).Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((IDictionary<TKey, TValue>)itemPair).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
return ((IDictionary<TKey, TValue>)itemPair).Remove(item);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IDictionary<TKey, TValue>)itemPair).GetEnumerator();
}
}
} | 24.795455 | 110 | 0.669569 | [
"MIT"
] | marcisd/com.marcisd.core | Modules/Collections/Runtime/RuntimeDictionary.cs | 2,182 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Collections_Generic_List_1_Single_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Collections.Generic.List<System.Single>);
args = new Type[]{typeof(System.Single)};
method = type.GetMethod("Add", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Add_0);
args = new Type[]{};
method = type.GetMethod("ToArray", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ToArray_1);
args = new Type[]{};
method = type.GetConstructor(flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Ctor_0);
}
static StackObject* Add_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Single @item = *(float*)&ptr_of_this_method->Value;
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Collections.Generic.List<System.Single> instance_of_this_method = (System.Collections.Generic.List<System.Single>)typeof(System.Collections.Generic.List<System.Single>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
instance_of_this_method.Add(@item);
return __ret;
}
static StackObject* ToArray_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Collections.Generic.List<System.Single> instance_of_this_method = (System.Collections.Generic.List<System.Single>)typeof(System.Collections.Generic.List<System.Single>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ToArray();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* __ret = ILIntepreter.Minus(__esp, 0);
var result_of_this_method = new System.Collections.Generic.List<System.Single>();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
}
}
| 42.348837 | 264 | 0.694399 | [
"MIT"
] | lantuma/DDZ | Unity/Assets/Model/ILBinding/System_Collections_Generic_List_1_Single_Binding.cs | 3,642 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace WebRTCme
{
public interface IBlob
{
int Size { get; }
string Type { get; }
Task<byte[]> ArrayBuffer();
IBlob Slice(int start = 0, int end = 0, string contentType = "");
////IReadableStream Stream();
Task<string> Text();
object GetNativeObject();
}
}
| 17.32 | 73 | 0.595843 | [
"MIT"
] | BlazorHub/WebRTCme | WebRTCme.Api/Interfaces/IBlob.cs | 435 | C# |
using System;
namespace Microsoft.Maui.Graphics
{
public static class GeometryUtil
{
public const float Epsilon = 0.0000000001f;
public static float GetDistance(float x1, float y1, float x2, float y2)
{
var a = x2 - x1;
var b = y2 - y1;
return (float) Math.Sqrt(a * a + b * b);
}
public static float GetAngleAsDegrees(float x1, float y1, float x2, float y2)
{
var dx = x1 - x2;
var dy = y1 - y2;
var radians = (float) Math.Atan2(dy, dx);
var degrees = radians * 180.0f / (float) Math.PI;
return 180 - degrees;
}
public static float DegreesToRadians(float angle)
{
return (float) Math.PI * angle / 180;
}
public static double DegreesToRadians(double angle)
{
return Math.PI * angle / 180;
}
public static float RadiansToDegrees(float angle)
{
return angle * (180 / (float) Math.PI);
}
public static double RadiansToDegrees(double angle)
{
return angle * (180 / Math.PI);
}
public static PointF RotatePoint(PointF point, float angle)
{
var radians = DegreesToRadians(angle);
var x = (float) (Math.Cos(radians) * point.X - Math.Sin(radians) * point.Y);
var y = (float) (Math.Sin(radians) * point.X + Math.Cos(radians) * point.Y);
return new PointF(x, y);
}
public static PointF RotatePoint(PointF center, PointF point, float angle)
{
var radians = DegreesToRadians(angle);
var x = center.X + (float) (Math.Cos(radians) * (point.X - center.X) - Math.Sin(radians) * (point.Y - center.Y));
var y = center.Y + (float) (Math.Sin(radians) * (point.X - center.X) + Math.Cos(radians) * (point.Y - center.Y));
return new PointF(x, y);
}
public static float GetSweep(float angle1, float angle2, bool clockwise)
{
if (clockwise)
{
if (angle2 > angle1)
{
return angle1 + (360 - angle2);
}
else
{
return angle1 - angle2;
}
}
else
{
if (angle1 > angle2)
{
return angle2 + (360 - angle1);
}
else
{
return angle2 - angle1;
}
}
}
public static PointF PolarToPoint(float angleInRadians, float fx, float fy)
{
var sin = (float) Math.Sin(angleInRadians);
var cos = (float) Math.Cos(angleInRadians);
return new PointF(fx * cos, fy * sin);
}
/// <summary>
/// Gets the point on an ellipse that corresponds to the given angle.
/// </summary>
/// <returns>The point.</returns>
/// <param name="x">The x position of the bounding rectangle.</param>
/// <param name="y">The y position of the bounding rectangle.</param>
/// <param name="width">The width of the bounding rectangle.</param>
/// <param name="height">The height of the bounding rectangle.</param>
/// <param name="angleInDegrees">Angle in degrees.</param>
public static PointF EllipseAngleToPoint(float x, float y, float width, float height, float angleInDegrees)
{
var radians = DegreesToRadians(angleInDegrees);
var cx = x + width / 2;
var cy = y + height / 2;
var point = PolarToPoint(radians, width / 2, height / 2);
point.X += cx;
point.Y += cy;
return point;
}
public static PointF GetOppositePoint(PointF pivot, PointF oppositePoint)
{
var dx = oppositePoint.X - pivot.X;
var dy = oppositePoint.Y - pivot.Y;
return new PointF(pivot.X - dx, pivot.Y - dy);
}
/**
* Return true if c is between a and b.
*/
private static bool IsBetween(float a, float b, float c)
{
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
/**
* Check if two points are on the same side of a given line.
* Algorithm from Sedgewick page 350.
*
* @param x0, y0, x1, y1 The line.
* @param px0, py0 First point.
* @param px1, py1 Second point.
* @return <0 if points on opposite sides.
* =0 if one of the points is exactly on the line
* >0 if points on same side.
*/
private static int SameSide(float x0, float y0, float x1, float y1, float px0, float py0, float px1, float py1)
{
var sameSide = 0;
var dx = x1 - x0;
var dy = y1 - y0;
var dx1 = px0 - x0;
var dy1 = py0 - y0;
var dx2 = px1 - x1;
var dy2 = py1 - y1;
// Cross product of the vector from the endpoint of the line to the point
var c1 = dx * dy1 - dy * dx1;
var c2 = dx * dy2 - dy * dx2;
// ReSharper disable CompareOfFloatsByEqualityOperator
if (c1 != 0 && c2 != 0)
{
sameSide = c1 < 0 != c2 < 0 ? -1 : 1;
}
else if (dx == 0 && dx1 == 0 && dx2 == 0)
{
sameSide = !IsBetween(y0, y1, py0) && !IsBetween(y0, y1, py1) ? 1 : 0;
}
else if (dy == 0 && dy1 == 0 && dy2 == 0)
{
sameSide = !IsBetween(x0, x1, px0) && !IsBetween(x0, x1, px1) ? 1 : 0;
}
// ReSharper restore CompareOfFloatsByEqualityOperator
return sameSide;
}
/**
* Check if two line segments intersects. Integer domain.
*
* @param x0, y0, x1, y1 End points of first line to check.
* @param x2, yy, x3, y3 End points of second line to check.
* @return True if the two lines intersects.
*/
public static bool IsLineIntersectingLine(
float x0,
float y0,
float x1,
float y1,
float x2,
float y2,
float x3,
float y3)
{
var s1 = SameSide(x0, y0, x1, y1, x2, y2, x3, y3);
var s2 = SameSide(x2, y2, x3, y3, x0, y0, x1, y1);
return s1 <= 0 && s2 <= 0;
}
public static float GetFactor(float aMin, float aMax, float aValue)
{
var vAdjustedValue = aValue - aMin;
var vRange = aMax - aMin;
if (Math.Abs(vAdjustedValue - vRange) < Epsilon)
{
return 1;
}
return vAdjustedValue / vRange;
}
public static float GetLinearValue(float aMin, float aMax, float aFactor)
{
var d = aMax - aMin;
d *= aFactor;
return aMin + d;
}
}
}
| 25.169565 | 116 | 0.603558 | [
"MIT"
] | junior-ts/Microsoft.Maui.Graphics | src/Microsoft.Maui.Graphics/GeometryUtil.cs | 5,789 | C# |
/*
* Based on OpenIZ - Based on OpenIZ, Copyright (C) 2015 - 2019 Mohawk College of Applied Arts and Technology
* Portions Copyright 2019-2020, Fyfe Software Inc. and the SanteSuite Contributors (See NOTICE)
*
* 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.
*
* User: fyfej (Justin Fyfe)
* Date: 2019-11-27
*/
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Newtonsoft.Json;
using RestSrvr;
using RestSrvr.Attributes;
using RestSrvr.Message;
using SanteDB.Core.Diagnostics;
using SanteDB.Core.Model.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace SanteDB.Messaging.FHIR.Rest.Serialization
{
/// <summary>
/// Represents a dispatch message formatter which uses the JSON.NET serialization
/// </summary>
/// <remarks>This serialization is used because the SanteDB FHIR resources have extra features not contained in the pure HL7 API provided by HL7 International (such as operators to/from primitiives, generation of text, etc.). This
/// dispatch formatter is responsible for the serialization and de-serialization of FHIR objects to/from JSON and XML using the SanteDB classes for FHIR resources.</remarks>
public class FhirMessageDispatchFormatter : IDispatchMessageFormatter
{
// Trace source
private Tracer m_traceSource = new Tracer(FhirConstants.TraceSourceName);
// Known types
private static Type[] s_knownTypes = typeof(IFhirServiceContract).GetCustomAttributes<ServiceKnownResourceAttribute>().Select(o => o.Type).ToArray();
/// <summary>
/// Creates a new instance of the FHIR message dispatch formatter
/// </summary>
public FhirMessageDispatchFormatter()
{
}
/// <summary>
/// Deserialize the request
/// </summary>
public void DeserializeRequest(EndpointOperation operation, RestRequestMessage request, object[] parameters)
{
try
{
var httpRequest = RestOperationContext.Current.IncomingRequest;
string contentType = httpRequest.Headers["Content-Type"];
for (int pNumber = 0; pNumber < parameters.Length; pNumber++)
{
var parm = operation.Description.InvokeMethod.GetParameters()[pNumber];
// Simple parameter
if (parameters[pNumber] != null) continue;
// Use XML Serializer
if (contentType?.StartsWith("application/fhir+xml") == true)
{
using (XmlReader bodyReader = XmlReader.Create(request.Body))
{
while (bodyReader.NodeType != XmlNodeType.Element)
bodyReader.Read();
Type eType = s_knownTypes.FirstOrDefault(o => o.GetCustomAttribute<XmlRootAttribute>()?.ElementName == bodyReader.LocalName &&
o.GetCustomAttribute<XmlRootAttribute>()?.Namespace == bodyReader.NamespaceURI);
var serializer = XmlModelSerializerFactory.Current.CreateSerializer(eType);
parameters[pNumber] = serializer.Deserialize(request.Body);
}
}
// Use JSON Serializer
else if (contentType?.StartsWith("application/fhir+json") == true)
{
// Now read the JSON data
Object fhirObject = null;
using (StreamReader sr = new StreamReader(request.Body))
{
string fhirContent = sr.ReadToEnd();
fhirObject = new FhirJsonParser().Parse(fhirContent);
}
// Now we want to serialize the FHIR MODEL object and re-parse as our own API bundle object
if (fhirObject != null)
{
MemoryStream ms = new MemoryStream(new FhirXmlSerializer().SerializeToBytes(fhirObject as Hl7.Fhir.Model.Resource));
var xsz = XmlModelSerializerFactory.Current.CreateSerializer(fhirObject.GetType());
parameters[pNumber] = xsz.Deserialize(ms);
}
else
parameters[pNumber] = null;
}
else if (contentType != null)// TODO: Binaries
throw new InvalidOperationException("Invalid request format");
}
}
catch (Exception e)
{
this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
throw;
}
}
/// <summary>
/// Serialize the reply
/// </summary>
public void SerializeResponse(RestResponseMessage responseMessage, object[] parameters, object result)
{
try
{
// Outbound control
var httpRequest = RestOperationContext.Current.IncomingRequest;
string accepts = httpRequest.Headers["Accept"],
contentType = httpRequest.Headers["Content-Type"],
formatParm = httpRequest.QueryString["_format"];
// Result is serializable
if (result?.GetType().GetCustomAttribute<XmlTypeAttribute>() != null ||
result?.GetType().GetCustomAttribute<JsonObjectAttribute>() != null)
{
XmlSerializer xsz = XmlModelSerializerFactory.Current.CreateSerializer(result.GetType());
MemoryStream ms = new MemoryStream();
xsz.Serialize(ms, result);
contentType = "application/fhir+xml";
ms.Seek(0, SeekOrigin.Begin);
// The request was in JSON or the accept is JSON
if (accepts?.StartsWith("application/fhir+json") == true ||
contentType?.StartsWith("application/fhir+json") == true ||
formatParm?.Contains("application/fhir+json") == true)
{
// Parse XML object
Object fhirObject = null;
using (StreamReader sr = new StreamReader(ms))
{
String fhirContent = sr.ReadToEnd();
var parser = new FhirXmlParser();
parser.Settings.AllowUnrecognizedEnums = true;
parser.Settings.AcceptUnknownMembers = true;
parser.Settings.DisallowXsiAttributesOnRoot = false;
fhirObject = parser.Parse<Resource>(fhirContent);
}
// Now we serialize to JSON
byte[] body = new FhirJsonSerializer().SerializeToBytes(fhirObject as Hl7.Fhir.Model.Resource);
ms.Dispose();
ms = new MemoryStream(body);
// Prepare reply for the WCF pipeline
contentType = "application/fhir+json";
}
responseMessage.Body = ms;
}
else if (result is XmlSchema)
{
MemoryStream ms = new MemoryStream();
(result as XmlSchema).Write(ms);
ms.Seek(0, SeekOrigin.Begin);
contentType = "text/xml";
responseMessage.Body = ms;
}
else if (result is Stream) // TODO: This is messy, clean it up
{
responseMessage.Body = result as Stream;
}
RestOperationContext.Current.OutgoingResponse.ContentType = contentType;
RestOperationContext.Current.OutgoingResponse.AppendHeader("X-PoweredBy", String.Format("{0} v{1} ({2})", Assembly.GetEntryAssembly().GetName().Name, Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion));
RestOperationContext.Current.OutgoingResponse.AppendHeader("X-GeneratedOn", DateTime.Now.ToString("o"));
}
catch (Exception e)
{
this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
throw;
}
}
}
}
| 45.985294 | 325 | 0.564226 | [
"Apache-2.0"
] | chochohtunn/santedb | SanteDB.Messaging.FHIR/Rest/Serialization/FhirMessageDispatchFormatter.cs | 9,383 | C# |
namespace MassTransit.Courier.Contexts
{
using System;
using System.Threading;
using Context;
using Contracts;
public abstract class TimeoutCourierContextProxy :
TimeoutConsumeContext<RoutingSlip>,
CourierContext
{
readonly CourierContext _courierContext;
protected TimeoutCourierContextProxy(CourierContext courierContext, CancellationToken cancellationToken)
: base(courierContext, cancellationToken)
{
_courierContext = courierContext;
}
DateTime CourierContext.Timestamp => _courierContext.Timestamp;
TimeSpan CourierContext.Elapsed => _courierContext.Elapsed;
Guid CourierContext.TrackingNumber => _courierContext.TrackingNumber;
Guid CourierContext.ExecutionId => _courierContext.ExecutionId;
string CourierContext.ActivityName => _courierContext.ActivityName;
}
}
| 32.678571 | 112 | 0.723497 | [
"ECL-2.0",
"Apache-2.0"
] | AhmedKhalil777/MassTransit | src/MassTransit/Courier/Contexts/TimeoutCourierContextProxy.cs | 915 | C# |
namespace Phantasma.Core.Log
{
/// <summary>
/// Represents the kind of the log message.
/// </summary>
public enum LogEntryKind
{
None,
Message,
Success,
Warning,
Error,
Debug,
}
}
| 15.9375 | 47 | 0.501961 | [
"MIT"
] | pau121/PhantasmaChain | Phantasma.Core/Log/LogKind.cs | 257 | C# |
using Redb.OBAC.DB;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Redb.OBAC.Permissions;
namespace Redb.OBAC.MySql
{
public class MySqlObacStorageProvider : IObacStorageProvider
{
private readonly MySqlObacConfig _config;
public MySqlObacStorageProvider(MySqlObacConfig config)
{
if (config?.Connection == null) throw new ArgumentNullException(nameof(config));
_config = config;
}
public MySqlObacStorageProvider(string connectionString)
{
if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
_config = new MySqlObacConfig { Connection = connectionString };
}
public ObacDbContext CreateObacContext() => new MySqlObacDbContext(_config.Connection);
public async Task EnsureDatabaseExists()
{
var ctx = CreateObacContext();
if (_config.NoMigrate)
{
//await ctx.Database.EnsureCreatedAsync();
await Task.Run(() => ctx.Database.EnsureCreated()); // https://bugs.mysql.com/bug.php?id=102937
}
else
{
await ctx.Database.MigrateAsync();
}
}
public IEffectivePermissionStorage CreateDbDefaultEffectivePermissionsStorage()
{
throw new System.NotImplementedException();
}
}
}
| 31.020408 | 112 | 0.634211 | [
"Apache-2.0"
] | redberriespro/Redb.OBAC | Redb.OBAC.MySql/MySqlObacStorageProvider.cs | 1,522 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using Unity.Profiling;
namespace Obi
{
[AddComponentMenu("Physics/Obi/Obi Rope Chain Renderer", 885)]
[ExecuteInEditMode]
public class ObiRopeChainRenderer : MonoBehaviour
{
static ProfilerMarker m_UpdateChainRopeRendererChunksPerfMarker = new ProfilerMarker("UpdateChainRopeRenderer");
[HideInInspector][SerializeField] public List<GameObject> linkInstances;
[SerializeProperty("RandomizeLinks")]
[SerializeField] private bool randomizeLinks = false;
public Vector3 linkScale = Vector3.one; /**< Scale of chain links.*/
public List<GameObject> linkPrefabs = new List<GameObject>();
[Range(0, 1)]
public float twistAnchor = 0; /**< Normalized position of twisting origin along rope.*/
public float sectionTwist = 0; /**< Amount of twist applied to each section, in degrees.*/
ObiPathFrame frame = new ObiPathFrame();
void Awake()
{
ClearChainLinkInstances();
}
public bool RandomizeLinks
{
get { return randomizeLinks; }
set
{
if (value != randomizeLinks)
{
randomizeLinks = value;
CreateChainLinkInstances(GetComponent<ObiRopeBase>());
}
}
}
void OnEnable()
{
GetComponent<ObiRopeBase>().OnInterpolate += UpdateRenderer;
}
void OnDisable()
{
GetComponent<ObiRopeBase>().OnInterpolate -= UpdateRenderer;
ClearChainLinkInstances();
}
/**
* Destroys all chain link instances. Used when the chain must be re-created from scratch, and when the actor is disabled/destroyed.
*/
public void ClearChainLinkInstances()
{
if (linkInstances == null)
return;
for (int i = 0; i < linkInstances.Count; ++i)
{
if (linkInstances[i] != null)
GameObject.DestroyImmediate(linkInstances[i]);
}
linkInstances.Clear();
}
public void CreateChainLinkInstances(ObiRopeBase rope)
{
ClearChainLinkInstances();
if (linkPrefabs.Count > 0)
{
for (int i = 0; i < rope.particleCount; ++i)
{
int index = randomizeLinks ? UnityEngine.Random.Range(0, linkPrefabs.Count) : i % linkPrefabs.Count;
GameObject linkInstance = null;
if (linkPrefabs[index] != null)
{
linkInstance = GameObject.Instantiate(linkPrefabs[index]);
linkInstance.transform.SetParent(rope.transform, false);
linkInstance.hideFlags = HideFlags.HideAndDontSave;
linkInstance.SetActive(false);
}
linkInstances.Add(linkInstance);
}
}
}
public void UpdateRenderer(ObiActor actor)
{
using (m_UpdateChainRopeRendererChunksPerfMarker.Auto())
{
var rope = actor as ObiRopeBase;
// In case there are no link prefabs to instantiate:
if (linkPrefabs.Count == 0)
return;
// Regenerate instances if needed:
if (linkInstances == null || linkInstances.Count < rope.particleCount)
{
CreateChainLinkInstances(rope);
}
var blueprint = rope.blueprint;
int elementCount = rope.elements.Count;
float twist = -sectionTwist * elementCount * twistAnchor;
//we will define and transport a reference frame along the curve using parallel transport method:
frame.Reset();
frame.SetTwist(twist);
int lastParticle = -1;
for (int i = 0; i < elementCount; ++i)
{
ObiStructuralElement elm = rope.elements[i];
Vector3 pos = rope.GetParticlePosition(elm.particle1);
Vector3 nextPos = rope.GetParticlePosition(elm.particle2);
Vector3 linkVector = nextPos - pos;
Vector3 tangent = linkVector.normalized;
if (rope.blueprint.usesOrientedParticles)
{
frame.Transport(nextPos, tangent, rope.GetParticleOrientation(elm.particle1) * Vector3.up, twist);
twist += sectionTwist;
}
else
{
frame.Transport(nextPos, tangent, sectionTwist);
}
if (linkInstances[i] != null)
{
linkInstances[i].SetActive(true);
Transform linkTransform = linkInstances[i].transform;
linkTransform.position = pos + linkVector * 0.5f;
linkTransform.localScale = rope.GetParticleMaxRadius(elm.particle1) * 2 * linkScale;
linkTransform.rotation = Quaternion.LookRotation(tangent, frame.normal);
}
lastParticle = elm.particle2;
}
for (int i = elementCount; i < linkInstances.Count; ++i)
{
if (linkInstances[i] != null)
linkInstances[i].SetActive(false);
}
}
}
}
}
| 33.668605 | 140 | 0.518218 | [
"MIT"
] | CalvinFehl/ColtsWithCalvin | Assets/Obi/Scripts/RopeAndRod/Rendering/ObiRopeChainRenderer.cs | 5,791 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc.RazorPages
{
internal class RazorPagesOptionsConfigureCompatibilityOptions : ConfigureCompatibilityOptions<RazorPagesOptions>
{
public RazorPagesOptionsConfigureCompatibilityOptions(
ILoggerFactory loggerFactory,
IOptions<MvcCompatibilityOptions> compatibilityOptions)
: base(loggerFactory, compatibilityOptions)
{
}
protected override IReadOnlyDictionary<string, object> DefaultValues
{
get
{
var values = new Dictionary<string, object>();
if (Version >= CompatibilityVersion.Version_2_1)
{
values[nameof(RazorPagesOptions.AllowAreas)] = true;
values[nameof(RazorPagesOptions.AllowMappingHeadRequestsToGetHandler)] = true;
}
if (Version >= CompatibilityVersion.Version_2_2)
{
values[nameof(RazorPagesOptions.AllowDefaultHandlingForOptionsRequests)] = true;
}
return values;
}
}
}
}
| 34.904762 | 116 | 0.645293 | [
"Apache-2.0"
] | 251763889/Mvc | src/Microsoft.AspNetCore.Mvc.RazorPages/RazorPagesOptionsConfigureCompatibilityOptions.cs | 1,468 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class WaterCollector : MonoBehaviour
{
private Pipe pipe;
void Start()
{
pipe = GetComponentInParent<Pipe>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
// if (pipe.collectWater(collision.gameObject.GetComponent<Rigidbody2D>().velocity, this.tag))
// Destroy(collision.gameObject, 0.1f);
if (pipe.collectWater(collision.gameObject, this.tag)) {
// StartCoroutine(destroyWater(collision.gameObject));
collision.gameObject.SetActive(false);
}
}
IEnumerator destroyWater(GameObject water){
yield return new WaitForSeconds(0.08f);
water.SetActive(false);
}
}
| 26.903226 | 103 | 0.645084 | [
"MIT"
] | OccularFlow/Of-Mice-And-Messages | Assets/Team23/Scripts/Pipes/WaterCollector.cs | 836 | C# |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Linq;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Net;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using System.Reflection;
using NUnit.Framework;
#pragma warning disable 618
namespace Cassandra.IntegrationTests.Core
{
[Category("short")]
public class BasicTypeTests : SharedClusterTest
{
[Test]
[TestCassandraVersion(2, 0)]
public void QueryBinding()
{
string tableName = CreateSimpleTableAndInsert(0);
var sst = new SimpleStatement(string.Format("INSERT INTO {0}(id, label) VALUES(?, ?)", tableName));
Session.Execute(sst.Bind(new object[] { Guid.NewGuid(), "label" }));
}
/// <summary>
/// Validates that the Session.GetRequest (called within ExecuteAsync) method uses the session default paging size
/// which was set previously when the Builder was initialized
/// </summary>
[Test]
[TestCassandraVersion(2, 0)]
public void PagingOnBoundStatementTest_Async_UsingConfigBasedPagingSetting()
{
var pageSize = 10;
var queryOptions = new QueryOptions().SetPageSize(pageSize);
Builder builder = new Builder().WithQueryOptions(queryOptions).WithDefaultKeyspace(KeyspaceName);
builder.AddContactPoint(TestCluster.InitialContactPoint);
using (ISession session = builder.Build().Connect())
{
var totalRowLength = 1003;
Tuple<string, string> tableNameAndStaticKeyVal = CreateTableWithCompositeIndexAndInsert(session, totalRowLength);
string statementToBeBound = "SELECT * from " + tableNameAndStaticKeyVal.Item1 + " where label=?";
PreparedStatement preparedStatementWithoutPaging = session.Prepare(statementToBeBound);
PreparedStatement preparedStatementWithPaging = session.Prepare(statementToBeBound);
BoundStatement boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(tableNameAndStaticKeyVal.Item2);
BoundStatement boundStatemetWithPaging = preparedStatementWithPaging.Bind(tableNameAndStaticKeyVal.Item2);
var rsWithSessionPagingInherited = session.ExecuteAsync(boundStatemetWithPaging).Result;
var rsWithoutPagingInherited = Session.Execute(boundStatemetWithoutPaging);
//Check that the internal list of items count is pageSize
Assert.AreEqual(pageSize, rsWithSessionPagingInherited.InnerQueueCount);
Assert.AreEqual(totalRowLength, rsWithoutPagingInherited.InnerQueueCount);
var allTheRowsPaged = rsWithSessionPagingInherited.ToList();
Assert.AreEqual(totalRowLength, allTheRowsPaged.Count);
}
}
[Test]
[TestCassandraVersion(2, 0)]
public void PagingOnBoundStatementTest()
{
var pageSize = 10;
var totalRowLength = 1003;
Tuple<string, string> tableNameAndStaticKeyVal = CreateTableWithCompositeIndexAndInsert(Session, totalRowLength);
string statementToBeBound = "SELECT * from " + tableNameAndStaticKeyVal.Item1 + " where label=?";
PreparedStatement preparedStatementWithoutPaging = Session.Prepare(statementToBeBound);
PreparedStatement preparedStatementWithPaging = Session.Prepare(statementToBeBound);
BoundStatement boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(tableNameAndStaticKeyVal.Item2);
BoundStatement boundStatemetWithPaging = preparedStatementWithPaging.Bind(tableNameAndStaticKeyVal.Item2);
boundStatemetWithPaging.SetPageSize(pageSize);
var rsWithPaging = Session.Execute(boundStatemetWithPaging);
var rsWithoutPaging = Session.Execute(boundStatemetWithoutPaging);
//Check that the internal list of items count is pageSize
Assert.AreEqual(pageSize, rsWithPaging.InnerQueueCount);
Assert.AreEqual(totalRowLength, rsWithoutPaging.InnerQueueCount);
var allTheRowsPaged = rsWithPaging.ToList();
Assert.AreEqual(totalRowLength, allTheRowsPaged.Count);
}
[Test]
[TestCassandraVersion(2, 0)]
public void PagingOnBoundStatementTest_PageOverOneRow()
{
var pageSize = 10;
var totalRowLength = 11;
string tableName = CreateSimpleTableAndInsert(totalRowLength);
// insert a guid that we'll keep track of
Guid guid = Guid.NewGuid();
Session.Execute(string.Format("INSERT INTO {2} (id, label) VALUES({0},'{1}')", guid, "LABEL_12345", tableName));
string statementToBeBound = "SELECT * from " + tableName + " where id=?";
PreparedStatement preparedStatementWithoutPaging = Session.Prepare(statementToBeBound);
PreparedStatement preparedStatementWithPaging = Session.Prepare(statementToBeBound);
BoundStatement boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(guid);
BoundStatement boundStatemetWithPaging = preparedStatementWithPaging.Bind(guid);
boundStatemetWithPaging.SetPageSize(pageSize);
var rsWithPaging = Session.Execute(boundStatemetWithPaging);
var rsWithoutPaging = Session.Execute(boundStatemetWithoutPaging);
//Check that the internal list of items count is pageSize
Assert.AreEqual(1, rsWithPaging.InnerQueueCount);
Assert.AreEqual(1, rsWithoutPaging.InnerQueueCount);
var allTheRowsPaged = rsWithPaging.ToList();
Assert.AreEqual(1, allTheRowsPaged.Count);
}
[Test]
[TestCassandraVersion(2, 0)]
public void PagingOnBoundStatementTest_PageOverZeroRows()
{
var pageSize = 10;
var totalRowLength = 11;
string tableName = CreateSimpleTableAndInsert(totalRowLength);
// insert a guid that we'll keep track of
Guid guid = Guid.NewGuid();
string statementToBeBound = "SELECT * from " + tableName + " where id=?";
PreparedStatement preparedStatementWithoutPaging = Session.Prepare(statementToBeBound);
PreparedStatement preparedStatementWithPaging = Session.Prepare(statementToBeBound);
BoundStatement boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(guid);
BoundStatement boundStatemetWithPaging = preparedStatementWithPaging.Bind(guid);
boundStatemetWithPaging.SetPageSize(pageSize);
var rsWithPaging = Session.Execute(boundStatemetWithPaging);
var rsWithoutPaging = Session.Execute(boundStatemetWithoutPaging);
//Check that the internal list of items count is pageSize
Assert.AreEqual(0, rsWithPaging.InnerQueueCount);
Assert.AreEqual(0, rsWithoutPaging.InnerQueueCount);
var allTheRowsPaged = rsWithPaging.ToList();
Assert.AreEqual(0, allTheRowsPaged.Count);
}
[Test]
[TestCassandraVersion(2, 0)]
public void PagingOnSimpleStatementTest()
{
var pageSize = 10;
var totalRowLength = 1003;
var table = CreateSimpleTableAndInsert(totalRowLength);
var statementWithPaging = new SimpleStatement("SELECT * FROM " + table);
var statementWithoutPaging = new SimpleStatement("SELECT * FROM " + table);
statementWithoutPaging.SetPageSize(int.MaxValue);
statementWithPaging.SetPageSize(pageSize);
var rsWithPaging = Session.Execute(statementWithPaging);
var rsWithoutPaging = Session.Execute(statementWithoutPaging);
//Check that the internal list of items count is pageSize
Assert.True(rsWithPaging.InnerQueueCount == pageSize);
Assert.True(rsWithoutPaging.InnerQueueCount == totalRowLength);
var allTheRowsPaged = rsWithPaging.ToList();
Assert.True(allTheRowsPaged.Count == totalRowLength);
}
[Test]
[TestCassandraVersion(2, 0)]
public void QueryPaging()
{
var pageSize = 10;
var totalRowLength = 1003;
var table = CreateSimpleTableAndInsert(totalRowLength);
var rsWithoutPaging = Session.Execute("SELECT * FROM " + table, int.MaxValue);
//It should have all the rows already in the inner list
Assert.AreEqual(totalRowLength, rsWithoutPaging.InnerQueueCount);
var rs = Session.Execute("SELECT * FROM " + table, pageSize);
//Check that the internal list of items count is pageSize
Assert.AreEqual(pageSize, rs.InnerQueueCount);
//Use Linq to iterate through all the rows
var allTheRowsPaged = rs.ToList();
Assert.AreEqual(totalRowLength, allTheRowsPaged.Count);
}
[Test]
[TestCassandraVersion(2, 0)]
public void QueryPagingParallel()
{
var pageSize = 25;
var totalRowLength = 300;
var table = CreateSimpleTableAndInsert(totalRowLength);
var query = new SimpleStatement(String.Format("SELECT * FROM {0} LIMIT 10000", table))
.SetPageSize(pageSize);
var rs = Session.Execute(query);
Assert.AreEqual(pageSize, rs.GetAvailableWithoutFetching());
var counterList = new ConcurrentBag<int>();
Action iterate = () =>
{
var counter = rs.Count();
counterList.Add(counter);
};
//Iterate in parallel the RowSet
Parallel.Invoke(iterate, iterate, iterate, iterate);
//Check that the sum of all rows in different threads is the same as total rows
Assert.AreEqual(totalRowLength, counterList.Sum());
}
[Test]
[TestCassandraVersion(2, 0)]
public void QueryPagingMultipleTimesOverTheSameStatement()
{
var pageSize = 25;
var totalRowLength = 300;
var times = 10;
var table = CreateSimpleTableAndInsert(totalRowLength);
var statement = new SimpleStatement(String.Format("SELECT * FROM {0} LIMIT 10000", table))
.SetPageSize(pageSize);
var counter = 0;
for (var i = 0; i < times; i++)
{
var rs = Session.Execute(statement);
counter += rs.Count();
}
//Check that the sum of all rows in different threads is the same as total rows
Assert.AreEqual(totalRowLength * times, counter);
}
[Test]
[TestCassandraVersion(2, 0)]
public void QueryPagingManual()
{
var pageSize = 10;
var totalRowLength = 15;
var table = CreateSimpleTableAndInsert(totalRowLength);
var rs = Session.Execute(new SimpleStatement("SELECT * FROM " + table).SetAutoPage(false).SetPageSize(pageSize));
Assert.NotNull(rs.PagingState);
//It should have just the first page of rows
Assert.AreEqual(pageSize, rs.InnerQueueCount);
//Linq iteration should not make it to page
Assert.AreEqual(pageSize, rs.Count());
rs = Session.Execute(new SimpleStatement("SELECT * FROM " + table).SetAutoPage(false).SetPageSize(pageSize).SetPagingState(rs.PagingState));
//It should only contain the following page rows
Assert.AreEqual(totalRowLength - pageSize, rs.Count());
}
[Test]
public void QueryTraceEnabledTest()
{
var rs = Session.Execute(new SimpleStatement("SELECT * from system.local").EnableTracing());
Assert.NotNull(rs.Info.QueryTrace);
Assert.AreEqual(IPAddress.Parse(TestCluster.InitialContactPoint), rs.Info.QueryTrace.Coordinator);
Assert.Greater(rs.Info.QueryTrace.Events.Count, 0);
if (Session.BinaryProtocolVersion >= 4)
{
Assert.NotNull(rs.Info.QueryTrace.ClientAddress);
}
else
{
Assert.Null(rs.Info.QueryTrace.ClientAddress);
}
}
[Test]
public void QueryTraceDisabledByDefaultTest()
{
var rs = Session.Execute(new SimpleStatement("SELECT * from system.local"));
Assert.Null(rs.Info.QueryTrace);
}
/// Tests that the default consistency level for queries is LOCAL_ONE
///
/// LocalOne_Is_Default_Consistency tests that the default consistency level for all queries is LOCAL_ONE. It performs
/// a simple select statement and verifies that the result set metadata shows that the achieved consistency level is LOCAL_ONE.
///
/// @since 3.0.0
/// @jira_ticket CSHARP-378
/// @expected_result The default consistency level should be LOCAL_ONE
///
/// @test_category consistency
[Test]
public void LocalOne_Is_Default_Consistency()
{
var rs = Session.Execute(new SimpleStatement("SELECT * from system.local"));
Assert.AreEqual(ConsistencyLevel.LocalOne, rs.Info.AchievedConsistency);
}
[Test]
public void Counter()
{
TestCounters();
}
[Test]
public void TypeBlob()
{
InsertingSingleValue(typeof(byte));
}
[Test]
public void TypeASCII()
{
InsertingSingleValue(typeof(Char));
}
[Test]
public void TypeDecimal()
{
InsertingSingleValue(typeof(Decimal));
}
[Test]
public void TypeVarInt()
{
InsertingSingleValue(typeof(BigInteger));
}
[Test]
public void TypeBigInt()
{
InsertingSingleValue(typeof(Int64));
}
[Test]
public void TypeDouble()
{
InsertingSingleValue(typeof(Double));
}
[Test]
public void TypeFloat()
{
InsertingSingleValue(typeof(Single));
}
[Test]
public void TypeInt()
{
InsertingSingleValue(typeof(Int32));
}
[Test]
public void TypeBoolean()
{
InsertingSingleValue(typeof(Boolean));
}
[Test]
public void TypeUUID()
{
InsertingSingleValue(typeof(Guid));
}
[Test]
public void TypeTimestamp()
{
TimestampTest();
}
[Test]
public void TypeInt_Max()
{
ExceedingCassandraType(typeof(Int32), typeof(Int32));
}
[Test]
public void TypeBigInt_Max()
{
ExceedingCassandraType(typeof(Int64), typeof(Int64));
}
[Test]
public void TypeFloat_Max()
{
ExceedingCassandraType(typeof(Single), typeof(Single));
}
[Test]
public void TypeDouble_Max()
{
ExceedingCassandraType(typeof(Double), typeof(Double));
}
[Test]
public void ExceedingCassandraInt()
{
ExceedingCassandraType(typeof(Int32), typeof(Int64), false);
}
[Test]
public void ExceedingCassandraFloat()
{
ExceedingCassandraType(typeof(Single), typeof(Double), false);
}
/// <summary>
/// Test the convertion of a decimal value ( with a negative scale) stored in a column.
///
/// @jira CSHARP-453 https://datastax-oss.atlassian.net/browse/CSHARP-453
///
/// </summary>
[Test]
public void DecimalWithNegativeScaleTest()
{
const string query = "CREATE TABLE decimal_neg_scale(id uuid PRIMARY KEY, value decimal);";
QueryTools.ExecuteSyncNonQuery(Session, query);
const string insertQuery = @"INSERT INTO decimal_neg_scale (id, value) VALUES (?, ?)";
var preparedStatement = Session.Prepare(insertQuery);
const int scale = -1;
var scaleBytes = BitConverter.GetBytes(scale);
if (BitConverter.IsLittleEndian)
Array.Reverse(scaleBytes);
var bytes = new byte[scaleBytes.Length + 1];
Array.Copy(scaleBytes, bytes, scaleBytes.Length);
bytes[scaleBytes.Length] = 5;
var firstRowValues = new object[] { Guid.NewGuid(), bytes };
Session.Execute(preparedStatement.Bind(firstRowValues));
var row = Session.Execute("SELECT * FROM decimal_neg_scale").First();
var decValue = row.GetValue<decimal>("value");
Assert.AreEqual(50, decValue);
const string dropQuery = "DROP TABLE decimal_neg_scale;";
QueryTools.ExecuteSyncNonQuery(Session, dropQuery);
}
////////////////////////////////////
/// Test Helpers
////////////////////////////////////
/// <summary>
/// Creates a table and inserts a number of records synchronously.
/// </summary>
/// <returns>The name of the table</returns>
private string CreateSimpleTableAndInsert(int rowsInTable)
{
string tableName = TestUtils.GetUniqueTableName();
QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"
CREATE TABLE {0}(
id uuid PRIMARY KEY,
label text);", tableName));
for (int i = 0; i < rowsInTable; i++)
{
Session.Execute(string.Format("INSERT INTO {2} (id, label) VALUES({0},'{1}')", Guid.NewGuid(), "LABEL" + i, tableName));
}
return tableName;
}
/// <summary>
/// Creates a table with a composite index and inserts a number of records synchronously.
/// </summary>
/// <returns>The name of the table</returns>
private Tuple<string, string> CreateTableWithCompositeIndexAndInsert(ISession session, int rowsInTable)
{
string tableName = TestUtils.GetUniqueTableName();
string staticClusterKeyStr = "staticClusterKeyStr";
QueryTools.ExecuteSyncNonQuery(session, string.Format(@"
CREATE TABLE {0} (
id text,
label text,
PRIMARY KEY (label, id));",
tableName));
for (int i = 0; i < rowsInTable; i++)
{
session.Execute(string.Format("INSERT INTO {2} (label, id) VALUES('{0}','{1}')", staticClusterKeyStr, Guid.NewGuid().ToString(), tableName));
}
Tuple<string, string> infoTuple = new Tuple<string, string>(tableName, staticClusterKeyStr);
return infoTuple;
}
public void ExceedingCassandraType(Type toExceed, Type toExceedWith, bool sameOutput = true)
{
string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(toExceed);
string tableName = TestUtils.GetUniqueTableName();
var query = String.Format("CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, label text, number {1});", tableName, cassandraDataTypeName);
QueryTools.ExecuteSyncNonQuery(Session, query);
object Minimum = toExceedWith.GetTypeInfo().GetField("MinValue").GetValue(this);
object Maximum = toExceedWith.GetTypeInfo().GetField("MaxValue").GetValue(this);
var row1 = new object[3] { Guid.NewGuid(), "Minimum", Minimum };
var row2 = new object[3] { Guid.NewGuid(), "Maximum", Maximum };
var toInsert_and_Check = new List<object[]>(2) { row1, row2 };
if (toExceedWith == typeof(Double) || toExceedWith == typeof(Single))
{
Minimum = Minimum.GetType().GetTypeInfo().GetMethod("ToString", new[] { typeof(string) }).Invoke(Minimum, new object[1] { "r" });
Maximum = Maximum.GetType().GetTypeInfo().GetMethod("ToString", new[] { typeof(string) }).Invoke(Maximum, new object[1] { "r" });
if (!sameOutput) //for ExceedingCassandra_FLOAT() test case
{
toInsert_and_Check[0][2] = Single.NegativeInfinity;
toInsert_and_Check[1][2] = Single.PositiveInfinity;
}
}
try
{
QueryTools.ExecuteSyncNonQuery(Session,
string.Format("INSERT INTO {0}(tweet_id, label, number) VALUES ({1}, '{2}', {3});", tableName,
toInsert_and_Check[0][0], toInsert_and_Check[0][1], Minimum), null);
QueryTools.ExecuteSyncNonQuery(Session,
string.Format("INSERT INTO {0}(tweet_id, label, number) VALUES ({1}, '{2}', {3});", tableName,
toInsert_and_Check[1][0], toInsert_and_Check[1][1], Maximum), null);
}
catch (InvalidQueryException)
{
if (!sameOutput && toExceed == typeof(Int32)) //for ExceedingCassandra_INT() test case
{
return;
}
}
QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.One, toInsert_and_Check);
}
public void TestCounters()
{
string tableName = TestUtils.GetUniqueTableName();
try
{
var query = string.Format("CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, incdec counter);", tableName);
QueryTools.ExecuteSyncNonQuery(Session, query);
}
catch (AlreadyExistsException)
{
}
Guid tweet_id = Guid.NewGuid();
Parallel.For(0, 100,
i =>
{
QueryTools.ExecuteSyncNonQuery(Session,
string.Format(@"UPDATE {0} SET incdec = incdec {2} WHERE tweet_id = {1};", tableName,
tweet_id, (i % 2 == 0 ? "-" : "+") + i));
});
QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(),
new List<object[]> { new object[2] { tweet_id, (Int64)50 } });
}
public void InsertingSingleValue(Type tp)
{
string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(tp);
string tableName = TestUtils.GetUniqueTableName();
try
{
var query = string.Format(@"CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, value {1});", tableName, cassandraDataTypeName);
QueryTools.ExecuteSyncNonQuery(Session, query);
}
catch (AlreadyExistsException)
{
}
var toInsert = new List<object[]>(1);
object val = Randomm.RandomVal(tp);
if (tp == typeof(string))
val = "'" + val.ToString().Replace("'", "''") + "'";
var row1 = new object[2] { Guid.NewGuid(), val };
toInsert.Add(row1);
bool isFloatingPoint = false;
if (row1[1].GetType() == typeof(string) || row1[1].GetType() == typeof(byte[]))
QueryTools.ExecuteSyncNonQuery(Session,
string.Format("INSERT INTO {0}(tweet_id,value) VALUES ({1}, {2});", tableName, toInsert[0][0],
row1[1].GetType() == typeof(byte[])
? "0x" + CqlQueryTools.ToHex((byte[])toInsert[0][1])
: "'" + toInsert[0][1] + "'"), null);
// rndm.GetType().GetMethod("Next" + tp.Name).Invoke(rndm, new object[] { })
else
{
if (tp == typeof(Single) || tp == typeof(Double))
isFloatingPoint = true;
QueryTools.ExecuteSyncNonQuery(Session,
string.Format("INSERT INTO {0}(tweet_id,value) VALUES ({1}, {2});", tableName, toInsert[0][0],
!isFloatingPoint
? toInsert[0][1]
: toInsert[0][1].GetType()
.GetMethod("ToString", new[] { typeof(string) })
.Invoke(toInsert[0][1], new object[] { "r" })), null);
}
QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), toInsert);
}
public void TimestampTest()
{
string tableName = TestUtils.GetUniqueTableName();
var createQuery = string.Format(@"CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, ts timestamp);", tableName);
QueryTools.ExecuteSyncNonQuery(Session, createQuery);
QueryTools.ExecuteSyncNonQuery(Session,
string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
"2011-02-03 04:05+0000"), null);
QueryTools.ExecuteSyncNonQuery(Session,
string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
220898707200000), null);
QueryTools.ExecuteSyncNonQuery(Session, string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(), 0),
null);
QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
}
}
}
| 42.725309 | 157 | 0.576717 | [
"Apache-2.0"
] | 902Software/csharp-driver | src/Cassandra.IntegrationTests/Core/BasicTypeTests.cs | 27,688 | C# |
using System;
namespace CcAcca.LogEvents
{
public class AppStoppedLogEventInfo : LogEventInfo
{
private const string ShutdownMetricKey = "ShutdownMsec";
private const string RuntimeMetricKey = "RuntimeMinutes";
public AppStoppedLogEventInfo(DateTime? signalTime = null, DateTime? appStarted = null) : base("Stopped", LogPrefixes.AppEvent)
{
if (signalTime.HasValue)
{
ShutdownDuration = DateTime.Now - signalTime.Value;
}
if (appStarted.HasValue)
{
TotalRuntime = DateTime.Now - appStarted.Value;
}
}
public TimeSpan ShutdownDuration
{
get => Metrics.ContainsKey(ShutdownMetricKey)
? TimeSpan.FromMilliseconds(Metrics[ShutdownMetricKey])
: TimeSpan.Zero;
set => Metrics[ShutdownMetricKey] = Math.Round(value.TotalMilliseconds, 0);
}
public TimeSpan TotalRuntime
{
get => Metrics.ContainsKey(RuntimeMetricKey)
? TimeSpan.FromMinutes(Metrics[RuntimeMetricKey])
: TimeSpan.Zero;
set => Metrics[RuntimeMetricKey] = Math.Round(value.TotalMinutes, 2);
}
}
} | 33.473684 | 135 | 0.592767 | [
"MIT"
] | christianacca/LogEvents | src/CcAcca.LogEvents/AppStoppedLogEventInfo.cs | 1,274 | C# |
using System.Collections.Generic;
namespace Veldrid.Assets
{
public static class CreatedResourceCache
{
private static readonly Dictionary<object, object> s_cache = new Dictionary<object, object>();
public static void ClearCache() => s_cache.Clear();
public static bool TryGetCachedItem<TKey, TValue>(TKey key, out TValue value)
{
object fromCache;
if (!s_cache.TryGetValue(key, out fromCache))
{
value = default(TValue);
return false;
}
else
{
value = (TValue)fromCache;
return true;
}
}
public static void CacheItem<TKey, TValue>(TKey key, TValue value)
{
s_cache.Add(key, value);
}
}
}
| 26.741935 | 102 | 0.54041 | [
"MIT"
] | mellinoe/Veldrid-3.0 | src/Veldrid.Assets/CreatedResourceCache.cs | 831 | C# |
using TaskoMask.Application.Share.Dtos.Workspace.Owners;
using TaskoMask.Application.Share.Helpers;
using TaskoMask.Application.Core.Queries;
namespace TaskoMask.Application.Workspace.Owners.Queries.Models
{
public class SearchOwnersQuery:BaseQuery<PaginatedListReturnType<OwnerOutputDto>>
{
public SearchOwnersQuery(int page, int recordsPerPage, string term)
{
Page = page;
RecordsPerPage = recordsPerPage;
Term = term;
}
public int Page { get;}
public int RecordsPerPage { get; }
public string Term { get; }
}
}
| 29.142857 | 84 | 0.678105 | [
"MIT"
] | GhalamborM/TaskoMask | Src/Libraries/2-Application/Application/Workspace/Owners/Queries/Models/SearchOwnersQuery.cs | 614 | C# |
//
// MidiJack - MIDI Input Plugin for Unity
//
// Copyright (C) 2013-2016 Keijiro Takahashi
//
// 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.
//
namespace MidiJack
{
// MIDI channel names
public enum MidiChannel
{
Ch1, // 0
Ch2, // 1
Ch3,
Ch4,
Ch5,
Ch6,
Ch7,
Ch8,
Ch9,
Ch10,
Ch11,
Ch12,
Ch13,
Ch14,
Ch15,
Ch16,
All // 16
}
// MIDI message structure
public struct MidiMessage
{
public uint source; // MIDI source (endpoint) ID
public byte status; // MIDI status byte
public byte data1; // MIDI data bytes
public byte data2;
public MidiMessage(ulong data)
{
source = (uint)(data & 0xffffffffUL);
status = (byte)((data >> 32) & 0xff);
data1 = (byte)((data >> 40) & 0xff);
data2 = (byte)((data >> 48) & 0xff);
}
public MidiMessage(uint source, byte status, byte data1, byte data2)
{
this.source = source;
this.status = status;
this.data1 = data1;
this.data2 = data2;
}
public override string ToString()
{
const string fmt = "s({0:X2}) d({1:X2},{2:X2}) from {3:X8}";
return string.Format(fmt, status, data1, data2, source);
}
}
}
| 31.113924 | 80 | 0.604963 | [
"Unlicense"
] | Ivorforce/MidiJack | Assets/MidiJack/Midi.cs | 2,458 | 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 TaskerClient.Properties
{
/// <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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TaskerClient.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;
}
}
}
}
| 38.625 | 178 | 0.60338 | [
"BSD-3-Clause"
] | grzegorzpietrzak321/TaskerClient | Properties/Resources.Designer.cs | 2,783 | C# |
namespace ClearHl7.Codes.V280
{
/// <summary>
/// HL7 Version 2 Table 0168 - Processing Priority.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0168</remarks>
public enum CodeProcessingPriority
{
/// <summary>
/// A - As soon as possible (a priority lower than stat).
/// </summary>
AsSoonAsPossible,
/// <summary>
/// B - Do at bedside or portable (may be used with other codes).
/// </summary>
DoAtBedsideOrPortable,
/// <summary>
/// C - Measure continuously (e.g., arterial line blood pressure).
/// </summary>
MeasureContinuously,
/// <summary>
/// P - Preoperative (to be done prior to surgery).
/// </summary>
Preoperative,
/// <summary>
/// R - Routine.
/// </summary>
Routine,
/// <summary>
/// S - Stat (do immediately).
/// </summary>
Stat,
/// <summary>
/// T - Timing critical (do as near as possible to requested time).
/// </summary>
TimingCritical
}
} | 26.909091 | 75 | 0.48902 | [
"MIT"
] | davebronson/clear-hl7-net | src/ClearHl7.Codes/V280/CodeProcessingPriority.cs | 1,186 | 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("MvxPluginNugetTest.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Zuehlke Engineering")]
[assembly: AssemblyProduct("MvxPluginNugetTest.iOS")]
[assembly: AssemblyCopyright("Copyright � Zuehlke Engineering 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")]
// 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("2.1.3")]
[assembly: AssemblyVersion("2.1.3")]
[assembly: AssemblyFileVersion("2.0.0")]
| 39.189189 | 84 | 0.754483 | [
"Apache-2.0"
] | xabre/MvvmCross---Bluetooth-LE | .build/PluginNugetTest/MvxPluginNugetTest.iOS/Properties/AssemblyInfo.cs | 1,452 | C# |
using CLAP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCApp.WebServices.SubmitResumeWebService;
namespace TCApp.Cmd
{
class Actions
{
SubmitResumeSoapClient client = new SubmitResumeSoapClient();
[Verb]
void GetInstructions()
{
Console.WriteLine("INSTRUCTIONS.. SHOULD YOU CHOOSE TO ACCEPT:\n\n{0}", client.GetInstructions());
}
[Verb]
void SubmitInformation([Required]string fname, [Required]string lname, [Required]string email, [Required]string phone)
{
var furtherInstructions = client.SubmitInformation(fname, lname, email, phone);
Console.WriteLine("FURTHER INSTRUCTIONS... SHOULD YOU CHOOSE TO ACCEPT:\n\n{0}", furtherInstructions);
}
}
}
| 29.310345 | 126 | 0.674118 | [
"MIT"
] | krcourville/tc-app | TCApp.Console/Actions.cs | 852 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client
{
public sealed class GitCommitChange
: IPropagatePropertyAccessPath
{
public GitCommitChange() { }
public GitCommitChange(GitCommitChangeType changeType, string revision, GitFile? old = null, GitFile? @new = null, GitDiffSize? diffSize = null, string? path = null)
{
ChangeType = changeType;
Old = old;
New = @new;
Revision = revision;
DiffSize = diffSize;
Path = path;
}
private PropertyValue<GitCommitChangeType> _changeType = new PropertyValue<GitCommitChangeType>(nameof(GitCommitChange), nameof(ChangeType));
[Required]
[JsonPropertyName("changeType")]
public GitCommitChangeType ChangeType
{
get => _changeType.GetValue();
set => _changeType.SetValue(value);
}
private PropertyValue<GitFile?> _old = new PropertyValue<GitFile?>(nameof(GitCommitChange), nameof(Old));
[JsonPropertyName("old")]
public GitFile? Old
{
get => _old.GetValue();
set => _old.SetValue(value);
}
private PropertyValue<GitFile?> _new = new PropertyValue<GitFile?>(nameof(GitCommitChange), nameof(New));
[JsonPropertyName("new")]
public GitFile? New
{
get => _new.GetValue();
set => _new.SetValue(value);
}
private PropertyValue<string> _revision = new PropertyValue<string>(nameof(GitCommitChange), nameof(Revision));
[Required]
[JsonPropertyName("revision")]
public string Revision
{
get => _revision.GetValue();
set => _revision.SetValue(value);
}
private PropertyValue<GitDiffSize?> _diffSize = new PropertyValue<GitDiffSize?>(nameof(GitCommitChange), nameof(DiffSize));
[JsonPropertyName("diffSize")]
public GitDiffSize? DiffSize
{
get => _diffSize.GetValue();
set => _diffSize.SetValue(value);
}
private PropertyValue<string?> _path = new PropertyValue<string?>(nameof(GitCommitChange), nameof(Path));
[JsonPropertyName("path")]
public string? Path
{
get => _path.GetValue();
set => _path.SetValue(value);
}
public void SetAccessPath(string path, bool validateHasBeenSet)
{
_changeType.SetAccessPath(path, validateHasBeenSet);
_old.SetAccessPath(path, validateHasBeenSet);
_new.SetAccessPath(path, validateHasBeenSet);
_revision.SetAccessPath(path, validateHasBeenSet);
_diffSize.SetAccessPath(path, validateHasBeenSet);
_path.SetAccessPath(path, validateHasBeenSet);
}
}
}
| 33.439655 | 173 | 0.602733 | [
"Apache-2.0"
] | PatrickRatzow/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Dtos/GitCommitChange.generated.cs | 3,879 | C# |
using System.Collections.Generic;
using System.Diagnostics;
namespace WK.Info.Services
{
[DebuggerDisplay("{Vocab,nq}")]
public class VocabModel
{
public string Vocab { get; set; }
public string Kana { get; set; }
public List<string> Meanings { get; set; }
public List<TagModel> Tags { get; set; }
}
public class VocabModelRaw : List<List<object>>
{
}
}
| 19.578947 | 48 | 0.693548 | [
"MIT"
] | luffyuzumaki/WK.Info | WK.Info/Services/Models/Vocab.cs | 374 | C# |
using System;
#if !NETSTANDARD1_4
using System.Runtime.Serialization;
using System.Security.Permissions;
#endif
namespace Expressive.Exceptions
{
/// <summary>
/// Represents an error that is thrown when a missing token is detected inside an <see cref="Expression"/>.
/// </summary>
#if !NETSTANDARD1_4
[Serializable]
#endif
public sealed class MissingTokenException : Exception
{
/// <summary>
/// Gets the token that is missing from the <see cref="Expression"/>.
/// </summary>
public char MissingToken { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="MissingTokenException"/> class with a specified error message and missing token.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="missingToken">The token that is missing.</param>
internal MissingTokenException(string message, char missingToken)
: base(message)
{
this.MissingToken = missingToken;
}
#if !NETSTANDARD1_4
/// <summary>
/// Set the <see cref="SerializationInfo"/> with information about this exception.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("MissingToken", MissingToken);
}
#endif
}
}
| 37.918367 | 146 | 0.65662 | [
"MIT"
] | bijington/expressive | Source/Expressive/Exceptions/MissingTokenException.cs | 1,860 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace QuickstartIdentityServer
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 26.148148 | 70 | 0.651558 | [
"MIT"
] | jinyuttt/QuickstarAuthServer | QuickstartIdentityServer/Program.cs | 706 | C# |
using System;
class MoonGravity
{
static void Main()
{
double manWeight = double.Parse(Console.ReadLine());
Console.WriteLine("{0:F3}", manWeight * 0.17);
}
}
| 15.833333 | 60 | 0.594737 | [
"MIT"
] | jorosoft/Telerik-Academy | Homeworks/C# Part 1/03.OperatorsAndExpressions/02.MoonGravity/MoonGravity.cs | 192 | C# |
/*
* Copyright 2010-2014 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 secretsmanager-2017-10-17.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.SecretsManager.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SecretsManager.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeleteSecret Request Marshaller
/// </summary>
public class DeleteSecretRequestMarshaller : IMarshaller<IRequest, DeleteSecretRequest> , 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((DeleteSecretRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DeleteSecretRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SecretsManager");
string target = "secretsmanager.DeleteSecret";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-10-17";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetForceDeleteWithoutRecovery())
{
context.Writer.WritePropertyName("ForceDeleteWithoutRecovery");
context.Writer.Write(publicRequest.ForceDeleteWithoutRecovery);
}
if(publicRequest.IsSetRecoveryWindowInDays())
{
context.Writer.WritePropertyName("RecoveryWindowInDays");
context.Writer.Write(publicRequest.RecoveryWindowInDays);
}
if(publicRequest.IsSetSecretId())
{
context.Writer.WritePropertyName("SecretId");
context.Writer.Write(publicRequest.SecretId);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DeleteSecretRequestMarshaller _instance = new DeleteSecretRequestMarshaller();
internal static DeleteSecretRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteSecretRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.068376 | 139 | 0.622038 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/SecretsManager/Generated/Model/Internal/MarshallTransformations/DeleteSecretRequestMarshaller.cs | 4,220 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class questMenuState_ConditionType : questIUIConditionType
{
[Ordinal(0)] [RED("state")] public CEnum<questEUIMenuState> State { get; set; }
public questMenuState_ConditionType(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 26.75 | 115 | 0.731308 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/questMenuState_ConditionType.cs | 413 | C# |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(giri_webdev_livedemo.Startup))]
namespace giri_webdev_livedemo
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 19.333333 | 70 | 0.672414 | [
"MIT"
] | giri-webdev/giri-webdev.net.democodes | giri-webdev-livedemo/Startup.cs | 292 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace LibraryFactory
{
public interface ICon
{
//string _name;//err
}
public interface IConTrue
{
void InitCon();
DataTable GetTable();
string GetName();
}
public class con1 : ICon { }
public class con2 : ICon { }
public class CreateIconer
{
public static ICon CreateIcon(string name)
{
ICon a = null;
switch (name)
{
case "con1": a = new con1(); break;
case "con2": a = new con2(); break;
}
return a;
}
}
}
| 19.358974 | 52 | 0.490066 | [
"Unlicense"
] | lbbgit/TimeRace_Financial-IQ | TimeRace_Financial-IQ/LibraryFactory/_interface.cs | 757 | C# |
//
// IPopupWindowBackend.cs
//
// Author:
// Vsevolod Kukol <sevoku@microsoft.com>
//
// Copyright (c) 2017 (c) Microsoft Corporation
//
// 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.
namespace Xwt.Backends
{
public interface IPopupWindowBackend : IWindowBackend
{
void Initialize (IWindowFrameEventSink sink, PopupWindow.PopupType type);
}
}
| 40.647059 | 80 | 0.759768 | [
"MIT"
] | Bert1974/xwt | Xwt/Xwt.Backends/IPopupWindowBackend.cs | 1,384 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Bot.Builder.Luis.Models
{
using System;
using System.Collections.Generic;
using Microsoft.Rest;
using Newtonsoft.Json;
public partial class LuisResult
{
/// <summary>
/// Initializes a new instance of the LuisResult class.
/// </summary>
public LuisResult() { }
/// <summary>
/// Initializes a new instance of the LuisResult class.
/// </summary>
public LuisResult(string query, IList<EntityRecommendation> entities, IntentRecommendation topScoringIntent = default(IntentRecommendation), IList<IntentRecommendation> intents = default(IList<IntentRecommendation>), IList<CompositeEntity> compositeEntities = default(IList<CompositeEntity>), DialogResponse dialog = default(DialogResponse), string alteredQuery = default(string))
{
Query = query;
TopScoringIntent = topScoringIntent;
Intents = intents;
Entities = entities;
CompositeEntities = compositeEntities;
Dialog = dialog;
AlteredQuery = alteredQuery;
}
/// <summary>
/// The query sent to LUIS.
/// </summary>
[JsonProperty(PropertyName = "query")]
public string Query { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "topScoringIntent")]
public IntentRecommendation TopScoringIntent { get; set; }
/// <summary>
/// The intents found in the query text.
/// </summary>
[JsonProperty(PropertyName = "intents")]
public IList<IntentRecommendation> Intents { get; set; } = Array.Empty<IntentRecommendation>();
/// <summary>
/// The entities found in the query text.
/// </summary>
[JsonProperty(PropertyName = "entities")]
public IList<EntityRecommendation> Entities { get; set; } = Array.Empty<EntityRecommendation>();
/// <summary>
/// The composite entities found in the utterance.
/// </summary>
[JsonProperty(PropertyName = "compositeEntities")]
public IList<CompositeEntity> CompositeEntities { get; set; } = Array.Empty<CompositeEntity>();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "dialog")]
public DialogResponse Dialog { get; set; }
/// <summary>
/// The altered query used by LUIS to extract intent and entities. For
/// example, when Bing spell check is enabled for a model, this field
/// will contain the spell checked utterance.
/// </summary>
[JsonProperty(PropertyName = "alteredQuery")]
public string AlteredQuery { get; set; }
/// <summary>
/// Gets or sets the sentiment.
/// </summary>
/// <value>
/// The sentiment.
/// </value>
[JsonProperty(PropertyName = "sentimentAnalysis")]
public Sentiment Sentiment { get; set; }
/// <summary>
/// Validate the object. Throws ValidationException if validation fails.
/// </summary>
public virtual void Validate()
{
if (Query == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Query");
}
if (Entities == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Entities");
}
if (this.Entities != null)
{
foreach (var element in this.Entities)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.CompositeEntities != null)
{
foreach (var element1 in this.CompositeEntities)
{
if (element1 != null)
{
element1.Validate();
}
}
}
}
}
}
| 35.491935 | 388 | 0.562827 | [
"MIT"
] | Bhaskers-Blu-Org2/BotBuilder-V3 | CSharp/Library/Microsoft.Bot.Builder/Luis/Models/LuisResult.cs | 4,401 | C# |
using System;
using System.Collections;
using System.IO;
using My2C2P.Org.BouncyCastle.Asn1;
using My2C2P.Org.BouncyCastle.Asn1.Cms;
using My2C2P.Org.BouncyCastle.Asn1.CryptoPro;
using My2C2P.Org.BouncyCastle.Asn1.Nist;
using My2C2P.Org.BouncyCastle.Asn1.Oiw;
using My2C2P.Org.BouncyCastle.Asn1.Pkcs;
using My2C2P.Org.BouncyCastle.Asn1.TeleTrust;
using My2C2P.Org.BouncyCastle.Asn1.X509;
using My2C2P.Org.BouncyCastle.Asn1.X9;
using My2C2P.Org.BouncyCastle.Crypto;
using My2C2P.Org.BouncyCastle.Crypto.Parameters;
using My2C2P.Org.BouncyCastle.Security;
using My2C2P.Org.BouncyCastle.Utilities;
using My2C2P.Org.BouncyCastle.Utilities.Collections;
using My2C2P.Org.BouncyCastle.X509;
using My2C2P.Org.BouncyCastle.X509.Store;
namespace My2C2P.Org.BouncyCastle.Cms
{
public class DefaultDigestAlgorithmIdentifierFinder
{
private static readonly IDictionary digestOids = Platform.CreateHashtable();
private static readonly IDictionary digestNameToOids = Platform.CreateHashtable();
static DefaultDigestAlgorithmIdentifierFinder()
{
//
// digests
//
digestOids.Add(OiwObjectIdentifiers.MD4WithRsaEncryption, PkcsObjectIdentifiers.MD4);
digestOids.Add(OiwObjectIdentifiers.MD4WithRsa, PkcsObjectIdentifiers.MD4);
digestOids.Add(OiwObjectIdentifiers.Sha1WithRsa, OiwObjectIdentifiers.IdSha1);
digestOids.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption, NistObjectIdentifiers.IdSha224);
digestOids.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption, NistObjectIdentifiers.IdSha256);
digestOids.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption, NistObjectIdentifiers.IdSha384);
digestOids.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption, NistObjectIdentifiers.IdSha512);
digestOids.Add(PkcsObjectIdentifiers.MD2WithRsaEncryption, PkcsObjectIdentifiers.MD2);
digestOids.Add(PkcsObjectIdentifiers.MD4WithRsaEncryption, PkcsObjectIdentifiers.MD4);
digestOids.Add(PkcsObjectIdentifiers.MD5WithRsaEncryption, PkcsObjectIdentifiers.MD5);
digestOids.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption, OiwObjectIdentifiers.IdSha1);
digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha1, OiwObjectIdentifiers.IdSha1);
digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha224, NistObjectIdentifiers.IdSha224);
digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha256, NistObjectIdentifiers.IdSha256);
digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha384, NistObjectIdentifiers.IdSha384);
digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha512, NistObjectIdentifiers.IdSha512);
digestOids.Add(X9ObjectIdentifiers.IdDsaWithSha1, OiwObjectIdentifiers.IdSha1);
digestOids.Add(NistObjectIdentifiers.DsaWithSha224, NistObjectIdentifiers.IdSha224);
digestOids.Add(NistObjectIdentifiers.DsaWithSha256, NistObjectIdentifiers.IdSha256);
digestOids.Add(NistObjectIdentifiers.DsaWithSha384, NistObjectIdentifiers.IdSha384);
digestOids.Add(NistObjectIdentifiers.DsaWithSha512, NistObjectIdentifiers.IdSha512);
digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128, TeleTrusTObjectIdentifiers.RipeMD128);
digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160, TeleTrusTObjectIdentifiers.RipeMD160);
digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256, TeleTrusTObjectIdentifiers.RipeMD256);
digestOids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, CryptoProObjectIdentifiers.GostR3411);
digestOids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001, CryptoProObjectIdentifiers.GostR3411);
digestNameToOids.Add("SHA-1", OiwObjectIdentifiers.IdSha1);
digestNameToOids.Add("SHA-224", NistObjectIdentifiers.IdSha224);
digestNameToOids.Add("SHA-256", NistObjectIdentifiers.IdSha256);
digestNameToOids.Add("SHA-384", NistObjectIdentifiers.IdSha384);
digestNameToOids.Add("SHA-512", NistObjectIdentifiers.IdSha512);
digestNameToOids.Add("SHA1", OiwObjectIdentifiers.IdSha1);
digestNameToOids.Add("SHA224", NistObjectIdentifiers.IdSha224);
digestNameToOids.Add("SHA256", NistObjectIdentifiers.IdSha256);
digestNameToOids.Add("SHA384", NistObjectIdentifiers.IdSha384);
digestNameToOids.Add("SHA512", NistObjectIdentifiers.IdSha512);
digestNameToOids.Add("SHA3-224", NistObjectIdentifiers.IdSha3_224);
digestNameToOids.Add("SHA3-256", NistObjectIdentifiers.IdSha3_256);
digestNameToOids.Add("SHA3-384", NistObjectIdentifiers.IdSha3_384);
digestNameToOids.Add("SHA3-512", NistObjectIdentifiers.IdSha3_512);
digestNameToOids.Add("SHAKE-128", NistObjectIdentifiers.IdShake128);
digestNameToOids.Add("SHAKE-256", NistObjectIdentifiers.IdShake256);
digestNameToOids.Add("GOST3411", CryptoProObjectIdentifiers.GostR3411);
digestNameToOids.Add("MD2", PkcsObjectIdentifiers.MD2);
digestNameToOids.Add("MD4", PkcsObjectIdentifiers.MD4);
digestNameToOids.Add("MD5", PkcsObjectIdentifiers.MD5);
digestNameToOids.Add("RIPEMD128", TeleTrusTObjectIdentifiers.RipeMD128);
digestNameToOids.Add("RIPEMD160", TeleTrusTObjectIdentifiers.RipeMD160);
digestNameToOids.Add("RIPEMD256", TeleTrusTObjectIdentifiers.RipeMD256);
}
public AlgorithmIdentifier find(AlgorithmIdentifier sigAlgId)
{
AlgorithmIdentifier digAlgId;
if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss))
{
digAlgId = RsassaPssParameters.GetInstance(sigAlgId.Parameters).HashAlgorithm;
}
else
{
digAlgId = new AlgorithmIdentifier((DerObjectIdentifier)digestOids[sigAlgId.Algorithm], DerNull.Instance);
}
return digAlgId;
}
public AlgorithmIdentifier find(String digAlgName)
{
return new AlgorithmIdentifier((DerObjectIdentifier)digestNameToOids[digAlgName], DerNull.Instance);
}
}
public class CmsSignedGenerator
{
/**
* Default type for the signed data.
*/
public static readonly string Data = CmsObjectIdentifiers.Data.Id;
public static readonly string DigestSha1 = OiwObjectIdentifiers.IdSha1.Id;
public static readonly string DigestSha224 = NistObjectIdentifiers.IdSha224.Id;
public static readonly string DigestSha256 = NistObjectIdentifiers.IdSha256.Id;
public static readonly string DigestSha384 = NistObjectIdentifiers.IdSha384.Id;
public static readonly string DigestSha512 = NistObjectIdentifiers.IdSha512.Id;
public static readonly string DigestMD5 = PkcsObjectIdentifiers.MD5.Id;
public static readonly string DigestGost3411 = CryptoProObjectIdentifiers.GostR3411.Id;
public static readonly string DigestRipeMD128 = TeleTrusTObjectIdentifiers.RipeMD128.Id;
public static readonly string DigestRipeMD160 = TeleTrusTObjectIdentifiers.RipeMD160.Id;
public static readonly string DigestRipeMD256 = TeleTrusTObjectIdentifiers.RipeMD256.Id;
public static readonly string EncryptionRsa = PkcsObjectIdentifiers.RsaEncryption.Id;
public static readonly string EncryptionDsa = X9ObjectIdentifiers.IdDsaWithSha1.Id;
public static readonly string EncryptionECDsa = X9ObjectIdentifiers.ECDsaWithSha1.Id;
public static readonly string EncryptionRsaPss = PkcsObjectIdentifiers.IdRsassaPss.Id;
public static readonly string EncryptionGost3410 = CryptoProObjectIdentifiers.GostR3410x94.Id;
public static readonly string EncryptionECGost3410 = CryptoProObjectIdentifiers.GostR3410x2001.Id;
internal IList _certs = Platform.CreateArrayList();
internal IList _crls = Platform.CreateArrayList();
internal IList _signers = Platform.CreateArrayList();
internal IDictionary _digests = Platform.CreateHashtable();
protected readonly SecureRandom rand;
protected CmsSignedGenerator()
: this(new SecureRandom())
{
}
/// <summary>Constructor allowing specific source of randomness</summary>
/// <param name="rand">Instance of <c>SecureRandom</c> to use.</param>
protected CmsSignedGenerator(
SecureRandom rand)
{
this.rand = rand;
}
internal protected virtual IDictionary GetBaseParameters(
DerObjectIdentifier contentType,
AlgorithmIdentifier digAlgId,
byte[] hash)
{
IDictionary param = Platform.CreateHashtable();
if (contentType != null)
{
param[CmsAttributeTableParameter.ContentType] = contentType;
}
param[CmsAttributeTableParameter.DigestAlgorithmIdentifier] = digAlgId;
param[CmsAttributeTableParameter.Digest] = hash.Clone();
return param;
}
internal protected virtual Asn1Set GetAttributeSet(
Asn1.Cms.AttributeTable attr)
{
return attr == null
? null
: new DerSet(attr.ToAsn1EncodableVector());
}
public void AddCertificates(
IX509Store certStore)
{
CollectionUtilities.AddRange(_certs, CmsUtilities.GetCertificatesFromStore(certStore));
}
public void AddCrls(
IX509Store crlStore)
{
CollectionUtilities.AddRange(_crls, CmsUtilities.GetCrlsFromStore(crlStore));
}
/**
* Add the attribute certificates contained in the passed in store to the
* generator.
*
* @param store a store of Version 2 attribute certificates
* @throws CmsException if an error occurse processing the store.
*/
public void AddAttributeCertificates(
IX509Store store)
{
try
{
foreach (IX509AttributeCertificate attrCert in store.GetMatches(null))
{
_certs.Add(new DerTaggedObject(false, 2,
AttributeCertificate.GetInstance(Asn1Object.FromByteArray(attrCert.GetEncoded()))));
}
}
catch (Exception e)
{
throw new CmsException("error processing attribute certs", e);
}
}
/**
* Add a store of precalculated signers to the generator.
*
* @param signerStore store of signers
*/
public void AddSigners(
SignerInformationStore signerStore)
{
foreach (SignerInformation o in signerStore.GetSigners())
{
_signers.Add(o);
AddSignerCallback(o);
}
}
/**
* Return a map of oids and byte arrays representing the digests calculated on the content during
* the last generate.
*
* @return a map of oids (as String objects) and byte[] representing digests.
*/
public IDictionary GetGeneratedDigests()
{
return Platform.CreateHashtable(_digests);
}
internal virtual void AddSignerCallback(
SignerInformation si)
{
}
internal static SignerIdentifier GetSignerIdentifier(X509Certificate cert)
{
return new SignerIdentifier(CmsUtilities.GetIssuerAndSerialNumber(cert));
}
internal static SignerIdentifier GetSignerIdentifier(byte[] subjectKeyIdentifier)
{
return new SignerIdentifier(new DerOctetString(subjectKeyIdentifier));
}
}
}
| 44.488806 | 124 | 0.698398 | [
"MIT"
] | 2C2P/My2C2PPKCS7 | My2C2PPKCS7/cms/CMSSignedGenerator.cs | 11,923 | C# |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects.GuiControls
{
public unsafe class GuiPaneControl : GuiControl
{
public GuiPaneControl()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiPaneControlCreateInstance());
}
public GuiPaneControl(uint pId) : base(pId)
{
}
public GuiPaneControl(string pName) : base(pName)
{
}
public GuiPaneControl(IntPtr pObjPtr) : base(pObjPtr)
{
}
public GuiPaneControl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public GuiPaneControl(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiPaneControlGetCaption(IntPtr ctrl);
private static _GuiPaneControlGetCaption _GuiPaneControlGetCaptionFunc;
internal static IntPtr GuiPaneControlGetCaption(IntPtr ctrl)
{
if (_GuiPaneControlGetCaptionFunc == null)
{
_GuiPaneControlGetCaptionFunc =
(_GuiPaneControlGetCaption)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlGetCaption"), typeof(_GuiPaneControlGetCaption));
}
return _GuiPaneControlGetCaptionFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiPaneControlSetCaption(IntPtr ctrl, string caption);
private static _GuiPaneControlSetCaption _GuiPaneControlSetCaptionFunc;
internal static void GuiPaneControlSetCaption(IntPtr ctrl, string caption)
{
if (_GuiPaneControlSetCaptionFunc == null)
{
_GuiPaneControlSetCaptionFunc =
(_GuiPaneControlSetCaption)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlSetCaption"), typeof(_GuiPaneControlSetCaption));
}
_GuiPaneControlSetCaptionFunc(ctrl, caption);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiPaneControlGetCaptionID(IntPtr ctrl);
private static _GuiPaneControlGetCaptionID _GuiPaneControlGetCaptionIDFunc;
internal static IntPtr GuiPaneControlGetCaptionID(IntPtr ctrl)
{
if (_GuiPaneControlGetCaptionIDFunc == null)
{
_GuiPaneControlGetCaptionIDFunc =
(_GuiPaneControlGetCaptionID)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlGetCaptionID"), typeof(_GuiPaneControlGetCaptionID));
}
return _GuiPaneControlGetCaptionIDFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiPaneControlSetCaptionID(IntPtr ctrl, string captionID);
private static _GuiPaneControlSetCaptionID _GuiPaneControlSetCaptionIDFunc;
internal static void GuiPaneControlSetCaptionID(IntPtr ctrl, string captionID)
{
if (_GuiPaneControlSetCaptionIDFunc == null)
{
_GuiPaneControlSetCaptionIDFunc =
(_GuiPaneControlSetCaptionID)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlSetCaptionID"), typeof(_GuiPaneControlSetCaptionID));
}
_GuiPaneControlSetCaptionIDFunc(ctrl, captionID);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _GuiPaneControlGetCollapsable(IntPtr ctrl);
private static _GuiPaneControlGetCollapsable _GuiPaneControlGetCollapsableFunc;
internal static bool GuiPaneControlGetCollapsable(IntPtr ctrl)
{
if (_GuiPaneControlGetCollapsableFunc == null)
{
_GuiPaneControlGetCollapsableFunc =
(_GuiPaneControlGetCollapsable)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlGetCollapsable"), typeof(_GuiPaneControlGetCollapsable));
}
return _GuiPaneControlGetCollapsableFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiPaneControlSetCollapsable(IntPtr ctrl, bool collapsable);
private static _GuiPaneControlSetCollapsable _GuiPaneControlSetCollapsableFunc;
internal static void GuiPaneControlSetCollapsable(IntPtr ctrl, bool collapsable)
{
if (_GuiPaneControlSetCollapsableFunc == null)
{
_GuiPaneControlSetCollapsableFunc =
(_GuiPaneControlSetCollapsable)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlSetCollapsable"), typeof(_GuiPaneControlSetCollapsable));
}
_GuiPaneControlSetCollapsableFunc(ctrl, collapsable);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _GuiPaneControlGetBarBehindText(IntPtr ctrl);
private static _GuiPaneControlGetBarBehindText _GuiPaneControlGetBarBehindTextFunc;
internal static bool GuiPaneControlGetBarBehindText(IntPtr ctrl)
{
if (_GuiPaneControlGetBarBehindTextFunc == null)
{
_GuiPaneControlGetBarBehindTextFunc =
(_GuiPaneControlGetBarBehindText)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlGetBarBehindText"), typeof(_GuiPaneControlGetBarBehindText));
}
return _GuiPaneControlGetBarBehindTextFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiPaneControlSetBarBehindText(IntPtr ctrl, bool enable);
private static _GuiPaneControlSetBarBehindText _GuiPaneControlSetBarBehindTextFunc;
internal static void GuiPaneControlSetBarBehindText(IntPtr ctrl, bool enable)
{
if (_GuiPaneControlSetBarBehindTextFunc == null)
{
_GuiPaneControlSetBarBehindTextFunc =
(_GuiPaneControlSetBarBehindText)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlSetBarBehindText"), typeof(_GuiPaneControlSetBarBehindText));
}
_GuiPaneControlSetBarBehindTextFunc(ctrl, enable);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiPaneControlCreateInstance();
private static _GuiPaneControlCreateInstance _GuiPaneControlCreateInstanceFunc;
internal static IntPtr GuiPaneControlCreateInstance()
{
if (_GuiPaneControlCreateInstanceFunc == null)
{
_GuiPaneControlCreateInstanceFunc =
(_GuiPaneControlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlCreateInstance"), typeof(_GuiPaneControlCreateInstance));
}
return _GuiPaneControlCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiPaneControlSetCollapsed(IntPtr ctrl, bool collapsed);
private static _GuiPaneControlSetCollapsed _GuiPaneControlSetCollapsedFunc;
internal static void GuiPaneControlSetCollapsed(IntPtr ctrl, bool collapsed)
{
if (_GuiPaneControlSetCollapsedFunc == null)
{
_GuiPaneControlSetCollapsedFunc =
(_GuiPaneControlSetCollapsed)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiPaneControlSetCollapsed"), typeof(_GuiPaneControlSetCollapsed));
}
_GuiPaneControlSetCollapsedFunc(ctrl, collapsed);
}
}
#endregion
#region Properties
public string Caption
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.GuiPaneControlGetCaption(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiPaneControlSetCaption(ObjectPtr->ObjPtr, value);
}
}
public string CaptionID
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.GuiPaneControlGetCaptionID(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiPaneControlSetCaptionID(ObjectPtr->ObjPtr, value);
}
}
public bool Collapsable
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiPaneControlGetCollapsable(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiPaneControlSetCollapsable(ObjectPtr->ObjPtr, value);
}
}
public bool BarBehindText
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiPaneControlGetBarBehindText(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiPaneControlSetBarBehindText(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
public void SetCollapsed(bool collapsed)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiPaneControlSetCollapsed(ObjectPtr->ObjPtr, collapsed);
}
#endregion
}
} | 41.675472 | 166 | 0.680279 | [
"MIT"
] | lukaspj/Torque6-Embedded-C- | Torque6/Engine/SimObjects/GuiControls/GuiPaneControl.cs | 11,044 | C# |
using Dragablz;
using MetroFtpClient.Core.Base;
using MetroFtpClient.Core.Configuration;
using MetroFtpClient.Core.Interfaces;
using MetroFtpClient.Infrastructure.Constants;
using MetroFtpClient.Infrastructure.Events;
using MetroFtpClient.Infrastructure.Interfaces;
using MetroFtpClient.Infrastructure.Notifications;
using MetroFtpClient.Model;
using Microsoft.Practices.Unity;
using Prism.Events;
using Prism.Interactivity.InteractionRequest;
using Prism.Regions;
namespace MetroFtpClient.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
/// <summary>
/// CTOR
/// </summary>
/// <param name="unityContainer">The unity container.</param>
/// <param name="regionManager">The region manager.</param>
/// <param name="eventAggrgator">The event aggregator.</param>
public MainWindowViewModel(IUnityContainer unityContainer, IRegionManager regionManager, IEventAggregator eventAggrgator) :
base(unityContainer, regionManager, eventAggrgator)
{
this.Title = "Metro FTP Client";
// Register to events
EventAggregator.GetEvent<UpdateStatusBarMessageEvent>().Subscribe(OnUpdateStatusBarMessageEventHandler);
_interTabClient = new DefaultInterTabClient();
this.ShowAddOrUpdateConnectionPopupRequest = this.Container.Resolve<InteractionRequest<AddOrUpdateConnectionNotification>>(InteractionRequests.ShowAddOrUpdateConnectionPopupRequest);
// Load application config
this.LoadApplicationConfigFile();
}
#region Event-Handler
private void OnUpdateStatusBarMessageEventHandler(string statusBarMessage)
{
this.StatusBarMessage = statusBarMessage;
}
#endregion Event-Handler
#region TabControl
private readonly IInterTabClient _interTabClient;
public IInterTabClient InterTabClient
{
get { return _interTabClient; }
}
/// <summary>
/// Callback to handle tab closing.
/// </summary>
public ItemActionCallback ClosingTabItemHandler
{
get { return ClosingTabItemHandlerImpl; }
}
/// <summary>
/// Callback to handle tab closing.
/// </summary>
private void ClosingTabItemHandlerImpl(ItemActionCallbackArgs<TabablzControl> args)
{
//in here you can dispose stuff or cancel the close
//here's your view model:
var viewModel = args.DragablzItem.DataContext as TabContent;
if (viewModel != null)
{
string title = Container?.Resolve<ILocalizerService>(ServiceNames.LocalizerService)?.GetLocalizedString("OverviewPageTitle");
if (viewModel.Header.Equals(title))
{
args.Cancel();
}
}
//Debug.Assert(viewModel != null);
//here's how you can cancel stuff:
//args.Cancel();
}
#endregion TabControl
/// <summary>
/// Load configuration file
/// </summary>
/// <returns></returns>
private IConfigurationFile LoadApplicationConfigFile()
{
// Create config file
IConfigurationFile configFile = new XmlConfigurationFile(FileAndFolderConstants.ApplicationConfigFile);
if (!configFile.Load())
{
// Add section GeneralSettings
configFile.Sections.Add("GeneralSettings");
this.CheckGeneralSettings(configFile);
}
else
{
// Check general settings
this.CheckGeneralSettings(configFile);
}
// Save config file
configFile.Save();
// Register global application file
this.Container.RegisterInstance<IConfigurationFile>(FileAndFolderConstants.ApplicationConfigFile, configFile);
return configFile;
}
/// <summary>
/// Check general settings
/// </summary>
/// <param name="configFile"></param>
private void CheckGeneralSettings(IConfigurationFile configFile)
{
// Check if section exists
if (configFile.Sections["GeneralSettings"] == null)
configFile.Sections.Add("GeneralSettings");
// Check settings
if (configFile.Sections["GeneralSettings"].Settings["Theme"] == null)
configFile.Sections["GeneralSettings"].Settings.Add("Theme", "BaseLight", "BaseLight", typeof(System.String));
if (configFile.Sections["GeneralSettings"].Settings["Language"] == null)
configFile.Sections["GeneralSettings"].Settings.Add("Language", "de", "de", typeof(System.String));
if (configFile.Sections["GeneralSettings"].Settings["AccentColor"] == null)
configFile.Sections["GeneralSettings"].Settings.Add("AccentColor", "Cyan", "Cyan", typeof(System.String));
}
#region Properties
private string statusBarMessage;
/// <summary>
/// Status-Bar message
/// </summary>
public string StatusBarMessage
{
get { return statusBarMessage; }
private set { this.SetProperty<string>(ref this.statusBarMessage, value); }
}
private InteractionRequest<AddOrUpdateConnectionNotification> showAddOrUpdateConnectionPopupRequest = null;
/// <summary>
/// Interaction request to show the add or update connection popup
/// </summary>
public InteractionRequest<AddOrUpdateConnectionNotification> ShowAddOrUpdateConnectionPopupRequest
{
get
{
return this.showAddOrUpdateConnectionPopupRequest;
}
private set
{
this.SetProperty<InteractionRequest<AddOrUpdateConnectionNotification>>(ref this.showAddOrUpdateConnectionPopupRequest, value);
}
}
#endregion Properties
}
} | 35.017045 | 194 | 0.624371 | [
"MIT"
] | punker76/MetroFtpClient | UI/MetroFtpClient/ViewModels/MainWindowViewModel.cs | 6,165 | C# |
using System;
using System.Linq;
using EPiServer.Commerce.Order;
using EPiServer.Commerce.Order.Internal;
using EPiServer.ServiceLocation;
using Mediachase.Commerce;
namespace EPiServer.Reference.Commerce.Site.Features.Checkout.Services
{
[ServiceConfiguration]
public class ConfirmationService
{
private readonly IOrderRepository _orderRepository;
private readonly ICurrentMarket _currentMarket;
public ConfirmationService(
IOrderRepository orderRepository,
ICurrentMarket currentMarket)
{
_orderRepository = orderRepository;
_currentMarket = currentMarket;
}
public IPurchaseOrder GetOrder(int orderNumber)
{
return _orderRepository.Load<IPurchaseOrder>(orderNumber);
}
public IPurchaseOrder CreateFakePurchaseOrder()
{
var form = new InMemoryOrderForm
{
Payments =
{
new InMemoryPayment
{
BillingAddress = new InMemoryOrderAddress(),
PaymentMethodName = "CashOnDelivery"
}
}
};
form.Shipments.First().ShippingAddress = new InMemoryOrderAddress();
var market = _currentMarket.GetCurrentMarket();
var purchaseOrder = new InMemoryPurchaseOrder
{
Currency = _currentMarket.GetCurrentMarket().DefaultCurrency,
MarketId = market.MarketId,
MarketName = market.MarketName,
PricesIncludeTax = market.PricesIncludeTax,
OrderLink = new OrderReference(0, string.Empty, Guid.Empty, typeof(IPurchaseOrder))
};
purchaseOrder.Forms.Add(form);
return purchaseOrder;
}
}
} | 32.482759 | 99 | 0.597665 | [
"Apache-2.0"
] | Geta/geta-optimizely-googleproductfeed | sandbox/Quicksilver/EPiServer.Reference.Commerce.Site/Features/Checkout/Services/ConfirmationService.cs | 1,886 | C# |
namespace herental.BL.Interfaces
{
public interface IPriceFormulaManager
{
decimal CalculatePrice(string typeName, int period);
}
} | 22.571429 | 61 | 0.683544 | [
"MIT"
] | deemoowoor/herental | herental.BL/Interfaces/IPriceFormulaManager.cs | 160 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BroadwayBuilder.Api.Models
{
public class NumberOfSuccessfulLoginsResponseModel
{
public int Month { get; set; }
public int Year { get; set; }
public int AverageSuccessfulLogins { get; set; }
public int MinSuccessfulLogins { get; set; }
public int MaxSuccessfulLogins { get; set; }
}
} | 27.125 | 56 | 0.679724 | [
"MIT"
] | BryceMoser/Broadway-Builder | BroadwayBuilder.Api/Models/NumberOfSuccessfulLoginsResponseModel.cs | 436 | C# |
using UnityEngine;
[
CreateAssetMenu(
fileName = "STSPlayerInventory",
menuName = "ScriptableObjects/STS/PlayerInventory",
order = 5)
]
public class STSPlayerInventory : ScriptableObject
{
public enum InventoryItemType
{
pizza = 1,
cake = 2,
swabstick = 3,
nullItem = 4
}
public InventoryItemType inventoryItemType;
public bool holdingItem = false;
public STSFood stsFood;
}
| 17.846154 | 59 | 0.633621 | [
"MIT"
] | xmliszt/CB2.0 | CB2.0/Assets/Scripts/StopTheSpread/ScriptableObjects/STSPlayerInventory.cs | 464 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Desktop;
using ClearCanvas.Desktop.Tools;
using ClearCanvas.Desktop.Actions;
namespace ClearCanvas.Samples.Google.Calendar
{
[MenuAction("apply", "global-menus/MenuTools/MenuToolsMyTools/SchedulingTool", "Apply")]
[ButtonAction("apply", "global-toolbars/ToolbarMyTools/SchedulingTool", "Apply")]
[Tooltip("apply", "SchedulingToolTooltip")]
[IconSet("apply", IconScheme.Colour, "Icons.SchedulingToolSmall.png", "Icons.SchedulingToolMedium.png", "Icons.SchedulingToolLarge.png")]
[ExtensionOf(typeof(ClearCanvas.Desktop.DesktopToolExtensionPoint))]
public class SchedulingTool : Tool<ClearCanvas.Desktop.IDesktopToolContext>
{
private Shelf _shelf;
/// <summary>
/// Default constructor. A no-args constructor is required by the
/// framework. Do not remove.
/// </summary>
public SchedulingTool()
{
}
/// <summary>
/// Called by the framework when the user clicks the "apply" menu item or toolbar button.
/// </summary>
public void Apply()
{
// check if the shelf already exists
if (_shelf == null)
{
// create a new shelf that hosts the SchedulingComponent
_shelf = ApplicationComponent.LaunchAsShelf(
this.Context.DesktopWindow,
new SchedulingComponent(),
SR.SchedulingTool,
ShelfDisplayHint.DockRight|ShelfDisplayHint.DockAutoHide,
delegate(IApplicationComponent c)
{
_shelf = null; // destroy the shelf when the user closes it
});
}
else
{
// activate existing shelf
_shelf.Activate();
}
}
}
}
| 33.855072 | 142 | 0.597175 | [
"Apache-2.0"
] | SNBnani/Xian | Samples/Google/Calendar/SchedulingTool.cs | 2,336 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Binance;
using System.Linq;
namespace BinanceConsoleApp.Controllers
{
internal class GetAggregateTradesFrom : IHandleCommand
{
public async Task<bool> HandleAsync(string command, CancellationToken token = default)
{
if (!command.StartsWith("aggTradesFrom ", StringComparison.OrdinalIgnoreCase) &&
!command.Equals("aggTradesFrom", StringComparison.OrdinalIgnoreCase))
return false;
var args = command.Split(' ');
if (args.Length < 2)
{
lock (Program.ConsoleSync)
{
Console.WriteLine("An aggregate trade ID is required.");
}
}
string symbol = Symbol.BTC_USDT;
var limit = 10;
if (!long.TryParse(args[1], out var fromId))
{
symbol = args[1];
fromId = 0;
if (args.Length > 2)
{
long.TryParse(args[2], out fromId);
}
}
else
{
if (args.Length > 2)
{
int.TryParse(args[2], out limit);
}
}
if (args.Length > 3)
{
int.TryParse(args[3], out limit);
}
var trades = (await Program.Api.GetAggregateTradesFromAsync(symbol, fromId, limit, token))
.Reverse().ToArray();
lock (Program.ConsoleSync)
{
Console.WriteLine();
if (!trades.Any())
{
Console.WriteLine(" [None]");
}
else
{
foreach (var trade in trades)
{
Program.Display(trade);
}
}
Console.WriteLine();
}
return true;
}
}
}
| 26.909091 | 102 | 0.436293 | [
"MIT"
] | ajkagy/binance | samples/BinanceConsoleApp/Controllers/GetAggregateTradesFrom.cs | 2,074 | C# |
namespace PenBreakout.Components
{
public class Controllable : Component
{
}
} | 13 | 41 | 0.681319 | [
"MIT"
] | Nhawdge/pen-breakout | src/Components/Controllable.cs | 91 | C# |
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Linq;
using Abp.Organizations;
using VOU.Authorization.Roles;
namespace VOU.Authorization.Users
{
public class UserStore : AbpUserStore<Role, User>
{
public UserStore(
IUnitOfWorkManager unitOfWorkManager,
IRepository<User, long> userRepository,
IRepository<Role> roleRepository,
IAsyncQueryableExecuter asyncQueryableExecuter,
IRepository<UserRole, long> userRoleRepository,
IRepository<UserLogin, long> userLoginRepository,
IRepository<UserClaim, long> userClaimRepository,
IRepository<UserPermissionSetting, long> userPermissionSettingRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository)
: base(
unitOfWorkManager,
userRepository,
roleRepository,
asyncQueryableExecuter,
userRoleRepository,
userLoginRepository,
userClaimRepository,
userPermissionSettingRepository,
userOrganizationUnitRepository,
organizationUnitRoleRepository)
{
}
}
}
| 35.973684 | 85 | 0.656181 | [
"MIT"
] | BugBear96/VOU | aspnet-core/src/VOU.Core/Authorization/Users/UserStore.cs | 1,367 | C# |
using System;
using System.Reflection;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Services.Maps;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Sharpnado.Infrastructure;
namespace Sample.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
// Should add UWP side assembly to rendererAssemblies
var rendererAssemblies = new []
{
typeof(Xamarin.Forms.GoogleMaps.UWP.MapRenderer).GetTypeInfo().Assembly
};
Xamarin.Forms.Forms.Init(e, rendererAssemblies);
InternalLogger.EnableLogging = true;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
Xamarin.FormsGoogleMaps.Init("uZZHK7NHcEVrgcvDeklV~fVgyPHDxXanPEls2KeJ1_Q~Aulz4feTcIflGlHHfZzky3-uKMqV0AIl3kwdK1fzyZayy85x2pQ7lVDaJy3MT3RZ");
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 39.257143 | 157 | 0.612082 | [
"MIT"
] | alexsandrocruz/SkiaSharpnado | RunAway!/Sample.UWP/App.xaml.cs | 4,124 | C# |
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V251.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V251.Segment{
///<summary>
/// Represents an HL7 RXD message segment.
/// This segment has the following fields:<ol>
///<li>RXD-1: Dispense Sub-ID Counter (NM)</li>
///<li>RXD-2: Dispense/Give Code (CE)</li>
///<li>RXD-3: Date/Time Dispensed (TS)</li>
///<li>RXD-4: Actual Dispense Amount (NM)</li>
///<li>RXD-5: Actual Dispense Units (CE)</li>
///<li>RXD-6: Actual Dosage Form (CE)</li>
///<li>RXD-7: Prescription Number (ST)</li>
///<li>RXD-8: Number of Refills Remaining (NM)</li>
///<li>RXD-9: Dispense Notes (ST)</li>
///<li>RXD-10: Dispensing Provider (XCN)</li>
///<li>RXD-11: Substitution Status (ID)</li>
///<li>RXD-12: Total Daily Dose (CQ)</li>
///<li>RXD-13: Dispense-to Location (LA2)</li>
///<li>RXD-14: Needs Human Review (ID)</li>
///<li>RXD-15: Pharmacy/Treatment Supplier's Special Dispensing Instructions (CE)</li>
///<li>RXD-16: Actual Strength (NM)</li>
///<li>RXD-17: Actual Strength Unit (CE)</li>
///<li>RXD-18: Substance Lot Number (ST)</li>
///<li>RXD-19: Substance Expiration Date (TS)</li>
///<li>RXD-20: Substance Manufacturer Name (CE)</li>
///<li>RXD-21: Indication (CE)</li>
///<li>RXD-22: Dispense Package Size (NM)</li>
///<li>RXD-23: Dispense Package Size Unit (CE)</li>
///<li>RXD-24: Dispense Package Method (ID)</li>
///<li>RXD-25: Supplementary Code (CE)</li>
///<li>RXD-26: Initiating Location (CE)</li>
///<li>RXD-27: Packaging/Assembly Location (CE)</li>
///<li>RXD-28: Actual Drug Strength Volume (NM)</li>
///<li>RXD-29: Actual Drug Strength Volume Units (CWE)</li>
///<li>RXD-30: Dispense to Pharmacy (CWE)</li>
///<li>RXD-31: Dispense to Pharmacy Address (XAD)</li>
///<li>RXD-32: Pharmacy Order Type (ID)</li>
///<li>RXD-33: Dispense Type (CWE)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class RXD : AbstractSegment {
/**
* Creates a RXD (Pharmacy/Treatment Dispense) segment object that belongs to the given
* message.
*/
public RXD(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(NM), true, 1, 4, new System.Object[]{message}, "Dispense Sub-ID Counter");
this.add(typeof(CE), true, 1, 250, new System.Object[]{message}, "Dispense/Give Code");
this.add(typeof(TS), true, 1, 26, new System.Object[]{message}, "Date/Time Dispensed");
this.add(typeof(NM), true, 1, 20, new System.Object[]{message}, "Actual Dispense Amount");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Actual Dispense Units");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Actual Dosage Form");
this.add(typeof(ST), true, 1, 20, new System.Object[]{message}, "Prescription Number");
this.add(typeof(NM), false, 1, 20, new System.Object[]{message}, "Number of Refills Remaining");
this.add(typeof(ST), false, 0, 200, new System.Object[]{message}, "Dispense Notes");
this.add(typeof(XCN), false, 0, 200, new System.Object[]{message}, "Dispensing Provider");
this.add(typeof(ID), false, 1, 1, new System.Object[]{message, 167}, "Substitution Status");
this.add(typeof(CQ), false, 1, 10, new System.Object[]{message}, "Total Daily Dose");
this.add(typeof(LA2), false, 1, 200, new System.Object[]{message}, "Dispense-to Location");
this.add(typeof(ID), false, 1, 1, new System.Object[]{message, 136}, "Needs Human Review");
this.add(typeof(CE), false, 0, 250, new System.Object[]{message}, "Pharmacy/Treatment Supplier's Special Dispensing Instructions");
this.add(typeof(NM), false, 1, 20, new System.Object[]{message}, "Actual Strength");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Actual Strength Unit");
this.add(typeof(ST), false, 0, 20, new System.Object[]{message}, "Substance Lot Number");
this.add(typeof(TS), false, 0, 26, new System.Object[]{message}, "Substance Expiration Date");
this.add(typeof(CE), false, 0, 250, new System.Object[]{message}, "Substance Manufacturer Name");
this.add(typeof(CE), false, 0, 250, new System.Object[]{message}, "Indication");
this.add(typeof(NM), false, 1, 20, new System.Object[]{message}, "Dispense Package Size");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Dispense Package Size Unit");
this.add(typeof(ID), false, 1, 2, new System.Object[]{message, 321}, "Dispense Package Method");
this.add(typeof(CE), false, 0, 250, new System.Object[]{message}, "Supplementary Code");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Initiating Location");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Packaging/Assembly Location");
this.add(typeof(NM), false, 1, 5, new System.Object[]{message}, "Actual Drug Strength Volume");
this.add(typeof(CWE), false, 1, 250, new System.Object[]{message}, "Actual Drug Strength Volume Units");
this.add(typeof(CWE), false, 1, 180, new System.Object[]{message}, "Dispense to Pharmacy");
this.add(typeof(XAD), false, 1, 106, new System.Object[]{message}, "Dispense to Pharmacy Address");
this.add(typeof(ID), false, 1, 1, new System.Object[]{message, 480}, "Pharmacy Order Type");
this.add(typeof(CWE), false, 1, 250, new System.Object[]{message}, "Dispense Type");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns Dispense Sub-ID Counter(RXD-1).
///</summary>
public NM DispenseSubIDCounter
{
get{
NM ret = null;
try
{
IType t = this.GetField(1, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Dispense/Give Code(RXD-2).
///</summary>
public CE DispenseGiveCode
{
get{
CE ret = null;
try
{
IType t = this.GetField(2, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Date/Time Dispensed(RXD-3).
///</summary>
public TS DateTimeDispensed
{
get{
TS ret = null;
try
{
IType t = this.GetField(3, 0);
ret = (TS)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Actual Dispense Amount(RXD-4).
///</summary>
public NM ActualDispenseAmount
{
get{
NM ret = null;
try
{
IType t = this.GetField(4, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Actual Dispense Units(RXD-5).
///</summary>
public CE ActualDispenseUnits
{
get{
CE ret = null;
try
{
IType t = this.GetField(5, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Actual Dosage Form(RXD-6).
///</summary>
public CE ActualDosageForm
{
get{
CE ret = null;
try
{
IType t = this.GetField(6, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Prescription Number(RXD-7).
///</summary>
public ST PrescriptionNumber
{
get{
ST ret = null;
try
{
IType t = this.GetField(7, 0);
ret = (ST)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Number of Refills Remaining(RXD-8).
///</summary>
public NM NumberOfRefillsRemaining
{
get{
NM ret = null;
try
{
IType t = this.GetField(8, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Dispense Notes(RXD-9).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public ST GetDispenseNotes(int rep)
{
ST ret = null;
try
{
IType t = this.GetField(9, rep);
ret = (ST)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Dispense Notes (RXD-9).
///</summary>
public ST[] GetDispenseNotes() {
ST[] ret = null;
try {
IType[] t = this.GetField(9);
ret = new ST[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (ST)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Dispense Notes (RXD-9).
///</summary>
public int DispenseNotesRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(9);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Dispensing Provider(RXD-10).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public XCN GetDispensingProvider(int rep)
{
XCN ret = null;
try
{
IType t = this.GetField(10, rep);
ret = (XCN)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Dispensing Provider (RXD-10).
///</summary>
public XCN[] GetDispensingProvider() {
XCN[] ret = null;
try {
IType[] t = this.GetField(10);
ret = new XCN[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (XCN)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Dispensing Provider (RXD-10).
///</summary>
public int DispensingProviderRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(10);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Substitution Status(RXD-11).
///</summary>
public ID SubstitutionStatus
{
get{
ID ret = null;
try
{
IType t = this.GetField(11, 0);
ret = (ID)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Total Daily Dose(RXD-12).
///</summary>
public CQ TotalDailyDose
{
get{
CQ ret = null;
try
{
IType t = this.GetField(12, 0);
ret = (CQ)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Dispense-to Location(RXD-13).
///</summary>
public LA2 DispenseToLocation
{
get{
LA2 ret = null;
try
{
IType t = this.GetField(13, 0);
ret = (LA2)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Needs Human Review(RXD-14).
///</summary>
public ID NeedsHumanReview
{
get{
ID ret = null;
try
{
IType t = this.GetField(14, 0);
ret = (ID)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Pharmacy/Treatment Supplier's Special Dispensing Instructions(RXD-15).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CE GetPharmacyTreatmentSupplierSSpecialDispensingInstructions(int rep)
{
CE ret = null;
try
{
IType t = this.GetField(15, rep);
ret = (CE)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Pharmacy/Treatment Supplier's Special Dispensing Instructions (RXD-15).
///</summary>
public CE[] GetPharmacyTreatmentSupplierSSpecialDispensingInstructions() {
CE[] ret = null;
try {
IType[] t = this.GetField(15);
ret = new CE[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CE)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Pharmacy/Treatment Supplier's Special Dispensing Instructions (RXD-15).
///</summary>
public int PharmacyTreatmentSupplierSSpecialDispensingInstructionsRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(15);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Actual Strength(RXD-16).
///</summary>
public NM ActualStrength
{
get{
NM ret = null;
try
{
IType t = this.GetField(16, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Actual Strength Unit(RXD-17).
///</summary>
public CE ActualStrengthUnit
{
get{
CE ret = null;
try
{
IType t = this.GetField(17, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Substance Lot Number(RXD-18).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public ST GetSubstanceLotNumber(int rep)
{
ST ret = null;
try
{
IType t = this.GetField(18, rep);
ret = (ST)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Substance Lot Number (RXD-18).
///</summary>
public ST[] GetSubstanceLotNumber() {
ST[] ret = null;
try {
IType[] t = this.GetField(18);
ret = new ST[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (ST)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Substance Lot Number (RXD-18).
///</summary>
public int SubstanceLotNumberRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(18);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Substance Expiration Date(RXD-19).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public TS GetSubstanceExpirationDate(int rep)
{
TS ret = null;
try
{
IType t = this.GetField(19, rep);
ret = (TS)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Substance Expiration Date (RXD-19).
///</summary>
public TS[] GetSubstanceExpirationDate() {
TS[] ret = null;
try {
IType[] t = this.GetField(19);
ret = new TS[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (TS)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Substance Expiration Date (RXD-19).
///</summary>
public int SubstanceExpirationDateRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(19);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Substance Manufacturer Name(RXD-20).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CE GetSubstanceManufacturerName(int rep)
{
CE ret = null;
try
{
IType t = this.GetField(20, rep);
ret = (CE)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Substance Manufacturer Name (RXD-20).
///</summary>
public CE[] GetSubstanceManufacturerName() {
CE[] ret = null;
try {
IType[] t = this.GetField(20);
ret = new CE[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CE)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Substance Manufacturer Name (RXD-20).
///</summary>
public int SubstanceManufacturerNameRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(20);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Indication(RXD-21).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CE GetIndication(int rep)
{
CE ret = null;
try
{
IType t = this.GetField(21, rep);
ret = (CE)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Indication (RXD-21).
///</summary>
public CE[] GetIndication() {
CE[] ret = null;
try {
IType[] t = this.GetField(21);
ret = new CE[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CE)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Indication (RXD-21).
///</summary>
public int IndicationRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(21);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Dispense Package Size(RXD-22).
///</summary>
public NM DispensePackageSize
{
get{
NM ret = null;
try
{
IType t = this.GetField(22, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Dispense Package Size Unit(RXD-23).
///</summary>
public CE DispensePackageSizeUnit
{
get{
CE ret = null;
try
{
IType t = this.GetField(23, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Dispense Package Method(RXD-24).
///</summary>
public ID DispensePackageMethod
{
get{
ID ret = null;
try
{
IType t = this.GetField(24, 0);
ret = (ID)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Supplementary Code(RXD-25).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CE GetSupplementaryCode(int rep)
{
CE ret = null;
try
{
IType t = this.GetField(25, rep);
ret = (CE)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Supplementary Code (RXD-25).
///</summary>
public CE[] GetSupplementaryCode() {
CE[] ret = null;
try {
IType[] t = this.GetField(25);
ret = new CE[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CE)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Supplementary Code (RXD-25).
///</summary>
public int SupplementaryCodeRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(25);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Initiating Location(RXD-26).
///</summary>
public CE InitiatingLocation
{
get{
CE ret = null;
try
{
IType t = this.GetField(26, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Packaging/Assembly Location(RXD-27).
///</summary>
public CE PackagingAssemblyLocation
{
get{
CE ret = null;
try
{
IType t = this.GetField(27, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Actual Drug Strength Volume(RXD-28).
///</summary>
public NM ActualDrugStrengthVolume
{
get{
NM ret = null;
try
{
IType t = this.GetField(28, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Actual Drug Strength Volume Units(RXD-29).
///</summary>
public CWE ActualDrugStrengthVolumeUnits
{
get{
CWE ret = null;
try
{
IType t = this.GetField(29, 0);
ret = (CWE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Dispense to Pharmacy(RXD-30).
///</summary>
public CWE DispenseToPharmacy
{
get{
CWE ret = null;
try
{
IType t = this.GetField(30, 0);
ret = (CWE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Dispense to Pharmacy Address(RXD-31).
///</summary>
public XAD DispenseToPharmacyAddress
{
get{
XAD ret = null;
try
{
IType t = this.GetField(31, 0);
ret = (XAD)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Pharmacy Order Type(RXD-32).
///</summary>
public ID PharmacyOrderType
{
get{
ID ret = null;
try
{
IType t = this.GetField(32, 0);
ret = (ID)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Dispense Type(RXD-33).
///</summary>
public CWE DispenseType
{
get{
CWE ret = null;
try
{
IType t = this.GetField(33, 0);
ret = (CWE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
}} | 35.166521 | 139 | 0.643315 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Model.V251/Segment/RXD.cs | 40,125 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class LabelSFLongLineWrapping : AtlasDemoNew
{
CCLabel label1;
public LabelSFLongLineWrapping()
{
// Long sentence
label1 = new CCLabel(LabelFNTMultiLineAlignment.LongSentencesExample, "fonts/arial", 26, CCLabelFormat.SpriteFont);
label1.LabelFormat.Alignment = CCTextAlignment.Center;
label1.AnchorPoint = CCPoint.AnchorMiddleTop;
AddChild(label1);
}
protected override void AddedToScene()
{
base.AddedToScene();
var s = Layer.VisibleBoundsWorldspace.Size;
label1.Dimensions = new CCSize(s.Width, 0);
label1.Position = s.Center;
}
public override string Title
{
get {
return "New Label + SpriteFont";
}
}
public override string Subtitle
{
get {
return "Uses the new Label with SpriteFont. Testing auto-wrapping";
}
}
}
}
| 25.108696 | 127 | 0.580952 | [
"MIT"
] | YersonSolano/CocosSharp | tests/tests/classes/tests/LabelTestNew/LabelSFLongLineWrapping.cs | 1,155 | C# |
using System.CodeDom.Compiler;
namespace Sspe.Service
{
[GeneratedCode("Visual Studio", "1")]
partial class ServiceInstaller
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
} | 29.026316 | 107 | 0.564823 | [
"MIT"
] | markallanson/sspe | SmallSensorPublishingService/ServiceInstaller.Designer.cs | 1,105 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace VaporStore.Data.Models
{
public class Genre
{
public Genre()
{
this.Games = new HashSet<Game>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<Game> Games { get; set; }
}
}
//• Id – integer, Primary Key
//• Name – text (required)
//• Games - collection of type Game
| 21.583333 | 52 | 0.604247 | [
"MIT"
] | NikolayLutakov/Entity-Framework-Core | Exam Preps/01 C# DB Advanced Exam Last Reslove - 08 August 2020/VaporStore/Data/Models/Genre.cs | 530 | C# |
using System;
namespace PCRE.Tests.Pcre
{
public sealed class TestPattern : IEquatable<TestPattern>
{
public string FullString { get; set; }
public string Pattern { get; set; }
public string OptionsString { get; set; }
public PcreOptions PatternOptions { get; set; }
public PcreOptions ResetOptionBits { get; set; }
public int LineNumber { get; set; }
public bool AllMatches { get; set; }
public bool GetRemainingString { get; set; }
public bool ExtractMarks { get; set; }
public bool HexEncoding { get; set; }
public bool IncludeInfo { get; set; }
public string ReplaceWith { get; set; }
public bool SubjectLiteral { get; set; }
public bool NotSupported { get; set; }
public uint JitStack { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as TestPattern);
}
public bool Equals(TestPattern other)
{
return other != null && string.Equals(FullString, other.FullString);
}
public override int GetHashCode() => FullString?.GetHashCode() ?? 0;
public static bool operator ==(TestPattern left, TestPattern right) => Equals(left, right);
public static bool operator !=(TestPattern left, TestPattern right) => !Equals(left, right);
public override string ToString() => FullString ?? "???";
}
}
| 30.416667 | 100 | 0.610959 | [
"BSD-3-Clause"
] | am11/pcre-net | src/PCRE.NET.Tests/Pcre/TestPattern.cs | 1,462 | C# |
////////////////////////////////////////////////////////////////////////
//
// This file is part of pdn-mozjpeg, a FileType plugin for Paint.NET
// that saves JPEG images using the mozjpeg encoder.
//
// Copyright (c) 2021 Nicholas Hayes
//
// This file is licensed under the MIT License.
// See LICENSE.txt for complete licensing and attribution information.
//
////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace MozJpegFileType.Exif
{
internal static class ExifParser
{
/// <summary>
/// Parses the EXIF data into a collection of properties.
/// </summary>
/// <param name="bytes">The EXIF data.</param>
/// <returns>
/// A collection containing the EXIF properties.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="bytes"/> is null.
///
/// -or-
///
/// <paramref name="arrayPool"/> is null.
/// </exception>
internal static ExifValueCollection Parse(byte[] bytes, PaintDotNet.AppModel.IArrayPoolService arrayPool)
{
if (bytes is null)
{
throw new ArgumentNullException(nameof(bytes));
}
ExifValueCollection metadataEntries = null;
MemoryStream stream = new MemoryStream(bytes, writable: false);
try
{
Endianess? byteOrder = TryDetectTiffByteOrder(stream);
if (byteOrder.HasValue)
{
using (EndianBinaryReader reader = new EndianBinaryReader(stream, byteOrder.Value, arrayPool))
{
stream = null;
ushort signature = reader.ReadUInt16();
if (signature == TiffConstants.Signature)
{
uint ifdOffset = reader.ReadUInt32();
List<ParserIFDEntry> entries = ParseDirectories(reader, ifdOffset);
metadataEntries = new ExifValueCollection(ConvertIFDEntriesToMetadataEntries(reader, entries));
}
}
}
}
catch (EndOfStreamException)
{
}
finally
{
stream?.Dispose();
}
return metadataEntries;
}
private static List<MetadataEntry> ConvertIFDEntriesToMetadataEntries(EndianBinaryReader reader, List<ParserIFDEntry> entries)
{
List<MetadataEntry> metadataEntries = new List<MetadataEntry>(entries.Count);
bool swapNumberByteOrder = reader.Endianess == Endianess.Big;
for (int i = 0; i < entries.Count; i++)
{
ParserIFDEntry entry = entries[i];
byte[] propertyData;
if (entry.OffsetFieldContainsValue)
{
propertyData = entry.GetValueBytesFromOffset();
if (propertyData is null)
{
continue;
}
}
else
{
long bytesToRead = entry.Count * TagDataTypeUtil.GetSizeInBytes(entry.Type);
// Skip any tags that are empty or larger than 2 GB.
if (bytesToRead == 0 || bytesToRead > int.MaxValue)
{
continue;
}
uint offset = entry.Offset;
if ((offset + bytesToRead) > reader.Length)
{
continue;
}
reader.Position = offset;
propertyData = reader.ReadBytes((int)bytesToRead);
if (swapNumberByteOrder)
{
// Paint.NET converts all multi-byte numbers to little-endian.
switch (entry.Type)
{
case TagDataType.Short:
case TagDataType.SShort:
propertyData = SwapShortArrayToLittleEndian(propertyData, entry.Count);
break;
case TagDataType.Long:
case TagDataType.SLong:
case TagDataType.Float:
propertyData = SwapLongArrayToLittleEndian(propertyData, entry.Count);
break;
case TagDataType.Rational:
case TagDataType.SRational:
propertyData = SwapRationalArrayToLittleEndian(propertyData, entry.Count);
break;
case TagDataType.Double:
propertyData = SwapDoubleArrayToLittleEndian(propertyData, entry.Count);
break;
case TagDataType.Byte:
case TagDataType.Ascii:
case TagDataType.Undefined:
case TagDataType.SByte:
default:
break;
}
}
}
metadataEntries.Add(new MetadataEntry(entry.Section, entry.Tag, entry.Type, propertyData));
}
return metadataEntries;
}
private static List<ParserIFDEntry> ParseDirectories(EndianBinaryReader reader, uint firstIFDOffset)
{
List<ParserIFDEntry> items = new List<ParserIFDEntry>();
bool foundExif = false;
bool foundGps = false;
bool foundInterop = false;
Queue<MetadataOffset> ifdOffsets = new Queue<MetadataOffset>();
ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Image, firstIFDOffset));
while (ifdOffsets.Count > 0)
{
MetadataOffset metadataOffset = ifdOffsets.Dequeue();
MetadataSection section = metadataOffset.Section;
uint offset = metadataOffset.Offset;
if (offset >= reader.Length)
{
continue;
}
reader.Position = offset;
ushort count = reader.ReadUInt16();
if (count == 0)
{
continue;
}
items.Capacity += count;
for (int i = 0; i < count; i++)
{
ParserIFDEntry entry = new ParserIFDEntry(reader, section);
switch (entry.Tag)
{
case TiffConstants.Tags.ExifIFD:
if (!foundExif)
{
foundExif = true;
ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Exif, entry.Offset));
}
break;
case TiffConstants.Tags.GpsIFD:
if (!foundGps)
{
foundGps = true;
ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Gps, entry.Offset));
}
break;
case TiffConstants.Tags.InteropIFD:
if (!foundInterop)
{
foundInterop = true;
ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Interop, entry.Offset));
}
break;
case TiffConstants.Tags.StripOffsets:
case TiffConstants.Tags.RowsPerStrip:
case TiffConstants.Tags.StripByteCounts:
case TiffConstants.Tags.SubIFDs:
case TiffConstants.Tags.ThumbnailOffset:
case TiffConstants.Tags.ThumbnailLength:
// Skip the thumbnail and/or preview images.
// The StripOffsets and StripByteCounts tags are used to store a preview image in some formats.
// The SubIFDs tag is used to store thumbnails in TIFF and for storing other data in some camera formats.
//
// Note that some cameras will also store a thumbnail as part of their private data in the EXIF MakerNote tag.
// The EXIF MakerNote tag is treated as an opaque blob, so those thumbnails will be preserved.
break;
default:
items.Add(entry);
break;
}
System.Diagnostics.Debug.WriteLine(entry.ToString());
}
}
return items;
}
private static unsafe byte[] SwapDoubleArrayToLittleEndian(byte[] values, uint count)
{
fixed (byte* pBytes = values)
{
ulong* ptr = (ulong*)pBytes;
ulong* ptrEnd = ptr + count;
while (ptr < ptrEnd)
{
*ptr = EndianUtil.Swap(*ptr);
ptr++;
}
}
return values;
}
private static unsafe byte[] SwapLongArrayToLittleEndian(byte[] values, uint count)
{
fixed (byte* pBytes = values)
{
uint* ptr = (uint*)pBytes;
uint* ptrEnd = ptr + count;
while (ptr < ptrEnd)
{
*ptr = EndianUtil.Swap(*ptr);
ptr++;
}
}
return values;
}
private static unsafe byte[] SwapRationalArrayToLittleEndian(byte[] values, uint count)
{
// A rational value consists of two 4-byte values, a numerator and a denominator.
long itemCount = (long)count * 2;
fixed (byte* pBytes = values)
{
uint* ptr = (uint*)pBytes;
uint* ptrEnd = ptr + itemCount;
while (ptr < ptrEnd)
{
*ptr = EndianUtil.Swap(*ptr);
ptr++;
}
}
return values;
}
private static unsafe byte[] SwapShortArrayToLittleEndian(byte[] values, uint count)
{
fixed (byte* pBytes = values)
{
ushort* ptr = (ushort*)pBytes;
ushort* ptrEnd = ptr + count;
while (ptr < ptrEnd)
{
*ptr = EndianUtil.Swap(*ptr);
ptr++;
}
}
return values;
}
private static Endianess? TryDetectTiffByteOrder(Stream stream)
{
int byte1 = stream.ReadByte();
if (byte1 == -1)
{
return null;
}
int byte2 = stream.ReadByte();
if (byte2 == -1)
{
return null;
}
ushort byteOrderMarker = (ushort)(byte1 | (byte2 << 8));
if (byteOrderMarker == TiffConstants.BigEndianByteOrderMarker)
{
return Endianess.Big;
}
else if (byteOrderMarker == TiffConstants.LittleEndianByteOrderMarker)
{
return Endianess.Little;
}
else
{
return null;
}
}
private readonly struct ParserIFDEntry
{
#pragma warning disable IDE0032 // Use auto property
private readonly IFDEntry entry;
private readonly MetadataSection section;
private readonly bool offsetIsBigEndian;
#pragma warning restore IDE0032 // Use auto property
public ParserIFDEntry(EndianBinaryReader reader, MetadataSection section)
{
this.entry = new IFDEntry(reader);
this.section = section;
this.offsetIsBigEndian = reader.Endianess == Endianess.Big;
}
public ushort Tag => this.entry.Tag;
public TagDataType Type => this.entry.Type;
public uint Count => this.entry.Count;
public uint Offset => this.entry.Offset;
public bool OffsetFieldContainsValue
{
get
{
return TagDataTypeUtil.ValueFitsInOffsetField(this.Type, this.Count);
}
}
#pragma warning disable IDE0032 // Use auto property
public MetadataSection Section => this.section;
#pragma warning restore IDE0032 // Use auto property
public unsafe byte[] GetValueBytesFromOffset()
{
if (!this.OffsetFieldContainsValue)
{
return null;
}
TagDataType type = this.entry.Type;
uint count = this.entry.Count;
uint offset = this.entry.Offset;
if (count == 0)
{
return Array.Empty<byte>();
}
// Paint.NET always stores data in little-endian byte order.
byte[] bytes;
if (type == TagDataType.Byte ||
type == TagDataType.Ascii ||
type == TagDataType.SByte ||
type == TagDataType.Undefined)
{
bytes = new byte[count];
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
break;
case 2:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
bytes[3] = (byte)(offset & 0x000000ff);
break;
}
}
else
{
switch (count)
{
case 1:
bytes[0] = (byte)(offset & 0x000000ff);
break;
case 2:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
bytes[3] = (byte)((offset >> 24) & 0x000000ff);
break;
}
}
}
else if (type == TagDataType.Short || type == TagDataType.SShort)
{
int byteArrayLength = unchecked((int)count) * sizeof(ushort);
bytes = new byte[byteArrayLength];
fixed (byte* ptr = bytes)
{
ushort* ushortPtr = (ushort*)ptr;
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
ushortPtr[0] = (ushort)((offset >> 16) & 0x0000ffff);
break;
case 2:
ushortPtr[0] = (ushort)((offset >> 16) & 0x0000ffff);
ushortPtr[1] = (ushort)(offset & 0x0000ffff);
break;
}
}
else
{
switch (count)
{
case 1:
ushortPtr[0] = (ushort)(offset & 0x0000ffff);
break;
case 2:
ushortPtr[0] = (ushort)(offset & 0x0000ffff);
ushortPtr[1] = (ushort)((offset >> 16) & 0x0000ffff);
break;
}
}
}
}
else
{
bytes = new byte[4];
fixed (byte* ptr = bytes)
{
// The offset is stored as little-endian in memory.
*(uint*)ptr = offset;
}
}
return bytes;
}
public override string ToString()
{
if (this.OffsetFieldContainsValue)
{
return string.Format("Tag={0}, Type={1}, Count={2}, Value={3}",
this.entry.Tag.ToString(CultureInfo.InvariantCulture),
this.entry.Type.ToString(),
this.entry.Count.ToString(CultureInfo.InvariantCulture),
GetValueStringFromOffset());
}
else
{
return string.Format("Tag={0}, Type={1}, Count={2}, Offset=0x{3}",
this.entry.Tag.ToString(CultureInfo.InvariantCulture),
this.entry.Type.ToString(),
this.entry.Count.ToString(CultureInfo.InvariantCulture),
this.entry.Offset.ToString("X", CultureInfo.InvariantCulture));
}
}
private string GetValueStringFromOffset()
{
string valueString;
TagDataType type = this.entry.Type;
uint count = this.entry.Count;
uint offset = this.entry.Offset;
if (count == 0)
{
return string.Empty;
}
int typeSizeInBytes = TagDataTypeUtil.GetSizeInBytes(type);
if (typeSizeInBytes == 1)
{
byte[] bytes = new byte[count];
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
break;
case 2:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
bytes[3] = (byte)(offset & 0x000000ff);
break;
}
}
else
{
switch (count)
{
case 1:
bytes[0] = (byte)(offset & 0x000000ff);
break;
case 2:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
bytes[3] = (byte)((offset >> 24) & 0x000000ff);
break;
}
}
if (type == TagDataType.Ascii)
{
valueString = Encoding.ASCII.GetString(bytes).TrimEnd('\0');
}
else if (count == 1)
{
valueString = bytes[0].ToString(CultureInfo.InvariantCulture);
}
else
{
StringBuilder builder = new StringBuilder();
uint lastItemIndex = count - 1;
for (int i = 0; i < count; i++)
{
builder.Append(bytes[i].ToString(CultureInfo.InvariantCulture));
if (i < lastItemIndex)
{
builder.Append(",");
}
}
valueString = builder.ToString();
}
}
else if (typeSizeInBytes == 2)
{
ushort[] values = new ushort[count];
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
break;
case 2:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
values[1] = (ushort)(offset & 0x0000ffff);
break;
}
}
else
{
switch (count)
{
case 1:
values[0] = (ushort)(offset & 0x0000ffff);
break;
case 2:
values[0] = (ushort)(offset & 0x0000ffff);
values[1] = (ushort)((offset >> 16) & 0x0000ffff);
break;
}
}
if (count == 1)
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture);
break;
}
}
else
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture) + "," +
((short)values[1]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture) + "," +
values[1].ToString(CultureInfo.InvariantCulture);
break;
}
}
}
else
{
valueString = offset.ToString(CultureInfo.InvariantCulture);
}
return valueString;
}
}
private readonly struct MetadataOffset
{
public MetadataOffset(MetadataSection section, uint offset)
{
this.Section = section;
this.Offset = offset;
}
public MetadataSection Section { get; }
public uint Offset { get; }
}
}
}
| 38.509272 | 138 | 0.386924 | [
"MIT"
] | 0xC0000054/pdn-mozjpeg | src/Exif/ExifParser.cs | 26,997 | 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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
// The Windows implementation of PipeStream sets the stream's handle during
// creation, and as such should always have a handle, but the Unix implementation
// sometimes sets the handle not during creation but later during connection.
// As such, validation during member access needs to verify a valid handle on
// Windows, but can't assume a valid handle on Unix.
internal const bool CheckOperationsRequiresSetHandle = false;
/// <summary>Characters that can't be used in a pipe's name.</summary>
private static readonly char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars();
/// <summary>Characters that can't be used in an absolute path pipe's name.</summary>
private static readonly char[] s_invalidPathNameChars = Path.GetInvalidPathChars();
/// <summary>Prefix to prepend to all pipe names.</summary>
private static readonly string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_");
internal static string GetPipePath(string serverName, string pipeName)
{
if (serverName != "." && serverName != Interop.Sys.GetHostName())
{
// Cross-machine pipes are not supported.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes);
}
if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
{
// Match Windows constraint
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
// Since pipes are stored as files in the system we support either an absolute path to a file name
// or a file name. The support of absolute path was added to allow working around the limited
// length available for the pipe name when concatenated with the temp path, while being
// cross-platform with Windows (which has only '\' as an invalid char).
if (Path.IsPathRooted(pipeName))
{
if (pipeName.IndexOfAny(s_invalidPathNameChars) >= 0 || pipeName[pipeName.Length - 1] == Path.DirectorySeparatorChar)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_InvalidPipeNameChars);
// Caller is in full control of file location.
return pipeName;
}
if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_InvalidPipeNameChars);
}
// The pipe is created directly under Path.GetTempPath() with "CoreFXPipe_" prefix.
//
// We previously didn't put it into a subdirectory because it only existed on disk for the duration
// between when the server started listening in WaitForConnection and when the client
// connected, after which the pipe was deleted. We now create the pipe when the
// server stream is created, which leaves it on disk longer, but we can't change the
// naming scheme used as that breaks the ability for code running on an older
// runtime to connect to code running on the newer runtime. That means we're stuck
// with a tmp file for the lifetime of the server stream.
return s_pipePrefix + pipeName;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
if (safePipeHandle.NamedPipeSocket == null)
{
Interop.Sys.FileStatus status;
int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status));
if (result == 0)
{
if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO &&
(status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// nop
}
internal virtual void DisposeCore(bool disposing)
{
// nop
}
private unsafe int ReadCore(Span<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, receive on the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Read syscall as is done
// for reading an anonymous pipe. However, for a non-blocking socket, Read could
// end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case
// is already handled by Socket.Receive, so we use it here.
try
{
return socket.Receive(buffer, SocketFlags.None);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, read from the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr, buffer.Length));
Debug.Assert(result <= buffer.Length);
return result;
}
}
private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, send to the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Write syscall as is done
// for writing to anonymous pipe. However, for a non-blocking socket, Write could
// end up returning EWOULDBLOCK rather than blocking waiting for space available.
// Such a case is already handled by Socket.Send, so we use it here.
try
{
while (buffer.Length > 0)
{
int bytesWritten = socket.Send(buffer, SocketFlags.None);
buffer = buffer.Slice(bytesWritten);
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, write the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
while (buffer.Length > 0)
{
int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr, buffer.Length));
buffer = buffer.Slice(bytesWritten);
}
}
}
private async ValueTask<int> ReadAsyncCore(Memory<byte> destination, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
try
{
return await InternalHandle.NamedPipeSocket.ReceiveAsync(destination, SocketFlags.None, cancellationToken).ConfigureAwait(false);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private async Task WriteAsyncCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
try
{
while (source.Length > 0)
{
int bytesWritten = await _handle.NamedPipeSocket.SendAsync(source, SocketFlags.None, cancellationToken).ConfigureAwait(false);
Debug.Assert(bytesWritten > 0 && bytesWritten <= source.Length);
source = source.Slice(bytesWritten);
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private IOException GetIOExceptionForSocketException(SocketException e)
{
if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE
{
State = PipeState.Broken;
}
return new IOException(e.Message, e);
}
// Blocks until the other end of the pipe has read in all written buffer.
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
// For named pipes on sockets, we could potentially partially implement this
// via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However,
// that would require polling, and it wouldn't actually mean that the other
// end has read all of the data, just that the data has left this end's buffer.
throw new PlatformNotSupportedException(); // not fully implementable on unix
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return GetPipeBufferSize();
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return GetPipeBufferSize();
}
}
public virtual PipeTransmissionMode ReadMode
{
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
}
// nop, since it's already the only valid value
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// We want to ensure that only one asynchronous operation is actually in flight
/// at a time. The base Stream class ensures this by serializing execution via a
/// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due
/// to having specialized support for cancellation, we do the same serialization here.
/// </summary>
private SemaphoreSlim _asyncActiveSemaphore;
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
private static void CreateDirectory(string directoryPath)
{
int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask);
// If successful created, we're done.
if (result >= 0)
return;
// If the directory already exists, consider it a success.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EEXIST)
return;
// Otherwise, fail.
throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true);
}
/// <summary>Creates an anonymous pipe.</summary>
/// <param name="reader">The resulting reader end of the pipe.</param>
/// <param name="writer">The resulting writer end of the pipe.</param>
internal static unsafe void CreateAnonymousPipe(out SafePipeHandle reader, out SafePipeHandle writer)
{
// Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations
reader = new SafePipeHandle();
writer = new SafePipeHandle();
// Create the OS pipe. We always create it as O_CLOEXEC (trying to do so atomically) so that the
// file descriptors aren't inherited. Then if inheritability was requested, we opt-in the child file
// descriptor later; if the server file descriptor was also inherited, closing the server file
// descriptor would fail to signal EOF for the child side.
int* fds = stackalloc int[2];
Interop.CheckIo(Interop.Sys.Pipe(fds, Interop.Sys.PipeFlags.O_CLOEXEC));
// Store the file descriptors into our safe handles
reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]);
writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]);
}
internal int CheckPipeCall(int result)
{
if (result == -1)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
State = PipeState.Broken;
throw Interop.GetExceptionForIoErrno(errorInfo);
}
return result;
}
private int GetPipeBufferSize()
{
if (!Interop.Sys.Fcntl.CanGetSetPipeSz)
{
throw new PlatformNotSupportedException(); // OS does not support getting pipe size
}
// If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction).
// If we don't, just return the buffer size that was passed to the constructor.
return _handle != null ?
CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) :
_outBufferSize;
}
internal static void ConfigureSocket(
Socket s, SafePipeHandle pipeHandle,
PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
{
if (inBufferSize > 0)
{
s.ReceiveBufferSize = inBufferSize;
}
if (outBufferSize > 0)
{
s.SendBufferSize = outBufferSize;
}
// Sockets are created with O_CLOEXEC. If inheritability has been requested, we need to unset the flag.
if (inheritability == HandleInheritability.Inheritable &&
Interop.Sys.Fcntl.SetFD(s.SafeHandle, 0) == -1)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
}
switch (direction)
{
case PipeDirection.In:
s.Shutdown(SocketShutdown.Send);
break;
case PipeDirection.Out:
s.Shutdown(SocketShutdown.Receive);
break;
}
}
internal static Exception CreateExceptionForLastError(string pipeName = null)
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
return error.Error == Interop.Error.ENOTSUP ?
new PlatformNotSupportedException(SR.Format(SR.PlatformNotSupported_OperatingSystemError, nameof(Interop.Error.ENOTSUP))) :
Interop.GetExceptionForIoErrno(error, pipeName);
}
}
}
| 44.046296 | 194 | 0.593494 | [
"MIT"
] | RobSiklos/corefx | src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs | 19,028 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x1015_2125-fefdfaf4")]
public void Method_1015_2125()
{
ii(0x1015_2125, 5); push(0x6c); /* push 0x6c */
ii(0x1015_212a, 5); call(Definitions.sys_check_available_stack_size, 0x1_3c23);/* call 0x10165d52 */
ii(0x1015_212f, 1); push(ebx); /* push ebx */
ii(0x1015_2130, 1); push(ecx); /* push ecx */
ii(0x1015_2131, 1); push(esi); /* push esi */
ii(0x1015_2132, 1); push(edi); /* push edi */
ii(0x1015_2133, 1); push(ebp); /* push ebp */
ii(0x1015_2134, 2); mov(ebp, esp); /* mov ebp, esp */
ii(0x1015_2136, 6); sub(esp, 0x3c); /* sub esp, 0x3c */
ii(0x1015_213c, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */
ii(0x1015_213f, 3); mov(memd[ss, ebp - 4], edx); /* mov [ebp-0x4], edx */
ii(0x1015_2142, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_2145, 5); call(0x1007_623c, -0xd_bf0e); /* call 0x1007623c */
ii(0x1015_214a, 2); mov(ebx, eax); /* mov ebx, eax */
ii(0x1015_214c, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_214f, 3); mov(edx, memd[ds, eax + 6]); /* mov edx, [eax+0x6] */
ii(0x1015_2152, 3); sar(edx, 0x10); /* sar edx, 0x10 */
ii(0x1015_2155, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_2158, 3); mov(al, memb[ds, eax + 38]); /* mov al, [eax+0x26] */
ii(0x1015_215b, 5); and(eax, 0xff); /* and eax, 0xff */
ii(0x1015_2160, 6); imul(ecx, eax, 0x247); /* imul ecx, eax, 0x247 */
ii(0x1015_2166, 5); mov(eax, 0x101c_a468); /* mov eax, 0x101ca468 */
ii(0x1015_216b, 2); add(eax, ecx); /* add eax, ecx */
ii(0x1015_216d, 5); call(0x100d_fd2c, -0x7_2446); /* call 0x100dfd2c */
ii(0x1015_2172, 2); cmp(ebx, eax); /* cmp ebx, eax */
ii(0x1015_2174, 2); if(jz(0x1015_2187, 0x11)) goto l_0x1015_2187;/* jz 0x10152187 */
ii(0x1015_2176, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1015_2178, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_217b, 3); add(eax, 0x70); /* add eax, 0x70 */
ii(0x1015_217e, 5); call(0x1013_ad71, -0x1_7412); /* call 0x1013ad71 */
ii(0x1015_2183, 2); test(al, al); /* test al, al */
ii(0x1015_2185, 2); if(jnz(0x1015_218c, 5)) goto l_0x1015_218c;/* jnz 0x1015218c */
l_0x1015_2187:
ii(0x1015_2187, 5); jmp(0x1015_2312, 0x186); goto l_0x1015_2312;/* jmp 0x10152312 */
l_0x1015_218c:
ii(0x1015_218c, 3); lea(eax, memd[ss, ebp - 20]); /* lea eax, [ebp-0x14] */
ii(0x1015_218f, 5); call(0x1007_20b1, -0xe_00e3); /* call 0x100720b1 */
ii(0x1015_2194, 3); lea(eax, memd[ss, ebp - 32]); /* lea eax, [ebp-0x20] */
ii(0x1015_2197, 5); call(0x1007_20b1, -0xe_00eb); /* call 0x100720b1 */
ii(0x1015_219c, 3); lea(ebx, memd[ss, ebp - 32]); /* lea ebx, [ebp-0x20] */
ii(0x1015_219f, 3); lea(edx, memd[ss, ebp - 20]); /* lea edx, [ebp-0x14] */
ii(0x1015_21a2, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_21a5, 3); add(eax, 0x70); /* add eax, 0x70 */
ii(0x1015_21a8, 5); call(0x1015_5314, 0x3167); /* call 0x10155314 */
ii(0x1015_21ad, 5); call(0x1014_3616, -0xeb9c); /* call 0x10143616 */
ii(0x1015_21b2, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_21b5, 5); call(0x1015_09a6, -0x1814); /* call 0x101509a6 */
ii(0x1015_21ba, 3); movsx(edx, ax); /* movsx edx, ax */
ii(0x1015_21bd, 2); mov(eax, edx); /* mov eax, edx */
ii(0x1015_21bf, 3); sar(edx, 0x1f); /* sar edx, 0x1f */
ii(0x1015_21c2, 3); shl(edx, 2); /* shl edx, 0x2 */
ii(0x1015_21c5, 2); sbb(eax, edx); /* sbb eax, edx */
ii(0x1015_21c7, 3); sar(eax, 2); /* sar eax, 0x2 */
ii(0x1015_21ca, 3); mov(memd[ss, ebp - 36], eax); /* mov [ebp-0x24], eax */
ii(0x1015_21cd, 3); mov(eax, memd[ss, ebp - 18]); /* mov eax, [ebp-0x12] */
ii(0x1015_21d0, 4); cmp(ax, memw[ss, ebp - 36]); /* cmp ax, [ebp-0x24] */
ii(0x1015_21d4, 2); if(jge(0x1015_2248, 0x72)) goto l_0x1015_2248;/* jge 0x10152248 */
ii(0x1015_21d6, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_21d9, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1015_21db, 3); mov(dl, memb[ds, eax + 38]); /* mov dl, [eax+0x26] */
ii(0x1015_21de, 2); xor(eax, eax); /* xor eax, eax */
ii(0x1015_21e0, 5); mov(al, memb[ds, 0x101c_37da]); /* mov al, [0x101c37da] */
ii(0x1015_21e5, 2); cmp(edx, eax); /* cmp edx, eax */
ii(0x1015_21e7, 2); if(jnz(0x1015_21f2, 9)) goto l_0x1015_21f2;/* jnz 0x101521f2 */
ii(0x1015_21e9, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_21ec, 4); cmp(memb[ds, eax + 62], 1); /* cmp byte [eax+0x3e], 0x1 */
ii(0x1015_21f0, 2); if(jnz(0x1015_21f4, 2)) goto l_0x1015_21f4;/* jnz 0x101521f4 */
l_0x1015_21f2:
ii(0x1015_21f2, 2); jmp(0x1015_2243, 0x4f); goto l_0x1015_2243;/* jmp 0x10152243 */
l_0x1015_21f4:
ii(0x1015_21f4, 5); call(0x100c_aa00, -0x8_77f9); /* call 0x100caa00 */
ii(0x1015_21f9, 5); and(eax, 0xff); /* and eax, 0xff */
ii(0x1015_21fe, 1); push(eax); /* push eax */
ii(0x1015_21ff, 5); call(0x100c_aa20, -0x8_77e4); /* call 0x100caa20 */
ii(0x1015_2204, 2); mov(ecx, eax); /* mov ecx, eax */
ii(0x1015_2206, 2); xor(ebx, ebx); /* xor ebx, ebx */
ii(0x1015_2208, 5); mov(edx, 2); /* mov edx, 0x2 */
ii(0x1015_220d, 4); movsx(eax, memw[ss, ebp - 36]); /* movsx eax, word [ebp-0x24] */
ii(0x1015_2211, 1); push(eax); /* push eax */
ii(0x1015_2212, 5); mov(eax, StringDefinitions.IRawMaterialNeededToUpgrade);/* mov eax, 0x101adee4 */
ii(0x1015_2217, 1); push(eax); /* push eax */
ii(0x1015_2218, 5); mov(eax, 0x50); /* mov eax, 0x50 */
ii(0x1015_221d, 1); push(eax); /* push eax */
ii(0x1015_221e, 3); lea(eax, memd[ss, ebp - 40]); /* lea eax, [ebp-0x28] */
ii(0x1015_2221, 5); call(Definitions.my_string_ctor, -0x1_073e);/* call 0x10141ae8 */
ii(0x1015_2226, 1); push(eax); /* push eax */
ii(0x1015_2227, 5); call(0x1014_2037, -0x1_01f5); /* call 0x10142037 */
ii(0x1015_222c, 3); add(esp, 0x10); /* add esp, 0x10 */
ii(0x1015_222f, 5); call(Definitions.my_strobj_c_str_v2, -0xc_8a6c);/* call 0x100897c8 */
ii(0x1015_2234, 5); call(0x1011_5d23, -0x3_c516); /* call 0x10115d23 */
ii(0x1015_2239, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1015_223b, 3); lea(eax, memd[ss, ebp - 40]); /* lea eax, [ebp-0x28] */
ii(0x1015_223e, 5); call(Definitions.my_string_dtor, -0x1_0719);/* call 0x10141b2a */
l_0x1015_2243:
ii(0x1015_2243, 5); jmp(0x1015_2312, 0xca); goto l_0x1015_2312;/* jmp 0x10152312 */
l_0x1015_2248:
ii(0x1015_2248, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_224b, 5); call(0x1014_f78c, -0x2ac4); /* call 0x1014f78c */
ii(0x1015_2250, 2); xor(ecx, ecx); /* xor ecx, ecx */
ii(0x1015_2252, 2); xor(ebx, ebx); /* xor ebx, ebx */
ii(0x1015_2254, 3); mov(eax, memd[ss, ebp - 36]); /* mov eax, [ebp-0x24] */
ii(0x1015_2257, 2); neg(eax); /* neg eax */
ii(0x1015_2259, 3); movsx(edx, ax); /* movsx edx, ax */
ii(0x1015_225c, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_225f, 3); add(eax, 0x70); /* add eax, 0x70 */
ii(0x1015_2262, 5); call(0x1015_5314, 0x30ad); /* call 0x10155314 */
ii(0x1015_2267, 5); call(0x100d_7a9c, -0x7_a7d0); /* call 0x100d7a9c */
ii(0x1015_226c, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_226f, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1015_2271, 3); mov(dl, memb[ds, eax + 38]); /* mov dl, [eax+0x26] */
ii(0x1015_2274, 2); xor(eax, eax); /* xor eax, eax */
ii(0x1015_2276, 5); mov(al, memb[ds, 0x101c_37da]); /* mov al, [0x101c37da] */
ii(0x1015_227b, 2); cmp(edx, eax); /* cmp edx, eax */
ii(0x1015_227d, 2); if(jnz(0x1015_2288, 9)) goto l_0x1015_2288;/* jnz 0x10152288 */
ii(0x1015_227f, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_2282, 4); cmp(memb[ds, eax + 62], 1); /* cmp byte [eax+0x3e], 0x1 */
ii(0x1015_2286, 2); if(jnz(0x1015_228d, 5)) goto l_0x1015_228d;/* jnz 0x1015228d */
l_0x1015_2288:
ii(0x1015_2288, 5); jmp(0x1015_2312, 0x85); goto l_0x1015_2312;/* jmp 0x10152312 */
l_0x1015_228d:
ii(0x1015_228d, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_2290, 5); call(0x1007_623c, -0xd_c059); /* call 0x1007623c */
ii(0x1015_2295, 5); call(0x100e_f36c, -0x6_2f2e); /* call 0x100ef36c */
ii(0x1015_229a, 3); movsx(edx, ax); /* movsx edx, ax */
ii(0x1015_229d, 3); lea(eax, memd[ss, ebp - 52]); /* lea eax, [ebp-0x34] */
ii(0x1015_22a0, 5); call(0x1014_f905, -0x29a0); /* call 0x1014f905 */
ii(0x1015_22a5, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_22a8, 3); mov(ebx, memd[ds, eax + 26]); /* mov ebx, [eax+0x1a] */
ii(0x1015_22ab, 3); sar(ebx, 0x10); /* sar ebx, 0x10 */
ii(0x1015_22ae, 3); mov(edx, memd[ss, ebp - 4]); /* mov edx, [ebp-0x4] */
ii(0x1015_22b1, 3); mov(edx, memd[ds, edx + 24]); /* mov edx, [edx+0x18] */
ii(0x1015_22b4, 3); sar(edx, 0x10); /* sar edx, 0x10 */
ii(0x1015_22b7, 3); lea(eax, memd[ss, ebp - 56]); /* lea eax, [ebp-0x38] */
ii(0x1015_22ba, 5); call(0x1007_6aac, -0xd_b813); /* call 0x10076aac */
ii(0x1015_22bf, 2); mov(ecx, memd[ds, eax]); /* mov ecx, [eax] */
ii(0x1015_22c1, 3); mov(ebx, memd[ss, ebp - 4]); /* mov ebx, [ebp-0x4] */
ii(0x1015_22c4, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1015_22c6, 4); movsx(eax, memw[ss, ebp - 36]); /* movsx eax, word [ebp-0x24] */
ii(0x1015_22ca, 1); push(eax); /* push eax */
ii(0x1015_22cb, 3); lea(eax, memd[ss, ebp - 52]); /* lea eax, [ebp-0x34] */
ii(0x1015_22ce, 1); push(eax); /* push eax */
ii(0x1015_22cf, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_22d2, 3); mov(eax, memd[ds, eax + 6]); /* mov eax, [eax+0x6] */
ii(0x1015_22d5, 3); sar(eax, 0x10); /* sar eax, 0x10 */
ii(0x1015_22d8, 3); imul(eax, eax, 0x33); /* imul eax, eax, 0x33 */
ii(0x1015_22db, 6); push(memd[ds, eax + 0x101c_81d7]); /* push dword [eax+0x101c81d7] */
ii(0x1015_22e1, 5); mov(eax, StringDefinitions.SUpgradedToMarkSForIRawMaterial);/* mov eax, 0x101adf07 */
ii(0x1015_22e6, 1); push(eax); /* push eax */
ii(0x1015_22e7, 5); mov(eax, 0x50); /* mov eax, 0x50 */
ii(0x1015_22ec, 1); push(eax); /* push eax */
ii(0x1015_22ed, 3); lea(eax, memd[ss, ebp - 60]); /* lea eax, [ebp-0x3c] */
ii(0x1015_22f0, 5); call(Definitions.my_string_ctor, -0x1_080d);/* call 0x10141ae8 */
ii(0x1015_22f5, 1); push(eax); /* push eax */
ii(0x1015_22f6, 5); call(0x1014_2037, -0x1_02c4); /* call 0x10142037 */
ii(0x1015_22fb, 3); add(esp, 0x18); /* add esp, 0x18 */
ii(0x1015_22fe, 5); call(Definitions.my_strobj_c_str_v2, -0xc_8b3b);/* call 0x100897c8 */
ii(0x1015_2303, 5); call(0x1011_5b60, -0x3_c7a8); /* call 0x10115b60 */
ii(0x1015_2308, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1015_230a, 3); lea(eax, memd[ss, ebp - 60]); /* lea eax, [ebp-0x3c] */
ii(0x1015_230d, 5); call(Definitions.my_string_dtor, -0x1_07e8);/* call 0x10141b2a */
l_0x1015_2312:
ii(0x1015_2312, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_2315, 5); call(0x1014_f08b, -0x328f); /* call 0x1014f08b */
ii(0x1015_231a, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1015_231c, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_231f, 5); add(eax, 0x82); /* add eax, 0x82 */
ii(0x1015_2324, 5); call(0x1007_6630, -0xd_bcf9); /* call 0x10076630 */
ii(0x1015_2329, 5); mov(edx, 0x101c_37bc); /* mov edx, 0x101c37bc */
ii(0x1015_232e, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_2331, 5); call(0x1007_6d98, -0xd_b59e); /* call 0x10076d98 */
ii(0x1015_2336, 2); test(al, al); /* test al, al */
ii(0x1015_2338, 2); if(jz(0x1015_2342, 8)) goto l_0x1015_2342;/* jz 0x10152342 */
ii(0x1015_233a, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1015_233d, 5); call(0x1010_094d, -0x5_19f5); /* call 0x1010094d */
l_0x1015_2342:
ii(0x1015_2342, 5); mov(edx, 0x101c_37bc); /* mov edx, 0x101c37bc */
ii(0x1015_2347, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_234a, 5); call(0x1007_6d98, -0xd_b5b7); /* call 0x10076d98 */
ii(0x1015_234f, 2); test(al, al); /* test al, al */
ii(0x1015_2351, 2); if(jz(0x1015_2372, 0x1f)) goto l_0x1015_2372;/* jz 0x10152372 */
ii(0x1015_2353, 7); cmp(memb[ds, 0x101c_3889], 0); /* cmp byte [0x101c3889], 0x0 */
ii(0x1015_235a, 2); if(jnz(0x1015_2365, 9)) goto l_0x1015_2365;/* jnz 0x10152365 */
ii(0x1015_235c, 7); cmp(memb[ds, 0x101c_388a], 0); /* cmp byte [0x101c388a], 0x0 */
ii(0x1015_2363, 2); if(jz(0x1015_236a, 5)) goto l_0x1015_236a;/* jz 0x1015236a */
l_0x1015_2365:
ii(0x1015_2365, 5); call(0x100f_f5c1, -0x5_2da9); /* call 0x100ff5c1 */
l_0x1015_236a:
ii(0x1015_236a, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_236d, 5); call(0x100f_f637, -0x5_2d3b); /* call 0x100ff637 */
l_0x1015_2372:
ii(0x1015_2372, 5); mov(edx, 1); /* mov edx, 0x1 */
ii(0x1015_2377, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1015_237a, 5); call(0x1015_2605, 0x286); /* call 0x10152605 */
ii(0x1015_237f, 2); mov(esp, ebp); /* mov esp, ebp */
ii(0x1015_2381, 1); pop(ebp); /* pop ebp */
ii(0x1015_2382, 1); pop(edi); /* pop edi */
ii(0x1015_2383, 1); pop(esi); /* pop esi */
ii(0x1015_2384, 1); pop(ecx); /* pop ecx */
ii(0x1015_2385, 1); pop(ebx); /* pop ebx */
ii(0x1015_2386, 1); ret(); /* ret */
}
}
}
| 85.518692 | 119 | 0.45533 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-1015-2125.cs | 18,301 | C# |
using System;
using System.Threading.Tasks;
using ActiveMQ.Artemis.Client.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace ActiveMQ.Artemis.Client.Extensions.AspNetCore.Tests.Observables
{
public class SendObserverSpec
{
private readonly ITestOutputHelper _testOutputHelper;
public SendObserverSpec(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
[Fact]
public async Task Should_call_PreSend_and_PostSend_on_message_SendAsync()
{
var sendObserver = new TestSendObserver();
var address = Guid.NewGuid().ToString();
await using var testFixture = await TestFixture.CreateAsync(_testOutputHelper, builder =>
{
builder.Services.AddSingleton(sendObserver);
builder.AddProducer<TestProducer>(address)
.AddSendObserver<TestSendObserver>();
});
var testProducer = testFixture.Services.GetService<TestProducer>();
await testProducer.Producer.SendAsync(new Message("foo"), testFixture.CancellationToken);
Assert.True(sendObserver.PreSendCalled);
Assert.True(sendObserver.PostSendCalled);
}
[Fact]
public async Task Should_call_PreSend_and_PostSend_on_message_Send()
{
var sendObserver = new TestSendObserver();
var address = Guid.NewGuid().ToString();
await using var testFixture = await TestFixture.CreateAsync(_testOutputHelper, builder =>
{
builder.Services.AddSingleton(sendObserver);
builder.AddProducer<TestProducer>(address)
.AddSendObserver<TestSendObserver>();
});
var testProducer = testFixture.Services.GetService<TestProducer>();
testProducer.Producer.Send(new Message("foo"), testFixture.CancellationToken);
Assert.True(sendObserver.PreSendCalled);
Assert.True(sendObserver.PostSendCalled);
}
private class TestProducer
{
public IProducer Producer { get; }
public TestProducer(IProducer producer) => Producer = producer;
}
private class TestSendObserver : ISendObserver
{
public bool PreSendCalled { get; private set; }
public void PreSend(string address, RoutingType? routingType, Message message) => PreSendCalled = true;
public bool PostSendCalled { get; private set; }
public void PostSend(string address, RoutingType? routingType, Message message) => PostSendCalled = true;
}
}
} | 38.638889 | 117 | 0.647735 | [
"MIT"
] | Havret/activemq-artemis-extensions | test/ArtemisNetClient.Extensions.Tests/Observables/SendObserverSpec.cs | 2,784 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.Events;
using EasyNetQ.Topology;
namespace EasyNetQ.Consumer
{
public class PersistentMultipleConsumer : IConsumer
{
private readonly ICollection<Tuple<IQueue, Func<byte[], MessageProperties, MessageReceivedInfo, CancellationToken, Task>>> queueConsumerPairs;
private readonly IPersistentConnection connection;
private readonly IConsumerConfiguration configuration;
private readonly IInternalConsumerFactory internalConsumerFactory;
private readonly IEventBus eventBus;
private readonly ConcurrentDictionary<IInternalConsumer, object> internalConsumers =
new ConcurrentDictionary<IInternalConsumer, object>();
private readonly IList<IDisposable> subscriptions = new List<IDisposable>();
private ConsumerCancellation consumerCancellation;
public PersistentMultipleConsumer(
ICollection<Tuple<IQueue, Func<byte[], MessageProperties, MessageReceivedInfo, CancellationToken, Task>>> queueConsumerPairs,
IPersistentConnection connection,
IConsumerConfiguration configuration,
IInternalConsumerFactory internalConsumerFactory,
IEventBus eventBus)
{
Preconditions.CheckNotNull(queueConsumerPairs, nameof(queueConsumerPairs));
Preconditions.CheckNotNull(connection, nameof(connection));
Preconditions.CheckNotNull(internalConsumerFactory, nameof(internalConsumerFactory));
Preconditions.CheckNotNull(eventBus, nameof(eventBus));
Preconditions.CheckNotNull(configuration, nameof(configuration));
this.queueConsumerPairs = queueConsumerPairs;
this.connection = connection;
this.configuration = configuration;
this.internalConsumerFactory = internalConsumerFactory;
this.eventBus = eventBus;
}
public IDisposable StartConsuming()
{
subscriptions.Add(eventBus.Subscribe<ConnectionCreatedEvent>(e => ConnectionOnConnected()));
subscriptions.Add(eventBus.Subscribe<ConnectionDisconnectedEvent>(e => ConnectionOnDisconnected()));
StartConsumingInternal();
consumerCancellation = new ConsumerCancellation(Dispose);
return consumerCancellation;
}
private void StartConsumingInternal()
{
if (disposed) return;
if (!connection.IsConnected)
{
return;
}
var internalConsumer = internalConsumerFactory.CreateConsumer();
internalConsumers.TryAdd(internalConsumer, null);
internalConsumer.Cancelled += consumer => Dispose();
internalConsumer.StartConsuming(
connection,
queueConsumerPairs,
configuration
);
}
private void ConnectionOnDisconnected()
{
internalConsumerFactory.OnDisconnected();
internalConsumers.Clear();
}
private void ConnectionOnConnected()
{
StartConsumingInternal();
}
private bool disposed;
public void Dispose()
{
if (disposed) return;
disposed = true;
consumerCancellation.OnCancel(queueConsumerPairs);
eventBus.Publish(new StoppedConsumingEvent(this));
foreach (var subscription in subscriptions)
{
subscription.Dispose();
}
foreach (var internalConsumer in internalConsumers.Keys)
{
internalConsumer.Dispose();
}
}
}
} | 33.808696 | 150 | 0.652263 | [
"MIT"
] | rtaylor01/EasyNetQ | Source/EasyNetQ/Consumer/PersistentMultipleConsumer.cs | 3,890 | 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.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The type WorkbookTableRowsCollectionRequestBuilder.
/// </summary>
public partial class WorkbookTableRowsCollectionRequestBuilder : BaseRequestBuilder, IWorkbookTableRowsCollectionRequestBuilder
{
/// <summary>
/// Constructs a new WorkbookTableRowsCollectionRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public WorkbookTableRowsCollectionRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public IWorkbookTableRowsCollectionRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public IWorkbookTableRowsCollectionRequest Request(IEnumerable<Option> options)
{
return new WorkbookTableRowsCollectionRequest(this.RequestUrl, this.Client, options);
}
/// <summary>
/// Gets an <see cref="IWorkbookTableRowRequestBuilder"/> for the specified WorkbookTableWorkbookTableRow.
/// </summary>
/// <param name="id">The ID for the WorkbookTableWorkbookTableRow.</param>
/// <returns>The <see cref="IWorkbookTableRowRequestBuilder"/>.</returns>
public IWorkbookTableRowRequestBuilder this[string id]
{
get
{
return new WorkbookTableRowRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client);
}
}
}
}
| 39.177419 | 153 | 0.592013 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/WorkbookTableRowsCollectionRequestBuilder.cs | 2,429 | C# |
using System;
using System.Runtime.InteropServices;
using MyoSharp.Device;
namespace MyoSharp.Communication
{
public interface IChannelBridge
{
#region Methods
ulong EventGetTimestamp32(IntPtr evt);
ulong EventGetTimestamp64(IntPtr evt);
MyoEventType EventGetType32(IntPtr evt);
MyoEventType EventGetType64(IntPtr evt);
IntPtr EventGetMyo32(IntPtr evt);
IntPtr EventGetMyo64(IntPtr evt);
MyoResult InitHub32(out IntPtr hub, string applicationIdentifier, out IntPtr error);
MyoResult InitHub64(out IntPtr hub, string applicationIdentifier, out IntPtr error);
MyoResult ShutdownHub32(IntPtr hub, out IntPtr error);
MyoResult ShutdownHub64(IntPtr hub, out IntPtr error);
MyoResult Run32(IntPtr hub, uint durationMs, MyoRunHandler handler, IntPtr userData, out IntPtr error);
MyoResult Run64(IntPtr hub, uint durationMs, MyoRunHandler handler, IntPtr userData, out IntPtr error);
#endregion
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate MyoRunHandlerResult MyoRunHandler(IntPtr userData, IntPtr evt);
public enum MyoRunHandlerResult
{
Continue,
Stop
}
} | 27.173913 | 111 | 0.7152 | [
"MIT"
] | rizalishan/MyoSharpWithoutContracts | MyoSharp/Communication/IChannelBridge.cs | 1,252 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Math.Raw;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecT131FieldElement
: ECFieldElement
{
protected readonly ulong[] x;
public SecT131FieldElement(BigInteger x)
{
if (x == null || x.SignValue < 0 || x.BitLength > 131)
throw new ArgumentException("value invalid for SecT131FieldElement", "x");
this.x = SecT131Field.FromBigInteger(x);
}
public SecT131FieldElement()
{
this.x = Nat192.Create64();
}
protected internal SecT131FieldElement(ulong[] x)
{
this.x = x;
}
public override bool IsOne
{
get { return Nat192.IsOne64(x); }
}
public override bool IsZero
{
get { return Nat192.IsZero64(x); }
}
public override bool TestBitZero()
{
return (x[0] & 1UL) != 0UL;
}
public override BigInteger ToBigInteger()
{
return Nat192.ToBigInteger64(x);
}
public override string FieldName
{
get { return "SecT131Field"; }
}
public override int FieldSize
{
get { return 131; }
}
public override ECFieldElement Add(ECFieldElement b)
{
ulong[] z = Nat192.Create64();
SecT131Field.Add(x, ((SecT131FieldElement)b).x, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement AddOne()
{
ulong[] z = Nat192.Create64();
SecT131Field.AddOne(x, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement Subtract(ECFieldElement b)
{
// Addition and Subtraction are the same in F2m
return Add(b);
}
public override ECFieldElement Multiply(ECFieldElement b)
{
ulong[] z = Nat192.Create64();
SecT131Field.Multiply(x, ((SecT131FieldElement)b).x, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement MultiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
return MultiplyPlusProduct(b, x, y);
}
public override ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y)
{
ulong[] ax = this.x, bx = ((SecT131FieldElement)b).x;
ulong[] xx = ((SecT131FieldElement)x).x, yx = ((SecT131FieldElement)y).x;
ulong[] tt = Nat.Create64(5);
SecT131Field.MultiplyAddToExt(ax, bx, tt);
SecT131Field.MultiplyAddToExt(xx, yx, tt);
ulong[] z = Nat192.Create64();
SecT131Field.Reduce(tt, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement Divide(ECFieldElement b)
{
return Multiply(b.Invert());
}
public override ECFieldElement Negate()
{
return this;
}
public override ECFieldElement Square()
{
ulong[] z = Nat192.Create64();
SecT131Field.Square(x, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement SquareMinusProduct(ECFieldElement x, ECFieldElement y)
{
return SquarePlusProduct(x, y);
}
public override ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElement y)
{
ulong[] ax = this.x;
ulong[] xx = ((SecT131FieldElement)x).x, yx = ((SecT131FieldElement)y).x;
ulong[] tt = Nat.Create64(5);
SecT131Field.SquareAddToExt(ax, tt);
SecT131Field.MultiplyAddToExt(xx, yx, tt);
ulong[] z = Nat192.Create64();
SecT131Field.Reduce(tt, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement SquarePow(int pow)
{
if (pow < 1)
return this;
ulong[] z = Nat192.Create64();
SecT131Field.SquareN(x, pow, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement Invert()
{
ulong[] z = Nat192.Create64();
SecT131Field.Invert(x, z);
return new SecT131FieldElement(z);
}
public override ECFieldElement Sqrt()
{
ulong[] z = Nat192.Create64();
SecT131Field.Sqrt(x, z);
return new SecT131FieldElement(z);
}
public virtual int Representation
{
get { return F2mFieldElement.Ppb; }
}
public virtual int M
{
get { return 131; }
}
public virtual int K1
{
get { return 2; }
}
public virtual int K2
{
get { return 3; }
}
public virtual int K3
{
get { return 8; }
}
public override bool Equals(object obj)
{
return Equals(obj as SecT131FieldElement);
}
public override bool Equals(ECFieldElement other)
{
return Equals(other as SecT131FieldElement);
}
public virtual bool Equals(SecT131FieldElement other)
{
if (this == other)
return true;
if (null == other)
return false;
return Nat192.Eq64(x, other.x);
}
public override int GetHashCode()
{
return 131832 ^ Arrays.GetHashCode(x, 0, 3);
}
}
}
#endif
| 26.479638 | 113 | 0.537081 | [
"MIT"
] | Manolomon/space-checkers | client/Assets/Libs/Best HTTP (Pro)/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/custom/sec/SecT131FieldElement.cs | 5,852 | C# |
using System;
using System.Diagnostics;
using My2C2P.Org.BouncyCastle.Crypto.Utilities;
namespace My2C2P.Org.BouncyCastle.Math.Raw
{
internal abstract class Nat448
{
public static void Copy64(ulong[] x, ulong[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
z[4] = x[4];
z[5] = x[5];
z[6] = x[6];
}
public static ulong[] Create64()
{
return new ulong[7];
}
public static ulong[] CreateExt64()
{
return new ulong[14];
}
public static bool Eq64(ulong[] x, ulong[] y)
{
for (int i = 6; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static ulong[] FromBigInteger64(BigInteger x)
{
if (x.SignValue < 0 || x.BitLength > 448)
throw new ArgumentException();
ulong[] z = Create64();
int i = 0;
while (x.SignValue != 0)
{
z[i++] = (ulong)x.LongValue;
x = x.ShiftRight(64);
}
return z;
}
public static bool IsOne64(ulong[] x)
{
if (x[0] != 1UL)
{
return false;
}
for (int i = 1; i < 7; ++i)
{
if (x[i] != 0UL)
{
return false;
}
}
return true;
}
public static bool IsZero64(ulong[] x)
{
for (int i = 0; i < 7; ++i)
{
if (x[i] != 0UL)
{
return false;
}
}
return true;
}
public static BigInteger ToBigInteger64(ulong[] x)
{
byte[] bs = new byte[56];
for (int i = 0; i < 7; ++i)
{
ulong x_i = x[i];
if (x_i != 0L)
{
Pack.UInt64_To_BE(x_i, bs, (6 - i) << 3);
}
}
return new BigInteger(1, bs);
}
}
}
| 22.980198 | 61 | 0.348126 | [
"MIT"
] | 2C2P/My2C2PPKCS7 | My2C2PPKCS7/math/raw/Nat448.cs | 2,323 | C# |
namespace IdentityServer.Admin.Core.Dtos.IdentityResource
{
public class PagedIdentityResourceDto : BasePagedDto<IdentityResourceForPage>
{
}
public class IdentityResourceForPage
{
public int Id { get; set; }
public string Name { get; set; }
}
}
| 20.642857 | 81 | 0.67474 | [
"MIT"
] | Olek-HZQ/IdentityServerManagement | src/IdentityServer.Admin.Core/Dtos/IdentityResource/PagedIdentityResourceDto.cs | 291 | C# |
using System.ComponentModel.DataAnnotations;
namespace OurCleanFuture.Data.Entities;
public enum ExternalStatus
{
[Display(Name = "N/A")]
NotApplicable = 0,
[Display(Name = "Complete")]
Complete = 1,
[Display(Name = "In progress")]
InProgress = 2,
[Display(Name = "Not started")]
NotStarted = 3,
[Display(Name = "Ongoing")]
Ongoing = 4
} | 18.285714 | 45 | 0.635417 | [
"Apache-2.0"
] | ytgov-env/climate-change-indicators | src/OurCleanFuture.Data/Entities/ExternalStatus.cs | 386 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Roslynator.Testing.CSharp;
using Xunit;
namespace Roslynator.CSharp.CodeFixes.Tests
{
public class CS0621VirtualOrAbstractMembersCannotBePrivateTests : AbstractCSharpCompilerDiagnosticFixVerifier<ModifiersCodeFixProvider>
{
public override string DiagnosticId { get; } = CompilerDiagnosticIdentifiers.VirtualOrAbstractMembersCannotBePrivate;
[Fact, Trait(Traits.CodeFix, CompilerDiagnosticIdentifiers.VirtualOrAbstractMembersCannotBePrivate)]
public async Task Test_ChangeAccessibilityToPublic()
{
await VerifyFixAsync(@"
class C
{
private virtual void M()
{
}
}
", @"
class C
{
public virtual void M()
{
}
}
", equivalenceKey: EquivalenceKey.Create(DiagnosticId, nameof(AccessibilityFilter.Public)));
}
[Fact, Trait(Traits.CodeFix, CompilerDiagnosticIdentifiers.VirtualOrAbstractMembersCannotBePrivate)]
public async Task Test_RemoveVirtualModifier()
{
await VerifyFixAsync(@"
class C
{
private virtual void M()
{
}
}
", @"
class C
{
private void M()
{
}
}
", equivalenceKey: EquivalenceKey.Create(DiagnosticId, nameof(SyntaxKind.VirtualKeyword)));
}
[Fact, Trait(Traits.CodeFix, CompilerDiagnosticIdentifiers.VirtualOrAbstractMembersCannotBePrivate)]
public async Task Test_RemoveAbstractModifier()
{
await VerifyNoFixAsync(@"
abstract class C
{
abstract void M();
}
",
equivalenceKey: EquivalenceKey.Create(DiagnosticId, nameof(SyntaxKind.VirtualKeyword)));
}
}
}
| 27.014925 | 160 | 0.716575 | [
"Apache-2.0"
] | esirko/Roslynator | src/Tests/CodeFixes.Tests/CS0621VirtualOrAbstractMembersCannotBePrivateTests.cs | 1,812 | C# |
namespace WindowsFormsApp1
{
partial class Form1
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージド リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows フォーム デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.numericUpDown3 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown4 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown5 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown6 = new System.Windows.Forms.NumericUpDown();
this.label7 = new System.Windows.Forms.Label();
this.numericUpDown7 = new System.Windows.Forms.NumericUpDown();
this.label8 = new System.Windows.Forms.Label();
this.numericUpDown8 = new System.Windows.Forms.NumericUpDown();
this.label9 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.label21 = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.label19 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label18 = new System.Windows.Forms.Label();
this.label17 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.panel2 = new System.Windows.Forms.Panel();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.panel3 = new System.Windows.Forms.Panel();
this.panel8 = new System.Windows.Forms.Panel();
this.button19 = new System.Windows.Forms.Button();
this.button14 = new System.Windows.Forms.Button();
this.button18 = new System.Windows.Forms.Button();
this.button15 = new System.Windows.Forms.Button();
this.trackBar1 = new System.Windows.Forms.TrackBar();
this.button13 = new System.Windows.Forms.Button();
this.button12 = new System.Windows.Forms.Button();
this.button11 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.panel4 = new System.Windows.Forms.Panel();
this.label16 = new System.Windows.Forms.Label();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.label15 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.panel7 = new System.Windows.Forms.Panel();
this.button17 = new System.Windows.Forms.Button();
this.button16 = new System.Windows.Forms.Button();
this.label14 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.button9 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.listBox3 = new System.Windows.Forms.ListBox();
this.listBox2 = new System.Windows.Forms.ListBox();
this.listBox1 = new System.Windows.Forms.ListBox();
this.splitter4 = new System.Windows.Forms.Splitter();
this.splitter3 = new System.Windows.Forms.Splitter();
this.splitter1 = new System.Windows.Forms.Splitter();
this.panel5 = new System.Windows.Forms.Panel();
this.panel6 = new System.Windows.Forms.Panel();
this.splitter2 = new System.Windows.Forms.Splitter();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown8)).BeginInit();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.panel3.SuspendLayout();
this.panel8.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.panel4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.panel7.SuspendLayout();
this.panel5.SuspendLayout();
this.panel6.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.button1.Location = new System.Drawing.Point(647, 6);
this.button1.Margin = new System.Windows.Forms.Padding(4);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(137, 41);
this.button1.TabIndex = 0;
this.button1.Text = "train";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(647, 60);
this.button2.Margin = new System.Windows.Forms.Padding(4);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(137, 39);
this.button2.TabIndex = 1;
this.button2.Text = "train_stop";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// button3
//
this.button3.Location = new System.Drawing.Point(792, 60);
this.button3.Margin = new System.Windows.Forms.Padding(4);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(137, 39);
this.button3.TabIndex = 3;
this.button3.Text = "test_stop";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.button4.Location = new System.Drawing.Point(792, 6);
this.button4.Margin = new System.Windows.Forms.Padding(4);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(137, 41);
this.button4.TabIndex = 2;
this.button4.Text = "test";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// button5
//
this.button5.Location = new System.Drawing.Point(4, 4);
this.button5.Margin = new System.Windows.Forms.Padding(4);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(160, 35);
this.button5.TabIndex = 4;
this.button5.Text = "CVS file";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(4, 49);
this.button6.Margin = new System.Windows.Forms.Padding(4);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(160, 34);
this.button6.TabIndex = 10;
this.button6.Text = "Generate input";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 32);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(296, 15);
this.label1.TabIndex = 11;
this.label1.Text = "Frequency of the data to train on and predict";
this.toolTip1.SetToolTip(this.label1, "Data interval\r\n5minute -> 5min\r\n2monthly -> 2M\r\n1day -> 1D\r\n12hour -> 12H \r\n30sec" +
" -> 0.5min\r\n\r\n• M: monthly\r\n• W: weekly\r\n• D: daily\r\n• H: hourly\r\n• min: every m" +
"inute");
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(330, 28);
this.textBox1.Margin = new System.Windows.Forms.Padding(4);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(99, 22);
this.textBox1.TabIndex = 12;
this.textBox1.Text = "1M";
this.toolTip1.SetToolTip(this.textBox1, "Data interval\r\n5minute -> 5min\r\n2monthly -> 2M\r\n1day -> 1D\r\n12hour -> 12H \r\n30sec" +
" -> 0.5min\r\n\r\n• M: monthly\r\n• W: weekly\r\n• D: daily\r\n• H: hourly\r\n• min: every m" +
"inute\r\n");
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(7, 64);
this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(214, 15);
this.label4.TabIndex = 13;
this.label4.Text = "Length of the prediction horizon";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(7, 98);
this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(105, 15);
this.label5.TabIndex = 15;
this.label5.Text = "context_length ";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(7, 130);
this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(53, 15);
this.label6.TabIndex = 17;
this.label6.Text = "epochs";
//
// numericUpDown3
//
this.numericUpDown3.Location = new System.Drawing.Point(330, 60);
this.numericUpDown3.Margin = new System.Windows.Forms.Padding(4);
this.numericUpDown3.Maximum = new decimal(new int[] {
400,
0,
0,
0});
this.numericUpDown3.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown3.Name = "numericUpDown3";
this.numericUpDown3.Size = new System.Drawing.Size(100, 22);
this.numericUpDown3.TabIndex = 19;
this.numericUpDown3.Value = new decimal(new int[] {
12,
0,
0,
0});
//
// numericUpDown4
//
this.numericUpDown4.Location = new System.Drawing.Point(330, 91);
this.numericUpDown4.Margin = new System.Windows.Forms.Padding(4);
this.numericUpDown4.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.numericUpDown4.Minimum = new decimal(new int[] {
2,
0,
0,
0});
this.numericUpDown4.Name = "numericUpDown4";
this.numericUpDown4.Size = new System.Drawing.Size(100, 22);
this.numericUpDown4.TabIndex = 20;
this.numericUpDown4.Value = new decimal(new int[] {
24,
0,
0,
0});
//
// numericUpDown5
//
this.numericUpDown5.Location = new System.Drawing.Point(330, 127);
this.numericUpDown5.Margin = new System.Windows.Forms.Padding(4);
this.numericUpDown5.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.numericUpDown5.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown5.Name = "numericUpDown5";
this.numericUpDown5.Size = new System.Drawing.Size(100, 22);
this.numericUpDown5.TabIndex = 21;
this.numericUpDown5.Value = new decimal(new int[] {
5,
0,
0,
0});
//
// numericUpDown6
//
this.numericUpDown6.Location = new System.Drawing.Point(330, 160);
this.numericUpDown6.Margin = new System.Windows.Forms.Padding(4);
this.numericUpDown6.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDown6.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown6.Name = "numericUpDown6";
this.numericUpDown6.Size = new System.Drawing.Size(100, 22);
this.numericUpDown6.TabIndex = 23;
this.numericUpDown6.Value = new decimal(new int[] {
32,
0,
0,
0});
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(7, 162);
this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(72, 15);
this.label7.TabIndex = 22;
this.label7.Text = "batch_size";
//
// numericUpDown7
//
this.numericUpDown7.Location = new System.Drawing.Point(330, 190);
this.numericUpDown7.Margin = new System.Windows.Forms.Padding(4);
this.numericUpDown7.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDown7.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown7.Name = "numericUpDown7";
this.numericUpDown7.Size = new System.Drawing.Size(100, 22);
this.numericUpDown7.TabIndex = 25;
this.numericUpDown7.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(7, 192);
this.label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(76, 15);
this.label8.TabIndex = 24;
this.label8.Text = "num_layers";
//
// numericUpDown8
//
this.numericUpDown8.Location = new System.Drawing.Point(330, 226);
this.numericUpDown8.Margin = new System.Windows.Forms.Padding(4);
this.numericUpDown8.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDown8.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown8.Name = "numericUpDown8";
this.numericUpDown8.Size = new System.Drawing.Size(100, 22);
this.numericUpDown8.TabIndex = 27;
this.numericUpDown8.Value = new decimal(new int[] {
40,
0,
0,
0});
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(7, 228);
this.label9.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(68, 15);
this.label9.TabIndex = 26;
this.label9.Text = "num_cells";
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.label21);
this.panel1.Controls.Add(this.label20);
this.panel1.Controls.Add(this.comboBox2);
this.panel1.Controls.Add(this.textBox3);
this.panel1.Controls.Add(this.label19);
this.panel1.Controls.Add(this.textBox2);
this.panel1.Controls.Add(this.label18);
this.panel1.Controls.Add(this.label17);
this.panel1.Controls.Add(this.comboBox1);
this.panel1.Controls.Add(this.label9);
this.panel1.Controls.Add(this.numericUpDown8);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.numericUpDown7);
this.panel1.Controls.Add(this.textBox1);
this.panel1.Controls.Add(this.label8);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.numericUpDown6);
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label7);
this.panel1.Controls.Add(this.label6);
this.panel1.Controls.Add(this.numericUpDown5);
this.panel1.Controls.Add(this.numericUpDown3);
this.panel1.Controls.Add(this.numericUpDown4);
this.panel1.Location = new System.Drawing.Point(184, 6);
this.panel1.Margin = new System.Windows.Forms.Padding(4);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(455, 385);
this.panel1.TabIndex = 28;
//
// label21
//
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(7, 349);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(64, 15);
this.label21.TabIndex = 39;
this.label21.Text = "encoding";
//
// label20
//
this.label20.AutoSize = true;
this.label20.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label20.Location = new System.Drawing.Point(3, 0);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(89, 15);
this.label20.TabIndex = 39;
this.label20.Text = "Parameters";
//
// comboBox2
//
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Items.AddRange(new object[] {
"cp932",
"shift_jis",
"utf_16",
"utf_7",
"utf_8"});
this.comboBox2.Location = new System.Drawing.Point(274, 341);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(160, 23);
this.comboBox2.TabIndex = 39;
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(369, 312);
this.textBox3.Margin = new System.Windows.Forms.Padding(4);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(61, 22);
this.textBox3.TabIndex = 44;
this.textBox3.Text = "0.1";
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(7, 319);
this.label19.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(85, 15);
this.label19.TabIndex = 43;
this.label19.Text = "dropout_rate";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(369, 282);
this.textBox2.Margin = new System.Windows.Forms.Padding(4);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(61, 22);
this.textBox2.TabIndex = 42;
this.textBox2.Text = "0.001";
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(7, 285);
this.label18.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(86, 15);
this.label18.TabIndex = 41;
this.label18.Text = "learning_rate";
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(7, 258);
this.label17.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(80, 15);
this.label17.TabIndex = 40;
this.label17.Text = "distr_output";
//
// comboBox1
//
this.comboBox1.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.comboBox1.ForeColor = System.Drawing.SystemColors.HotTrack;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(274, 255);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(155, 23);
this.comboBox1.TabIndex = 39;
//
// panel2
//
this.panel2.Controls.Add(this.checkBox1);
this.panel2.Controls.Add(this.button6);
this.panel2.Controls.Add(this.button5);
this.panel2.Location = new System.Drawing.Point(4, 6);
this.panel2.Margin = new System.Windows.Forms.Padding(4);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(172, 385);
this.panel2.TabIndex = 29;
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.checkBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.checkBox1.Location = new System.Drawing.Point(7, 363);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(93, 19);
this.checkBox1.TabIndex = 37;
this.checkBox1.Text = "use GPU";
this.checkBox1.UseVisualStyleBackColor = true;
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(110, 52);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(4);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(611, 517);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 30;
this.pictureBox1.TabStop = false;
//
// panel3
//
this.panel3.Controls.Add(this.panel8);
this.panel3.Controls.Add(this.button13);
this.panel3.Controls.Add(this.button12);
this.panel3.Controls.Add(this.button11);
this.panel3.Controls.Add(this.button8);
this.panel3.Controls.Add(this.button7);
this.panel3.Dock = System.Windows.Forms.DockStyle.Top;
this.panel3.Location = new System.Drawing.Point(0, 0);
this.panel3.Margin = new System.Windows.Forms.Padding(4);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(884, 116);
this.panel3.TabIndex = 31;
//
// panel8
//
this.panel8.BackColor = System.Drawing.SystemColors.Control;
this.panel8.Controls.Add(this.button19);
this.panel8.Controls.Add(this.button14);
this.panel8.Controls.Add(this.button18);
this.panel8.Controls.Add(this.button15);
this.panel8.Controls.Add(this.trackBar1);
this.panel8.Location = new System.Drawing.Point(8, 42);
this.panel8.Name = "panel8";
this.panel8.Size = new System.Drawing.Size(765, 70);
this.panel8.TabIndex = 31;
//
// button19
//
this.button19.Location = new System.Drawing.Point(708, 28);
this.button19.Name = "button19";
this.button19.Size = new System.Drawing.Size(36, 24);
this.button19.TabIndex = 46;
this.button19.Text = "-";
this.button19.UseVisualStyleBackColor = true;
this.button19.Click += new System.EventHandler(this.button19_Click);
//
// button14
//
this.button14.Location = new System.Drawing.Point(4, 15);
this.button14.Margin = new System.Windows.Forms.Padding(4);
this.button14.Name = "button14";
this.button14.Size = new System.Drawing.Size(137, 37);
this.button14.TabIndex = 42;
this.button14.Text = "train plot";
this.button14.UseVisualStyleBackColor = true;
this.button14.Click += new System.EventHandler(this.button14_Click);
//
// button18
//
this.button18.Location = new System.Drawing.Point(708, 2);
this.button18.Name = "button18";
this.button18.Size = new System.Drawing.Size(36, 24);
this.button18.TabIndex = 45;
this.button18.Text = "+";
this.button18.UseVisualStyleBackColor = true;
this.button18.Click += new System.EventHandler(this.button18_Click);
//
// button15
//
this.button15.Location = new System.Drawing.Point(149, 15);
this.button15.Margin = new System.Windows.Forms.Padding(4);
this.button15.Name = "button15";
this.button15.Size = new System.Drawing.Size(137, 37);
this.button15.TabIndex = 43;
this.button15.Text = "test plot";
this.button15.UseVisualStyleBackColor = true;
this.button15.Click += new System.EventHandler(this.button15_Click);
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(311, 9);
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(391, 56);
this.trackBar1.TabIndex = 44;
this.trackBar1.Visible = false;
this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// button13
//
this.button13.Location = new System.Drawing.Point(471, 6);
this.button13.Margin = new System.Windows.Forms.Padding(4);
this.button13.Name = "button13";
this.button13.Size = new System.Drawing.Size(100, 29);
this.button13.TabIndex = 41;
this.button13.Text = "load model";
this.button13.UseVisualStyleBackColor = true;
this.button13.Click += new System.EventHandler(this.button13_Click);
//
// button12
//
this.button12.Location = new System.Drawing.Point(363, 6);
this.button12.Margin = new System.Windows.Forms.Padding(4);
this.button12.Name = "button12";
this.button12.Size = new System.Drawing.Size(100, 29);
this.button12.TabIndex = 40;
this.button12.Text = "save model";
this.button12.UseVisualStyleBackColor = true;
this.button12.Click += new System.EventHandler(this.button12_Click);
//
// button11
//
this.button11.Location = new System.Drawing.Point(255, 6);
this.button11.Margin = new System.Windows.Forms.Padding(4);
this.button11.Name = "button11";
this.button11.Size = new System.Drawing.Size(100, 29);
this.button11.TabIndex = 39;
this.button11.Text = "Viewer";
this.button11.UseVisualStyleBackColor = true;
this.button11.Click += new System.EventHandler(this.button11_Click);
//
// button8
//
this.button8.Location = new System.Drawing.Point(147, 6);
this.button8.Margin = new System.Windows.Forms.Padding(4);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(100, 29);
this.button8.TabIndex = 38;
this.button8.Text = "clipborad";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// button7
//
this.button7.BackColor = System.Drawing.Color.Blue;
this.button7.ForeColor = System.Drawing.Color.Yellow;
this.button7.Location = new System.Drawing.Point(8, 6);
this.button7.Margin = new System.Windows.Forms.Padding(4);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(131, 29);
this.button7.TabIndex = 37;
this.button7.Text = "image fit";
this.button7.UseVisualStyleBackColor = false;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// panel4
//
this.panel4.Controls.Add(this.label16);
this.panel4.Controls.Add(this.numericUpDown1);
this.panel4.Controls.Add(this.label15);
this.panel4.Controls.Add(this.label13);
this.panel4.Controls.Add(this.label12);
this.panel4.Controls.Add(this.label3);
this.panel4.Controls.Add(this.label2);
this.panel4.Controls.Add(this.panel7);
this.panel4.Controls.Add(this.splitter3);
this.panel4.Controls.Add(this.panel2);
this.panel4.Controls.Add(this.button1);
this.panel4.Controls.Add(this.button2);
this.panel4.Controls.Add(this.button4);
this.panel4.Controls.Add(this.panel1);
this.panel4.Controls.Add(this.button3);
this.panel4.Dock = System.Windows.Forms.DockStyle.Left;
this.panel4.Location = new System.Drawing.Point(0, 0);
this.panel4.Margin = new System.Windows.Forms.Padding(4);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(944, 969);
this.panel4.TabIndex = 32;
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(647, 115);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(62, 15);
this.label16.TabIndex = 38;
this.label16.Text = "plot step";
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(715, 113);
this.numericUpDown1.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.numericUpDown1.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(76, 22);
this.numericUpDown1.TabIndex = 37;
this.numericUpDown1.Value = new decimal(new int[] {
3,
0,
0,
0});
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(647, 227);
this.label15.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(54, 15);
this.label15.TabIndex = 36;
this.label15.Text = "NRMSE";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(647, 212);
this.label13.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(44, 15);
this.label13.TabIndex = 35;
this.label13.Text = "MAPE";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(647, 197);
this.label12.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(44, 15);
this.label12.TabIndex = 34;
this.label12.Text = "MASE";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
this.label3.Location = new System.Drawing.Point(647, 172);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(38, 15);
this.label3.TabIndex = 33;
this.label3.Text = "MSE";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
this.label2.Location = new System.Drawing.Point(647, 157);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 15);
this.label2.TabIndex = 32;
this.label2.Text = "RMSE";
//
// panel7
//
this.panel7.Controls.Add(this.button17);
this.panel7.Controls.Add(this.button16);
this.panel7.Controls.Add(this.label14);
this.panel7.Controls.Add(this.label10);
this.panel7.Controls.Add(this.label11);
this.panel7.Controls.Add(this.button9);
this.panel7.Controls.Add(this.button10);
this.panel7.Controls.Add(this.listBox3);
this.panel7.Controls.Add(this.listBox2);
this.panel7.Controls.Add(this.listBox1);
this.panel7.Controls.Add(this.splitter4);
this.panel7.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel7.Location = new System.Drawing.Point(4, 399);
this.panel7.Margin = new System.Windows.Forms.Padding(4);
this.panel7.Name = "panel7";
this.panel7.Size = new System.Drawing.Size(940, 570);
this.panel7.TabIndex = 30;
//
// button17
//
this.button17.Location = new System.Drawing.Point(243, 17);
this.button17.Name = "button17";
this.button17.Size = new System.Drawing.Size(50, 28);
this.button17.TabIndex = 118;
this.button17.Text = "rev";
this.button17.UseVisualStyleBackColor = true;
this.button17.Click += new System.EventHandler(this.button17_Click);
//
// button16
//
this.button16.Location = new System.Drawing.Point(174, 17);
this.button16.Name = "button16";
this.button16.Size = new System.Drawing.Size(63, 29);
this.button16.TabIndex = 117;
this.button16.Text = "all";
this.button16.UseVisualStyleBackColor = true;
this.button16.Click += new System.EventHandler(this.button16_Click);
//
// label14
//
this.label14.AutoSize = true;
this.label14.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label14.Location = new System.Drawing.Point(349, 31);
this.label14.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(132, 15);
this.label14.TabIndex = 116;
this.label14.Text = "dynamic features";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label10.Location = new System.Drawing.Point(659, 31);
this.label10.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(38, 15);
this.label10.TabIndex = 115;
this.label10.Text = "time";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label11.Location = new System.Drawing.Point(8, 31);
this.label11.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(50, 15);
this.label11.TabIndex = 114;
this.label11.Text = "target";
//
// button9
//
this.button9.Location = new System.Drawing.Point(551, 17);
this.button9.Margin = new System.Windows.Forms.Padding(4, 2, 4, 2);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(43, 27);
this.button9.TabIndex = 113;
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.button9_Click);
//
// button10
//
this.button10.Location = new System.Drawing.Point(499, 16);
this.button10.Margin = new System.Windows.Forms.Padding(4, 2, 4, 2);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(44, 28);
this.button10.TabIndex = 112;
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.button10_Click);
//
// listBox3
//
this.listBox3.FormattingEnabled = true;
this.listBox3.ItemHeight = 15;
this.listBox3.Location = new System.Drawing.Point(347, 50);
this.listBox3.Margin = new System.Windows.Forms.Padding(4);
this.listBox3.Name = "listBox3";
this.listBox3.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.listBox3.Size = new System.Drawing.Size(257, 499);
this.listBox3.TabIndex = 5;
//
// listBox2
//
this.listBox2.FormattingEnabled = true;
this.listBox2.ItemHeight = 15;
this.listBox2.Location = new System.Drawing.Point(661, 50);
this.listBox2.Margin = new System.Windows.Forms.Padding(4);
this.listBox2.Name = "listBox2";
this.listBox2.Size = new System.Drawing.Size(257, 499);
this.listBox2.TabIndex = 4;
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.ItemHeight = 15;
this.listBox1.Location = new System.Drawing.Point(7, 50);
this.listBox1.Margin = new System.Windows.Forms.Padding(4);
this.listBox1.Name = "listBox1";
this.listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.listBox1.Size = new System.Drawing.Size(271, 499);
this.listBox1.TabIndex = 3;
this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
this.listBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.listBox1_MouseDown);
//
// splitter4
//
this.splitter4.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.splitter4.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter4.Location = new System.Drawing.Point(0, 0);
this.splitter4.Margin = new System.Windows.Forms.Padding(4);
this.splitter4.Name = "splitter4";
this.splitter4.Size = new System.Drawing.Size(940, 10);
this.splitter4.TabIndex = 0;
this.splitter4.TabStop = false;
//
// splitter3
//
this.splitter3.Cursor = System.Windows.Forms.Cursors.HSplit;
this.splitter3.Location = new System.Drawing.Point(0, 0);
this.splitter3.Margin = new System.Windows.Forms.Padding(4);
this.splitter3.Name = "splitter3";
this.splitter3.Size = new System.Drawing.Size(4, 969);
this.splitter3.TabIndex = 31;
this.splitter3.TabStop = false;
//
// splitter1
//
this.splitter1.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.splitter1.Location = new System.Drawing.Point(944, 0);
this.splitter1.Margin = new System.Windows.Forms.Padding(4);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(4, 969);
this.splitter1.TabIndex = 33;
this.splitter1.TabStop = false;
//
// panel5
//
this.panel5.Controls.Add(this.panel6);
this.panel5.Controls.Add(this.splitter2);
this.panel5.Controls.Add(this.panel3);
this.panel5.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel5.Location = new System.Drawing.Point(948, 0);
this.panel5.Margin = new System.Windows.Forms.Padding(4);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(884, 969);
this.panel5.TabIndex = 34;
//
// panel6
//
this.panel6.AutoScroll = true;
this.panel6.BackColor = System.Drawing.SystemColors.Control;
this.panel6.Controls.Add(this.pictureBox1);
this.panel6.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel6.Location = new System.Drawing.Point(0, 120);
this.panel6.Margin = new System.Windows.Forms.Padding(4);
this.panel6.Name = "panel6";
this.panel6.Size = new System.Drawing.Size(884, 849);
this.panel6.TabIndex = 33;
//
// splitter2
//
this.splitter2.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.splitter2.Cursor = System.Windows.Forms.Cursors.HSplit;
this.splitter2.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter2.Location = new System.Drawing.Point(0, 116);
this.splitter2.Margin = new System.Windows.Forms.Padding(4);
this.splitter2.Name = "splitter2";
this.splitter2.Size = new System.Drawing.Size(884, 4);
this.splitter2.TabIndex = 32;
this.splitter2.TabStop = false;
//
// toolTip1
//
this.toolTip1.AutoPopDelay = 50000;
this.toolTip1.InitialDelay = 50;
this.toolTip1.IsBalloon = true;
this.toolTip1.ReshowDelay = 100;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.ClientSize = new System.Drawing.Size(1832, 969);
this.Controls.Add(this.panel5);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel4);
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "Form1";
this.Text = "deepAR";
((System.ComponentModel.ISupportInitialize)(this.numericUpDown3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown8)).EndInit();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.panel3.ResumeLayout(false);
this.panel8.ResumeLayout(false);
this.panel8.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.panel7.ResumeLayout(false);
this.panel7.PerformLayout();
this.panel5.ResumeLayout(false);
this.panel6.ResumeLayout(false);
this.panel6.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.NumericUpDown numericUpDown3;
private System.Windows.Forms.NumericUpDown numericUpDown4;
private System.Windows.Forms.NumericUpDown numericUpDown5;
private System.Windows.Forms.NumericUpDown numericUpDown6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.NumericUpDown numericUpDown7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.NumericUpDown numericUpDown8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.Splitter splitter2;
private System.Windows.Forms.Panel panel6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Panel panel7;
private System.Windows.Forms.Splitter splitter4;
private System.Windows.Forms.Splitter splitter3;
private System.Windows.Forms.ListBox listBox2;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.ListBox listBox3;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button button12;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Button button13;
private System.Windows.Forms.Button button15;
private System.Windows.Forms.Button button14;
private System.Windows.Forms.Button button16;
private System.Windows.Forms.Button button17;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.TrackBar trackBar1;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.Button button19;
private System.Windows.Forms.Button button18;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.Panel panel8;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.ComboBox comboBox2;
}
}
| 47.443082 | 159 | 0.572481 | [
"MIT"
] | Sanaxen/deepAR | WindowsFormsApp1/WindowsFormsApp1/Form1.Designer.cs | 54,482 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Examine;
using Examine.LuceneEngine.Providers;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Examine;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Mvc;
using Umbraco.Web.Search;
using SearchResult = Umbraco.Web.Models.ContentEditing.SearchResult;
namespace Umbraco.Web.Editors
{
[PluginController("UmbracoApi")]
public class ExamineManagementController : UmbracoAuthorizedJsonController
{
private readonly IExamineManager _examineManager;
private readonly ILogger _logger;
private readonly IAppPolicyCache _runtimeCache;
private readonly IndexRebuilder _indexRebuilder;
public ExamineManagementController(IExamineManager examineManager, ILogger logger,
AppCaches appCaches,
IndexRebuilder indexRebuilder)
{
_examineManager = examineManager;
_logger = logger;
_runtimeCache = appCaches.RuntimeCache;
_indexRebuilder = indexRebuilder;
}
/// <summary>
/// Get the details for indexers
/// </summary>
/// <returns></returns>
public IEnumerable<ExamineIndexModel> GetIndexerDetails()
{
return _examineManager.Indexes.Select(CreateModel).OrderBy(x => x.Name.TrimEnd("Indexer"));
}
/// <summary>
/// Get the details for searchers
/// </summary>
/// <returns></returns>
public IEnumerable<ExamineSearcherModel> GetSearcherDetails()
{
var model = new List<ExamineSearcherModel>(
_examineManager.RegisteredSearchers.Select(searcher => new ExamineSearcherModel { Name = searcher.Name })
.OrderBy(x => x.Name.TrimEnd("Searcher"))); //order by name , but strip the "Searcher" from the end if it exists
return model;
}
public SearchResults GetSearchResults(string searcherName, string query, int pageIndex = 0, int pageSize = 20)
{
if (query.IsNullOrWhiteSpace())
return SearchResults.Empty();
var msg = ValidateSearcher(searcherName, out var searcher);
if (!msg.IsSuccessStatusCode)
throw new HttpResponseException(msg);
var results = Examine.ExamineExtensions.TryParseLuceneQuery(query)
? searcher.CreateQuery().NativeQuery(query).Execute(maxResults: pageSize * (pageIndex + 1))
: searcher.Search(query, maxResults: pageSize * (pageIndex + 1));
var pagedResults = results.Skip(pageIndex * pageSize);
return new SearchResults
{
TotalRecords = results.TotalItemCount,
Results = pagedResults.Select(x => new SearchResult
{
Id = x.Id,
Score = x.Score,
//order the values by key
Values = new Dictionary<string, string>(x.Values.OrderBy(y => y.Key).ToDictionary(y => y.Key, y => y.Value))
})
};
}
/// <summary>
/// Check if the index has been rebuilt
/// </summary>
/// <param name="indexName"></param>
/// <returns></returns>
/// <remarks>
/// This is kind of rudimentary since there's no way we can know that the index has rebuilt, we
/// have a listener for the index op complete so we'll just check if that key is no longer there in the runtime cache
/// </remarks>
public ExamineIndexModel PostCheckRebuildIndex(string indexName)
{
var validate = ValidateIndex(indexName, out var index);
if (!validate.IsSuccessStatusCode)
throw new HttpResponseException(validate);
validate = ValidatePopulator(index);
if (!validate.IsSuccessStatusCode)
throw new HttpResponseException(validate);
var cacheKey = "temp_indexing_op_" + indexName;
var found = AppCaches.RuntimeCache.Get(cacheKey);
//if its still there then it's not done
return found != null
? null
: CreateModel(index);
}
/// <summary>
/// Rebuilds the index
/// </summary>
/// <param name="indexName"></param>
/// <returns></returns>
public HttpResponseMessage PostRebuildIndex(string indexName)
{
var validate = ValidateIndex(indexName, out var index);
if (!validate.IsSuccessStatusCode)
return validate;
validate = ValidatePopulator(index);
if (!validate.IsSuccessStatusCode)
return validate;
_logger.Info<ExamineManagementController, string>("Rebuilding index '{IndexName}'", indexName);
//remove it in case there's a handler there already
index.IndexOperationComplete -= Indexer_IndexOperationComplete;
//now add a single handler
index.IndexOperationComplete += Indexer_IndexOperationComplete;
try
{
var cacheKey = "temp_indexing_op_" + index.Name;
//put temp val in cache which is used as a rudimentary way to know when the indexing is done
AppCaches.RuntimeCache.Insert(cacheKey, () => "tempValue", TimeSpan.FromMinutes(5));
_indexRebuilder.RebuildIndex(indexName);
////populate it
//foreach (var populator in _populators.Where(x => x.IsRegistered(indexName)))
// populator.Populate(index);
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
//ensure it's not listening
index.IndexOperationComplete -= Indexer_IndexOperationComplete;
Logger.Error<ExamineManagementController>(ex, "An error occurred rebuilding index");
var response = Request.CreateResponse(HttpStatusCode.Conflict);
response.Content =
new
StringContent($"The index could not be rebuilt at this time, most likely there is another thread currently writing to the index. Error: {ex}");
response.ReasonPhrase = "Could Not Rebuild";
return response;
}
}
private ExamineIndexModel CreateModel(IIndex index)
{
var indexName = index.Name;
if (!(index is IIndexDiagnostics indexDiag))
{
if (index is LuceneIndex luceneIndex)
indexDiag = new LuceneIndexDiagnostics(luceneIndex, Logger);
else
indexDiag = new GenericIndexDiagnostics(index);
}
var isHealth = indexDiag.IsHealthy();
var properties = new Dictionary<string, object>
{
[nameof(IIndexDiagnostics.DocumentCount)] = indexDiag.DocumentCount,
[nameof(IIndexDiagnostics.FieldCount)] = indexDiag.FieldCount,
};
foreach (var p in indexDiag.Metadata)
properties[p.Key] = p.Value;
var indexerModel = new ExamineIndexModel
{
Name = indexName,
HealthStatus = isHealth.Success ? (isHealth.Result ?? "Healthy") : (isHealth.Result ?? "Unhealthy"),
ProviderProperties = properties,
CanRebuild = _indexRebuilder.CanRebuild(index)
};
return indexerModel;
}
private HttpResponseMessage ValidateSearcher(string searcherName, out ISearcher searcher)
{
//try to get the searcher from the indexes
if (_examineManager.TryGetIndex(searcherName, out var index))
{
searcher = index.GetSearcher();
return Request.CreateResponse(HttpStatusCode.OK);
}
//if we didn't find anything try to find it by an explicitly declared searcher
if (_examineManager.TryGetSearcher(searcherName, out searcher))
return Request.CreateResponse(HttpStatusCode.OK);
var response1 = Request.CreateResponse(HttpStatusCode.BadRequest);
response1.Content = new StringContent($"No searcher found with name = {searcherName}");
response1.ReasonPhrase = "Searcher Not Found";
return response1;
}
private HttpResponseMessage ValidatePopulator(IIndex index)
{
if (_indexRebuilder.CanRebuild(index))
return Request.CreateResponse(HttpStatusCode.OK);
var response = Request.CreateResponse(HttpStatusCode.BadRequest);
response.Content = new StringContent($"The index {index.Name} cannot be rebuilt because it does not have an associated {typeof(IIndexPopulator)}");
response.ReasonPhrase = "Index cannot be rebuilt";
return response;
}
private HttpResponseMessage ValidateIndex(string indexName, out IIndex index)
{
index = null;
if (_examineManager.TryGetIndex(indexName, out index))
{
//return Ok!
return Request.CreateResponse(HttpStatusCode.OK);
}
var response = Request.CreateResponse(HttpStatusCode.BadRequest);
response.Content = new StringContent($"No index found with name = {indexName}");
response.ReasonPhrase = "Index Not Found";
return response;
}
private void Indexer_IndexOperationComplete(object sender, EventArgs e)
{
var indexer = (IIndex)sender;
_logger.Debug<ExamineManagementController, string>("Logging operation completed for index {IndexName}", indexer.Name);
//ensure it's not listening anymore
indexer.IndexOperationComplete -= Indexer_IndexOperationComplete;
_logger
.Info<ExamineManagementController
>($"Rebuilding index '{indexer.Name}' done.");
var cacheKey = "temp_indexing_op_" + indexer.Name;
_runtimeCache.Clear(cacheKey);
}
}
}
| 38.7 | 167 | 0.601876 | [
"MIT"
] | AaronSadlerUK/Umbraco-CMS | src/Umbraco.Web/Editors/ExamineManagementController.cs | 10,451 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using WordPressPCL.Interfaces;
using WordPressPCL.Models;
using WordPressPCL.Utility;
namespace WordPressPCL.Client
{
/// <summary>
/// Client class for interaction with Post revisions endpoint WP REST API
/// </summary>
public class PostRevisions : IReadOperation<PostRevision>, IDeleteOperation
{
private HttpHelper _httpHelper;
private string _defaultPath;
private const string _methodPath = "revisions";
private int _postId;
/// <summary>
/// Constructor
/// </summary>
/// <param name="httpHelper">reference to HttpHelper class for interaction with HTTP</param>
/// <param name="defaultPath">path to site, EX. http://demo.com/wp-json/ </param>
/// <param name="postId">ID of post</param>
public PostRevisions(ref HttpHelper httpHelper, string defaultPath,int postId)
{
_httpHelper = httpHelper;
_defaultPath = defaultPath;
_postId = postId;
}
/// <summary>
/// Delete Entity
/// </summary>
/// <param name="ID">Entity Id</param>
/// <returns>Result of operation</returns>
public Task<bool> Delete(int ID)
{
return _httpHelper.DeleteRequest($"{_defaultPath}posts/{_postId}/{_methodPath}/{ID}?force=true");
}
/// <summary>
/// Get latest
/// </summary>
/// <param name="embed">include embed info</param>
/// <param name="useAuth">Send request with authentication header</param>
/// <returns>Latest PostRevisions</returns>
public Task<IEnumerable<PostRevision>> Get(bool embed = false, bool useAuth = true)
{
return _httpHelper.GetRequest<IEnumerable<PostRevision>>($"{_defaultPath}posts/{_postId}/{_methodPath}", embed, useAuth);
}
/// <summary>
/// Get All
/// </summary>
/// <param name="embed">Include embed info</param>
/// <param name="useAuth">Send request with authentication header</param>
/// <returns>List of all result</returns>
public Task<IEnumerable<PostRevision>> GetAll(bool embed = false, bool useAuth = true)
{
return _httpHelper.GetRequest<IEnumerable<PostRevision>>($"{_defaultPath}posts/{_postId}/{_methodPath}", embed, useAuth);
}
/// <summary>
/// Get Entity by Id
/// </summary>
/// <param name="ID">ID</param>
/// <param name="embed">include embed info</param>
/// <param name="useAuth">Send request with authentication header</param>
/// <returns>Entity by Id</returns>
public Task<PostRevision> GetByID(object ID, bool embed = false, bool useAuth = true)
{
return _httpHelper.GetRequest<PostRevision>($"{_defaultPath}posts/{_postId}/{_methodPath}/{ID}", embed, useAuth);
}
}
}
| 39.171053 | 133 | 0.61001 | [
"MIT"
] | BlueByteSystemsInc/WordPressPCL | WordPressPCL/Client/PostRevisions.cs | 2,979 | C# |
using Evergine.Framework;
using Evergine.Framework.Services;
using Evergine.Framework.Threading;
using Evergine.Platform;
namespace HeightMap
{
public partial class MyApplication : Application
{
public MyApplication()
{
this.Container.RegisterType<Clock>();
this.Container.RegisterType<TimerFactory>();
this.Container.RegisterType<Random>();
this.Container.RegisterType<ErrorHandler>();
this.Container.RegisterType<ScreenContextManager>();
this.Container.RegisterType<GraphicsPresenter>();
this.Container.RegisterType<AssetsDirectory>();
this.Container.RegisterType<AssetsService>();
this.Container.RegisterType<ForegroundTaskSchedulerService>();
this.Container.RegisterType<WorkActionScheduler>();
}
public override void Initialize()
{
base.Initialize();
// Get ScreenContextManager
var screenContextManager = this.Container.Resolve<ScreenContextManager>();
var assetsService = this.Container.Resolve<AssetsService>();
// Navigate to scene
var scene = assetsService.Load<MyScene>(EvergineContent.Scenes.HeightMapScene_wescene);
ScreenContext screenContext = new ScreenContext(scene);
screenContextManager.To(screenContext);
}
}
}
| 36.179487 | 99 | 0.659816 | [
"MIT"
] | Jorgemagic/ShaderEffectsCollection | HeightMap/HeightMap/MyApplication.cs | 1,411 | 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.Collections.Generic.IComparer_1.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.Collections.Generic
{
public partial interface IComparer<T>
{
#region Methods and constructors
int Compare(T x, T y);
#endregion
}
}
| 44.875 | 463 | 0.773445 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/MsCorlib/Sources/System.Collections.Generic.IComparer_1.cs | 2,154 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.Content;
using AndroidX.AppCompat.App;
using MvvmMobile.Core.Navigation;
using MvvmMobile.Core.ViewModel;
using MvvmMobile.Droid.Navigation;
using MvvmMobile.Sample.Core.Navigation;
namespace MvvmMobile.Sample.Droid.Navigation
{
public class CustomNavigation : ICustomNavigation
{
private AppNavigation _appNavigation;
public CustomNavigation(INavigation anAppNavigation)
{
_appNavigation = anAppNavigation as AppNavigation;
}
public Context GetContext()
{
return _appNavigation.GetContext();
}
public Dictionary<Type, Type> GetViewMapper()
{
return _appNavigation.GetViewMapper();
}
public void NavigateBack(Action done = null, BackBehaviour behaviour = BackBehaviour.CloseLastSubView, bool animated = true)
{
_appNavigation.NavigateBack(done, behaviour, animated);
}
public void NavigateBack(Action<Guid> callbackAction, Guid payloadId, Action done = null, BackBehaviour behaviour = BackBehaviour.CloseLastSubView, bool animated = true)
{
_appNavigation.NavigateBack(callbackAction, payloadId, done, behaviour, animated);
}
public Task NavigateBack<T>() where T : IBaseViewModel
{
return _appNavigation.NavigateBack<T>();
}
public Task NavigateBack<T>(Action<Guid> callbackAction, Guid payloadId) where T : IBaseViewModel
{
return _appNavigation.NavigateBack<T>(callbackAction, payloadId);
}
public void NavigateTo(Type viewModelType, IPayload parameter = null, Action<Guid> callback = null, bool clearHistory = false, bool animated = true)
{
_appNavigation.NavigateTo(viewModelType, parameter, callback, animated);
}
public void NavigateTo<T>(IPayload parameter = null, Action<Guid> callback = null, bool clearHistory = false, bool animated = true) where T : IBaseViewModel
{
_appNavigation.NavigateTo<T>(parameter, callback, clearHistory, animated);
}
public void NavigateToSubView(Type viewModelType, IPayload parameter = null, Action<Guid> callback = null, bool clearHistory = false)
{
_appNavigation.NavigateToSubView(viewModelType, parameter, callback, clearHistory);
}
public void NavigateToSubView<T>(IPayload parameter = null, Action<Guid> callback = null, bool clearHistory = false) where T : IBaseViewModel
{
_appNavigation.NavigateToSubView<T>(parameter, callback, clearHistory);
}
public async Task NavigateToRoot()
{
await Task.Delay(1);
if (GetContext() is AppCompatActivity activity)
{
var intent = new Intent(GetContext(), typeof(Activities.Start.StartActivity));
intent.AddFlags(ActivityFlags.ClearTop);
GetContext().StartActivity(intent);
}
else
{
System.Diagnostics.Debug.WriteLine("AppNavigation.NavigateBack<T>: Context is null or not an AppCompatActivity!");
}
}
public async Task NavigateBack(Type viewModelInterfaceType)
{
await _appNavigation?.NavigateBack(viewModelInterfaceType);
}
public async Task NavigateBack(Type viewModelInterfaceType, Action<Guid> callbackAction, Guid payloadId)
{
await _appNavigation?.NavigateBack(viewModelInterfaceType, callbackAction, payloadId);
}
}
} | 37.55 | 178 | 0.647403 | [
"MIT"
] | Manne990/MvvmMobile | Samples/MvvmMobile.Sample.Droid/Navigation/CustomNavigation.cs | 3,757 | C# |
using System;
namespace WFBooooot.IOT.Service.Warframe.NightWave
{
public class ActiveChallengesItem
{
/// <summary>
///
/// </summary>
public string id { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime activation { get; set; }
/// <summary>
/// 持续时间
/// </summary>
public string startString { get; set; }
/// <summary>
/// 结束时间
/// </summary>
public DateTime? expiry { get; set; }
/// <summary>
/// 是否激活
/// </summary>
public bool active { get; set; }
/// <summary>
/// 是否每日
/// </summary>
public bool isDaily { get; set; }
/// <summary>
/// 是否精英任务
/// </summary>
public bool isElite { get; set; }
/// <summary>
/// 描述
/// </summary>
public string desc { get; set; }
/// <summary>
/// 标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 声望奖励
/// </summary>
public int reputation { get; set; }
}
} | 24.3125 | 50 | 0.431877 | [
"Apache-2.0"
] | maxzhang666/WFBOOOOOT | WFBooooot.IOT/Service/Warframe/NightWave/ActiveChallengesItem.cs | 1,235 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Enemy_Health_Script : MonoBehaviour
{
public float health;
public float maxHealth;
public GameObject healthBarUI;
public Slider slider;
// Start is called before the first frame update
void Start()
{
health = maxHealth;
slider.value = CalculateHealth();
}
// Update is called once per frame
void Update()
{
slider.value = CalculateHealth();
if(health < maxHealth)
{
healthBarUI.SetActive(true);
}
if(health <= 0)
{
Destroy(gameObject);
}
if(health > maxHealth)
{
health = maxHealth;
}
}
float CalculateHealth()
{
return health / maxHealth;
}
}
| 18.229167 | 52 | 0.571429 | [
"MIT"
] | CapstoneBloomfieldWarofWorlds/WarGame2 | Assets/Jose_Assets/Jose_Scripts/Enemy_Health_Script.cs | 877 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NMF.Serialization
{
public class UnknownElementEventArgs : EventArgs
{
public UnknownElementEventArgs(object context, string propertyXml)
{
if (context == null) throw new ArgumentNullException("context");
if (propertyXml == null) throw new ArgumentNullException("propertyXml");
Context = context;
PropertyXml = propertyXml;
}
public object Context { get; }
public string PropertyXml { get; }
}
}
| 25.083333 | 84 | 0.642857 | [
"BSD-3-Clause"
] | NMFCode/NMF | Models/Serialization/UnknownElementEventArgs.cs | 604 | 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 medialive-2017-10-14.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.MediaLive.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.MediaLive.Model.Internal.MarshallTransformations
{
/// <summary>
/// WavSettings Marshaller
/// </summary>
public class WavSettingsMarshaller : IRequestMarshaller<WavSettings, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(WavSettings requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetBitDepth())
{
context.Writer.WritePropertyName("bitDepth");
context.Writer.Write(requestObject.BitDepth);
}
if(requestObject.IsSetCodingMode())
{
context.Writer.WritePropertyName("codingMode");
context.Writer.Write(requestObject.CodingMode);
}
if(requestObject.IsSetSampleRate())
{
context.Writer.WritePropertyName("sampleRate");
context.Writer.Write(requestObject.SampleRate);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static WavSettingsMarshaller Instance = new WavSettingsMarshaller();
}
} | 33.756757 | 108 | 0.638511 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/WavSettingsMarshaller.cs | 2,498 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PIM
{
public partial class RelatorioDeVendas : Form
{
public RelatorioDeVendas()
{
InitializeComponent();
}
private void btnSair_Click(object sender, EventArgs e)
{
MenuPrincipal menu = new MenuPrincipal();
menu.Show();
this.Close();
}
}
}
| 20.535714 | 62 | 0.634783 | [
"Apache-2.0"
] | Wesleydlr/Teste | PIMPublish/PIM/RelatorioDeVendas.cs | 577 | C# |
// <auto-generated>
// ReSharper disable ConvertPropertyToExpressionBody
// ReSharper disable DoNotCallOverridableMethodsInConstructor
// ReSharper disable EmptyNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable PartialMethodWithSinglePart
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable RedundantOverridenMember
// ReSharper disable UseNameofExpression
// TargetFrameworkVersion = 4.6
#pragma warning disable 1591 // Ignore "Missing XML Comment" warning
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
// BusinessEntityAddress
///<summary>
/// Cross-reference table mapping customers, vendors, and employees to their addresses.
///</summary>
[Table("BusinessEntityAddress", Schema = "Person")]
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.37.2.0")]
public class Person_BusinessEntityAddress
{
///<summary>
/// Primary key. Foreign key to BusinessEntity.BusinessEntityID.
///</summary>
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Column(@"BusinessEntityID", Order = 1, TypeName = "int")]
[Index(@"PK_BusinessEntityAddress_BusinessEntityID_AddressID_AddressTypeID", 1, IsUnique = true, IsClustered = true)]
[Required]
[Key]
[Display(Name = "Business entity ID")]
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// Primary key. Foreign key to Address.AddressID.
///</summary>
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Column(@"AddressID", Order = 2, TypeName = "int")]
[Index(@"IX_BusinessEntityAddress_AddressID", 1, IsUnique = false, IsClustered = false)]
[Index(@"PK_BusinessEntityAddress_BusinessEntityID_AddressID_AddressTypeID", 2, IsUnique = true, IsClustered = true)]
[Required]
[Key]
[Display(Name = "Address ID")]
public int AddressId { get; set; } // AddressID (Primary key)
///<summary>
/// Primary key. Foreign key to AddressType.AddressTypeID.
///</summary>
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Column(@"AddressTypeID", Order = 3, TypeName = "int")]
[Index(@"IX_BusinessEntityAddress_AddressTypeID", 1, IsUnique = false, IsClustered = false)]
[Index(@"PK_BusinessEntityAddress_BusinessEntityID_AddressID_AddressTypeID", 3, IsUnique = true, IsClustered = true)]
[Required]
[Key]
[Display(Name = "Address type ID")]
public int AddressTypeId { get; set; } // AddressTypeID (Primary key)
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
[Column(@"rowguid", Order = 4, TypeName = "uniqueidentifier")]
[Index(@"AK_BusinessEntityAddress_rowguid", 1, IsUnique = true, IsClustered = false)]
[Required]
[Display(Name = "Rowguid")]
public System.Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
[Column(@"ModifiedDate", Order = 5, TypeName = "datetime")]
[Required]
[DataType(DataType.DateTime)]
[Display(Name = "Modified date")]
public System.DateTime ModifiedDate { get; set; } // ModifiedDate
// Foreign keys
/// <summary>
/// Parent Person_Address pointed by [BusinessEntityAddress].([AddressId]) (FK_BusinessEntityAddress_Address_AddressID)
/// </summary>
[ForeignKey("AddressId"), Required] public virtual Person_Address Person_Address { get; set; } // FK_BusinessEntityAddress_Address_AddressID
/// <summary>
/// Parent Person_AddressType pointed by [BusinessEntityAddress].([AddressTypeId]) (FK_BusinessEntityAddress_AddressType_AddressTypeID)
/// </summary>
[ForeignKey("AddressTypeId"), Required] public virtual Person_AddressType Person_AddressType { get; set; } // FK_BusinessEntityAddress_AddressType_AddressTypeID
/// <summary>
/// Parent Person_BusinessEntity pointed by [BusinessEntityAddress].([BusinessEntityId]) (FK_BusinessEntityAddress_BusinessEntity_BusinessEntityID)
/// </summary>
[ForeignKey("BusinessEntityId"), Required] public virtual Person_BusinessEntity Person_BusinessEntity { get; set; } // FK_BusinessEntityAddress_BusinessEntity_BusinessEntityID
public Person_BusinessEntityAddress()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
}
}
}
// </auto-generated>
| 44.063063 | 183 | 0.682069 | [
"MIT"
] | enriqueescobar-askida/Kinito.AdventureWorks2017 | Entities/Person_BusinessEntityAddress.cs | 4,891 | C# |
// Copyright 2021 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.Analytics.Admin.V1Alpha.Snippets
{
using Google.Analytics.Admin.V1Alpha;
using System.Threading.Tasks;
public sealed partial class GeneratedAnalyticsAdminServiceClientStandaloneSnippets
{
/// <summary>Snippet for GetDataSharingSettingsAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetDataSharingSettingsResourceNamesAsync()
{
// Create client
AnalyticsAdminServiceClient analyticsAdminServiceClient = await AnalyticsAdminServiceClient.CreateAsync();
// Initialize request argument(s)
DataSharingSettingsName name = DataSharingSettingsName.FromAccount("[ACCOUNT]");
// Make the request
DataSharingSettings response = await analyticsAdminServiceClient.GetDataSharingSettingsAsync(name);
}
}
}
| 41.2 | 118 | 0.717233 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/analytics/admin/v1alpha/google-analytics-admin-v1alpha-csharp/Google.Analytics.Admin.V1Alpha.StandaloneSnippets/AnalyticsAdminServiceClient.GetDataSharingSettingsResourceNamesAsyncSnippet.g.cs | 1,648 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Azure.Tests;
using Fluent.Tests.Common;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using Xunit;
namespace Fluent.Tests.PrivateDns
{
public class PrivateDnsZone
{
[Fact]
public void CanCreateWithDefaultETag()
{
using (var context = FluentMockContext.Start(GetType().FullName))
{
var region = Region.AsiaSouthEast;
var groupName = TestUtilities.GenerateName("prdnsgp-");
var topLevelDomain = $"{TestUtilities.GenerateName("www.contoso-")}.com";
var azure = TestHelper.CreateRollupClient();
var privateDnsZoneManager = TestHelper.CreatePrivateDnsZoneManager();
try
{
var privateDnsZone = azure.PrivateDnsZones.Define(topLevelDomain)
.WithNewResourceGroup(groupName, region)
.WithETagCheck()
.Create();
Assert.NotNull(privateDnsZone.ETag);
var target = privateDnsZoneManager.PrivateDnsZones.GetById(privateDnsZone.Id);
Assert.NotNull(target);
var found = false;
var privateDnsZoneList = privateDnsZoneManager.PrivateDnsZones.List();
foreach(var zone in privateDnsZoneList)
{
if(string.Equals(zone.Name, topLevelDomain, StringComparison.OrdinalIgnoreCase))
{
found = true;
}
}
Assert.True(found);
}
finally
{
try
{
azure.ResourceGroups.BeginDeleteByName(groupName);
}
catch
{
}
}
}
}
[Fact]
public void CanUpdateWithExplicitETag()
{
using (var context = FluentMockContext.Start(GetType().FullName))
{
var region = Region.AsiaSouthEast;
var groupName = TestUtilities.GenerateName("prdnsgp-");
var topLevelDomain = $"{TestUtilities.GenerateName("www.contoso-")}.com";
var azure = TestHelper.CreateRollupClient();
try
{
var resourceGroup = azure.ResourceGroups.Define(groupName)
.WithRegion(region)
.Create();
var privateDnsZone = azure.PrivateDnsZones.Define(topLevelDomain)
.WithExistingResourceGroup(resourceGroup)
.WithETagCheck()
.Create();
Assert.NotNull(privateDnsZone.ETag);
EnsureETagExceptionIsThrown(() =>
{
//The request of update should fail because ETag mismatch
privateDnsZone.Update()
.WithEtagCheck(privateDnsZone.ETag + "-foo")
.Apply();
});
privateDnsZone.Update()
.WithEtagCheck(privateDnsZone.ETag)
.Apply();
}
finally
{
try
{
azure.ResourceGroups.BeginDeleteByName(groupName);
}
catch
{
}
}
}
}
[Fact]
public void CanDeleteWithExplicitETag()
{
using (var context = FluentMockContext.Start(GetType().FullName))
{
var region = Region.AsiaSouthEast;
var groupName = TestUtilities.GenerateName("prdnsgp-");
var topLevelDomain = $"{TestUtilities.GenerateName("www.contoso-")}.com";
var azure = TestHelper.CreateRollupClient();
var privateDnsZoneManager = TestHelper.CreatePrivateDnsZoneManager();
try
{
var privateDnsZone = azure.PrivateDnsZones.Define(topLevelDomain)
.WithNewResourceGroup(groupName, region)
.WithETagCheck()
.Create();
Assert.NotNull(privateDnsZone.ETag);
EnsureETagExceptionIsThrown(() =>
{
//The request of deletion should fail because ETag mismatch
azure.PrivateDnsZones.DeleteById(privateDnsZone.Id, privateDnsZone.ETag + "-foo");
});
azure.PrivateDnsZones.DeleteById(privateDnsZone.Id, privateDnsZone.ETag);
}
finally
{
try
{
azure.ResourceGroups.BeginDeleteByName(groupName);
}
catch
{
}
}
}
}
private void EnsureETagExceptionIsThrown(Action action)
{
var isCloudExceptionThrown = false;
var isCloudErrorSet = false;
var isCodeSet = false;
var isPreconditionFailedCodeSet = false;
try
{
action();
}
catch (CloudException exception)
{
isCloudExceptionThrown = true;
CloudError cloudError = exception.Body;
if (cloudError != null)
{
isCloudErrorSet = true;
isCodeSet = cloudError.Code != null;
if (isCodeSet)
{
isPreconditionFailedCodeSet = cloudError.Code.Contains("PreconditionFailed");
}
}
}
Assert.True(isCloudExceptionThrown, "Expected CloudException is not thrown");
Assert.True(isCloudErrorSet, "Expected CloudError property is not set in CloudException");
Assert.True(isCodeSet, "Expected CloudError.Code property is not set");
Assert.True(isPreconditionFailedCodeSet, "Expected PreconditionFailed code is not set indicating ETag concurrency check failure");
}
}
}
| 37.20765 | 142 | 0.487443 | [
"MIT"
] | Azure/azure-libraries-for-net | Tests/Fluent.Tests/PrivateDns/PrivateDnsZoneTests.cs | 6,811 | C# |
// Wi Advice (https://github.com/raste/WiAdvice)(http://www.wiadvice.com/)
// Copyright (c) 2015 Georgi Kolev.
// Licensed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0).
using System;
using System.Web.Services;
using DataAccess;
using BusinessLayer;
namespace UserInterface
{
public partial class Registration : BasePage
{
private EntitiesUsers userContext = new EntitiesUsers();
private Entities objectContext = null;
private BusinessLog businessLog = null;
private void Page_Init(object sender, EventArgs e)
{
objectContext = CreateEntities();
businessLog = new BusinessLog(CommonCode.CurrentUser.GetCurrentUserId(), Request.UserHostAddress);
}
protected void Page_PreRender(object sender, EventArgs e)
{
tbUsername.Attributes.Add("onblur", string.Format("JSCheckData('{0}','usernameReg','{1}','');", tbUsername.ClientID, lblCUser.ClientID));
tbPassword.Attributes.Add("onblur", string.Format("JSCheckData('{0}','passFormat','{1}','');", tbPassword.ClientID, lblCPassword.ClientID));
tbEmail.Attributes.Add("onblur", string.Format("JSCheckData('{0}','emailFormat','{1}','');", tbEmail.ClientID, lblCEmail.ClientID));
}
protected void Page_Load(object sender, EventArgs e)
{
SetRedirrectOnLogIn();
CheckUser(); // Checks user , if hes logged then it doesnt show the reg panel
ShowInfo();
}
/// <summary>
/// returns true if user is logged in automatically after his registration (happens right after registration only)
/// </summary>
private Boolean IsNewUserCurrentlyRegistered()
{
object newUser = Session["newUserRegistered"];
bool result = false;
if (newUser != null)
{
bool isNewUser = false;
if (bool.TryParse(newUser.ToString(), out isNewUser))
{
if (isNewUser == true)
{
lblReg.Text = GetLocalResourceObject("regSuccessful").ToString();
lblReg.Visible = true;
regPanel.Visible = false;
Session["newUserRegistered"] = null;
result = true;
}
}
}
return result;
}
private void ShowInfo()
{
Title = GetLocalResourceObject("title").ToString();
if (regPanel.Visible)
{
BusinessSiteText businessText = new BusinessSiteText();
SiteNews regAbout = businessText.GetSiteText(objectContext, "registration");
if (regAbout != null && regAbout.visible)
{
lblRegAbout.Text = regAbout.description;
}
else
{
lblRegAbout.Visible = false;
}
lblUsernameRules.Text = string.Format
("{0}<br />{1} {2}-{3} {4}.", GetLocalResourceObject("usernameRules"), GetLocalResourceObject("usernameRules2")
, Configuration.UsersMinUserNameLength, Configuration.UsersMaxUserNameLength, GetLocalResourceObject("characters"));
lblPassRules.Text = string.Format
("{0}<br />{1} {2}-{3} {4}.", GetLocalResourceObject("passwordRules"), GetLocalResourceObject("passwordRules2")
, Configuration.UsersMinPasswordLength, Configuration.UsersMaxPasswordLength, GetLocalResourceObject("characters"));
lblMailRules.Text = GetLocalResourceObject("emailRules").ToString();
lblSecretRules.Text = string.Format("{0}<br />{1}", GetLocalResourceObject("qnaRules")
, GetLocalResourceObject("qnaRules2"));
}
lblCUser.Text = "";
lblCPassword.Text = "";
lblCEmail.Text = "";
SetLocalText();
}
private void SetLocalText()
{
lblRegForm.Text = GetLocalResourceObject("regForm").ToString();
lblUsername.Text = GetLocalResourceObject("username").ToString();
lblPassword.Text = GetLocalResourceObject("password").ToString();
lblRPassword.Text = GetLocalResourceObject("repPassword").ToString();
lblEmail.Text = GetLocalResourceObject("email").ToString();
lblSecQuest.Text = GetLocalResourceObject("secQuestion").ToString();
lblQuestInfo.Text = GetLocalResourceObject("questionInfo").ToString();
lblSecAnswer.Text = GetLocalResourceObject("answer").ToString();
lblCaptchaInfo.Text = GetLocalResourceObject("captchaInfo").ToString();
lblCaptchaInfo2.Text = GetLocalResourceObject("captchaInfo2").ToString();
lblIAgree.Text = GetLocalResourceObject("AgreeTerms").ToString();
lblIAgree2.Text = GetLocalResourceObject("AgreeTerms2").ToString();
hlTerms.Text = GetLocalResourceObject("terms").ToString();
btnSubmit.Text = GetGlobalResourceObject("SiteResources", "Submit").ToString();
tbPassword_PasswordStrength.PrefixText = string.Format("{0} ", GetLocalResourceObject("Strength").ToString());
tbPassword_PasswordStrength.TextStrengthDescriptions = string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}"
, GetLocalResourceObject("PassStrengthLvl1"), GetLocalResourceObject("PassStrengthLvl2"),
GetLocalResourceObject("PassStrengthLvl3"), GetLocalResourceObject("PassStrengthLvl4"),
GetLocalResourceObject("PassStrengthLvl5"), GetLocalResourceObject("PassStrengthLvl6"),
GetLocalResourceObject("PassStrengthLvl7"), GetLocalResourceObject("PassStrengthLvl8"),
GetLocalResourceObject("PassStrengthLvl9"), GetLocalResourceObject("PassStrengthLvl10"));
hlTerms.NavigateUrl = GetUrlWithVariant("Rules.aspx");
}
private void CheckUser()
{
long currentUserID = CommonCode.CurrentUser.GetCurrentUserId();
if (currentUserID > 0)
{
if (IsNewUserCurrentlyRegistered() == false)
{
regPanel.Visible = false;
lblReg.Text = GetLocalResourceObject("errLoggedIn").ToString();
lblReg.Visible = true;
}
}
else
{
regPanel.Visible = true;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (CommonCode.CurrentUser.GetCurrentUserId() > 0)
{
throw new CommonCode.UIException(string.Format("User ID = {0} tried to register new user"));
}
lblError.Visible = true;
BusinessIpBans businessIpBans = new BusinessIpBans();
if (businessIpBans.IsThereActiveBanForIpAdress(userContext, Request.UserHostAddress))
{
lblError.Text = GetLocalResourceObject("errIpBan").ToString();
return;
}
if (businessIpBans.CounRegisteredUsersFromIpAdress(userContext, Request.UserHostAddress)
> Configuration.RegisterMaxNumberRegistrationsFromIp)
{
lblError.Text = GetLocalResourceObject("errRegsReached").ToString();
return;
}
string error = "";
ccReg.ValidateCaptcha(tbCaptcha.Text);
tbCaptcha.Text = "";
if (ccReg.UserValidated == false)
{
lblError.Text = GetGlobalResourceObject("SiteResources", "errorIncLetters").ToString();
return;
}
if (cbAgreeTerms.Checked == false)
{
lblError.Text = GetLocalResourceObject("errTerms").ToString();
return;
}
string username = tbUsername.Text;
if (CommonCode.Validate.ValidateUserName(objectContext, ref username, out error))
{
if (CommonCode.Validate.ValidatePassword(tbPassword.Text, out error))
{
if (CommonCode.Validate.ValidateRepeatPassword(tbUsername.Text, tbPassword.Text, tbRPassword.Text, out error))
{
if (CommonCode.Validate.ValidateSecretQnA(1, 100, tbSecQuestion.Text))
{
if (CommonCode.Validate.ValidateSecretQnA(1, 100, tbSecAnswer.Text))
{
if (tbEmail.Text.Length > 0)
{
if (CommonCode.Validate.ValidateEmailAdress(tbEmail.Text, out error))
{
int maxNumUsersPerMail = Configuration.MaximumNumberOfUsersRegisteredWithMail;
BusinessUser businessUser = new BusinessUser();
if (businessUser.CountRegisteredUsersWithMail(userContext, tbEmail.Text) < maxNumUsersPerMail)
{
lblError.Visible = false;
RegisterUser( username, tbPassword.Text, tbEmail.Text, tbSecQuestion.Text, tbSecAnswer.Text);
}
else
{
error = string.Format("{0} {1} {2}", GetLocalResourceObject("errEmailRegsReached")
, maxNumUsersPerMail, GetLocalResourceObject("errEmailRegsReached2"));
}
}
}
else
{
lblError.Visible = false;
RegisterUser(tbUsername.Text, tbPassword.Text, tbEmail.Text, tbSecQuestion.Text, tbSecAnswer.Text);
}
}
else
{
error = GetLocalResourceObject("errIncAnswer").ToString();
}
}
else
{
error = GetLocalResourceObject("errIncQuest").ToString();
}
}
}
}
lblError.Text = error;
}
private void RegisterUser(String name, String password, String email, String secQuest, String secAnsw)
{
BusinessUser businessUser = new BusinessUser();
businessUser.RegisterUser(userContext, objectContext, name, password, email, businessLog, secQuest, secAnsw, false, null);
if (Configuration.SendActivationCodeOnRegistering == false)
{
LogInAfterRegistering(businessUser);
}
else
{
User newUser = businessUser.GetUserByNameAndPassword(userContext, tbUsername.Text, tbPassword.Text);
if (newUser == null)
{
throw new CommonCode.UIException(string.Format("Couldn`t gen user automatically after registering, username = {0}", tbUsername.Text));
}
if (!newUser.UserOptionsReference.IsLoaded)
{
newUser.UserOptionsReference.Load();
}
if (newUser.UserOptions.activated == false)
{
regPanel.Visible = false;
lblReg.Visible = true;
lblReg.Text = string.Format("{0}<br />{1}<br />{2}<br />", GetLocalResourceObject("accRegistered")
, GetLocalResourceObject("accRegistered2"), GetLocalResourceObject("accRegistered3"));
}
else
{
LogInAfterRegistering(businessUser);
}
}
}
private void LogInAfterRegistering(BusinessUser businessUser)
{
//////////////////////////////// automatic log in after registration///////////////////
long userID = businessUser.Login(objectContext, userContext, tbUsername.Text, tbPassword.Text);
if (userID > 0)
{
Session[CommonCode.CurrentUser.CurrentUserIdKey] = userID;
User currUser = businessUser.Get(userContext, userID, true);
businessUser.RemoveGuest(userID);
businessUser.AddLoggedUser(userContext, objectContext, currUser, businessLog);
BusinessStatistics businessStatistics = new BusinessStatistics();
businessStatistics.UserLogged(userContext);
Session.Add("newUserRegistered", true);
RedirectToSameUrl(Request.Url.ToString());
}
else
{
throw new CommonCode.UIException(string.Format("Couldn`t log in automatically after registering, username = {0}", tbUsername.Text));
}
}
[WebMethod]
public static string CheckData(string text, string type, string notUsed)
{
string error = "";
CommonCode.WebMethods.ValidateUserInput(text, type, "", out error);
return error;
}
}
}
| 42.498471 | 154 | 0.53472 | [
"Apache-2.0"
] | raste/WiAdvice | Source/User Interface/Registration.aspx.cs | 13,903 | C# |
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V23.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V23.Segment{
///<summary>
/// Represents an HL7 RDT message segment.
/// This segment has the following fields:<ol>
///<li>RDT-1: Column value (varies)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class RDT : AbstractSegment {
/**
* Creates a RDT (Table Row Data) segment object that belongs to the given
* message.
*/
public RDT(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(Varies), true, 1, 0, new System.Object[]{message}, "Column value");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns Column value(RDT-1).
///</summary>
public Varies ColumnValue
{
get{
Varies ret = null;
try
{
IType t = this.GetField(1, 0);
ret = (Varies)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
}} | 31 | 111 | 0.684823 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V23/Segment/RDT.cs | 1,891 | C# |
using System;
using UnityEngine;
public enum PickupType
{
SniperRifle = 0,
RedDot = 1,
Shield = 2,
Binoculars = 3,
Banana = 4,
SMG = 5,
Pistol = 6,
Grenade = 7,
SmokeGrenade = 8,
CSGrenade = 9,
LaserSensor = 10,
RemoteCharge = 11,
CardboardDecoy = 12,
SMGAmmox30 = 13,
PistolAmmox15 = 14,
SniperAmmox5 = 15,
Shotgun = 16,
ShotgunAmmox6 = 17
}
public class PickupProxy : MonoBehaviour
{
public PickupType pickupType;
public int addedAmmo = -1; //Ammo added to the weapons ammo stash
public int loadedAmmo = -1; //Ammo loaded in the weapon if you pick it up, use only if you want to replace the current magazine in the weapon
public string pickupMessage = ""; //Custom message for the pick up if you change things about it, like the ammo amount, to avoid default messages
public float respawnTime = -1; //Pick up will respawn after this amount of time
public Activator activatorToActivate; //Activate an activator when you pick up this pick up
} | 26.27027 | 146 | 0.729424 | [
"MIT"
] | DancingEngie/IntruderMafia | Assets/IntruderMM/Scripts/PickupProxy.cs | 972 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.