content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
namespace Caculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.Write("Enter a number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num1 + num2);
Console.ReadLine();
}
}
}
| 20.73913 | 59 | 0.536688 | [
"MIT"
] | lacie-life/ProgrammingLanguageCollection | C#/Caculator/Caculator/Program.cs | 479 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Businessunitadoxiospecialeventlocation operations.
/// </summary>
public partial interface IBusinessunitadoxiospecialeventlocation
{
/// <summary>
/// Get business_unit_adoxio_specialeventlocation from businessunits
/// </summary>
/// <param name='businessunitid'>
/// key: businessunitid of businessunit
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioSpecialeventlocationCollection>> GetWithHttpMessagesAsync(string businessunitid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get business_unit_adoxio_specialeventlocation from businessunits
/// </summary>
/// <param name='businessunitid'>
/// key: businessunitid of businessunit
/// </param>
/// <param name='adoxioSpecialeventlocationid'>
/// key: adoxio_specialeventlocationid of adoxio_specialeventlocation
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioSpecialeventlocation>> SpecialeventlocationByKeyWithHttpMessagesAsync(string businessunitid, string adoxioSpecialeventlocationid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 45.978947 | 555 | 0.615842 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/IBusinessunitadoxiospecialeventlocation.cs | 4,368 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 26.07.2021.
//
// <field>.AddMilliseconds(...)
//
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.DataTypes.Extensions;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.DateTime.SET001.EXT.AddMilliseconds{
////////////////////////////////////////////////////////////////////////////////
//using
using T_DATA =System.DateTime;
using T_DATA_U=System.DateTime;
using T_AMOUNT=System.Nullable<System.Double>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields__03__N2
public static class TestSet_001__fields__03__N2
{
private const string c_NameOf__TABLE="TEST_MODIFY_ROW";
private const string c_NameOf__COL_DATA="COL_TIMESTAMP";
private const string c_NameOf__COL_AMOUNT="COL_DOUBLE";
//-----------------------------------------------------------------------
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA)]
public T_DATA DATA { get; set; }
[Column(c_NameOf__COL_AMOUNT)]
public T_AMOUNT AMOUNT { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_01()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA c_data=new T_DATA_U(2021,7,26,14,27,53).AddTicks(1000+1);
System.Int64? testID=Helper__InsertRow(db,c_data,null);
//var c_ticks2
// =new T_DATA_U(2021,7,27,14,27,53).AddTicks(1000).Ticks;
const long c_ticks
=637629928730001000+2;
var recs=db.testTable.Where(r => r.DATA.AddMilliseconds((T_AMOUNT)r.AMOUNT)==new T_DATA_U(c_ticks) && r.TEST_ID==testID);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_AMOUNT).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (DATEADD(MILLISECOND,").N("t",c_NameOf__COL_AMOUNT).T(",").N("t",c_NameOf__COL_DATA).T(") = timestamp '2021-07-27 14:27:53.0001') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_01
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA valueOfData,
T_AMOUNT valueOfAmount)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.DATA=valueOfData;
newRecord.AMOUNT=valueOfAmount;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_AMOUNT).T(", ").N(c_NameOf__COL_DATA).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields__03__N2
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.DateTime.SET001.EXT.AddMilliseconds
| 31.871429 | 209 | 0.571044 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Funcs/DateTime/SET001/EXT/AddMilliseconds/TestSet_001__fields__03__N2.cs | 4,464 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Amazon.EC2.Util;
using Amazon.EC2;
namespace Amazon.DNXCore.IntegrationTests.EC2
{
public class ImageUtilitiesTest : TestBase<AmazonEC2Client>
{
static string[] imgs = { "WINDOWS_2012R2_BASE", "WINDOWS_2012R2_SQL_SERVER_EXPRESS_2014", "WINDOWS_2012R2_SQL_SERVER_STANDARD_2014", "WINDOWS_2012R2_SQL_SERVER_WEB_2014", "WINDOWS_2012_BASE","WINDOWS_2012_SQL_SERVER_EXPRESS_2014","WINDOWS_2012_SQL_SERVER_STANDARD_2014","WINDOWS_2012_SQL_SERVER_WEB_2014" };
[Trait(CategoryAttribute, "EC2")]
[Fact]
public async Task ImageTest()
{
foreach (string img in imgs)
{
var image = await ImageUtilities.FindImageAsync(Client, img).ConfigureAwait(false);
Assert.NotNull(image);
}
}
}
}
| 34.444444 | 315 | 0.693548 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/test/CoreCLR/IntegrationTests/IntegrationTests/EC2/ImageUtilitiesTest.cs | 932 | C# |
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.Serialization;
using UnityEngine.UI;
/// <summary>
/// Takes care of all things dialogue, whether they are coming from within a Timeline or just from the interaction with a character, or by any other mean.
/// Keeps track of choices in the dialogue (if any) and then gives back control to gameplay when appropriate.
/// </summary>
public class DialogueManager : MonoBehaviour
{
// [SerializeField] private ChoiceBox _choiceBox; // TODO: Demonstration purpose only. Remove or adjust later.
[SerializeField] private InputReader _inputReader = default;
private int _counter;
private bool _reachedEndOfDialogue { get => _counter >= _currentDialogue.DialogueLines.Count; }
[Header("Listening on channels")]
[SerializeField] private DialogueDataChannelSO _startDialogue = default;
[SerializeField] private DialogueChoiceChannelSO _makeDialogueChoiceEvent = default;
[Header("BoradCasting on channels")]
[SerializeField] private DialogueLineChannelSO _openUIDialogueEvent = default;
[SerializeField] private DialogueChoicesChannelSO _showChoicesUIEvent = default;
[SerializeField] private DialogueDataChannelSO _endDialogue = default;
[SerializeField] private VoidEventChannelSO _continueWithStep = default;
[SerializeField] private VoidEventChannelSO _closeDialogueUIEvent = default;
private DialogueDataSO _currentDialogue = default;
private void Start()
{
_startDialogue.OnEventRaised += DisplayDialogueData;
}
/// <summary>
/// Displays DialogueData in the UI, one by one.
/// </summary>
/// <param name="dialogueDataSO"></param>
public void DisplayDialogueData(DialogueDataSO dialogueDataSO)
{
BeginDialogueData(dialogueDataSO);
DisplayDialogueLine(_currentDialogue.DialogueLines[_counter], dialogueDataSO.Actor);
}
/// <summary>
/// Prepare DialogueManager when first time displaying DialogueData.
/// <param name="dialogueDataSO"></param>
private void BeginDialogueData(DialogueDataSO dialogueDataSO)
{
_counter = 0;
_inputReader.EnableDialogueInput();
_inputReader.advanceDialogueEvent += OnAdvance;
_currentDialogue = dialogueDataSO;
}
/// <summary>
/// Displays a line of dialogue in the UI, by requesting it to the <c>DialogueManager</c>.
/// This function is also called by <c>DialogueBehaviour</c> from clips on Timeline during cutscenes.
/// </summary>
/// <param name="dialogueLine"></param>
public void DisplayDialogueLine(LocalizedString dialogueLine, ActorSO actor)
{
_openUIDialogueEvent.RaiseEvent(dialogueLine, actor);
}
private void OnAdvance()
{
_counter++;
if (!_reachedEndOfDialogue)
{
DisplayDialogueLine(_currentDialogue.DialogueLines[_counter], _currentDialogue.Actor);
}
else
{
if (_currentDialogue.Choices.Count > 0)
{
DisplayChoices(_currentDialogue.Choices);
}
else
{
DialogueEndedAndCloseDialogueUI();
}
}
}
private void DisplayChoices(List<Choice> choices)
{
_inputReader.advanceDialogueEvent -= OnAdvance;
_makeDialogueChoiceEvent.OnEventRaised += MakeDialogueChoice;
_showChoicesUIEvent.RaiseEvent(choices);
}
private void MakeDialogueChoice(Choice choice)
{
_makeDialogueChoiceEvent.OnEventRaised -= MakeDialogueChoice;
if (choice.ActionType == ChoiceActionType.continueWithStep)
{
if (_continueWithStep != null)
_continueWithStep.RaiseEvent();
if (choice.NextDialogue != null)
DisplayDialogueData(choice.NextDialogue);
}
else
{
if (choice.NextDialogue != null)
DisplayDialogueData(choice.NextDialogue);
else
DialogueEndedAndCloseDialogueUI();
}
}
void DialogueEnded()
{
if (_endDialogue != null)
_endDialogue.RaiseEvent(_currentDialogue);
}
public void DialogueEndedAndCloseDialogueUI()
{
if (_endDialogue != null)
_endDialogue.RaiseEvent(_currentDialogue);
if (_closeDialogueUIEvent != null)
_closeDialogueUIEvent.RaiseEvent();
_inputReader.advanceDialogueEvent -= OnAdvance;
_inputReader.EnableGameplayInput();
}
}
| 27.61745 | 154 | 0.75966 | [
"Apache-2.0"
] | BrauCamaH/open-project-1 | UOP1_Project/Assets/Scripts/Dialogues/DialogueManager.cs | 4,117 | C# |
/*
* Copyright 2020 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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.
*/
using System;
using System.Collections.Generic;
namespace TCGGameService
{
public partial class User
{
UserMessageDispatcher tcpDispatcher = null;
InternalMessageDispatcher internalDispatcher = null;
public Int64 UID => tblUser?.uuid ?? 0;
public string lineUID => tblUser?.lineuserid ?? "";
public string nickName => tblUser?.nickname ?? "";
public Table.TblUser tblUser { get; set; }
string displayName { get; set; }
string pictureUrl { get; set; }
string statusMessage { get; set; }
private DateTime keep_Alive = DateTime.Now;
private DateTime check_Time = DateTime.Now;
public Int32 checkTime = Setting.ProgramSetting.Instance.serverHostInfo.keepAliveCheckTime;
public Int32 sendingCycle = Setting.ProgramSetting.Instance.serverHostInfo.sendingCycle;
public UserStateType stateType = UserStateType.None;
public string walletAddr { get; set; } = string.Empty;
string accessToken { get; set; } = string.Empty;
public void CheckTimeNowUpdate()
{
check_Time = DateTime.Now;
}
public void SetAccessToken(string token) => accessToken = token;
public string GetAccessToken()
{
return accessToken;
}
List<LBD.TokenTypeInfo> DefaultCardToTokenTypeInfo()
{
var result = new List<LBD.TokenTypeInfo>();
foreach (var defaultCard in TCGGameSrv.ResourceDataLoader.Data_DefaultDeck_List)
{
var tokenType = LBD.LBDApiManager.Instance.NonFungibleTokenMetaToTokenTypeInfo(defaultCard.heroCard.ToString());
if (null != tokenType)
result.Add(tokenType);
else
logger.Warn($"not found DefaultHeroCard mate data to tokentypeinfo meta={defaultCard.heroCard.ToString()} ");
foreach(var meta in defaultCard.deckCard)
{
tokenType = LBD.LBDApiManager.Instance.NonFungibleTokenMetaToTokenTypeInfo(meta.ToString());
if (null != tokenType)
result.Add(tokenType);
else
logger.Warn($"not found DefaultCard mate data to tokentypeinfo meta={defaultCard.heroCard.ToString()} ");
}
}
return result;
}
public static TcpMsg.CardInfo TokenInfoToCardInfo(LBD.TokenInfo tokenInfo)
{
var cardInfo = new TcpMsg.CardInfo()
{
tokenType = tokenInfo.tokenType,
tokenIndex = tokenInfo.tokenIdx,
meta = Convert.ToInt32(tokenInfo.meta)
};
return cardInfo;
}
List<TcpMsg.CardInfo> NonFungiblesToCardInfo()
{
var cardInfos = new List<TcpMsg.CardInfo>();
nonFungibles.ForEach(x => cardInfos.Add(TokenInfoToCardInfo(x)));
return cardInfos;
}
}
}
| 35.669903 | 129 | 0.621938 | [
"Apache-2.0"
] | line/blockchain-sample-mage-duel | Server/TCGSampleServer/Service/TCGGameService/User/User.Info.cs | 3,676 | C# |
using Microsoft.EntityFrameworkCore;
namespace RestWithASPNET5Udemy.Model.Context
{
public class PostgreSQLContext : DbContext
{
public PostgreSQLContext()
{
}
public PostgreSQLContext(DbContextOptions<PostgreSQLContext> options) : base(options)
{
}
public DbSet<Person> Persons { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<User> Users { get; set; }
}
}
| 20.125 | 93 | 0.600414 | [
"Apache-2.0"
] | ClaudioMauricioOliveira/RestWithASP-NET5Udemy | BONUS_RestWithASPNET5Udemy_Postgres/RestWithASPNET5Udemy/RestWithASPNET5Udemy/Model/Context/PostgreSQLContext.cs | 485 | C# |
namespace TDC_Testing_v1
{
partial class MotorControl
{
/// <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()
{
this.components = new System.ComponentModel.Container();
this.lblCurrentMotorDuty = new System.Windows.Forms.Label();
this.lblCurMotorSpeed = new System.Windows.Forms.Label();
this.chkMotorAutoRequests = new System.Windows.Forms.CheckBox();
this.timerMotorRequests = new System.Windows.Forms.Timer(this.components);
this.btnSetMotorDuty = new System.Windows.Forms.Button();
this.numMotorDuty = new System.Windows.Forms.NumericUpDown();
this.btnSetMotorTargetSpeed = new System.Windows.Forms.Button();
this.numMotorTargetSpeed = new System.Windows.Forms.NumericUpDown();
this.lblMotorTargeSpeed = new System.Windows.Forms.Label();
this.lblMotorManualPWM = new System.Windows.Forms.Label();
this.lblState = new System.Windows.Forms.Label();
this.btnResetMCU = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numMotorDuty)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMotorTargetSpeed)).BeginInit();
this.SuspendLayout();
//
// lblCurrentMotorDuty
//
this.lblCurrentMotorDuty.AutoSize = true;
this.lblCurrentMotorDuty.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblCurrentMotorDuty.Location = new System.Drawing.Point(16, 119);
this.lblCurrentMotorDuty.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCurrentMotorDuty.Name = "lblCurrentMotorDuty";
this.lblCurrentMotorDuty.Size = new System.Drawing.Size(163, 20);
this.lblCurrentMotorDuty.TabIndex = 2;
this.lblCurrentMotorDuty.Text = "Motor PWM Duty: N/A";
//
// lblCurMotorSpeed
//
this.lblCurMotorSpeed.AutoSize = true;
this.lblCurMotorSpeed.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblCurMotorSpeed.Location = new System.Drawing.Point(16, 89);
this.lblCurMotorSpeed.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCurMotorSpeed.Name = "lblCurMotorSpeed";
this.lblCurMotorSpeed.Size = new System.Drawing.Size(135, 20);
this.lblCurMotorSpeed.TabIndex = 3;
this.lblCurMotorSpeed.Text = "Motor Speed: N/A";
//
// chkMotorAutoRequests
//
this.chkMotorAutoRequests.AutoSize = true;
this.chkMotorAutoRequests.Location = new System.Drawing.Point(455, 22);
this.chkMotorAutoRequests.Name = "chkMotorAutoRequests";
this.chkMotorAutoRequests.Size = new System.Drawing.Size(96, 17);
this.chkMotorAutoRequests.TabIndex = 4;
this.chkMotorAutoRequests.Text = "Auto Requests";
this.chkMotorAutoRequests.UseVisualStyleBackColor = true;
this.chkMotorAutoRequests.CheckedChanged += new System.EventHandler(this.chkMotorAutoRequests_CheckedChanged);
//
// timerMotorRequests
//
this.timerMotorRequests.Interval = 200;
this.timerMotorRequests.Tick += new System.EventHandler(this.timerMotorRequests_Tick);
//
// btnSetMotorDuty
//
this.btnSetMotorDuty.Location = new System.Drawing.Point(319, 23);
this.btnSetMotorDuty.Margin = new System.Windows.Forms.Padding(2);
this.btnSetMotorDuty.Name = "btnSetMotorDuty";
this.btnSetMotorDuty.Size = new System.Drawing.Size(44, 24);
this.btnSetMotorDuty.TabIndex = 24;
this.btnSetMotorDuty.Text = "SET";
this.btnSetMotorDuty.UseVisualStyleBackColor = true;
this.btnSetMotorDuty.Click += new System.EventHandler(this.btnSetMotorDuty_Click);
//
// numMotorDuty
//
this.numMotorDuty.Location = new System.Drawing.Point(243, 25);
this.numMotorDuty.Margin = new System.Windows.Forms.Padding(2);
this.numMotorDuty.Maximum = new decimal(new int[] {
65000,
0,
0,
0});
this.numMotorDuty.Name = "numMotorDuty";
this.numMotorDuty.Size = new System.Drawing.Size(71, 20);
this.numMotorDuty.TabIndex = 23;
this.numMotorDuty.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// btnSetMotorTargetSpeed
//
this.btnSetMotorTargetSpeed.Location = new System.Drawing.Point(319, 52);
this.btnSetMotorTargetSpeed.Margin = new System.Windows.Forms.Padding(2);
this.btnSetMotorTargetSpeed.Name = "btnSetMotorTargetSpeed";
this.btnSetMotorTargetSpeed.Size = new System.Drawing.Size(44, 24);
this.btnSetMotorTargetSpeed.TabIndex = 27;
this.btnSetMotorTargetSpeed.Text = "SET";
this.btnSetMotorTargetSpeed.UseVisualStyleBackColor = true;
this.btnSetMotorTargetSpeed.Click += new System.EventHandler(this.btnSetMotorTargetSpeed_Click);
//
// numMotorTargetSpeed
//
this.numMotorTargetSpeed.Location = new System.Drawing.Point(243, 54);
this.numMotorTargetSpeed.Margin = new System.Windows.Forms.Padding(2);
this.numMotorTargetSpeed.Maximum = new decimal(new int[] {
30,
0,
0,
0});
this.numMotorTargetSpeed.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numMotorTargetSpeed.Name = "numMotorTargetSpeed";
this.numMotorTargetSpeed.Size = new System.Drawing.Size(71, 20);
this.numMotorTargetSpeed.TabIndex = 26;
this.numMotorTargetSpeed.Value = new decimal(new int[] {
15,
0,
0,
0});
//
// lblMotorTargeSpeed
//
this.lblMotorTargeSpeed.AutoSize = true;
this.lblMotorTargeSpeed.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblMotorTargeSpeed.Location = new System.Drawing.Point(16, 54);
this.lblMotorTargeSpeed.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblMotorTargeSpeed.Name = "lblMotorTargeSpeed";
this.lblMotorTargeSpeed.Size = new System.Drawing.Size(185, 20);
this.lblMotorTargeSpeed.TabIndex = 25;
this.lblMotorTargeSpeed.Text = "Motor Target Speed: N/A";
//
// lblMotorManualPWM
//
this.lblMotorManualPWM.AutoSize = true;
this.lblMotorManualPWM.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblMotorManualPWM.Location = new System.Drawing.Point(16, 26);
this.lblMotorManualPWM.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblMotorManualPWM.Name = "lblMotorManualPWM";
this.lblMotorManualPWM.Size = new System.Drawing.Size(182, 20);
this.lblMotorManualPWM.TabIndex = 28;
this.lblMotorManualPWM.Text = "Motor Manual PWM: N/A";
//
// lblState
//
this.lblState.AutoSize = true;
this.lblState.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblState.Location = new System.Drawing.Point(16, 148);
this.lblState.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblState.Name = "lblState";
this.lblState.Size = new System.Drawing.Size(82, 20);
this.lblState.TabIndex = 29;
this.lblState.Text = "State: N/A";
//
// btnResetMCU
//
this.btnResetMCU.BackColor = System.Drawing.Color.Yellow;
this.btnResetMCU.Location = new System.Drawing.Point(453, 52);
this.btnResetMCU.Margin = new System.Windows.Forms.Padding(2);
this.btnResetMCU.Name = "btnResetMCU";
this.btnResetMCU.Size = new System.Drawing.Size(98, 24);
this.btnResetMCU.TabIndex = 30;
this.btnResetMCU.Text = "Reset MCU";
this.btnResetMCU.UseVisualStyleBackColor = false;
this.btnResetMCU.Click += new System.EventHandler(this.btnResetMCU_Click);
//
// MotorControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btnResetMCU);
this.Controls.Add(this.lblState);
this.Controls.Add(this.lblMotorManualPWM);
this.Controls.Add(this.btnSetMotorTargetSpeed);
this.Controls.Add(this.numMotorTargetSpeed);
this.Controls.Add(this.lblMotorTargeSpeed);
this.Controls.Add(this.btnSetMotorDuty);
this.Controls.Add(this.numMotorDuty);
this.Controls.Add(this.chkMotorAutoRequests);
this.Controls.Add(this.lblCurMotorSpeed);
this.Controls.Add(this.lblCurrentMotorDuty);
this.Name = "MotorControl";
this.Size = new System.Drawing.Size(572, 322);
((System.ComponentModel.ISupportInitialize)(this.numMotorDuty)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMotorTargetSpeed)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblCurrentMotorDuty;
private System.Windows.Forms.Label lblCurMotorSpeed;
private System.Windows.Forms.CheckBox chkMotorAutoRequests;
private System.Windows.Forms.Timer timerMotorRequests;
private System.Windows.Forms.Button btnSetMotorDuty;
private System.Windows.Forms.NumericUpDown numMotorDuty;
private System.Windows.Forms.Button btnSetMotorTargetSpeed;
private System.Windows.Forms.NumericUpDown numMotorTargetSpeed;
private System.Windows.Forms.Label lblMotorTargeSpeed;
private System.Windows.Forms.Label lblMotorManualPWM;
private System.Windows.Forms.Label lblState;
private System.Windows.Forms.Button btnResetMCU;
}
}
| 50.653846 | 181 | 0.617818 | [
"MIT"
] | ICpachong/OpenTOFLidar | PC_Utility/LidarTestingUtility/MotorControl.Designer.cs | 11,855 | C# |
/*****************************************************************************
* Copyright 2016 Aurora Solutions
*
* http://www.aurorasolutions.io
*
* Aurora Solutions is an innovative services and product company at
* the forefront of the software industry, with processes and practices
* involving Domain Driven Design(DDD), Agile methodologies to build
* scalable, secure, reliable and high performance products.
*
* Trade Mirror provides an infrastructure for low latency trade copying
* services from master to child traders, and also trader to different
* channels including social media. It is a highly customizable solution
* with low-latency signal transmission capabilities. The tool can copy trades
* from sender and publish them to all subscribed receiver’s in real time
* across a local network or the internet. Trade Mirror is built using
* languages and frameworks that include C#, C++, WPF, WCF, Socket Programming,
* MySQL, NUnit and MT4 and MT5 MetaTrader platforms.
*
* 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.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.Text;
using System.Timers;
using TraceSourceLogger;
namespace Microsoft.ServiceModel.Samples
{
public class DataSource : ITradeMirrorCallback
{
private const int PortNumber = 6677;
private static readonly Type OType = typeof (DataSource);
private static byte[] Buffer { get; set; }
private static Socket _socket;
private static InstanceContext _site;
private static TradeMirrorClient _client;
private static Timer _heartbeatTimer;
private const int DelaySeconds = 30;
private const string HeartbeatMessage = "___autofxtools trademirror___Alive___";
/// <summary>
/// DataSource Main function
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
// Create a client
_site = new InstanceContext(null, new DataSource());
_client = new TradeMirrorClient(_site);
_heartbeatTimer = new Timer(DelaySeconds * 1000);
_heartbeatTimer.Elapsed += HeartbeatTimerElapsed;
_heartbeatTimer.AutoReset = true;
_heartbeatTimer.Enabled = true;
while (true)
{
ReadDataFromSocket();
}
}
/// <summary>
/// Processes the data received from AutoFXToolsSender
/// </summary>
private static void ProcessDataReceived(string signalInformation)
{
try
{
Logger.Debug("New Signal received = " + signalInformation, OType.FullName, "ProcessDataReceived");
Console.WriteLine("New Signal received = " + signalInformation);
_client.PublishNewSignal(signalInformation);
}
catch (Exception ex)
{
Logger.Error("Exception = " + ex.Message, OType.FullName, "ProcessDataReceived");
}
}
/// <summary>
/// Reads data from socket sent by AutoFXToolsSender
/// </summary>
public static void ReadDataFromSocket()
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(0, PortNumber));
_socket.Listen(100);
while (true)
{
Socket accpeted = _socket.Accept();
Buffer = new byte[accpeted.SendBufferSize];
int bytesRead = accpeted.Receive(Buffer);
Logger.Info("Number of bytes received form socket = " + bytesRead, OType.FullName,
"ReadDataFromSocket");
var formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}
string strData = Encoding.ASCII.GetString(formatted);
Logger.Info("Data received form socket = " + strData, OType.FullName, "ReadDataFromSocket");
ProcessDataReceived(strData);
accpeted.Close();
}
}
catch (Exception exception)
{
Logger.Error(exception, OType.FullName, "ReadDataFromSocket");
_socket.Close();
}
}
/// <summary>
///
/// </summary>
/// <param name="signalInformation"></param>
public void NewSignal(string signalInformation)
{
Console.WriteLine("Signal Received = " + signalInformation);
//TransformOrderInformation(signalInformation);
//PlaceOrder(signalInformation);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void HeartbeatTimerElapsed(object sender, ElapsedEventArgs e)
{
_client.PublishNewSignal(HeartbeatMessage + DateTime.UtcNow);
}
}
}
| 36.536585 | 115 | 0.574266 | [
"Apache-2.0"
] | trade-nexus/trade-mirror | Auto FX Tools Trade Mirror - Demo/Auto FX Tools Trade Mirror - Demo/datasource/Datasource.cs | 5,996 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Pipedrive.Helpers;
using Pipedrive.Internal;
namespace Pipedrive
{
/// <summary>
/// A connection for making API requests against URI endpoints.
/// Provides type-friendly convenience methods that wrap <see cref="IConnection"/> methods.
/// </summary>
public class ApiConnection : IApiConnection
{
readonly IApiPagination _pagination;
/// <summary>
/// Initializes a new instance of the <see cref="ApiConnection"/> class.
/// </summary>
/// <param name="connection">A connection for making HTTP requests</param>
public ApiConnection(IConnection connection) : this(connection, new ApiPagination())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiConnection"/> class.
/// </summary>
/// <param name="connection">A connection for making HTTP requests</param>
/// <param name="pagination">A paginator for paging API responses</param>
protected ApiConnection(IConnection connection, IApiPagination pagination)
{
Ensure.ArgumentNotNull(connection, nameof(connection));
Ensure.ArgumentNotNull(pagination, nameof(pagination));
Connection = connection;
_pagination = pagination;
}
/// <summary>
/// The underlying connection.
/// </summary>
public IConnection Connection { get; private set; }
/// <summary>
/// Gets the API resource at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource to get.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <returns>The API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<T> Get<T>(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return Get<T>(uri, null);
}
/// <summary>
/// Gets the API resource at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource to get.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <returns>The API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public async Task<T> Get<T>(Uri uri, IDictionary<string, string> parameters)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await Connection.Get<JsonResponse<T>>(uri, parameters, null).ConfigureAwait(false);
return response.Body.Data;
}
/// <summary>
/// Gets the API resource at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource to get.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <param name="accepts">Accept header to use for the API request</param>
/// <returns>The API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public async Task<T> Get<T>(Uri uri, IDictionary<string, string> parameters, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
var response = await Connection.Get<JsonResponse<T>>(uri, parameters, accepts).ConfigureAwait(false);
return response.Body.Data;
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> GetAll<T>(Uri uri)
{
return GetAll<T>(uri, ApiOptions.None);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="options">Options for changing the API response</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> GetAll<T>(Uri uri, ApiOptions options)
{
return GetAll<T>(uri, null, null, options);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> GetAll<T>(Uri uri, IDictionary<string, string> parameters)
{
return GetAll<T>(uri, parameters, null, ApiOptions.None);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="accepts">Accept header to use for the API request</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> GetAll<T>(Uri uri, string accepts)
{
return GetAll<T>(uri, null, accepts, ApiOptions.None);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <param name="options">Options for changing the API response</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> GetAll<T>(Uri uri, IDictionary<string, string> parameters, ApiOptions options)
{
return GetAll<T>(uri, parameters, null, options);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <param name="accepts">Accept header to use for the API request</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> GetAll<T>(Uri uri, IDictionary<string, string> parameters, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return _pagination.GetAllPages(async () => await GetPage<T>(uri, parameters, accepts).ConfigureAwait(false), uri);
}
public Task<IReadOnlyList<T>> GetAll<T>(Uri uri, IDictionary<string, string> parameters, string accepts, ApiOptions options)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(options, nameof(options));
parameters = Pagination.Setup(parameters, options);
return _pagination.GetAllPages(async () => await GetPage<T>(uri, parameters, accepts, options).ConfigureAwait(false), uri);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> SearchAll<T>(Uri uri)
{
return SearchAll<T>(uri, ApiOptions.None);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="options">Options for changing the API response</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> SearchAll<T>(Uri uri, ApiOptions options)
{
return SearchAll<T>(uri, null, null, options);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> SearchAll<T>(Uri uri, IDictionary<string, string> parameters)
{
return SearchAll<T>(uri, parameters, null, ApiOptions.None);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="accepts">Accept header to use for the API request</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> SearchAll<T>(Uri uri, string accepts)
{
return SearchAll<T>(uri, null, accepts, ApiOptions.None);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <param name="options">Options for changing the API response</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> SearchAll<T>(Uri uri, IDictionary<string, string> parameters, ApiOptions options)
{
return SearchAll<T>(uri, parameters, null, options);
}
/// <summary>
/// Gets all API resources in the list at the specified URI.
/// </summary>
/// <typeparam name="T">Type of the API resource in the list.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="parameters">Parameters to add to the API request</param>
/// <param name="accepts">Accept header to use for the API request</param>
/// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<IReadOnlyList<T>> SearchAll<T>(Uri uri, IDictionary<string, string> parameters, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return _pagination.GetAllPages(async () => await GetSearchPage<T>(uri, parameters, accepts).ConfigureAwait(false), uri);
}
public Task<IReadOnlyList<T>> SearchAll<T>(Uri uri, IDictionary<string, string> parameters, string accepts, ApiOptions options)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(options, nameof(options));
parameters = Pagination.Setup(parameters, options);
return _pagination.GetAllPages(async () => await GetSearchPage<T>(uri, parameters, accepts, options).ConfigureAwait(false), uri);
}
/// <summary>
/// Creates a new API resource in the list at the specified URI.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <returns><seealso cref="HttpStatusCode"/>Representing the received HTTP response</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task Post(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return Connection.Post(uri);
}
/// <summary>
/// Creates a new API resource in the list at the specified URI.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <returns>The created API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public async Task<T> Post<T>(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await Connection.Post<JsonResponse<T>>(uri).ConfigureAwait(false);
return response.Body.Data;
}
/// <summary>
/// Creates a new API resource in the list at the specified URI.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="data">Object that describes the new API resource; this will be serialized and used as the request's body</param>
/// <returns>The created API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<T> Post<T>(Uri uri, object data)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
return Post<T>(uri, data, null, null);
}
/// <summary>
/// Creates a new API resource in the list at the specified URI.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="data">Object that describes the new API resource; this will be serialized and used as the request's body</param>
/// <param name="accepts">Accept header to use for the API request</param>
/// <returns>The created API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public Task<T> Post<T>(Uri uri, object data, string accepts)
{
return Post<T>(uri, data, accepts, null);
}
/// <summary>
/// Creates a new API resource in the list at the specified URI.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI of the API resource to get</param>
/// <param name="data">Object that describes the new API resource; this will be serialized and used as the request's body</param>
/// <param name="accepts">Accept header to use for the API request</param>
/// <param name="contentType">Content type of the API request</param>
/// <returns>The created API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public async Task<T> Post<T>(Uri uri, object data, string accepts, string contentType)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
var response = await Connection.Post<JsonResponse<T>>(uri, data, accepts, contentType).ConfigureAwait(false);
return response.Body.Data;
}
public async Task<T> Post<T>(Uri uri, object data, string accepts, string contentType, TimeSpan timeout)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
var response = await Connection.Post<JsonResponse<T>>(uri, data, accepts, contentType, timeout).ConfigureAwait(false);
return response.Body.Data;
}
/// <summary>
/// Creates or replaces the API resource at the specified URI
/// </summary>
/// <param name="uri">URI of the API resource to put</param>
/// <returns>A <see cref="Task"/> for the request's execution.</returns>
public Task Put(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return Connection.Put(uri);
}
/// <summary>
/// Creates or replaces the API resource at the specified URI.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI of the API resource to create or replace</param>
/// <param name="data">Object that describes the API resource; this will be serialized and used as the request's body</param>
/// <returns>The created API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public async Task<T> Put<T>(Uri uri, object data)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
var response = await Connection.Put<JsonResponse<T>>(uri, data).ConfigureAwait(false);
return response.Body.Data;
}
/// <summary>
/// Deletes the API object at the specified URI.
/// </summary>
/// <param name="uri">URI of the API resource to delete</param>
/// <returns>A <see cref="Task"/> for the request's execution.</returns>
public Task Delete(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return Connection.Delete(uri);
}
/// <summary>
/// Deletes the API object at the specified URI.
/// </summary>
/// <param name="uri">URI of the API resource to delete</param>
/// <param name="data">Object that describes the API resource; this will be serialized and used as the request's body</param>
/// <returns>A <see cref="Task"/> for the request's execution.</returns>
public Task Delete(Uri uri, object data)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
return Connection.Delete(uri, data);
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request that expects an empty response.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="data">The object to serialize as the body of the request</param>
/// <param name="accepts">Specifies accept response media type</param>
/// <returns>The returned <seealso cref="HttpStatusCode"/></returns>
public Task Delete(Uri uri, object data, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
return Connection.Delete(uri, data, accepts);
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="data">The object to serialize as the body of the request</param>
public async Task<T> Delete<T>(Uri uri, object data)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
var response = await Connection.Delete<JsonResponse<T>>(uri, data).ConfigureAwait(false);
return response.Body.Data;
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request.
/// Attempts to map the response body to an object of type <typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">The type to map the response to</typeparam>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="data">The object to serialize as the body of the request</param>
/// <param name="accepts">Specifies accept response media type</param>
public async Task<T> Delete<T>(Uri uri, object data, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
var response = await Connection.Delete<JsonResponse<T>>(uri, data, accepts).ConfigureAwait(false);
return response.Body.Data;
}
/// <summary>
/// Executes a GET to the API object at the specified URI. This operation is appropriate for API calls which
/// queue long running calculations and return a collection of a resource.
/// It expects the API to respond with an initial 202 Accepted, and queries again until a 200 OK is received.
/// It returns an empty collection if it receives a 204 No Content response.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI of the API resource to update</param>
/// <param name="cancellationToken">A token used to cancel this potentially long running request</param>
/// <returns>The updated API resource.</returns>
/// <exception cref="ApiException">Thrown when an API error occurs.</exception>
public async Task<IReadOnlyList<T>> GetQueuedOperation<T>(Uri uri, CancellationToken cancellationToken)
{
while (true)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await Connection.GetResponse<IReadOnlyList<T>>(uri, cancellationToken).ConfigureAwait(false);
switch (response.HttpResponse.StatusCode)
{
case HttpStatusCode.Accepted:
continue;
case HttpStatusCode.NoContent:
return new ReadOnlyCollection<T>(new T[] { });
case HttpStatusCode.OK:
return response.Body;
}
throw new ApiException("Queued Operations expect status codes of Accepted, No Content, or OK.",
response.HttpResponse.StatusCode);
}
}
async Task<IReadOnlyPagedCollection<T>> GetSearchPage<T>(
Uri uri,
IDictionary<string, string> parameters,
string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await Connection.Get<JsonResponse<SearchResponse<List<T>>>>(uri, parameters, accepts).ConfigureAwait(false);
return new ReadOnlySearchPagedCollection<T>(
response,
nextPageUri => Connection.Get<JsonResponse<SearchResponse<List<T>>>>(nextPageUri, parameters, accepts));
}
async Task<IReadOnlyPagedCollection<TU>> GetSearchPage<TU>(
Uri uri,
IDictionary<string, string> parameters,
string accepts,
ApiOptions options)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var connection = Connection;
var response = await connection.Get<JsonResponse<SearchResponse<List<TU>>>>(uri, parameters, accepts).ConfigureAwait(false);
return new ReadOnlySearchPagedCollection<TU>(
response,
nextPageUri =>
{
var shouldContinue = Pagination.ShouldContinue(
nextPageUri,
options);
return shouldContinue
? connection.Get<JsonResponse<SearchResponse<List<TU>>>>(nextPageUri, parameters, accepts)
: null;
});
}
async Task<IReadOnlyPagedCollection<T>> GetPage<T>(
Uri uri,
IDictionary<string, string> parameters,
string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await Connection.Get<JsonResponse<List<T>>>(uri, parameters, accepts).ConfigureAwait(false);
return new ReadOnlyPagedCollection<T>(
response,
nextPageUri => Connection.Get<JsonResponse<List<T>>>(nextPageUri, parameters, accepts));
}
async Task<IReadOnlyPagedCollection<TU>> GetPage<TU>(
Uri uri,
IDictionary<string, string> parameters,
string accepts,
ApiOptions options)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var connection = Connection;
var response = await connection.Get<JsonResponse<List<TU>>>(uri, parameters, accepts).ConfigureAwait(false);
return new ReadOnlyPagedCollection<TU>(
response,
nextPageUri =>
{
var shouldContinue = Pagination.ShouldContinue(
nextPageUri,
options);
return shouldContinue
? connection.Get<JsonResponse<List<TU>>>(nextPageUri, parameters, accepts)
: null;
});
}
}
}
| 47.135972 | 141 | 0.605309 | [
"MIT"
] | Chinh-P/pipedrive-dotnet | src/Pipedrive.net/Http/ApiConnection.cs | 27,388 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication.Dtos
{
public class CategoryDto
{
public byte Id { get; set; }
public string Name { get; set; }
}
} | 18.384615 | 40 | 0.661088 | [
"MIT"
] | profemzy/OProbate | WebApplication/Dtos/CategoryDto.cs | 241 | C# |
using System;
using System.Reflection;
using System.Linq;
namespace BubbleEngine.LuaAPI
{
public class EmbeddedLoader
{
public bool hasFile(string name)
{
var f = "BubbleEngine." + name + ".lua";
var asm = Assembly.GetExecutingAssembly ();
var names = asm.GetManifestResourceNames ();
return names.Contains (f);
}
public string loadFile(string name)
{
var f = "BubbleEngine." + name + ".lua";
return EmbeddedResources.GetString (f);
}
}
}
| 20.608696 | 47 | 0.683544 | [
"MIT"
] | CallumDev/BubbleEngine | src/BubbleEngine/LuaAPI/EmbeddedLoader.cs | 476 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("DataBindingDemos.Views.SwitchIndicatorsPage.xaml", "Views/SwitchIndicatorsPage.xaml", typeof(global::DataBindingDemos.SwitchIndicatorsPage))]
namespace DataBindingDemos {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("Views/SwitchIndicatorsPage.xaml")]
public partial class SwitchIndicatorsPage : global::Xamarin.Forms.ContentPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Switch switch1;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Switch switch2;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private global::Xamarin.Forms.Switch switch3;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(SwitchIndicatorsPage));
switch1 = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Switch>(this, "switch1");
switch2 = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Switch>(this, "switch2");
switch3 = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Switch>(this, "switch3");
}
}
}
| 53.783784 | 204 | 0.653266 | [
"Apache-2.0"
] | ricshark/xamarin-forms-samples | DataBindingDemos/DataBindingDemos/DataBindingDemos/obj/Debug/netstandard2.0/Views/SwitchIndicatorsPage.xaml.g.cs | 1,990 | C# |
/*Write a recursive program for generating and printing all the combinations with duplicatesof k elements from n-element set. Example:*/
namespace Combinations
{
using System;
public class Startup
{
public const int N = 3;
public const int K = 3;
public static int[] Vector = new int[K];
public static void Main()
{
Combinations(0, 1);
}
private static void Combinations(int index, int start)
{
if (index >= K)
{
Console.WriteLine(string.Join(" ", Vector));
}
else
{
for (int i = start; i <= N; i++)
{
Vector[index] = i;
Combinations(index + 1, i);
}
}
}
}
}
| 24 | 137 | 0.464286 | [
"MIT"
] | danisio/DataStructuresAndAlgorithms-Homeworks | 07.Recursion/02.Combinations/Startup.cs | 842 | C# |
using System;
using System.Collections.Generic;
namespace Utilities.UnitTests
{
public class Test16 : IEquatable<Test16>
{
public Test16() { }
public Test16(int year)
{
Year = year;
}
public int Field;
public int Year { get; set; }
public string Segment { get; set; }
public string Country { get; set; }
public string Product { get; set; }
public string DiscountBand { get; set; }
public decimal UnitsSold { get; set; }
public string ManufacturingPrice { get; set; }
public string SalePrice { get; set; }
public string GrossSales { get; set; }
public string Discounts { get; set; }
public string Sales { get; set; }
public string COGS { get; set; }
public string Profit { get; set; }
public DateTime Date { get; set; }
public int MonthNumber { get; set; }
public string MonthName { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as Test16);
}
public void Test() { }
public bool Equals(Test16 other)
{
return other != null &&
Year == other.Year &&
Segment == other.Segment &&
Country == other.Country &&
Product == other.Product &&
DiscountBand == other.DiscountBand &&
UnitsSold == other.UnitsSold &&
ManufacturingPrice == other.ManufacturingPrice &&
SalePrice == other.SalePrice &&
GrossSales == other.GrossSales &&
Discounts == other.Discounts &&
Sales == other.Sales &&
COGS == other.COGS &&
Profit == other.Profit &&
Date == other.Date &&
MonthNumber == other.MonthNumber &&
MonthName == other.MonthName;
}
public override int GetHashCode()
{
int hashCode = 378801229;
hashCode = hashCode * -1521134295 + Year.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Segment);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Country);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Product);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(DiscountBand);
hashCode = hashCode * -1521134295 + UnitsSold.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(ManufacturingPrice);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(SalePrice);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(GrossSales);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Discounts);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Sales);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(COGS);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Profit);
hashCode = hashCode * -1521134295 + Date.GetHashCode();
hashCode = hashCode * -1521134295 + MonthNumber.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(MonthName);
return hashCode;
}
}
}
| 37.53012 | 104 | 0.692135 | [
"Unlicense"
] | ffhighwind/Utilities | UnitTests/Test16.cs | 3,117 | C# |
using System.Data;
using System.Linq;
namespace NPoco.DatabaseTypes
{
public class SqlServerCEDatabaseType : DatabaseType
{
public override string BuildPageQuery(long skip, long take, PagingHelper.SQLParts parts, ref object[] args)
{
var sqlPage = string.Format("{0}\nOFFSET @{1} ROWS FETCH NEXT @{2} ROWS ONLY", parts.sql, args.Length, args.Length + 1);
args = args.Concat(new object[] { skip, take }).ToArray();
return sqlPage;
}
public override object ExecuteInsert<T>(Database db, IDbCommand cmd, string primaryKeyName, T poco, object[] args)
{
db.ExecuteNonQueryHelper(cmd);
return db.ExecuteScalar<object>("SELECT @@@IDENTITY AS NewID;");
}
public override IsolationLevel GetDefaultTransactionIsolationLevel()
{
return IsolationLevel.ReadCommitted;
}
public override string GetProviderName()
{
return "System.Data.SqlServerCe.4.0";
}
}
} | 33.516129 | 132 | 0.625602 | [
"Apache-2.0"
] | asterd/NPoco.iSeries | NPoco/DatabaseTypes/SqlServerCEDatabaseType.cs | 1,039 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
static Program()
{
TestList = new Dictionary<string, Action>() {
["Create.Byte"] = CreateByte,
["Create.Double"] = CreateDouble,
["Create.Int16"] = CreateInt16,
["Create.Int32"] = CreateInt32,
["Create.Int64"] = CreateInt64,
["Create.SByte"] = CreateSByte,
["Create.Single"] = CreateSingle,
["Create.UInt16"] = CreateUInt16,
["Create.UInt32"] = CreateUInt32,
["Create.UInt64"] = CreateUInt64,
["CreateScalar.Byte"] = CreateScalarByte,
["CreateScalar.Double"] = CreateScalarDouble,
["CreateScalar.Int16"] = CreateScalarInt16,
["CreateScalar.Int32"] = CreateScalarInt32,
["CreateScalar.Int64"] = CreateScalarInt64,
["CreateScalar.SByte"] = CreateScalarSByte,
["CreateScalar.Single"] = CreateScalarSingle,
["CreateScalar.UInt16"] = CreateScalarUInt16,
["CreateScalar.UInt32"] = CreateScalarUInt32,
["CreateScalar.UInt64"] = CreateScalarUInt64,
["CreateScalarUnsafe.Byte"] = CreateScalarUnsafeByte,
["CreateScalarUnsafe.Double"] = CreateScalarUnsafeDouble,
["CreateScalarUnsafe.Int16"] = CreateScalarUnsafeInt16,
["CreateScalarUnsafe.Int32"] = CreateScalarUnsafeInt32,
["CreateScalarUnsafe.Int64"] = CreateScalarUnsafeInt64,
["CreateScalarUnsafe.SByte"] = CreateScalarUnsafeSByte,
["CreateScalarUnsafe.Single"] = CreateScalarUnsafeSingle,
["CreateScalarUnsafe.UInt16"] = CreateScalarUnsafeUInt16,
["CreateScalarUnsafe.UInt32"] = CreateScalarUnsafeUInt32,
["CreateScalarUnsafe.UInt64"] = CreateScalarUnsafeUInt64,
["CreateElement.Byte"] = CreateElementByte,
["CreateElement.Double"] = CreateElementDouble,
["CreateElement.Int16"] = CreateElementInt16,
["CreateElement.Int32"] = CreateElementInt32,
["CreateElement.Int64"] = CreateElementInt64,
["CreateElement.SByte"] = CreateElementSByte,
["CreateElement.Single"] = CreateElementSingle,
["CreateElement.UInt16"] = CreateElementUInt16,
["CreateElement.UInt32"] = CreateElementUInt32,
["CreateElement.UInt64"] = CreateElementUInt64,
["CreateVector.Byte"] = CreateVectorByte,
["CreateVector.Double"] = CreateVectorDouble,
["CreateVector.Int16"] = CreateVectorInt16,
["CreateVector.Int32"] = CreateVectorInt32,
["CreateVector.Int64"] = CreateVectorInt64,
["CreateVector.SByte"] = CreateVectorSByte,
["CreateVector.Single"] = CreateVectorSingle,
["CreateVector.UInt16"] = CreateVectorUInt16,
["CreateVector.UInt32"] = CreateVectorUInt32,
["CreateVector.UInt64"] = CreateVectorUInt64,
};
}
}
}
| 50.911765 | 73 | 0.583189 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/General/Vector128/Program.Vector128.cs | 3,462 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using ReconNess.Data.Npgsql;
namespace ReconNess.Data.Npgsql.Migrations
{
[DbContext(typeof(ReconNessContext))]
[Migration("20200529213740_AddRootDomain")]
partial class AddRootDomain
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
.HasAnnotation("ProductVersion", "3.1.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("ReconNess.Entities.Agent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Command")
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<bool>("IsBySubdomain")
.HasColumnType("boolean");
b.Property<DateTime>("LastRun")
.HasColumnType("timestamp without time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<bool>("OnlyIfHasHttpOpen")
.HasColumnType("boolean");
b.Property<bool>("OnlyIfIsAlive")
.HasColumnType("boolean");
b.Property<string>("Script")
.HasColumnType("text");
b.Property<bool>("SkipIfRanBefore")
.HasColumnType("boolean");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("Agents");
});
modelBuilder.Entity("ReconNess.Entities.AgentCategory", b =>
{
b.Property<Guid>("AgentId")
.HasColumnType("uuid");
b.Property<Guid>("CategoryId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("AgentId", "CategoryId");
b.HasIndex("CategoryId");
b.ToTable("AgentCategory");
});
modelBuilder.Entity("ReconNess.Entities.Category", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("Categories");
});
modelBuilder.Entity("ReconNess.Entities.Label", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Color")
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("Label");
b.HasData(
new
{
Id = new Guid("cde752b1-3f9e-4ba8-8706-35ad1c1e94ee"),
Color = "#0000FF",
CreatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
Deleted = false,
Name = "Checking",
UpdatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)
},
new
{
Id = new Guid("1cad5d54-5764-4366-bb2c-cdabc06b29dc"),
Color = "#FF0000",
CreatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
Deleted = false,
Name = "Vulnerable",
UpdatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)
},
new
{
Id = new Guid("e8942a1a-a535-41cd-941b-67bcc89fe5cd"),
Color = "#FF8C00",
CreatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
Deleted = false,
Name = "Interesting",
UpdatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)
},
new
{
Id = new Guid("cd4eb533-4c67-44df-826f-8786c0146721"),
Color = "#008000",
CreatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
Deleted = false,
Name = "Bounty",
UpdatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)
},
new
{
Id = new Guid("a0d15eac-ec24-4a10-9c3f-007e66f313fd"),
Color = "#A9A9A9",
CreatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
Deleted = false,
Name = "Ignore",
UpdatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)
});
});
modelBuilder.Entity("ReconNess.Entities.Note", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("Notes")
.HasColumnType("text");
b.Property<Guid?>("SubdomainId")
.HasColumnType("uuid");
b.Property<Guid?>("TargetId")
.HasColumnType("uuid");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("SubdomainId")
.IsUnique();
b.HasIndex("TargetId")
.IsUnique();
b.ToTable("Note");
});
modelBuilder.Entity("ReconNess.Entities.Reference", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Categories")
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("Url")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Reference");
});
modelBuilder.Entity("ReconNess.Entities.RootDomain", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<Guid?>("TargetId")
.HasColumnType("uuid");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("TargetId");
b.ToTable("RootDomains");
});
modelBuilder.Entity("ReconNess.Entities.Service", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int>("Port")
.HasColumnType("integer");
b.Property<Guid?>("SubdomainId")
.HasColumnType("uuid");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("SubdomainId");
b.ToTable("Services");
});
modelBuilder.Entity("ReconNess.Entities.ServiceHttp", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("ScreenshotHttpPNGBase64")
.HasColumnType("text");
b.Property<string>("ScreenshotHttpsPNGBase64")
.HasColumnType("text");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("ServicesHttp");
});
modelBuilder.Entity("ReconNess.Entities.ServiceHttpDirectory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("Directory")
.HasColumnType("text");
b.Property<string>("Method")
.HasColumnType("text");
b.Property<Guid?>("ServiceHttpId")
.HasColumnType("uuid");
b.Property<string>("Size")
.HasColumnType("text");
b.Property<string>("StatusCode")
.HasColumnType("text");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("ServiceHttpId");
b.ToTable("ServiceHttpDirectory");
});
modelBuilder.Entity("ReconNess.Entities.Subdomain", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<Guid?>("DomainId")
.HasColumnType("uuid");
b.Property<string>("FromAgents")
.HasColumnType("text");
b.Property<bool?>("HasHttpOpen")
.HasColumnType("boolean");
b.Property<string>("IpAddress")
.HasColumnType("text");
b.Property<bool?>("IsAlive")
.HasColumnType("boolean");
b.Property<bool?>("IsMainPortal")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<Guid?>("ServiceHttpId")
.HasColumnType("uuid");
b.Property<bool?>("Takeover")
.HasColumnType("boolean");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("DomainId");
b.HasIndex("ServiceHttpId");
b.ToTable("Subdomains");
});
modelBuilder.Entity("ReconNess.Entities.SubdomainLabel", b =>
{
b.Property<Guid>("SubdomainId")
.HasColumnType("uuid");
b.Property<Guid>("LabelId")
.HasColumnType("uuid");
b.HasKey("SubdomainId", "LabelId");
b.HasIndex("LabelId");
b.ToTable("SubdomainLabel");
});
modelBuilder.Entity("ReconNess.Entities.Target", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("BugBountyProgramUrl")
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<bool>("Deleted")
.HasColumnType("boolean");
b.Property<string>("InScope")
.HasColumnType("text");
b.Property<bool>("IsPrivate")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("OutOfScope")
.HasColumnType("text");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("Targets");
});
modelBuilder.Entity("ReconNess.Entities.AgentCategory", b =>
{
b.HasOne("ReconNess.Entities.Agent", "Agent")
.WithMany("AgentCategories")
.HasForeignKey("AgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ReconNess.Entities.Category", "Category")
.WithMany("AgentCategories")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ReconNess.Entities.Note", b =>
{
b.HasOne("ReconNess.Entities.Subdomain", "Subdomain")
.WithOne("Notes")
.HasForeignKey("ReconNess.Entities.Note", "SubdomainId");
b.HasOne("ReconNess.Entities.RootDomain", "Target")
.WithOne("Notes")
.HasForeignKey("ReconNess.Entities.Note", "TargetId");
});
modelBuilder.Entity("ReconNess.Entities.RootDomain", b =>
{
b.HasOne("ReconNess.Entities.Target", "Target")
.WithMany("RootDomains")
.HasForeignKey("TargetId");
});
modelBuilder.Entity("ReconNess.Entities.Service", b =>
{
b.HasOne("ReconNess.Entities.Subdomain", "Subdomain")
.WithMany("Services")
.HasForeignKey("SubdomainId");
});
modelBuilder.Entity("ReconNess.Entities.ServiceHttpDirectory", b =>
{
b.HasOne("ReconNess.Entities.ServiceHttp", "ServiceHttp")
.WithMany("Directories")
.HasForeignKey("ServiceHttpId");
});
modelBuilder.Entity("ReconNess.Entities.Subdomain", b =>
{
b.HasOne("ReconNess.Entities.RootDomain", "Domain")
.WithMany("Subdomains")
.HasForeignKey("DomainId");
b.HasOne("ReconNess.Entities.ServiceHttp", "ServiceHttp")
.WithMany("Subdomains")
.HasForeignKey("ServiceHttpId");
});
modelBuilder.Entity("ReconNess.Entities.SubdomainLabel", b =>
{
b.HasOne("ReconNess.Entities.Label", "Label")
.WithMany("Subdomains")
.HasForeignKey("LabelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ReconNess.Entities.Subdomain", "Subdomain")
.WithMany("Labels")
.HasForeignKey("SubdomainId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.569343 | 119 | 0.43019 | [
"MIT"
] | KeyStrOke95/reconness | src/DAL/ReconNess.Data.Npgsql/Migrations/20200529213740_AddRootDomain.Designer.cs | 20,042 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// AlipayCommerceIotDapplyOrderCancelResponse.
/// </summary>
public class AlipayCommerceIotDapplyOrderCancelResponse : AopResponse
{
/// <summary>
/// 物料申请单号
/// </summary>
[XmlElement("asset_apply_order_id")]
public string AssetApplyOrderId { get; set; }
}
}
| 24.055556 | 74 | 0.614319 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Response/AlipayCommerceIotDapplyOrderCancelResponse.cs | 445 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.trade.buyer.credit.confirm
/// </summary>
public class AlipayTradeBuyerCreditConfirmRequest : IAopRequest<AlipayTradeBuyerCreditConfirmResponse>
{
/// <summary>
/// 交易买家授信确认
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.trade.buyer.credit.confirm";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 25.806452 | 107 | 0.564375 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Request/AlipayTradeBuyerCreditConfirmRequest.cs | 3,216 | 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.Data;
using Microsoft.EntityFrameworkCore.Storage;
namespace Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqliteDateTimeTypeMapping : DateTimeTypeMapping
{
private const string DateTimeFormatConst = @"'{0:yyyy\-MM\-dd HH\:mm\:ss.FFFFFFF}'";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqliteDateTimeTypeMapping(
string storeType,
DbType? dbType = null)
: base(storeType, dbType)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected SqliteDateTimeTypeMapping(RelationalTypeMappingParameters parameters)
: base(parameters)
{
}
/// <summary>
/// Creates a copy of this mapping.
/// </summary>
/// <param name="parameters"> The parameters for this mapping. </param>
/// <returns> The newly created mapping. </returns>
protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
=> new SqliteDateTimeTypeMapping(parameters);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override string SqlLiteralFormatString
=> DateTimeFormatConst;
}
}
| 52.885246 | 113 | 0.67359 | [
"Apache-2.0"
] | 0x0309/efcore | src/EFCore.Sqlite.Core/Storage/Internal/SqliteDateTimeTypeMapping.cs | 3,226 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Jyx2;
using UnityEngine;
using XNode;
[CreateNodeMenu("对话")]
[NodeWidth(256)]
public class Jyx2TalkNode : Jyx2SimpleNode
{
private void Reset() {
name = "对话";
}
public int roleId;
public string content;
// Use this for initialization
protected override void Init() {
base.Init();
}
// Return the correct value of an output port when requested
public override object GetValue(NodePort port) {
return null; // Replace this
}
protected override void DoExecute()
{
Jyx2LuaBridge.Talk(roleId, content, "", 0);
}
} | 16.473684 | 61 | 0.710863 | [
"MIT"
] | Alinccc/jynew | jyx2/Assets/Scripts/EventsGraph/Nodes/Jyx2TalkNode.cs | 636 | C# |
using Shouldly.Tests.Strings;
using Shouldly.Tests.TestHelpers;
using Xunit;
namespace Shouldly.Tests.ShouldBeLessThan
{
public class CustomObjectScenario
{
[Fact]
public void CustomObjectScenarioShouldFail()
{
var customA = new Custom { Val = 1 };
var customB = new Custom { Val = 1 };
var comparer = new CustomComparer<Custom>();
Verify.ShouldFail(() =>
customA.ShouldBeLessThan(customB, comparer, "Some additional context"),
errorWithSource:
@"customA
should be less than
Shouldly.Tests.TestHelpers.Custom (000000)
but was
Shouldly.Tests.TestHelpers.Custom (000000)
Additional Info:
Some additional context",
errorWithoutSource:
@"Shouldly.Tests.TestHelpers.Custom (000000)
should be less than
Shouldly.Tests.TestHelpers.Custom (000000)
but was not
Additional Info:
Some additional context"
);
}
[Fact]
public void ShouldPass()
{
var customA = new Custom { Val = 2 };
var customB = new Custom { Val = 1 };
var comparer = new CustomComparer<Custom>();
customB.ShouldBeLessThan(customA, comparer);
}
}
}
| 24.653061 | 71 | 0.641556 | [
"BSD-3-Clause"
] | FrancisChung/shouldly | src/Shouldly.Tests/ShouldBeLessThan/CustomObjectScenario.cs | 1,210 | C# |
using Microsoft.Azure.Management.ProviderHub.Models;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.Azure.Management.ProviderHub.Tests
{
public class NotificationRegistrationTests
{
[Fact]
public void NotificationRegistrationsCRUDTests()
{
using (var context = MockContext.Start(GetType()))
{
string providerNamespace = "Microsoft.Contoso";
string notificationRegistrationName = "employeesNotificationRegistration";
var employeesResourceTypeProperties = new NotificationRegistrationPropertiesModel
{
NotificationMode = "EventHub",
MessageScope = "RegisteredSubscriptions",
IncludedEvents = new string[]
{
"*/write",
"Microsoft.Contoso/employees/delete"
},
NotificationEndpoints = new NotificationEndpoint[]
{
new NotificationEndpoint
{
Locations = new string[]
{
"",
"East US"
},
NotificationDestination = "/subscriptions/ac6bcfb5-3dc1-491f-95a6-646b89bf3e88/resourceGroups/mgmtexp-eastus/providers/Microsoft.EventHub/namespaces/unitedstates-mgmtexpint/eventhubs/armlinkednotifications"
}
}
};
var notificationRegistration = CreateNotificationRegistration(context, providerNamespace, notificationRegistrationName, employeesResourceTypeProperties);
Assert.NotNull(notificationRegistration);
notificationRegistration = GetNotificationRegistration(context, providerNamespace, notificationRegistrationName);
Assert.NotNull(notificationRegistration);
var notificationRegistrationsList = ListNotificationRegistration(context, providerNamespace);
Assert.NotNull(notificationRegistrationsList);
DeleteNotificationRegistration(context, providerNamespace, notificationRegistrationName);
var exception = Assert.Throws<ErrorResponseException>(() => GetNotificationRegistration(context, providerNamespace, notificationRegistrationName));
Assert.True(exception.Response.StatusCode == System.Net.HttpStatusCode.NotFound);
notificationRegistration = CreateNotificationRegistration(context, providerNamespace, notificationRegistrationName, employeesResourceTypeProperties);
Assert.NotNull(notificationRegistration);
}
}
private NotificationRegistration CreateNotificationRegistration(MockContext context, string providerNamespace, string notificationRegistrationName, NotificationRegistrationPropertiesModel properties)
{
ProviderHubClient client = GetProviderHubManagementClient(context);
return client.NotificationRegistrations.CreateOrUpdate(providerNamespace, notificationRegistrationName, properties);
}
private NotificationRegistration GetNotificationRegistration(MockContext context, string providerNamespace, string notificationRegistrationName)
{
ProviderHubClient client = GetProviderHubManagementClient(context);
return client.NotificationRegistrations.Get(providerNamespace, notificationRegistrationName);
}
private IPage<NotificationRegistration> ListNotificationRegistration(MockContext context, string providerNamespace)
{
ProviderHubClient client = GetProviderHubManagementClient(context);
return client.NotificationRegistrations.ListByProviderRegistration(providerNamespace);
}
private void DeleteNotificationRegistration(MockContext context, string providerNamespace, string notificationRegistrationName)
{
ProviderHubClient client = GetProviderHubManagementClient(context);
client.NotificationRegistrations.Delete(providerNamespace, notificationRegistrationName);
}
private ProviderHubClient GetProviderHubManagementClient(MockContext context)
{
return context.GetServiceClient<ProviderHubClient>();
}
}
}
| 50.488889 | 234 | 0.670995 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/providerhub/Microsoft.Azure.Management.ProviderHub/tests/ScenarioTests/NotificationRegistrationTests.cs | 4,544 | C# |
using System;
using System.Collections.Generic;
using Microservices.Services.Revenue.Domain.Seedwork;
namespace Microservices.Services.Revenue.Domain.AggregatesModel.TripAggregate
{
public class TripLeg : ValueObject
{
public Guid Id { get; private set; }
public string Route { get; private set; }
public decimal Revenue { get; private set; }
public TripLeg(string route = null, decimal revenue = 0)
{
// todo: Add validations.
Id = Guid.NewGuid();
Route = route;
Revenue = revenue;
}
protected override IEnumerable<object> GetAtomicValues()
{
yield return Route;
yield return Revenue;
}
}
} | 27.777778 | 77 | 0.608 | [
"Apache-2.0"
] | kavir-bheeroo/Microservices | src/Services/Revenue.Domain/AggregatesModel/TripAggregate/TripLeg.cs | 750 | C# |
using Ninject.Extensions.Factory;
using Ninject.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SharedComposer.Providers
{
public class NameProvider : StandardInstanceProvider
{
protected override string GetName(System.Reflection.MethodInfo methodInfo, object[] arguments)
{
return (string)arguments[0];
}
protected override IConstructorArgument[] GetConstructorArguments(MethodInfo methodInfo, object[] arguments)
{
return base.GetConstructorArguments(methodInfo, arguments).Skip(1).ToArray();
}
}
}
| 25.214286 | 116 | 0.719547 | [
"MIT"
] | LuisM000/Planchet | Planchet/SharedComposer/Providers/NameProvider.cs | 708 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace VoteTrackerAPI.Models.Database
{
public partial class Userpassword
{
public Guid Id { get; set; }
public Guid? UserId { get; set; }
public string Password { get; set; }
public bool? IsDeleted { get; set; }
public DateTime? ExpirationDate { get; set; }
}
}
| 22.764706 | 53 | 0.638243 | [
"MIT"
] | gmalenko/VoteTrackerAPI | Models/Database/Userpassword.cs | 389 | C# |
/**********************************************************************************************************************
* 描述:
* 接收请求文本消息。
*
* 变更历史:
* 作者:李亮 时间:2015年12月27日 新建
*
*********************************************************************************************************************/
using System.Xml.Serialization;
using Wlitsoft.Framework.WeixinSDK.Core;
using Wlitsoft.Framework.Common.Extension;
namespace Wlitsoft.Framework.WeixinSDK.Message.Request
{
/// <summary>
/// 接收请求文本消息。
/// </summary>
[XmlRoot("xml")]
public class RequestTextMessage : RequestMessageBase
{
#region RequestMessageBase 成员
/// <summary>
/// 获取 请求消息类型。
/// </summary>
[XmlIgnore]
public override RequestMsgType MsgType => RequestMsgType.Text;
#endregion
#region 公共属性
/// <summary>
/// 获取或设置 文本消息内容。
/// </summary>
public string Content { get; set; }
#endregion
}
}
| 24.731707 | 120 | 0.441815 | [
"Apache-2.0"
] | Wlitsoft/WeixinSDK | src/WeixinSDK/Message/Request/RequestTextMessage.cs | 1,148 | C# |
using Gicco.Infrastructure.Data;
using Gicco.Module.Catalog.Models;
using Gicco.Module.Catalog.Services;
using Gicco.Module.Catalog.ViewModels;
using Gicco.Module.Core.Models;
using Gicco.Module.Core.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace Gicco.Module.Mobile.Areas.Mobile.Controllers
{
[Area("Mobile")]
[Route("api/mobile/collection")]
public class CollectionApiController : Controller
{
private readonly IMediaService _mediaService;
private readonly IRepository<Category> _cateRepository;
private readonly IRepository<WidgetInstance> _widgetInstanceRepository;
private readonly IRepository<Product> _productRepository;
private readonly IProductPricingService _productPricingService;
public CollectionApiController(
IRepository<Category> cateRepository,
IRepository<WidgetInstance> widgetInstanceRepository,
IRepository<Product> productRepository,
IProductPricingService productPricingService,
IMediaService mediaService)
{
_cateRepository = cateRepository;
_mediaService = mediaService;
_widgetInstanceRepository = widgetInstanceRepository;
_productRepository = productRepository;
_productPricingService = productPricingService;
}
[HttpGet]
public IActionResult Collection()
{
var widgetInstances = _widgetInstanceRepository.Query()
.Where(x => x.WidgetId == WidgetIds.ProductWidget)
.OrderBy(x => x.DisplayOrder)
.Select(x => new
{
Id = x.Id,
WidgetName = x.Name,
Setting = JsonConvert.DeserializeObject<ProductWidgetSetting>(x.Data)
})
.ToList();
var productWidgets = new List<ProductWidgetComponentVm>();
foreach (var item in widgetInstances)
{
var model = new ProductWidgetComponentVm
{
Id = item.Id,
WidgetName = item.WidgetName,
Setting = item.Setting
};
var query = _productRepository.Query()
.Where(x => x.IsPublished && x.IsVisibleIndividually);
if (model.Setting.CategoryId.HasValue && model.Setting.CategoryId.Value > 0)
{
query = query.Where(x => x.Categories.Any(c => c.CategoryId == model.Setting.CategoryId.Value));
}
if (model.Setting.FeaturedOnly)
{
query = query.Where(x => x.IsFeatured);
}
model.Products = query
.Include(x => x.ThumbnailImage)
.OrderByDescending(x => x.CreatedOn)
.Take(model.Setting.NumberOfProducts)
.Select(x => ProductThumbnail.FromProduct(x)).ToList();
foreach (var product in model.Products)
{
product.ThumbnailUrl = _mediaService.GetThumbnailUrl(product.ThumbnailImage);
product.CalculatedProductPrice = _productPricingService.CalculateProductPrice(product);
}
productWidgets.Add(model);
};
return Json(productWidgets);
}
}
}
| 37.578947 | 116 | 0.589916 | [
"Apache-2.0"
] | dvbtham/gicco | src/Modules/Gicco.Module.Mobile/Areas/Mobile/Controllers/CollectionApiController.cs | 3,572 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace DeviceTesting.Pages.FloatingMultiButton
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class FloatingMultiButtonPage : ContentPage
{
public FloatingMultiButtonPage()
{
InitializeComponent();
}
}
} | 23.15 | 63 | 0.697624 | [
"MIT"
] | haavamoa/FirstUIFramework.Forms | src/DeviceTesting/DeviceTesting/Pages/FloatingMultiButton/FloatingMultiButtonPage.xaml.cs | 465 | C# |
using System;
using System.IO;
using NUnit.Framework;
using MongoDB.Driver;
namespace MongoDB.Driver.Bson
{
[TestFixture]
public class TestBsonBinary
{
[Test]
public void TestRoundTrip(){
Document idoc = new Document();
idoc.Add("b",new Binary(new byte[]{(byte)1,(byte)2}));
MemoryStream stream = new MemoryStream();
BsonWriter writer = new BsonWriter(stream);
writer.Write(idoc);
stream.Seek(0,SeekOrigin.Begin);
BsonReader reader = new BsonReader(stream);
Document odoc = reader.Read();
Assert.AreEqual(idoc.ToString(), odoc.ToString());
}
[Test]
public void TestBinaryRead ()
{
string hex = "28000000075f6964004b1971811d8b0f00c0000000056461746100070000000203000000e188b400";
byte[] data = DecodeHex (hex);
MemoryStream inmem = new MemoryStream (data);
BsonReader inreader = new BsonReader (inmem);
Document indoc = new Document ();
indoc = inreader.Read();
MemoryStream outmem = new MemoryStream ();
BsonWriter outwriter = new BsonWriter (outmem);
outwriter.Write(indoc);
byte[] outdata = outmem.ToArray ();
String outhex = BitConverter.ToString (outdata);
outhex = outhex.Replace ("-", "");
Assert.AreEqual (hex, outhex.ToLower());
}
protected static byte[] DecodeHex (string val)
{
int numberChars = val.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2) {
try {
bytes[i / 2] = Convert.ToByte (val.Substring (i, 2), 16);
} catch {
//failed to convert these 2 chars, they may contain illegal charracters
bytes[i / 2] = 0;
}
}
return bytes;
}
}
}
| 25.426471 | 100 | 0.632736 | [
"Apache-2.0"
] | sunnanking/mongodb-csharp | MongoDB.Net-Tests/Bson/TestBsonBinary.cs | 1,729 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestLog : MonoBehaviour
{
void Start()
{
Debug.Log("!!! Test Debug Log Message !!!");
Debug.LogError("!!! Test Error Log Message !!!");
}
} | 21.75 | 57 | 0.636015 | [
"MIT"
] | Howellm/AR_HoloLens2_Marker | Assets/Communications/TestLog.cs | 263 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aiven.Outputs
{
[OutputType]
public sealed class GetPgPgUserConfigResult
{
/// <summary>
/// custom password for admin user. Defaults to random string. *This must
/// be set only when a new service is being created.*
/// </summary>
public readonly string? AdminPassword;
/// <summary>
/// custom username for admin user. *This must be set only when a new service
/// is being created.*
/// </summary>
public readonly string? AdminUsername;
/// <summary>
/// the hour of day (in UTC) when backup for the service is started. New backup
/// is only started if previous backup has already completed.
/// </summary>
public readonly string? BackupHour;
/// <summary>
/// the minute of an hour when backup for the service is started. New backup
/// is only started if previous backup has already completed.
/// </summary>
public readonly string? BackupMinute;
/// <summary>
/// allow incoming connections from CIDR address block, e.g. `10.20.0.0/16`
/// </summary>
public readonly ImmutableArray<string> IpFilters;
/// <summary>
/// migrate data from existing server, has the following options:
/// </summary>
public readonly Outputs.GetPgPgUserConfigMigrationResult? Migration;
/// <summary>
/// PostgreSQL specific server provided values.
/// </summary>
public readonly Outputs.GetPgPgUserConfigPgResult? Pg;
/// <summary>
/// This setting is deprecated. Use read-replica service integration instead.
/// </summary>
public readonly string? PgReadReplica;
/// <summary>
/// Name of the PG Service from which to fork (deprecated, use service_to_fork_from).
/// This has effect only when a new service is being created.
/// </summary>
public readonly string? PgServiceToForkFrom;
/// <summary>
/// PostgreSQL major version.
/// </summary>
public readonly string? PgVersion;
/// <summary>
/// Enable pgbouncer.
/// </summary>
public readonly Outputs.GetPgPgUserConfigPgbouncerResult? Pgbouncer;
/// <summary>
/// PGLookout settings.
/// </summary>
public readonly Outputs.GetPgPgUserConfigPglookoutResult? Pglookout;
/// <summary>
/// Allow access to selected service ports from private networks.
/// </summary>
public readonly Outputs.GetPgPgUserConfigPrivateAccessResult? PrivateAccess;
/// <summary>
/// Allow access to selected service components through Privatelink.
/// </summary>
public readonly Outputs.GetPgPgUserConfigPrivatelinkAccessResult? PrivatelinkAccess;
/// <summary>
/// Name of another project to fork a service from. This has
/// effect only when a new service is being created.
/// </summary>
public readonly string? ProjectToForkFrom;
/// <summary>
/// Allow access to selected service ports from the public Internet
/// </summary>
public readonly Outputs.GetPgPgUserConfigPublicAccessResult? PublicAccess;
/// <summary>
/// Recovery target time when forking a service. This has effect
/// only when a new service is being created.
/// </summary>
public readonly string? RecoveryTargetTime;
/// <summary>
/// Name of another service to fork from. This has effect only
/// when a new service is being created.
/// </summary>
public readonly string? ServiceToForkFrom;
/// <summary>
/// Percentage of total RAM that the database server uses for
/// memory buffers. Valid range is 20-60 (float), which corresponds to 20% - 60%. This setting adjusts
/// the shared_buffers configuration value. The absolute maximum is 12 GB.
/// </summary>
public readonly string? SharedBuffersPercentage;
public readonly string? StaticIps;
/// <summary>
/// Synchronous replication type. Note that the service plan
/// also needs to support synchronous replication.
/// </summary>
public readonly string? SynchronousReplication;
/// <summary>
/// TimescaleDB extension configuration values.
/// </summary>
public readonly Outputs.GetPgPgUserConfigTimescaledbResult? Timescaledb;
/// <summary>
/// Variant of the PostgreSQL service, may affect the features that are
/// exposed by default. Options: `aiven` or `timescale`.
/// </summary>
public readonly string? Variant;
/// <summary>
/// Sets the maximum amount of memory to be used by a query operation (such
/// as a sort or hash table) before writing to temporary disk files, in MB. Default is 1MB + 0.075% of
/// total RAM (up to 32MB).
/// </summary>
public readonly string? WorkMem;
[OutputConstructor]
private GetPgPgUserConfigResult(
string? adminPassword,
string? adminUsername,
string? backupHour,
string? backupMinute,
ImmutableArray<string> ipFilters,
Outputs.GetPgPgUserConfigMigrationResult? migration,
Outputs.GetPgPgUserConfigPgResult? pg,
string? pgReadReplica,
string? pgServiceToForkFrom,
string? pgVersion,
Outputs.GetPgPgUserConfigPgbouncerResult? pgbouncer,
Outputs.GetPgPgUserConfigPglookoutResult? pglookout,
Outputs.GetPgPgUserConfigPrivateAccessResult? privateAccess,
Outputs.GetPgPgUserConfigPrivatelinkAccessResult? privatelinkAccess,
string? projectToForkFrom,
Outputs.GetPgPgUserConfigPublicAccessResult? publicAccess,
string? recoveryTargetTime,
string? serviceToForkFrom,
string? sharedBuffersPercentage,
string? staticIps,
string? synchronousReplication,
Outputs.GetPgPgUserConfigTimescaledbResult? timescaledb,
string? variant,
string? workMem)
{
AdminPassword = adminPassword;
AdminUsername = adminUsername;
BackupHour = backupHour;
BackupMinute = backupMinute;
IpFilters = ipFilters;
Migration = migration;
Pg = pg;
PgReadReplica = pgReadReplica;
PgServiceToForkFrom = pgServiceToForkFrom;
PgVersion = pgVersion;
Pgbouncer = pgbouncer;
Pglookout = pglookout;
PrivateAccess = privateAccess;
PrivatelinkAccess = privatelinkAccess;
ProjectToForkFrom = projectToForkFrom;
PublicAccess = publicAccess;
RecoveryTargetTime = recoveryTargetTime;
ServiceToForkFrom = serviceToForkFrom;
SharedBuffersPercentage = sharedBuffersPercentage;
StaticIps = staticIps;
SynchronousReplication = synchronousReplication;
Timescaledb = timescaledb;
Variant = variant;
WorkMem = workMem;
}
}
}
| 38.293532 | 110 | 0.621801 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-aiven | sdk/dotnet/Outputs/GetPgPgUserConfigResult.cs | 7,697 | 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("Urdf")]
[assembly: AssemblyDescription("URDF file parser for .NET applications")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Siemens AG")]
[assembly: AssemblyProduct("ROS#")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("d33101da-7196-4545-b708-c8e0c308c5fa")]
// 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.7.0.0")]
[assembly: AssemblyFileVersion("1.7.0.0")]
| 38.594595 | 84 | 0.745798 | [
"Apache-2.0"
] | 1441048907/ros-sharp | Libraries/Urdf/Properties/AssemblyInfo.cs | 1,431 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Compute.Models;
namespace Azure.ResourceManager.Compute
{
public partial class SharedGalleryImageData
{
internal static SharedGalleryImageData DeserializeSharedGalleryImageData(JsonElement element)
{
Optional<string> name = default;
Optional<AzureLocation> location = default;
Optional<OperatingSystemTypes> osType = default;
Optional<OperatingSystemStateTypes> osState = default;
Optional<DateTimeOffset> endOfLifeDate = default;
Optional<GalleryImageIdentifier> identifier = default;
Optional<RecommendedMachineConfiguration> recommended = default;
Optional<Disallowed> disallowed = default;
Optional<HyperVGeneration> hyperVGeneration = default;
Optional<IReadOnlyList<GalleryImageFeature>> features = default;
Optional<ImagePurchasePlan> purchasePlan = default;
Optional<string> uniqueId = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("location"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
location = new AzureLocation(property.Value.GetString());
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("osType"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
osType = property0.Value.GetString().ToOperatingSystemTypes();
continue;
}
if (property0.NameEquals("osState"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
osState = property0.Value.GetString().ToOperatingSystemStateTypes();
continue;
}
if (property0.NameEquals("endOfLifeDate"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
endOfLifeDate = property0.Value.GetDateTimeOffset("O");
continue;
}
if (property0.NameEquals("identifier"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
identifier = GalleryImageIdentifier.DeserializeGalleryImageIdentifier(property0.Value);
continue;
}
if (property0.NameEquals("recommended"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
recommended = RecommendedMachineConfiguration.DeserializeRecommendedMachineConfiguration(property0.Value);
continue;
}
if (property0.NameEquals("disallowed"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
disallowed = Disallowed.DeserializeDisallowed(property0.Value);
continue;
}
if (property0.NameEquals("hyperVGeneration"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
hyperVGeneration = new HyperVGeneration(property0.Value.GetString());
continue;
}
if (property0.NameEquals("features"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
List<GalleryImageFeature> array = new List<GalleryImageFeature>();
foreach (var item in property0.Value.EnumerateArray())
{
array.Add(GalleryImageFeature.DeserializeGalleryImageFeature(item));
}
features = array;
continue;
}
if (property0.NameEquals("purchasePlan"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
purchasePlan = ImagePurchasePlan.DeserializeImagePurchasePlan(property0.Value);
continue;
}
}
continue;
}
if (property.NameEquals("identifier"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("uniqueId"))
{
uniqueId = property0.Value.GetString();
continue;
}
}
continue;
}
}
return new SharedGalleryImageData(name.Value, Optional.ToNullable(location), uniqueId.Value, Optional.ToNullable(osType), Optional.ToNullable(osState), Optional.ToNullable(endOfLifeDate), identifier.Value, recommended.Value, disallowed.Value, Optional.ToNullable(hyperVGeneration), Optional.ToList(features), purchasePlan.Value);
}
}
}
| 46.820225 | 341 | 0.442045 | [
"MIT"
] | damodaravadhani/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/SharedGalleryImageData.Serialization.cs | 8,334 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace SE
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.363636 | 66 | 0.565041 | [
"Unlicense"
] | s54mtb/LEDS | WINapp/SE/SE/Program.cs | 494 | C# |
using cAlgo.API.Extensions.Enums;
using System;
namespace cAlgo.API.Extensions.Models
{
public class TdBar: IComparable
{
#region Properties
public int Index { get; set; }
public int Number { get; set; }
public BarType Type { get; set; }
#endregion
#region Methods
public int CompareTo(object obj)
{
return Index.CompareTo((obj as TdBar).Index);
}
#endregion
}
} | 18.230769 | 57 | 0.57384 | [
"MIT"
] | afhacker/cAlgo.API.Extensions | cAlgo.API.Extensions/Models/TdBar.cs | 476 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MegaCasting.WPF.View
{
/// <summary>
/// Logique d'interaction pour ViewPartnersList.xaml
/// </summary>
public partial class ViewPartnersList : UserControl
{
/// <summary>
/// Initialise la viewParternsList
/// </summary>
public ViewPartnersList()
{
InitializeComponent();
}
}
}
| 23.6875 | 56 | 0.69657 | [
"Apache-2.0"
] | MegaProduction/MegaCastingClientLourd | MegaCasting.WPF/View/ViewPartnersList.xaml.cs | 760 | C# |
using System;
using System.IO;
using System.Windows;
using System.Windows.Media;
using MahApps.Metro;
namespace View_Spot_of_City.UIControls.Theme
{
public static class MetroThemeMaster
{
public static void CreateAppStyleBy(Application application, Color color, bool changeImmediately = false)
{
var resourceDictionary = new ResourceDictionary();
{
resourceDictionary.Add("HighlightColor", color);
resourceDictionary.Add("AccentBaseColor", color);
resourceDictionary.Add("AccentColor", Color.FromArgb((byte)(204), color.R, color.G, color.B));
resourceDictionary.Add("AccentColor2", Color.FromArgb((byte)(153), color.R, color.G, color.B));
resourceDictionary.Add("AccentColor3", Color.FromArgb((byte)(102), color.R, color.G, color.B));
resourceDictionary.Add("AccentColor4", Color.FromArgb((byte)(51), color.R, color.G, color.B));
resourceDictionary.Add("HighlightBrush", GetSolidColorBrush((Color)resourceDictionary["HighlightColor"]));
resourceDictionary.Add("AccentBaseColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentBaseColor"]));
resourceDictionary.Add("AccentColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("AccentColorBrush2", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"]));
resourceDictionary.Add("AccentColorBrush3", GetSolidColorBrush((Color)resourceDictionary["AccentColor3"]));
resourceDictionary.Add("AccentColorBrush4", GetSolidColorBrush((Color)resourceDictionary["AccentColor4"]));
resourceDictionary.Add("WindowTitleColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("ProgressBrush", new LinearGradientBrush(
new GradientStopCollection(new[]
{
new GradientStop((Color)resourceDictionary["HighlightColor"], 0),
new GradientStop((Color)resourceDictionary["AccentColor3"], 1)
}),
new Point(0.001, 0.5), new Point(1.002, 0.5)));
resourceDictionary.Add("CheckmarkFill", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("RightArrowFill", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("IdealForegroundColor", IdealTextColor(color));
resourceDictionary.Add("IdealForegroundColorBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("IdealForegroundDisabledBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"], 0.4));
resourceDictionary.Add("AccentSelectedColorBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("MetroDataGrid.HighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("MetroDataGrid.HighlightTextBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("MetroDataGrid.MouseOverHighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor3"]));
resourceDictionary.Add("MetroDataGrid.FocusBorderBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"]));
resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightTextBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.OnSwitchBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.OnSwitchMouseOverBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"]));
resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.ThumbIndicatorCheckedBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
}
var resDictName = string.Format("ApplicationAccent_{0}.xaml", color.ToString().Replace("#", string.Empty));
var fileName = Path.Combine(Path.GetTempPath(), resDictName);
using (var writer = System.Xml.XmlWriter.Create(fileName, new System.Xml.XmlWriterSettings { Indent = true }))
{
System.Windows.Markup.XamlWriter.Save(resourceDictionary, writer);
writer.Close();
}
resourceDictionary = new ResourceDictionary() { Source = new Uri(fileName, UriKind.Absolute) };
var newAccent = new Accent { Name = resDictName, Resources = resourceDictionary };
ThemeManager.AddAccent(newAccent.Name, newAccent.Resources.Source);
if (changeImmediately)
{
//var applicationTheme = ThemeManager.AppThemes.First(x => string.Equals(x.Name, "BaseLight"));
// detect current application theme
Tuple<AppTheme, Accent> applicationTheme = ThemeManager.DetectAppStyle(application);
ThemeManager.ChangeAppStyle(application, newAccent, applicationTheme.Item1);
//ThemeManager.ChangeAppStyle(application, newAccent, ThemeManager.GetAppTheme("BaseLight"));
}
}
public static void CreateAppStyleBy(Window window, Color color, bool changeImmediately = false)
{
var resourceDictionary = new ResourceDictionary();
{
resourceDictionary.Add("HighlightColor", color);
resourceDictionary.Add("AccentBaseColor", color);
resourceDictionary.Add("AccentColor", Color.FromArgb((byte)(204), color.R, color.G, color.B));
resourceDictionary.Add("AccentColor2", Color.FromArgb((byte)(153), color.R, color.G, color.B));
resourceDictionary.Add("AccentColor3", Color.FromArgb((byte)(102), color.R, color.G, color.B));
resourceDictionary.Add("AccentColor4", Color.FromArgb((byte)(51), color.R, color.G, color.B));
resourceDictionary.Add("HighlightBrush", GetSolidColorBrush((Color)resourceDictionary["HighlightColor"]));
resourceDictionary.Add("AccentBaseColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentBaseColor"]));
resourceDictionary.Add("AccentColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("AccentColorBrush2", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"]));
resourceDictionary.Add("AccentColorBrush3", GetSolidColorBrush((Color)resourceDictionary["AccentColor3"]));
resourceDictionary.Add("AccentColorBrush4", GetSolidColorBrush((Color)resourceDictionary["AccentColor4"]));
resourceDictionary.Add("WindowTitleColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("ProgressBrush", new LinearGradientBrush(
new GradientStopCollection(new[]
{
new GradientStop((Color)resourceDictionary["HighlightColor"], 0),
new GradientStop((Color)resourceDictionary["AccentColor3"], 1)
}),
new Point(0.001, 0.5), new Point(1.002, 0.5)));
resourceDictionary.Add("CheckmarkFill", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("RightArrowFill", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("IdealForegroundColor", IdealTextColor(color));
resourceDictionary.Add("IdealForegroundColorBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("IdealForegroundDisabledBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"], 0.4));
resourceDictionary.Add("AccentSelectedColorBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("MetroDataGrid.HighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("MetroDataGrid.HighlightTextBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("MetroDataGrid.MouseOverHighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor3"]));
resourceDictionary.Add("MetroDataGrid.FocusBorderBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"]));
resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightTextBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.OnSwitchBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["AccentColor"]));
resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.OnSwitchMouseOverBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"]));
resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.ThumbIndicatorCheckedBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"]));
}
var resDictName = string.Format("ApplicationAccent_{0}.xaml", color.ToString().Replace("#", string.Empty));
var fileName = Path.Combine(Path.GetTempPath(), resDictName);
using (var writer = System.Xml.XmlWriter.Create(fileName, new System.Xml.XmlWriterSettings { Indent = true }))
{
System.Windows.Markup.XamlWriter.Save(resourceDictionary, writer);
writer.Close();
}
resourceDictionary = new ResourceDictionary() { Source = new Uri(fileName, UriKind.Absolute) };
var newAccent = new Accent { Name = resDictName, Resources = resourceDictionary };
ThemeManager.AddAccent(newAccent.Name, newAccent.Resources.Source);
if (changeImmediately)
{
//var applicationTheme = ThemeManager.AppThemes.First(x => string.Equals(x.Name, "BaseLight"));
// detect current application theme
Tuple<AppTheme, Accent> applicationTheme = ThemeManager.DetectAppStyle(window);
ThemeManager.ChangeAppStyle(window, newAccent, applicationTheme.Item1);
//ThemeManager.ChangeAppStyle(application, newAccent, ThemeManager.GetAppTheme("BaseLight"));
}
}
/// <summary>
/// Determining Ideal Text Color Based on Specified Background Color
/// http://www.codeproject.com/KB/GDI-plus/IdealTextColor.aspx
/// </summary>
/// <param name = "color">The bg.</param>
/// <returns></returns>
private static Color IdealTextColor(Color color)
{
const int nThreshold = 105;
var bgDelta = Convert.ToInt32((color.R * 0.299) + (color.G * 0.587) + (color.B * 0.114));
var foreColor = (255 - bgDelta < nThreshold) ? Colors.Black : Colors.White;
return foreColor;
}
private static SolidColorBrush GetSolidColorBrush(Color color, double opacity = 1d)
{
var brush = new SolidColorBrush(color) { Opacity = opacity };
brush.Freeze();
return brush;
}
}
}
| 68.852273 | 187 | 0.68031 | [
"Apache-2.0"
] | RS-GIS-Geeks/View-Spot-of-City | View-Spot-of-City/View-Spot-of-City.UIControls/Theme/MetroThemeMaster.cs | 12,120 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentValidation;
using FluentValidation.Results;
namespace Dolittle.Vanir.Backend.Validation
{
/// <summary>
/// Defines a system for working with validators.
/// </summary>
public interface IValidators
{
/// <summary>
/// Gets all validators in the system.
/// </summary>
IEnumerable<Type> All { get; }
/// <summary>
/// Check if there is a validator for a type.
/// </summary>
/// <param name="type">Type to check for</param>
/// <returns>True if there are validators, false if not</returns>
bool HasFor(Type type);
/// <summary>
/// Get validators for a specific type.
/// </summary>
/// <param name="type">Type to get for</param>
/// <returns>All <see cref="IEnumerable(T}">validators</see> for type</returns>
IEnumerable<IValidator> GetFor(Type type);
/// <summary>
/// Validate an instance.
/// </summary>
/// <param name="instanceToValidate">Instance to validate.</param>
/// <returns>The <see cref="ValidationResult">result</see> of the validation.</returns>
ValidationResult Validate<T>(T instanceToValidate);
/// <summary>
/// Validate an instance async.
/// </summary>
/// <param name="instanceToValidate">Instance to validate.</param>
/// <returns>The Task continuation for <see cref="ValidationResult">result</see> of the validation.</returns>
Task<ValidationResult> ValidateAsync<T>(T instanceToValidate);
}
}
| 35.54902 | 117 | 0.623828 | [
"MIT"
] | dolittle-entropy/applications-node | Source/DotNET/Backend/Validation/IValidators.cs | 1,813 | C# |
namespace ClassLib122
{
public class Class009
{
public static string Property => "ClassLib122";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib122/Class009.cs | 120 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.Psi.Spatial.Euclidean.Visualization
{
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Windows.Media;
using HelixToolkit.Wpf;
using Microsoft.Psi.Spatial.Euclidean;
using Microsoft.Psi.Visualization.Extensions;
using Microsoft.Psi.Visualization.VisualizationObjects;
/// <summary>
/// Implements a visualization object for a voxel grid of doubles.
/// </summary>
[VisualizationObject("Voxel grid.")]
public class NumericalVoxelGridVisualizationObject : VoxelGridVisualizationObject<BoxVisual3D, double>
{
private double threshold = 0;
private Color fillColor = Colors.Blue;
/// <summary>
/// Gets or sets the value threshold defining which voxels are shown.
/// </summary>
[DataMember]
[DisplayName("Threshold")]
[Description("The threshold value below which the voxel is not shown.")]
public double Threshold
{
get { return this.threshold; }
set { this.Set(nameof(this.Threshold), ref this.threshold, value); }
}
/// <summary>
/// Gets or sets the voxels fill color.
/// </summary>
[DataMember]
[DisplayName("Fill Color")]
[Description("The fill color of the voxels.")]
public Color FillColor
{
get { return this.fillColor; }
set { this.Set(nameof(this.FillColor), ref this.fillColor, value); }
}
/// <inheritdoc/>
public override void NotifyPropertyChanged(string propertyName)
{
if (propertyName == nameof(this.Threshold))
{
this.UpdateData();
}
base.NotifyPropertyChanged(propertyName);
}
/// <inheritdoc/>
protected override void UpdateVoxelVisuals(BoxVisual3D voxelVisual3D, Voxel<double> voxel)
{
voxelVisual3D.BeginEdit();
voxelVisual3D.Visible = this.GetVoxelVisibility(voxel);
if (voxelVisual3D.Visible)
{
voxelVisual3D.Fill = new LinearGradientBrush(this.FillColor, Color.FromArgb(128, this.FillColor.R, this.FillColor.G, this.FillColor.B), 45.0d);
voxelVisual3D.Width = voxel.VoxelSize * 0.9d;
voxelVisual3D.Height = voxel.VoxelSize * 0.9d;
voxelVisual3D.Length = voxel.VoxelSize * 0.9d;
voxelVisual3D.Center = voxel.GetCenter().ToPoint3D();
}
voxelVisual3D.EndEdit();
}
private bool GetVoxelVisibility(Voxel<double> voxel)
=> voxel.Value > this.threshold;
}
}
| 34.493827 | 159 | 0.613099 | [
"MIT"
] | Microsoft/psi | Sources/Spatial/Microsoft.Psi.Spatial.Euclidean.Visualization.Windows/NumericalVoxelGridVisualizationObject.cs | 2,796 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
namespace src
{
[AllowAnonymous]
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
private readonly ApplicationDbContext _context;
private readonly AuthenticationService _authenticationService;
public AuthController(
ILogger<AuthController> logger,
ApplicationDbContext context,
AuthenticationService authenticationService
)
{
_logger = logger;
_context = context;
_authenticationService = authenticationService;
}
[Route("Register")]
[HttpPost]
public async Task<ActionResult<UserDto>> Register(RegisterDto dto)
{
if (dto.password != dto.passwordRepeat)
{
return BadRequest(new
{
message = "password mismatch"
});
}
using (IDbContextTransaction transaction = _context.Database.BeginTransaction())
{
try
{
Person person = new Person();
this._context.Set<Person>().Attach(person);
User user = new User();
user.username = dto.username;
user.person = person;
user.accounts = new System.Collections.Generic.List<Account>();
user.isActive = true;
this._context.Set<User>().Attach(user);
Account account = new Account();
account.additionalType = "local";
account.email = dto.email;
account.password = dto.password;
account.userId = user.Id;
this._context.Set<Account>().Attach(account);
user.accounts.Add(account);
MovieList favoritesList = new MovieList();
favoritesList.additionalType = MovieList.FAVORITES;
favoritesList.owner = user;
this._context.Set<MovieList>().Attach(favoritesList);
MovieList watchList = new MovieList();
watchList.additionalType = MovieList.WATCHLIST;
watchList.owner = user;
this._context.Set<MovieList>().Attach(watchList);
await this._context.SaveChangesAsync();
await transaction.CommitAsync();
return new UserDto(user);
}
catch (Exception e)
{
await transaction.RollbackAsync();
throw new Exception(e.Message);
}
}
}
[Route("Login")]
[HttpPost]
public async Task<ActionResult<LoginResponseDto>> Login(LoginDto dto)
{
User user = await this._context.Users
.Where(u => dto.identifier == u.username && !u.isDeleted && !u.isDisabled && u.isActive)
.Include("accounts")
.Where(u => u.accounts.Any(a => a.password == dto.password))
.Include("person")
.FirstOrDefaultAsync();
if (!(user is null))
{
return new LoginResponseDto(this._authenticationService.GenerateJWT(new UserDto(user)), new UserDto(user));
}
Account account = await this._context.Accounts
.Where(a => a.email == dto.identifier && a.password == dto.password)
.FirstOrDefaultAsync();
if (account is null)
{
return Unauthorized();
}
else
{
User sUser = await this._context.Users
.Where(u => u.Id == account.userId && !u.isDeleted && !u.isDisabled && u.isActive)
.Include("person")
.FirstOrDefaultAsync();
return new LoginResponseDto(this._authenticationService.GenerateJWT(new UserDto(sUser)), new UserDto(sUser));
}
}
[Route("verify")]
[HttpGet]
public async Task<ActionResult<UserDto>> Verify() {
HttpContext localContext = this.HttpContext;
bool isAuthenticated = this.HttpContext.User.Identity.IsAuthenticated;
User user = this.HttpContext.Items["User"] as User;
if (isAuthenticated && !(user is null)) {
return new UserDto(user);
} else {
return Unauthorized();
}
}
}
public class RegisterDto
{
public string username { get; set; }
public string email { get; set; }
public string password { get; set; }
public string passwordRepeat { get; set; }
}
public class LoginDto
{
public string identifier { get; set; }
public string password { get; set; }
}
public class LoginResponseDto
{
public string token { get; set; }
public UserDto user { get; set; }
public LoginResponseDto() { }
public LoginResponseDto(string token, UserDto user)
{
this.token = token;
this.user = user;
}
}
}
| 29.08982 | 117 | 0.621449 | [
"MIT"
] | ADOPSE-Team17/not-imdb-backend | src/Controllers/AuthController.cs | 4,858 | C# |
namespace ImGuiNET
{
public enum ImGuiCol
{
Text = 0,
TextDisabled = 1,
WindowBg = 2,
ChildBg = 3,
PopupBg = 4,
Border = 5,
BorderShadow = 6,
FrameBg = 7,
FrameBgHovered = 8,
FrameBgActive = 9,
TitleBg = 10,
TitleBgActive = 11,
TitleBgCollapsed = 12,
MenuBarBg = 13,
ScrollbarBg = 14,
ScrollbarGrab = 15,
ScrollbarGrabHovered = 16,
ScrollbarGrabActive = 17,
CheckMark = 18,
SliderGrab = 19,
SliderGrabActive = 20,
Button = 21,
ButtonHovered = 22,
ButtonActive = 23,
Header = 24,
HeaderHovered = 25,
HeaderActive = 26,
Separator = 27,
SeparatorHovered = 28,
SeparatorActive = 29,
ResizeGrip = 30,
ResizeGripHovered = 31,
ResizeGripActive = 32,
Tab = 33,
TabHovered = 34,
TabActive = 35,
TabUnfocused = 36,
TabUnfocusedActive = 37,
PlotLines = 38,
PlotLinesHovered = 39,
PlotHistogram = 40,
PlotHistogramHovered = 41,
TextSelectedBg = 42,
DragDropTarget = 43,
NavHighlight = 44,
NavWindowingHighlight = 45,
NavWindowingDimBg = 46,
ModalWindowDimBg = 47,
COUNT = 48,
}
}
| 24.5 | 35 | 0.517493 | [
"MIT"
] | Arcnor/dear-imgui-unity | ImGuiNET/Wrapper/Generated/ImGuiCol.gen.cs | 1,372 | 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("FluentTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FluentTest")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2011")]
[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("245aef46-9f75-46ab-8f8d-eb747282aaac")]
// 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("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| 38.945946 | 85 | 0.727273 | [
"MIT"
] | andrewdavey/FluentTest | src/FluentTest/Properties/AssemblyInfo.cs | 1,444 | C# |
using System;
using System.Diagnostics;
using Windows.UI.Xaml.Controls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
using Xaml = Windows.UI.Xaml;
using MSCorp.FirstResponse.Client.UWP.Effects;
[assembly: ResolutionGroupName("FirstResponse")]
[assembly: ExportEffect(typeof(NativeStyleEffect), "NativeStyleEffect")]
namespace MSCorp.FirstResponse.Client.UWP.Effects
{
public class NativeStyleEffect : PlatformEffect
{
TextBox control;
protected override void OnAttached()
{
try
{
control = Control as TextBox;
var style = Xaml.Application.Current.Resources["FormTextBoxStyle"] as Xaml.Style;
control.Style = style;
}
catch (Exception ex)
{
Debug.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
protected override void OnDetached()
{
control = null;
}
}
}
| 26.763158 | 97 | 0.615536 | [
"MIT"
] | Bhaskers-Blu-Org2/demo-first-response-online | src/client/MSCorp.FirstResponse.Client.UWP/Effects/NativeStyleEffect.cs | 1,019 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Wafec.BobDog.Core.Common.Context.Identity
{
public class JwtPayload
{
public long Sequence { get; set; }
public string Name { get; set; }
}
}
| 19.153846 | 51 | 0.670683 | [
"MIT"
] | wafec/wafec-bobdog | WafecBobDogSolution/Wafec.BobDog.Core.Common/Context/Identity/JwtPayload.cs | 251 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Represents a field or constant.
/// </summary>
public interface IField : IMember, IVariable
{
/// <summary>
/// Gets the name of the field.
/// </summary>
new string Name { get; } // solve ambiguity between IMember.Name and IVariable.Name
/// <summary>
/// Gets whether this field is readonly.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Gets whether this field is volatile.
/// </summary>
bool IsVolatile { get; }
}
}
| 38.409091 | 93 | 0.729586 | [
"MIT"
] | AraHaan/ILSpy | ICSharpCode.Decompiler/TypeSystem/IField.cs | 1,692 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="InstanceSetActionPropertyStep.cs">
// SPDX-License-Identifier: MIT
// Copyright © 2019-2020 Esbjörn Redmo and contributors. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Mocklis.Steps.Lambda
{
#region Using Directives
using System;
using Mocklis.Core;
#endregion
/// <summary>
/// Class that represents a 'SetAction' property step, where the action receives a reference to the mock instance.
/// Inherits from the <see cref="PropertyStepWithNext{TValue}" /> class.
/// </summary>
/// <typeparam name="TValue">The type of the property.</typeparam>
/// <seealso cref="PropertyStepWithNext{TValue}" />
public class InstanceSetActionPropertyStep<TValue> : PropertyStepWithNext<TValue>
{
private readonly Action<object, TValue> _action;
/// <summary>
/// Initializes a new instance of the <see cref="SetActionPropertyStep{TValue}" /> class.
/// </summary>
/// <param name="action">An action to be invoked when the property is written to.</param>
public InstanceSetActionPropertyStep(Action<object, TValue> action)
{
_action = action ?? throw new ArgumentNullException(nameof(action));
}
/// <summary>
/// Called when a value is written to the property.
/// This implementation invokes the action with mock instance and the given value.
/// </summary>
/// <param name="mockInfo">Information about the mock through which the value is written.</param>
/// <param name="value">The value being written.</param>
public override void Set(IMockInfo mockInfo, TValue value)
{
_action(mockInfo.MockInstance, value);
}
}
}
| 41.875 | 122 | 0.570647 | [
"MIT"
] | eredmo/mocklis | src/Mocklis.BaseApi/Steps/Lambda/InstanceSetActionPropertyStep.cs | 2,012 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Eventarc.V1.Snippets
{
// [START eventarc_v1_generated_Eventarc_DeleteTrigger_async_flattened]
using Google.Cloud.Eventarc.V1;
using Google.LongRunning;
using System.Threading.Tasks;
public sealed partial class GeneratedEventarcClientSnippets
{
/// <summary>Snippet for DeleteTriggerAsync</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 DeleteTriggerAsync()
{
// Create client
EventarcClient eventarcClient = await EventarcClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/triggers/[TRIGGER]";
bool allowMissing = false;
// Make the request
Operation<Trigger, OperationMetadata> response = await eventarcClient.DeleteTriggerAsync(name, allowMissing);
// Poll until the returned long-running operation is complete
Operation<Trigger, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Trigger result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Trigger, OperationMetadata> retrievedResponse = await eventarcClient.PollOnceDeleteTriggerAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Trigger retrievedResult = retrievedResponse.Result;
}
}
}
// [END eventarc_v1_generated_Eventarc_DeleteTrigger_async_flattened]
}
| 44.4 | 133 | 0.687312 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Eventarc.V1/Google.Cloud.Eventarc.V1.GeneratedSnippets/EventarcClient.DeleteTriggerAsyncSnippet.g.cs | 2,664 | 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 Busy.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Busy.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;
}
}
}
}
| 44.28125 | 171 | 0.597742 | [
"MIT"
] | alibad/Blog | Windows Forms/Busy Form/Busy/Properties/Resources.Designer.cs | 2,836 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the query header to inspect. This setting must be provided as lower case characters.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
public WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentArgs()
{
}
}
}
| 39.730769 | 211 | 0.75605 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentArgs.cs | 1,033 | C# |
namespace Cosmos.I18N.Countries.Europe
{
/// <summary>
/// 法国(French Republic,欧洲,FR,FRA,250),法兰西共和国 <br />
/// Cosmos i18n code: i18n_country_faguo <br />
/// Cosmos region code: 200001
/// </summary>
public static partial class France
{
// ReSharper disable once InconsistentNaming
private static readonly CountryInfo _country;
static France()
{
_country = new CountryInfo
{
Country = Country.France,
CountryCode = CountryCode.FR,
CountryType = CountryType.Country,
BelongsToCountry = Country.France,
M49Code = "250",
Cep1CrCode = 2_00_001,
Alpha2Code = "FR",
Alpha3Code = "FRA",
Name = "French Republic",
ShorterForm = "France",
ChineseName = "法兰西共和国",
ChineseShorterForm = "法国",
ChineseAlias = "法兰西",
Continent = Continent.Europe,
I18NIdentityCode = I18N_IDENTITY_CODE,
GetRegionEnumValue = GetRegionEnumValue
};
}
/// <summary>
/// 法国(French Republic,欧洲,FR,FRA,250),法兰西共和国 <br />
/// Cosmos i18n code: i18n_country_faguo <br />
/// Cosmos region code: 200001
/// </summary>
public static CountryInfo Instance => _country;
/// <summary>
/// i18n
/// </summary>
// ReSharper disable once InconsistentNaming
public const string I18N_IDENTITY_CODE = "i18n_country_faguo";
/// <summary>
/// Get Cosmos Region Code (CEP-1/CRCode)
/// </summary>
public static long CosmosRegionCode => _country.Cep1CrCode;
/// <summary>
/// Get Cosmos Region Identity Code (CEP-1/IICode)
/// </summary>
public static string CosmosIdentityCode => _country.I18NIdentityCode;
/// <summary>
/// Get M49 code / ISO 3166-1 numeric
/// </summary>
public static string M49Code => _country.M49Code;
/// <summary>
/// Get Alpha2 code / ISO 3166-1 alpha-2
/// </summary>
public static string Alpha2Code => _country.Alpha2Code;
/// <summary>
/// Get Alpha3 code / ISO 3166-1 alpha-3
/// </summary>
public static string Alpha3Code => _country.Alpha3Code;
}
} | 33.040541 | 77 | 0.541922 | [
"Apache-2.0"
] | alexinea/I18N | src/Cosmos.I18N.Countries/Cosmos/I18N/Countries/Europe/France.cs | 2,535 | 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("SiteProvisioningWorkflowAppWebWeb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SiteProvisioningWorkflowAppWebWeb")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1bd5040-1ddc-41d1-9c29-efa06836171e")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.861111 | 84 | 0.756254 | [
"Apache-2.0"
] | AKrasheninnikov/PnP | Samples/Provisioning.Cloud.Workflow.AppWeb/Provisioning.Cloud.Workflow.AppWebWeb/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: mybank.finance.yulibao.capital.ransom
/// </summary>
public class MybankFinanceYulibaoCapitalRansomRequest : IAopRequest<MybankFinanceYulibaoCapitalRansomResponse>
{
/// <summary>
/// 网商银行余利宝赎回
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "mybank.finance.yulibao.capital.ransom";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.709091 | 114 | 0.607745 | [
"MIT"
] | BJDIIL/DiiL | Sdk/AlipaySdk/Request/MybankFinanceYulibaoCapitalRansomRequest.cs | 2,626 | C# |
using System;
using WildFarm.Models;
namespace WildFarm.Animals
{
public class Owl : Bird
{
public Owl(string name, double weight, double wingSize) : base(name, weight, wingSize)
{
WeightGain = 0.25;
}
public override void ProduceSound()
{
Console.WriteLine("Hoot Hoot");
}
}
}
| 19.210526 | 94 | 0.564384 | [
"MIT"
] | teodortenchev/C-Sharp-Advanced-Coursework | C# OOP Basics/Polymorphism/P3_WildFarm/Animals/Owl.cs | 367 | C# |
namespace HostSwitcher
{
partial class DetailsForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DetailsForm));
this.hostsDataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.hostsDataGridView)).BeginInit();
this.SuspendLayout();
//
// hostsDataGridView
//
this.hostsDataGridView.AllowUserToAddRows = false;
this.hostsDataGridView.AllowUserToDeleteRows = false;
this.hostsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.hostsDataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.hostsDataGridView.Location = new System.Drawing.Point(0, 0);
this.hostsDataGridView.Name = "hostsDataGridView";
this.hostsDataGridView.ReadOnly = true;
this.hostsDataGridView.Size = new System.Drawing.Size(562, 342);
this.hostsDataGridView.TabIndex = 0;
//
// DetailsForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(562, 342);
this.Controls.Add(this.hostsDataGridView);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "DetailsForm";
this.Text = "Decorated Host Details";
this.Load += new System.EventHandler(this.DetailsForm_Load);
((System.ComponentModel.ISupportInitialize)(this.hostsDataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView hostsDataGridView;
}
}
| 40.257143 | 143 | 0.618879 | [
"MIT"
] | smchristensen/HostSwitcher | HostSwitcher/DetailsForm.designer.cs | 2,820 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public class ExtendedEventPair : DynamicData
{
protected string _key;
protected string _value;
public string Key
{
get
{
return this._key;
}
set
{
this._key = value;
}
}
public string Value
{
get
{
return this._value;
}
set
{
this._value = value;
}
}
}
}
| 12.064516 | 45 | 0.596257 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/E/ExtendedEventPair.cs | 374 | C# |
namespace FaraMedia.Data.Schemas.ContentManagement {
using FaraMedia.Core.Domain.ContentManagement;
public sealed class PageConstants : UIElementConstantsBase<Page> {
public static class CacheKeys {
public static readonly string Pattern = Helpers.CachePattern();
public static readonly string ById = Helpers.CacheKey(p => p.Id);
}
public new sealed class Fields : UIElementConstantsBase<Page>.Fields {
public class Title {
public const int Length = 200;
public static readonly string Label = Helpers.Label<Title>();
}
public sealed class Body {
public static readonly string Label = Helpers.Label<Body>();
}
public sealed class Group {
public static readonly string Label = Helpers.Label<Group>();
}
}
}
} | 29.269231 | 72 | 0.726675 | [
"MIT"
] | m-sadegh-sh/FaraMedia | src/Libraries/FaraMedia.Data/Schemas/ContentManagement/PageConstants.fixed.cs | 761 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Compute.Latest.Inputs
{
/// <summary>
/// Profile for gallery sharing to subscription or tenant
/// </summary>
public sealed class SharingProfileArgs : Pulumi.ResourceArgs
{
/// <summary>
/// This property allows you to specify the permission of sharing gallery. <br><br> Possible values are: <br><br> **Private** <br><br> **Groups**
/// </summary>
[Input("permissions")]
public InputUnion<string, Pulumi.AzureNextGen.Compute.Latest.GallerySharingPermissionTypes>? Permissions { get; set; }
public SharingProfileArgs()
{
}
}
}
| 33.862069 | 189 | 0.674134 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/Latest/Inputs/SharingProfileArgs.cs | 982 | C# |
using System.Collections.Generic;
namespace prjDependencyInversionPrinciple
{
public interface IRelationshipBrowser
{
IEnumerable<Person> FindAllChildrenOf(string name);
}
}
| 19.6 | 59 | 0.755102 | [
"MIT"
] | luisferop/CsharpDesignPatterns | slnDesignPatterns/prjDependencyInversionPrinciple/IRelationshipBrowser.cs | 198 | C# |
using ProjectHermes.ShoppingList.Api.Domain.Common.Commands;
namespace ProjectHermes.ShoppingList.Api.Domain.StoreItems.Commands.CreateItem
{
public class CreateItemCommand : ICommand<bool>
{
public CreateItemCommand(ItemCreation itemCreation)
{
ItemCreation = itemCreation ?? throw new System.ArgumentNullException(nameof(itemCreation));
}
public ItemCreation ItemCreation { get; }
}
} | 31.785714 | 104 | 0.721348 | [
"MIT"
] | Velociraptor45/ProjectHermes-ShoppingList | Api/ShoppingList.Api.Domain/StoreItems/Commands/CreateItem/CreateItemCommand.cs | 447 | C# |
using TopModel.Core.Types;
using TopModel.Utils;
namespace TopModel.Core;
public interface IFieldProperty : IProperty
{
bool Required { get; }
Domain Domain { get; }
string? DefaultValue { get; }
TSType TS
{
get
{
if (Domain.TS == null)
{
throw new ModelException(Domain, $"Le type Typescript du domaine doit être renseigné.");
}
var fixedType = new TSType { Type = Domain.TS.Type, Import = Domain.TS.Import };
if (Domain.TS.Type == "string")
{
var prop = this is AliasProperty alp ? alp.Property : this;
if (prop is AssociationProperty ap && ap.Association.Reference && ap.Association.PrimaryKey!.Domain.Name != "DO_ID")
{
fixedType.Type = $"{ap.Association.Name}{ap.Association.PrimaryKey!.Name}";
}
else if (prop.PrimaryKey && prop.Class.Reference && prop.Class.PrimaryKey!.Domain.Name != "DO_ID")
{
fixedType.Type = $"{prop.Class.Name}{prop.Name}";
}
}
if (this is AliasProperty { ListDomain: not null })
{
fixedType.Type += "[]";
}
return fixedType;
}
}
IFieldProperty ResourceProperty => this is AliasProperty alp && alp.Label == alp.Property.Label
? alp.Property.ResourceProperty
: this;
string ResourceKey => $"{string.Join('.', ResourceProperty.Class.Namespace.Module.Split('.').Select(e => e.ToFirstLower()))}.{ResourceProperty.Class.Name.ToFirstLower()}.{ResourceProperty.Name.ToFirstLower()}";
string SqlName
{
get
{
var prop = !Class.IsPersistent && this is AliasProperty alp ? alp.Property : this;
return prop.Class.Extends != null && prop.PrimaryKey && Class.Trigram != null
? $"{Class.Trigram}_{ModelUtils.ConvertCsharp2Bdd(Name).Replace(prop.Class.SqlName + "_", string.Empty)}"
: prop is AssociationProperty ap
? ap.Association.PrimaryKey!.SqlName + (ap.Role != null ? $"_{ap.Role.Replace(" ", "_").ToUpper()}" : string.Empty)
: prop.Class.Trigram != null
? $"{prop.Class.Trigram}_{ModelUtils.ConvertCsharp2Bdd(prop.Name)}"
: ModelUtils.ConvertCsharp2Bdd(prop.Name);
}
}
string JavaName => this is AssociationProperty ap
? (ap.Association.Trigram?.ToLower().ToFirstUpper() ?? string.Empty) + ap.Association.PrimaryKey!.Name + (ap.Role?.Replace(" ", string.Empty) ?? string.Empty)
: (Class.Trigram?.ToLower().ToFirstUpper() ?? string.Empty) + Name;
} | 39.125 | 215 | 0.555911 | [
"MIT"
] | klee-contrib/topmodel | TopModel.Core/Model/IFieldProperty.cs | 2,821 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using VW.Interfaces;
using VW.Reflection;
using VW.Serializer.Intermediate;
namespace VW.Serializer
{
/// <summary>
/// Compiles a serializers for the given example user type.
/// </summary>
/// <typeparam name="TExample">The example user type.</typeparam>
/// <returns>A serializer for the given user example type.</returns>
internal sealed class VowpalWabbitSingleExampleSerializerCompiler<TExample> : IVowpalWabbitSerializerCompiler<TExample>
{
/// <summary>
/// Internal structure collecting all itmes required to marshal a single feature.
/// </summary>
internal sealed class FeatureExpressionInternal
{
/// <summary>
/// The supplied feature expression.
/// </summary>
internal FeatureExpression Source;
/// <summary>
/// The resolved mrarshalling method.
/// </summary>
internal MarshalMethod MarshalMethod;
}
/// <summary>
/// Describes the actual marshalling method and the feature type (e.g. <see cref="PreHashedFeature"/>).
/// </summary>
internal sealed class MarshalMethod
{
/// <summary>
/// The actual marshalling method.
/// </summary>
internal MethodInfo Method;
/// <summary>
/// The feature type (e.g. <see cref="PreHashedFeature"/>).
/// </summary>
internal Type MetaFeatureType;
}
/// <summary>
/// All discovered features.
/// </summary>
private FeatureExpressionInternal[] allFeatures;
private readonly Schema schema;
/// <summary>
/// Ordered list of featurizer types. Marshalling methods are resolved in order of this list.
/// <see cref="VowpalWabbitDefaultMarshaller"/> is added last as default.
/// </summary>
private readonly List<Type> marshallerTypes;
/// <summary>
/// The main body of the serializer holding preemptive calcutions (e.g. <see cref="PreHashedFeature"/>.
/// </summary>
private readonly List<Expression> body;
/// <summary>
/// The body executed for example.
/// </summary>
private readonly List<Expression> perExampleBody;
/// <summary>
/// Local variables.
/// </summary>
private readonly List<ParameterExpression> variables;
/// <summary>
/// Local variables holding namespaces.
/// </summary>
private readonly List<ParameterExpression> namespaceVariables;
/// <summary>
/// The parameter of the main lambda to <see cref="VowpalWabbit"/>.
/// </summary>
private ParameterExpression vwParameter;
/// <summary>
/// The parameter of the main lambda to <see cref="VowpalWabbitMarshalContext"/>.
/// </summary>
private ParameterExpression contextParameter;
/// <summary>
/// The parameter of the per example lambda to <see cref="VowpalWabbitExample"/>.
/// </summary>
private ParameterExpression exampleParameter;
/// <summary>
/// The parameter of the per example lambda to <see cref="ILabel"/>
/// </summary>
private ParameterExpression labelParameter;
/// <summary>
/// The list of featurizers.
/// </summary>
private readonly List<ParameterExpression> marshallers;
/// <summary>
/// The list of meta features such as <see cref="PreHashedFeature"/>.
/// </summary>
private readonly List<ParameterExpression> metaFeatures;
/// <summary>
/// If true, VowpalWabbit string generation is disabled.
/// </summary>
private readonly bool disableStringExampleGeneration;
internal VowpalWabbitSingleExampleSerializerCompiler(Schema schema, IReadOnlyList<Type> featurizerTypes, bool disableStringExampleGeneration)
{
if (schema == null || schema.Features.Count == 0)
throw new ArgumentException("schema");
Contract.EndContractBlock();
this.schema = schema;
this.disableStringExampleGeneration = disableStringExampleGeneration;
this.allFeatures = schema.Features.Select(f => new FeatureExpressionInternal { Source = f }).ToArray();
// collect the types used for marshalling
this.marshallerTypes = featurizerTypes == null ? new List<Type>() : new List<Type>(featurizerTypes);
// extract types from overrides defined on particular features
var overrideFeaturizerTypes = schema.Features
.Select(f => f.OverrideSerializeMethod)
.Where(o => o != null)
.Select(o => o.DeclaringType);
this.marshallerTypes.AddRange(overrideFeaturizerTypes);
// add as last
this.marshallerTypes.Add(typeof(VowpalWabbitDefaultMarshaller));
this.body = new List<Expression>();
this.perExampleBody = new List<Expression>();
this.variables = new List<ParameterExpression>();
this.namespaceVariables = new List<ParameterExpression>();
this.marshallers = new List<ParameterExpression>();
this.metaFeatures = new List<ParameterExpression>();
this.CreateMarshallers();
this.ResolveFeatureMarshallingMethods();
this.CreateParameters();
this.CreateLabel();
this.CreateNamespacesAndFeatures();
this.CreateLambdas();
this.Func = (Func<VowpalWabbit, Action<VowpalWabbitMarshalContext, TExample, ILabel>>)this.SourceExpression.CompileToFunc();
}
internal bool DisableStringExampleGeneration { get { return this.disableStringExampleGeneration; } }
/// <summary>
/// Creates a bound serializers.
/// </summary>
/// <param name="vw">The vw instance to bind to.</param>
/// <returns></returns>
IVowpalWabbitSerializer<TExample> IVowpalWabbitSerializerCompiler<TExample>.Create(VowpalWabbit vw)
{
return this.Create(vw);
}
public VowpalWabbitSingleExampleSerializer<TExample> Create(VowpalWabbit vw)
{
return new VowpalWabbitSingleExampleSerializer<TExample>(this, vw);
}
private void CreateLabel()
{
// CODE if (labelParameter == null)
this.perExampleBody.Add(Expression.IfThen(
Expression.NotEqual(this.labelParameter, Expression.Constant(null, typeof(ILabel))),
this.CreateMarshallerCall("MarshalLabel", this.contextParameter, this.labelParameter)));
var label = this.schema.Label;
if (label != null)
{
// CODE condition1 && condition2 && condition3 ...
var condition = label.ValueValidExpressionFactories
.Skip(1)
.Aggregate(
label.ValueValidExpressionFactories.First()(this.exampleParameter),
(cond, factory) => Expression.AndAlso(cond, factory(this.exampleParameter)));
// CODE if (labelParameter != null && example.Label != null && ...)
this.perExampleBody.Add(
Expression.IfThen(
Expression.AndAlso(
Expression.Equal(this.labelParameter, Expression.Constant(null, typeof(ILabel))),
condition),
// CODE MarshalLabel(context, example.Label)
this.CreateMarshallerCall("MarshalLabel",
this.contextParameter,
label.ValueExpressionFactory(this.exampleParameter))));
}
}
/// <summary>
/// Define variables and instantiate marshaller types.
/// </summary>
private void CreateMarshallers()
{
foreach (var marshallerType in this.marshallerTypes)
{
var marshaller = Expression.Parameter(marshallerType, "marshaller_" + marshallerType.Name);
this.marshallers.Add(marshaller);
this.variables.Add(marshaller);
// CODE new FeaturizerType(disableStringExampleGeneration)
var newExpr = CreateNew(marshallerType, Expression.Constant(disableStringExampleGeneration));
if (newExpr == null)
{
// CODE new MarshallerType()
newExpr = Expression.New(marshallerType);
}
// marshaller = new ...
this.body.Add(Expression.Assign(marshaller, newExpr));
}
}
private MarshalMethod ResolveFeatureMarshalMethod(FeatureExpression feature)
{
if (feature.OverrideSerializeMethod != null)
{
return new MarshalMethod
{
Method = feature.OverrideSerializeMethod,
MetaFeatureType = feature.OverrideSerializeMethod.GetParameters().Select(p => p.ParameterType).First(t => typeof(Feature).IsAssignableFrom(t))
};
}
string methodName;
Type[] metaFeatureTypeCandidates;
if (feature.FeatureType == typeof(string))
{
switch(feature.StringProcessing)
{
case StringProcessing.Escape:
methodName = "MarshalFeatureStringEscape";
break;
case StringProcessing.EscapeAndIncludeName:
methodName = "MarshalFeatureStringEscapeAndIncludeName";
break;
case StringProcessing.Split:
methodName = "MarshalFeatureStringSplit";
break;
default:
throw new ArgumentException("feature.StringProcessing is not supported: " + feature.StringProcessing);
}
metaFeatureTypeCandidates = new [] { typeof(Feature) };
}
else if (feature.FeatureType.IsEnum)
{
methodName = "MarshalEnumFeature";
metaFeatureTypeCandidates = new [] { typeof(EnumerizedFeature<>).MakeGenericType(feature.FeatureType) };
}
else if (feature.Enumerize)
{
methodName = "MarshalEnumerizeFeature";
metaFeatureTypeCandidates = new [] { typeof(Feature) };
}
else
{
// probe for PreHashedFeature marshal method, than fallback
methodName = "MarshalFeature";
metaFeatureTypeCandidates = new [] { typeof(PreHashedFeature), typeof(Feature) };
}
// remove Nullable<> from feature type
var featureType = feature.FeatureType;
if(featureType.IsGenericType &&
featureType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
featureType = featureType.GetGenericArguments()[0];
}
foreach (var metaFeatureType in metaFeatureTypeCandidates)
{
// find visitor.MarshalFeature(VowpalWabbitMarshallingContext context, Namespace ns, <PreHashedFeature|Feature> feature, <valueType> value)
var method = this.marshallerTypes
.Select(visitor => ReflectionHelper.FindMethod(
visitor,
methodName,
typeof(VowpalWabbitMarshalContext),
typeof(Namespace),
metaFeatureType,
featureType))
.FirstOrDefault(m => m != null);
if (method != null)
{
return new MarshalMethod
{
Method = method,
MetaFeatureType = metaFeatureType
};
}
}
return null;
}
/// <summary>
/// Resolve methods for each feature base on feature type and configuration.
/// </summary>
private void ResolveFeatureMarshallingMethods()
{
var validFeature = new List<FeatureExpressionInternal>(this.allFeatures.Length);
foreach (var feature in this.allFeatures)
{
feature.MarshalMethod = this.ResolveFeatureMarshalMethod(feature.Source);
if (feature.MarshalMethod != null)
validFeature.Add(feature);
}
this.allFeatures = validFeature.ToArray();
}
/// <summary>
/// define functions input parameter
/// </summary>
private void CreateParameters()
{
this.vwParameter = Expression.Parameter(typeof(VowpalWabbit), "vw");
this.contextParameter = Expression.Parameter(typeof(VowpalWabbitMarshalContext), "context");
this.exampleParameter = Expression.Parameter(typeof(TExample), "example");
this.labelParameter = Expression.Parameter(typeof(ILabel), "label");
}
/// <summary>
/// Instantiate the meta information object such as <see cref="PreHashedFeature"/>
/// for a given feature.
/// </summary>
/// <param name="featureInternal">The feature.</param>
/// <param name="namespace">The namespace.</param>
/// <returns>The "new" expression for the meta information object.</returns>
private Expression CreateFeature(FeatureExpressionInternal featureInternal, Expression @namespace)
{
FeatureExpression feature = featureInternal.Source;
var metaFeatureType = featureInternal.MarshalMethod.MetaFeatureType;
if (metaFeatureType.IsGenericType && metaFeatureType.GetGenericTypeDefinition() == typeof(EnumerizedFeature<>))
{
// preemptively calculate all hashes for each enum value
var featureParameter = Expression.Parameter(metaFeatureType);
var valueParameter = Expression.Parameter(feature.FeatureType);
var body = new List<Expression>();
var hashVariables = new List<ParameterExpression>();
foreach (var value in Enum.GetValues(feature.FeatureType))
{
var hashVar = Expression.Variable(typeof(UInt64));
hashVariables.Add(hashVar);
// CODE hashVar = feature.FeatureHashInternal(value);
body.Add(Expression.Assign(hashVar,
Expression.Call(featureParameter,
metaFeatureType.GetMethod("FeatureHashInternal"),
Expression.Constant(value))));
}
var cases = Enum.GetValues(feature.FeatureType)
.Cast<object>()
.Zip(hashVariables, (value, hash) => Expression.SwitchCase(
hash,
Expression.Constant(value, feature.FeatureType)))
.ToArray();
// expand the switch(value) { case enum1: return hash1; .... }
var hashSwitch = Expression.Switch(valueParameter,
Expression.Block(Expression.Throw(Expression.New(typeof(NotSupportedException))), Expression.Constant((UInt64)0, typeof(UInt64))),
cases);
// CODE return value => switch(value) { .... }
body.Add(Expression.Lambda(hashSwitch, valueParameter));
return CreateNew(
metaFeatureType,
this.vwParameter,
@namespace,
Expression.Constant(feature.Name, typeof(string)),
Expression.Constant(feature.AddAnchor),
Expression.Constant(feature.Dictify),
Expression.Lambda(Expression.Block(hashVariables, body), featureParameter));
}
else if (metaFeatureType == typeof(PreHashedFeature))
{
// CODE new PreHashedFeature(vw, namespace, "Name", "AddAnchor");
return CreateNew(
typeof(PreHashedFeature),
this.vwParameter,
@namespace,
Expression.Constant(feature.Name, typeof(string)),
Expression.Constant(feature.AddAnchor),
Expression.Constant(feature.Dictify));
}
else
// CODE new Feature("Name", ...)
return CreateNew(
metaFeatureType,
Expression.Constant(feature.Name, typeof(string)),
Expression.Constant(feature.AddAnchor),
Expression.Constant(feature.Dictify));
}
/// <summary>
/// Helper to create the "new" expression using a matching constructor.
/// </summary>
/// <param name="type">The type of the new object.</param>
/// <param name="constructorParameters">The actual parameters for the constructor.</param>
/// <returns>The "new" expression bound to <paramref name="constructorParameters"/>.</returns>
private static Expression CreateNew(Type type, params Expression[] constructorParameters)
{
var ctor = type.GetConstructor(constructorParameters.Select(e => e.Type).ToArray());
if (ctor == null)
return null;
return Expression.New(ctor, constructorParameters);
}
private void CreateNamespacesAndFeatures()
{
var featuresByNamespace = this.allFeatures.GroupBy(
f => new { f.Source.Namespace, f.Source.FeatureGroup },
f => f);
foreach (var ns in featuresByNamespace)
{
// each feature can have 2 additional parameters (namespace + feature)
// Visit(VowpalWabbit, CustomNamespace, CustomFeature)
// create default namespace object
var namespaceVariable = Expression.Variable(typeof(Namespace), "ns_" + ns.Key.FeatureGroup + ns.Key.Namespace);
this.variables.Add(namespaceVariable);
// CODE ns = new Namespace(vw, name, featureGroup);
this.body.Add(Expression.Assign(namespaceVariable,
CreateNew(
typeof(Namespace),
this.vwParameter,
Expression.Constant(ns.Key.Namespace, typeof(string)),
ns.Key.FeatureGroup == null ? (Expression)Expression.Constant(null, typeof(char?)) :
Expression.New((ConstructorInfo)ReflectionHelper.GetInfo((char v) => new char?(v)), Expression.Constant((char)ns.Key.FeatureGroup)))));
var featureVisits = new List<Expression>(ns.Count());
foreach (var feature in ns.OrderBy(f => f.Source.Order))
{
var newFeature = feature.Source.FeatureExpressionFactory != null ?
feature.Source.FeatureExpressionFactory(this.vwParameter, namespaceVariable) :
this.CreateFeature(feature, namespaceVariable);
var featureVariable = Expression.Variable(newFeature.Type, "feature_" + feature.Source.Name);
this.variables.Add(featureVariable);
// CODE var feature = new ...
this.body.Add(Expression.Assign(featureVariable, newFeature));
// TODO: optimize
var marshaller = this.marshallers.First(f => f.Type == feature.MarshalMethod.Method.ReflectedType);
var valueVariable = feature.Source.ValueExpressionFactory(this.exampleParameter);
Expression featureVisit;
if (feature.Source.IsNullable)
{
// if (value != null) featurzier.MarshalXXX(vw, context, ns, feature, (FeatureType)value);
featureVisit = Expression.IfThen(
Expression.NotEqual(valueVariable, Expression.Constant(null)),
Expression.Call(
marshaller,
feature.MarshalMethod.Method,
this.contextParameter,
namespaceVariable,
featureVariable,
Expression.Convert(valueVariable, feature.Source.FeatureType)));
}
else
{
// featurzier.MarshalXXX(vw, context, ns, feature, value);
featureVisit = Expression.Call(
marshaller,
feature.MarshalMethod.Method,
this.contextParameter,
namespaceVariable,
featureVariable,
valueVariable);
}
if (feature.Source.ValueValidExpressionFactories != null && feature.Source.ValueValidExpressionFactories.Count > 0)
{
// CODE condition1 && condition2 && condition3 ...
var condition = feature.Source.ValueValidExpressionFactories
.Skip(1)
.Aggregate(
feature.Source.ValueValidExpressionFactories.First()(this.exampleParameter),
(cond, factory) => Expression.AndAlso(cond, factory(this.exampleParameter)));
featureVisit = Expression.IfThen(condition, featureVisit);
}
featureVisits.Add(featureVisit);
}
var featureVisitLambda = Expression.Lambda(Expression.Block(featureVisits));
// CODE: featurizer.MarshalNamespace(context, namespace, { ... })
this.perExampleBody.Add(this.CreateMarshallerCall("MarshalNamespace", this.contextParameter, namespaceVariable, featureVisitLambda));
}
}
/// <summary>
/// Create the invocation expression of a marshalling method.
/// </summary>
/// <param name="methodName">The marshalling method to invoke.</param>
/// <param name="parameters">The parameters for this method.</param>
private MethodCallExpression CreateMarshallerCall(string methodName, params Expression[] parameters)
{
var parameterTypes = parameters.Select(p => p.Type).ToArray();
foreach (var marshaller in this.marshallers)
{
var method = marshaller.Type.GetMethod(methodName, parameterTypes);
if (method != null)
{
return Expression.Call(marshaller, method, parameters);
}
}
throw new ArgumentException("Unable to find MarshalNamespace(VowpalWabbitMarshallingContext, Namespace, Action) on any featurizer");
}
/// <summary>
/// Creates the main lambda and the per example lambda.
/// </summary>
private void CreateLambdas()
{
// CODE (TExample, Label) => { ... }
this.body.Add(
Expression.Lambda(
typeof(Action<VowpalWabbitMarshalContext, TExample, ILabel>),
Expression.Block(this.perExampleBody),
this.contextParameter, this.exampleParameter, this.labelParameter));
// CODE return (vw) => { ... return (ex, label) => { ... } }
this.SourceExpression = Expression.Lambda<Func<VowpalWabbit, Action<VowpalWabbitMarshalContext, TExample, ILabel>>>(
Expression.Block(this.variables, this.body), this.vwParameter);
}
/// <summary>
/// The source expression tree <seealso cref="Func"/> is built from.
/// </summary>
public Expression<Func<VowpalWabbit, Action<VowpalWabbitMarshalContext, TExample, ILabel>>> SourceExpression
{
get;
private set;
}
/// <summary>
/// The closure used for serialization.
/// </summary>
public Func<VowpalWabbit, Action<VowpalWabbitMarshalContext, TExample, ILabel>> Func
{
get;
private set;
}
}
}
| 42.944068 | 162 | 0.558077 | [
"BSD-3-Clause"
] | Sandy4321/vowpal_wabbit-1 | cs/cs/Serializer/VowpalWabbitSingleExampleSerializerCompiler.cs | 25,339 | C# |
// <auto-generated />
namespace Iris.DataLayer.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class ChangeItemCollactionConfig : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(ChangeItemCollactionConfig));
string IMigrationMetadata.Id
{
get { return "202005251226589_ChangeItemCollactionConfig"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 28.8 | 109 | 0.640046 | [
"MIT"
] | AmirCpu2/IrisStore | Iris.DataLayer/Migrations/202005251226589_ChangeItemCollactionConfig.Designer.cs | 864 | C# |
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using System;
using MongoDB.Driver;
using authServer.Models;
namespace authServer.Repositories
{
public class MongoPermissionRepository : IPermissionRepository
{
private const string collectionName = "Permissions";
private readonly IMongoCollection<Permission> collection;
private readonly FilterDefinitionBuilder<Permission> filterDefinitionBuilder = Builders<Permission>.Filter;
private readonly IUserRepository userRepository;
/// <summary>
/// initialisates the collection
/// </summary>
///
/// <param name="mongoClient">Correct MongoClient</param>
public MongoPermissionRepository(IMongoClient mongoClient)
{
IMongoDatabase database = mongoClient.GetDatabase(Startup.databaseName);
collection = database.GetCollection<Permission>(collectionName);
userRepository = new MongoDbUserRepository(mongoClient);
}
public async Task<string[]> getPermissions(Guid id)
{
var filter = filterDefinitionBuilder.Eq(permission => permission.id, id);
Permission permissions = await collection.Find(filter).SingleOrDefaultAsync();
return (permissions is null) ? new string[] { } : permissions.permissions;
}
public async Task addPermission(Guid id, string permission)
{
var filter = filterDefinitionBuilder.Eq(permission => permission.id, id);
Permission permissions = await collection.Find(filter).SingleOrDefaultAsync();
Permission newPermssions;
if (permissions is null)
{
newPermssions = new()
{
id = id,
permissions = new string[] { permission }
};
await collection.InsertOneAsync(newPermssions);
}
else
{
List<string> permissionsList = permissions.permissions.ToList();
permissionsList.Add(permission);
newPermssions = permissions with
{
permissions = permissionsList.ToArray()
};
await collection.ReplaceOneAsync(filter, newPermssions);
}
}
public async Task removePermission(Guid id, string permission)
{
User user = await userRepository.getUser(id);
if (user is null) throw new Exception("User does not exist");
var filter = filterDefinitionBuilder.Eq(permission => permission.id, user.id);
Permission permissions = await collection.Find(filter).SingleOrDefaultAsync();
if (permission is null) return;
List<string> permissionsList = permissions.permissions.ToList();
permissionsList.Remove(permission);
Permission newPermssions = permissions with
{
permissions = permissionsList.ToArray()
};
await collection.ReplaceOneAsync(filter, newPermssions);
}
public async Task<bool> hasPermission(Guid id, string permissionGroup, string permission)
{
string[] permissions = await getPermissions(id);
if (permission is null) return false;
if (Array.Exists(permissions, element => element == permissionGroup + ".*"
|| Array.Exists(permissions, element => element == permissionGroup + "." + permission)
|| Array.Exists(permissions, element => element == "*"))) return true;
if (permission == "?")
{
foreach (string perm in permissions)
{
if (perm.Split(".")[0] == permissionGroup) return true;
}
return false;
}
return false;
}
public async Task deletePermissionUser(Guid id)
{
await collection.DeleteOneAsync(user => user.id == id);
}
}
}
| 34.773109 | 115 | 0.589899 | [
"Apache-2.0"
] | mertdogan12/authServer | Repositories/MongoDbPermissionRepository.cs | 4,138 | C# |
// Copyright (c) Teroneko.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading.Tasks;
namespace Teronis.Microsoft.JSInterop.Dynamic.DynamicObjects
{
public interface IExplicitGenericConstrainedDynamicObject : IJSObjectReferenceFacade
{
ValueTask<T> TakeAndReturnBallast<T>(T ballast);
}
}
| 29.615385 | 101 | 0.771429 | [
"MIT"
] | teroneko/Teronis.DotNet | src/Microsoft/JSInterop/Dynamic/0/test/0/Dynamic/DynamicObjects/IExplicitGenericConstrainedDynamicObject.cs | 387 | C# |
//-----------------------------------------------------------------------
// <copyright file="MessageDispatchAndReceiveBenchmark.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.Actor.Dsl;
using Akka.Configuration;
using NBench;
namespace Akka.Tests.Performance.Dispatch
{
public class MessageDispatchAndReceiveBenchmark
{
protected ActorSystem System;
protected IActorRef TestActor;
protected Counter MsgReceived;
public static readonly Config Config = ConfigurationFactory.ParseString(@"
calling-thread-dispatcher{
executor="""+ typeof(CallingThreadExecutorConfigurator).AssemblyQualifiedName +@"""
throughput = 100
}
");
[PerfSetup]
public void Setup(BenchmarkContext context)
{
MsgReceived = context.GetCounter("MsgReceived");
System = ActorSystem.Create("PerfSys", Config);
Action<IActorDsl> actor = d => d.ReceiveAny((o, c) =>
{
MsgReceived.Increment();
});
TestActor = System.ActorOf(Props.Create(() => new Act(actor)).WithDispatcher("calling-thread-dispatcher"), "testactor");
// force initialization of the actor
TestActor.Tell("warmup");
MsgReceived.Decrement();
}
[PerfBenchmark(NumberOfIterations = 10, TestMode = TestMode.Measurement, RunMode = RunMode.Throughput, RunTimeMilliseconds = 1500, Skip = "Causes StackoverflowExceptions when coupled with CallingThreadDispatcher")]
[CounterMeasurement("MsgReceived")]
public void ActorMessagesPerSecond(BenchmarkContext context)
{
TestActor.Tell("hit");
}
[PerfCleanup]
public void TearDown()
{
System.Terminate().Wait();
}
}
}
| 34.983607 | 222 | 0.588097 | [
"Apache-2.0"
] | Flubik/akka.net | src/core/Akka.Tests.Performance/Dispatch/MessageDispatchAndReceiveBenchmark.cs | 2,136 | C# |
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Specifies options for the size of the stock icon.
/// </summary>
public enum StockIconSize
{
/// <summary>
/// Retrieve the small version of the icon, as specified by SM_CXSMICON and SM_CYSMICON system metrics.
/// </summary>
Small,
/// <summary>
/// Retrieve the large version of the icon, as specified by SM_CXICON and SM_CYICON system metrics.
/// </summary>
Large,
/// <summary>
/// Retrieve the shell-sized icons (instead of the size specified by the system metrics).
/// </summary>
ShellSize,
}
/// <summary>
/// Provides values used to specify which standard icon to retrieve.
/// </summary>
public enum StockIconIdentifier
{
/// <summary>
/// Icon for a document (blank page), no associated program.
/// </summary>
DocumentNotAssociated = 0,
/// <summary>
/// Icon for a document with an associated program.
/// </summary>
DocumentAssociated = 1,
/// <summary>
/// Icon for a generic application with no custom icon.
/// </summary>
Application = 2,
/// <summary>
/// Icon for a closed folder.
/// </summary>
Folder = 3,
/// <summary>
/// Icon for an open folder.
/// </summary>
FolderOpen = 4,
/// <summary>
/// Icon for a 5.25" floppy disk drive.
/// </summary>
Drive525 = 5,
/// <summary>
/// Icon for a 3.5" floppy disk drive.
/// </summary>
Drive35 = 6,
/// <summary>
/// Icon for a removable drive.
/// </summary>
DriveRemove = 7,
/// <summary>
/// Icon for a fixed (hard disk) drive.
/// </summary>
DriveFixed = 8,
/// <summary>
/// Icon for a network drive.
/// </summary>
DriveNetwork = 9,
/// <summary>
/// Icon for a disconnected network drive.
/// </summary>
DriveNetworkDisabled = 10,
/// <summary>
/// Icon for a CD drive.
/// </summary>
DriveCD = 11,
/// <summary>
/// Icon for a RAM disk drive.
/// </summary>
DriveRam = 12,
/// <summary>
/// Icon for an entire network.
/// </summary>
World = 13,
/// <summary>
/// Icon for a computer on the network.
/// </summary>
Server = 15,
/// <summary>
/// Icon for a printer.
/// </summary>
Printer = 16,
/// <summary>
/// Icon for My Network places.
/// </summary>
MyNetwork = 17,
/// <summary>
/// Icon for search (magnifying glass).
/// </summary>
Find = 22,
/// <summary>
/// Icon for help.
/// </summary>
Help = 23,
/// <summary>
/// Icon for an overlay indicating shared items.
/// </summary>
Share = 28,
/// <summary>
/// Icon for an overlay indicating shortcuts to items.
/// </summary>
Link = 29,
/// <summary>
/// Icon for an overlay for slow items.
/// </summary>
SlowFile = 30,
/// <summary>
/// Icon for a empty recycle bin.
/// </summary>
Recycler = 31,
/// <summary>
/// Icon for a full recycle bin.
/// </summary>
RecyclerFull = 32,
/// <summary>
/// Icon for audio CD media.
/// </summary>
MediaCDAudio = 40,
/// <summary>
/// Icon for a security lock.
/// </summary>
Lock = 47,
/// <summary>
/// Icon for a auto list.
/// </summary>
AutoList = 49,
/// <summary>
/// Icon for a network printer.
/// </summary>
PrinterNet = 50,
/// <summary>
/// Icon for a server share.
/// </summary>
ServerShare = 51,
/// <summary>
/// Icon for a Fax printer.
/// </summary>
PrinterFax = 52,
/// <summary>
/// Icon for a networked Fax printer.
/// </summary>
PrinterFaxNet = 53,
/// <summary>
/// Icon for print to file.
/// </summary>
PrinterFile = 54,
/// <summary>
/// Icon for a stack.
/// </summary>
Stack = 55,
/// <summary>
/// Icon for a SVCD media.
/// </summary>
MediaSvcd = 56,
/// <summary>
/// Icon for a folder containing other items.
/// </summary>
StuffedFolder = 57,
/// <summary>
/// Icon for an unknown drive.
/// </summary>
DriveUnknown = 58,
/// <summary>
/// Icon for a DVD drive.
/// </summary>
DriveDvd = 59,
/// <summary>
/// Icon for DVD media.
/// </summary>
MediaDvd = 60,
/// <summary>
/// Icon for DVD-RAM media.
/// </summary>
MediaDvdRam = 61,
/// <summary>
/// Icon for DVD-RW media.
/// </summary>
MediaDvdRW = 62,
/// <summary>
/// Icon for DVD-R media.
/// </summary>
MediaDvdR = 63,
/// <summary>
/// Icon for a DVD-ROM media.
/// </summary>
MediaDvdRom = 64,
/// <summary>
/// Icon for CD+ (Enhanced CD) media.
/// </summary>
MediaCDAudioPlus = 65,
/// <summary>
/// Icon for CD-RW media.
/// </summary>
MediaCDRW = 66,
/// <summary>
/// Icon for a CD-R media.
/// </summary>
MediaCDR = 67,
/// <summary>
/// Icon burning a CD.
/// </summary>
MediaCDBurn = 68,
/// <summary>
/// Icon for blank CD media.
/// </summary>
MediaBlankCD = 69,
/// <summary>
/// Icon for CD-ROM media.
/// </summary>
MediaCDRom = 70,
/// <summary>
/// Icon for audio files.
/// </summary>
AudioFiles = 71,
/// <summary>
/// Icon for image files.
/// </summary>
ImageFiles = 72,
/// <summary>
/// Icon for video files.
/// </summary>
VideoFiles = 73,
/// <summary>
/// Icon for mixed Files.
/// </summary>
MixedFiles = 74,
/// <summary>
/// Icon for a folder back.
/// </summary>
FolderBack = 75,
/// <summary>
/// Icon for a folder front.
/// </summary>
FolderFront = 76,
/// <summary>
/// Icon for a security shield. Use for UAC prompts only.
/// </summary>
Shield = 77,
/// <summary>
/// Icon for a warning.
/// </summary>
Warning = 78,
/// <summary>
/// Icon for an informational message.
/// </summary>
Info = 79,
/// <summary>
/// Icon for an error message.
/// </summary>
Error = 80,
/// <summary>
/// Icon for a key.
/// </summary>
Key = 81,
/// <summary>
/// Icon for software.
/// </summary>
Software = 82,
/// <summary>
/// Icon for a rename.
/// </summary>
Rename = 83,
/// <summary>
/// Icon for delete.
/// </summary>
Delete = 84,
/// <summary>
/// Icon for audio DVD media.
/// </summary>
MediaAudioDvd = 85,
/// <summary>
/// Icon for movie DVD media.
/// </summary>
MediaMovieDvd = 86,
/// <summary>
/// Icon for enhanced CD media.
/// </summary>
MediaEnhancedCD = 87,
/// <summary>
/// Icon for enhanced DVD media.
/// </summary>
MediaEnhancedDvd = 88,
/// <summary>
/// Icon for HD-DVD media.
/// </summary>
MediaHDDvd = 89,
/// <summary>
/// Icon for BluRay media.
/// </summary>
MediaBluRay = 90,
/// <summary>
/// Icon for VCD media.
/// </summary>
MediaVcd = 91,
/// <summary>
/// Icon for DVD+R media.
/// </summary>
MediaDvdPlusR = 92,
/// <summary>
/// Icon for DVD+RW media.
/// </summary>
MediaDvdPlusRW = 93,
/// <summary>
/// Icon for desktop computer.
/// </summary>
DesktopPC = 94,
/// <summary>
/// Icon for mobile computer (laptop/notebook).
/// </summary>
MobilePC = 95,
/// <summary>
/// Icon for users.
/// </summary>
Users = 96,
/// <summary>
/// Icon for smart media.
/// </summary>
MediaSmartMedia = 97,
/// <summary>
/// Icon for compact flash.
/// </summary>
MediaCompactFlash = 98,
/// <summary>
/// Icon for a cell phone.
/// </summary>
DeviceCellPhone = 99,
/// <summary>
/// Icon for a camera.
/// </summary>
DeviceCamera = 100,
/// <summary>
/// Icon for video camera.
/// </summary>
DeviceVideoCamera = 101,
/// <summary>
/// Icon for audio player.
/// </summary>
DeviceAudioPlayer = 102,
/// <summary>
/// Icon for connecting to network.
/// </summary>
NetworkConnect = 103,
/// <summary>
/// Icon for the Internet.
/// </summary>
Internet = 104,
/// <summary>
/// Icon for a ZIP file.
/// </summary>
ZipFile = 105,
/// <summary>
/// Icon for settings.
/// </summary>
Settings = 106,
// 107-131 are internal Vista RTM icons
// 132-159 for SP1 icons
/// <summary>
/// HDDVD Drive (all types)
/// </summary>
DriveHDDVD = 132,
/// <summary>
/// Icon for BluRay Drive (all types)
/// </summary>
DriveBluRay = 133,
/// <summary>
/// Icon for HDDVD-ROM Media
/// </summary>
MediaHDDVDROM = 134,
/// <summary>
/// Icon for HDDVD-R Media
/// </summary>
MediaHDDVDR = 135,
/// <summary>
/// Icon for HDDVD-RAM Media
/// </summary>
MediaHDDVDRAM = 136,
/// <summary>
/// Icon for BluRay ROM Media
/// </summary>
MediaBluRayROM = 137,
/// <summary>
/// Icon for BluRay R Media
/// </summary>
MediaBluRayR = 138,
/// <summary>
/// Icon for BluRay RE Media (Rewriable and RAM)
/// </summary>
MediaBluRayRE = 139,
/// <summary>
/// Icon for Clustered disk
/// </summary>
ClusteredDisk = 140,
}
}
| 27.866667 | 112 | 0.426606 | [
"Apache-2.0"
] | manuth/EnhanceForm | Microsoft.WindowsAPICodePack.Shell/StockIcons/StockIconEnums.cs | 11,706 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ampere
{
enum Suit
{
Clubs,
Hearts,
Diamonds,
Spades
}
enum Rank
{
Ace = 1,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
AcesHigh,
}
struct Card
{
public Suit Suit { get; }
public string SuitName => Suit.ToString();
public Rank Rank { get; }
public string RankName => Rank.ToString();
public Card(Suit suit, Rank rank)
{
Suit = suit;
Rank = rank;
}
}
class Deck
{
public List<Card> Cards { get; private set; }
public Deck() =>
Cards = new List<Card>(Suits().SelectMany(s => Ranks().Select(r => new Card(s, r))));
public Deck Shuffle()
{
Cards = new List<Card>(Cards.OrderBy(c => Rnd.Next));
return this;
}
public Card[] Draw(int count)
{
var cards = Cards.Take(count).ToArray();
Cards = Cards.Skip(count).ToList();
return cards;
}
private static IEnumerable<Rank> Ranks() =>
Enum.GetValues(typeof(Rank)).Cast<Rank>().Where(r => r != Rank.AcesHigh);
private static IEnumerable<Suit> Suits() =>
Enum.GetValues(typeof(Suit)).Cast<Suit>();
}
class CardSlot
{
public Card Card { get; set; }
public bool Keep { get; set; }
}
class Hand
{
public CardSlot[] CardSlots { get; }
private Card[] Cards => CardSlots.Select(cs => cs.Card).ToArray();
public Hand(Deck deck) =>
CardSlots = deck.Draw(5).Select(c => new CardSlot
{
Card = c,
Keep = false
}).ToArray();
public Hand Update(Deck deck)
{
var slotsToReplace = CardSlots.Where(c => !c.Keep);
if (!slotsToReplace.Any()) return this;
var newCards = new Queue<Card>(deck.Draw(slotsToReplace.Count()));
foreach (var slotToReplace in slotsToReplace)
slotToReplace.Card = newCards.Dequeue();
return this;
}
public (int Rank, bool HasHand, string Name)[] HandChecks =>
new[]
{
(0, true, "No Hand"),
(1, IsOnePair, "One Pair"),
(2, IsTwoPair, "Two Pair"),
(3, IsThreeOfAKind, "Three of a Kind"),
(4, IsStraight, "Straight"),
(5, IsFlush, "Flush"),
(6, IsFullHouse, "Full House"),
(7, IsFourOfAKind, "Four of a Kind"),
(8, IsStraightFlush, "Straight Flush"),
(9, IsRoyalFlush, "Royal Flush")
};
public bool IsOnePair => HasOfAKind(2);
public bool IsTwoPair =>
Cards.GroupBy(c => c.Rank).GroupBy(g => g.Count()).Any(g => g.Key == 2 && g.Count() == 2);
public bool IsThreeOfAKind => HasOfAKind(3);
public bool IsStraight => AreRanksSequential(Cards) ||
AreRanksSequential(Cards.Select(c => c.Rank == Rank.Ace ? new Card(c.Suit, Rank.AcesHigh) : c).ToArray());
public bool IsFlush =>
Cards.Select(c => c.Suit).Distinct().Count() == 1;
public bool IsFullHouse =>
IsThreeOfAKind && HasOfAKind(2);
public bool IsFourOfAKind => HasOfAKind(4);
public bool IsStraightFlush => IsFlush & IsStraight;
public bool IsRoyalFlush =>
IsStraightFlush && Cards.OrderBy(c => c.Rank).First().Rank == Rank.Ace &&
Cards.OrderByDescending(c => c.Rank).First().Rank == Rank.King;
private static bool AreRanksSequential(Card[] cards) =>
cards.Skip(1).Select((c, i) => c.Rank == (cards[i].Rank + 1)).All(x => x);
private bool HasOfAKind(int count) =>
Cards.GroupBy(c => c.Rank).Any(g => g.Count() == count);
}
class Pot
{
private List<IBettableItem> _items = new List<IBettableItem>();
public IEnumerable<IBettableItem> Items => _items;
internal void Add(params IBettableItem[] bet) => _items.AddRange(bet);
}
interface IBettableItem { }
interface IPokerPlayer
{
IBettableItem ReceiveAnte();
IBettableItem[] ReceiveBet(int allowedCards);
void ConfigureKeeps(Hand hand);
void Lose(Pot pot);
void Win(Pot pot);
void Tie();
}
class PokerRound
{
public Pot Pot { get; private set; }
public Hand PlayerHand { get; private set; }
public Hand OpponentHand { get; private set; }
public void Play(IPokerPlayer player, IPokerPlayer opponent)
{
Pot = new Pot();
Pot.Add(player.ReceiveAnte());
Pot.Add(opponent.ReceiveAnte());
var deck = new Deck().Shuffle();
PlayerHand = new Hand(deck);
OpponentHand = new Hand(deck);
Pot.Add(player.ReceiveBet(1));
var opponentBet = opponent.ReceiveBet(2);
Pot.Add(opponentBet);
if (opponentBet.Count() > 1)
Pot.Add(player.ReceiveBet(1));
player.ConfigureKeeps(this.PlayerHand);
PlayerHand.Update(deck);
opponent.ConfigureKeeps(this.OpponentHand);
OpponentHand.Update(deck);
var playerBet = player.ReceiveBet(1);
Pot.Add(playerBet);
if (playerBet.Any())
Pot.Add(opponent.ReceiveBet(1));
var playerHandValue = PlayerHand.HandChecks.Where(hc => hc.HasHand).OrderByDescending(hc => hc.Rank).FirstOrDefault();
var opponentHandValue = PlayerHand.HandChecks.Where(hc => hc.HasHand).OrderByDescending(hc => hc.Rank).FirstOrDefault();
if (playerHandValue.Rank < opponentHandValue.Rank)
{
player.Lose(Pot);
opponent.Win(Pot);
}
else if (playerHandValue.Rank > opponentHandValue.Rank)
{
player.Win(Pot);
opponent.Lose(Pot);
}
else
{
player.Tie();
opponent.Tie();
}
}
}
}
| 28.151515 | 132 | 0.52099 | [
"MIT"
] | srakowski/LD39 | Ampere/Ampere/Poker.cs | 6,505 | C# |
using System;
using System.Linq;
public class AppliedArithm
{
public static void Main()
{
var numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
string command;
while ((command = Console.ReadLine()) != "end")
{
switch (command)
{
case "add":
Func<int, int> add = n => n + 1;
ManipulateArray(numbers, add);
break;
case "multiply":
Func<int, int> multiply = n => n * 2;
ManipulateArray(numbers, multiply);
break;
case "subtract":
Func<int, int> subtract = n => n - 1;
ManipulateArray(numbers, subtract);
break;
case "print":
Console.WriteLine(string.Join(" ", numbers));
break;
default:
break;
}
}
}
private static void ManipulateArray(int[] numbers, Func<int, int> operation)
{
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = operation(numbers[i]);
}
}
} | 27.148936 | 80 | 0.418495 | [
"MIT"
] | PhilipYordanov/Software-University-C-Fundamentals-track | CSharpAdvance/Functional Programming - Exercises/FuncProgramming - Exercises/05. AppliedArithm/AppliedArithm.cs | 1,278 | C# |
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle(@"NuPattern.Runtime.RuntimeStore")]
[assembly: AssemblyDescription(@"")]
[assembly: AssemblyConfiguration("")]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo(@"NuPattern.Runtime.Core, PublicKey=00240000048000001401000006020000002400005253413100080000010001007beac0181d1669e636e92b9c5e54bd5fc1fd788892cbaa578d72a4a714a90d3a9d7eb67d976e216fe12435b42add0e9996668a611d761f48a872ff5c89d774f9d0efd7d6962c1bff84e2ce8229539f4da66204c7844511990057c6959fd62b5ce2a0c265ea633f4cd3ae1f292aefdb00b266c863f476f3c574573bb1bd36a8fa19d0de443658c262ecea16e7e502883ae071617300a6369a5b8590b71348c2053de41ab7a993a247443e010ebfafb2a21507d26334e968afa3bfbb47e10d9d0f9fd95d3d158e4645cf1d89c304792765e65904eb6be2be355e76d58756155ffa44fac32dd49ff7850bc1697b9ebde597a94d19f5f5131ce63e8a5f08bae616db")]
[assembly: InternalsVisibleTo(@"NuPattern.Runtime.UnitTests, PublicKey=00240000048000001401000006020000002400005253413100080000010001007beac0181d1669e636e92b9c5e54bd5fc1fd788892cbaa578d72a4a714a90d3a9d7eb67d976e216fe12435b42add0e9996668a611d761f48a872ff5c89d774f9d0efd7d6962c1bff84e2ce8229539f4da66204c7844511990057c6959fd62b5ce2a0c265ea633f4cd3ae1f292aefdb00b266c863f476f3c574573bb1bd36a8fa19d0de443658c262ecea16e7e502883ae071617300a6369a5b8590b71348c2053de41ab7a993a247443e010ebfafb2a21507d26334e968afa3bfbb47e10d9d0f9fd95d3d158e4645cf1d89c304792765e65904eb6be2be355e76d58756155ffa44fac32dd49ff7850bc1697b9ebde597a94d19f5f5131ce63e8a5f08bae616db")]
[assembly: InternalsVisibleTo(@"NuPattern.Runtime.IntegrationTests, PublicKey=00240000048000001401000006020000002400005253413100080000010001007beac0181d1669e636e92b9c5e54bd5fc1fd788892cbaa578d72a4a714a90d3a9d7eb67d976e216fe12435b42add0e9996668a611d761f48a872ff5c89d774f9d0efd7d6962c1bff84e2ce8229539f4da66204c7844511990057c6959fd62b5ce2a0c265ea633f4cd3ae1f292aefdb00b266c863f476f3c574573bb1bd36a8fa19d0de443658c262ecea16e7e502883ae071617300a6369a5b8590b71348c2053de41ab7a993a247443e010ebfafb2a21507d26334e968afa3bfbb47e10d9d0f9fd95d3d158e4645cf1d89c304792765e65904eb6be2be355e76d58756155ffa44fac32dd49ff7850bc1697b9ebde597a94d19f5f5131ce63e8a5f08bae616db")]
[assembly: InternalsVisibleTo(@"NuPattern.Runtime.Extensibility.UnitTests, PublicKey=00240000048000001401000006020000002400005253413100080000010001007beac0181d1669e636e92b9c5e54bd5fc1fd788892cbaa578d72a4a714a90d3a9d7eb67d976e216fe12435b42add0e9996668a611d761f48a872ff5c89d774f9d0efd7d6962c1bff84e2ce8229539f4da66204c7844511990057c6959fd62b5ce2a0c265ea633f4cd3ae1f292aefdb00b266c863f476f3c574573bb1bd36a8fa19d0de443658c262ecea16e7e502883ae071617300a6369a5b8590b71348c2053de41ab7a993a247443e010ebfafb2a21507d26334e968afa3bfbb47e10d9d0f9fd95d3d158e4645cf1d89c304792765e65904eb6be2be355e76d58756155ffa44fac32dd49ff7850bc1697b9ebde597a94d19f5f5131ce63e8a5f08bae616db")]
[assembly: InternalsVisibleTo(@"NuPattern.Runtime.Extensibility.IntegrationTests, PublicKey=00240000048000001401000006020000002400005253413100080000010001007beac0181d1669e636e92b9c5e54bd5fc1fd788892cbaa578d72a4a714a90d3a9d7eb67d976e216fe12435b42add0e9996668a611d761f48a872ff5c89d774f9d0efd7d6962c1bff84e2ce8229539f4da66204c7844511990057c6959fd62b5ce2a0c265ea633f4cd3ae1f292aefdb00b266c863f476f3c574573bb1bd36a8fa19d0de443658c262ecea16e7e502883ae071617300a6369a5b8590b71348c2053de41ab7a993a247443e010ebfafb2a21507d26334e968afa3bfbb47e10d9d0f9fd95d3d158e4645cf1d89c304792765e65904eb6be2be355e76d58756155ffa44fac32dd49ff7850bc1697b9ebde597a94d19f5f5131ce63e8a5f08bae616db")]
[assembly: InternalsVisibleTo(@"NuPattern.Library.UnitTests, PublicKey=00240000048000001401000006020000002400005253413100080000010001007beac0181d1669e636e92b9c5e54bd5fc1fd788892cbaa578d72a4a714a90d3a9d7eb67d976e216fe12435b42add0e9996668a611d761f48a872ff5c89d774f9d0efd7d6962c1bff84e2ce8229539f4da66204c7844511990057c6959fd62b5ce2a0c265ea633f4cd3ae1f292aefdb00b266c863f476f3c574573bb1bd36a8fa19d0de443658c262ecea16e7e502883ae071617300a6369a5b8590b71348c2053de41ab7a993a247443e010ebfafb2a21507d26334e968afa3bfbb47e10d9d0f9fd95d3d158e4645cf1d89c304792765e65904eb6be2be355e76d58756155ffa44fac32dd49ff7850bc1697b9ebde597a94d19f5f5131ce63e8a5f08bae616db")]
[assembly: InternalsVisibleTo(@"NuPattern.Library.IntegrationTests, PublicKey=00240000048000001401000006020000002400005253413100080000010001007beac0181d1669e636e92b9c5e54bd5fc1fd788892cbaa578d72a4a714a90d3a9d7eb67d976e216fe12435b42add0e9996668a611d761f48a872ff5c89d774f9d0efd7d6962c1bff84e2ce8229539f4da66204c7844511990057c6959fd62b5ce2a0c265ea633f4cd3ae1f292aefdb00b266c863f476f3c574573bb1bd36a8fa19d0de443658c262ecea16e7e502883ae071617300a6369a5b8590b71348c2053de41ab7a993a247443e010ebfafb2a21507d26334e968afa3bfbb47e10d9d0f9fd95d3d158e4645cf1d89c304792765e65904eb6be2be355e76d58756155ffa44fac32dd49ff7850bc1697b9ebde597a94d19f5f5131ce63e8a5f08bae616db")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] | 291 | 671 | 0.967545 | [
"Apache-2.0"
] | dbremner/nupattern | Src/Runtime/Source/Runtime.Store/Properties/AssemblyInfo.cs | 5,238 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#pragma warning disable CS0675 // Bitwise-or operator used on a sign-extended operand
namespace UnlockECU
{
/// <summary>
/// RDU222: seed |= A, ^= B, += C
/// </summary>
class RDU222 : SecurityProvider
{
public override bool GenerateKey(byte[] inSeed, byte[] outKey, int accessLevel, List<Parameter> parameters)
{
long paramA = BytesToInt(GetParameterBytearray(parameters, "a"), Endian.Big);
long paramB = BytesToInt(GetParameterBytearray(parameters, "b"), Endian.Big);
long paramC = BytesToInt(GetParameterBytearray(parameters, "c"), Endian.Big);
if ((inSeed.Length != 4) || (outKey.Length != 4))
{
return false;
}
long inSeedAsLong = BytesToInt(inSeed, Endian.Big);
inSeedAsLong |= paramA;
inSeedAsLong ^= paramB;
inSeedAsLong += paramC;
IntToBytes((uint)inSeedAsLong, outKey, Endian.Big);
return true;
}
public override string GetProviderName()
{
return "RDU222";
}
}
}
| 29.547619 | 115 | 0.593876 | [
"MIT"
] | ecumasterac/UnlockECU | UnlockECU/UnlockECU/Security/RDU222.cs | 1,243 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3dcommon.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
namespace TerraFX.Interop.DirectX;
/// <include file='D3D_SHADER_CBUFFER_FLAGS.xml' path='doc/member[@name="D3D_SHADER_CBUFFER_FLAGS"]/*' />
[Flags]
public enum D3D_SHADER_CBUFFER_FLAGS
{
/// <include file='D3D_SHADER_CBUFFER_FLAGS.xml' path='doc/member[@name="D3D_SHADER_CBUFFER_FLAGS.D3D_CBF_USERPACKED"]/*' />
D3D_CBF_USERPACKED = 1,
/// <include file='D3D_SHADER_CBUFFER_FLAGS.xml' path='doc/member[@name="D3D_SHADER_CBUFFER_FLAGS.D3D10_CBF_USERPACKED"]/*' />
D3D10_CBF_USERPACKED = D3D_CBF_USERPACKED,
/// <include file='D3D_SHADER_CBUFFER_FLAGS.xml' path='doc/member[@name="D3D_SHADER_CBUFFER_FLAGS.D3D_CBF_FORCE_DWORD"]/*' />
D3D_CBF_FORCE_DWORD = 0x7fffffff,
}
| 43.434783 | 145 | 0.761762 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/d3dcommon/D3D_SHADER_CBUFFER_FLAGS.cs | 1,001 | C# |
#nullable enable
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Android.Content;
using Android.Content.Res;
using Android.Provider;
using Android.Runtime;
using Android.Util;
using Android.Views;
namespace Microsoft.Maui.Essentials
{
partial class DeviceDisplayImplementation : IDeviceDisplay
{
OrientationEventListener? orientationListener;
public event EventHandler<DisplayInfoChangedEventArgs>? MainDisplayInfoChanged;
public bool KeepScreenOn
{
get
{
var window = Platform.GetCurrentActivity(true)?.Window;
var flags = window?.Attributes?.Flags ?? 0;
return flags.HasFlag(WindowManagerFlags.KeepScreenOn);
}
set
{
var window = Platform.GetCurrentActivity(true)?.Window;
if (value)
window?.AddFlags(WindowManagerFlags.KeepScreenOn);
else
window?.ClearFlags(WindowManagerFlags.KeepScreenOn);
}
}
public DisplayInfo GetMainDisplayInfo()
{
using var displayMetrics = new DisplayMetrics();
var display = GetDefaultDisplay();
#pragma warning disable CS0618 // Type or member is obsolete
display?.GetRealMetrics(displayMetrics);
#pragma warning restore CS0618 // Type or member is obsolete
return new DisplayInfo(
width: displayMetrics?.WidthPixels ?? 0,
height: displayMetrics?.HeightPixels ?? 0,
density: displayMetrics?.Density ?? 0,
orientation: CalculateOrientation(),
rotation: CalculateRotation(),
rate: display?.RefreshRate ?? 0);
}
public void StartScreenMetricsListeners()
{
orientationListener = new Listener(Platform.AppContext, OnScreenMetricsChanged);
orientationListener.Enable();
}
public void StopScreenMetricsListeners()
{
orientationListener?.Disable();
orientationListener?.Dispose();
orientationListener = null;
}
void OnScreenMetricsChanged()
{
var metrics = GetMainDisplayInfo();
MainDisplayInfoChanged?.Invoke(this, new DisplayInfoChangedEventArgs(metrics));
}
DisplayRotation CalculateRotation()
{
var display = GetDefaultDisplay();
return display?.Rotation switch
{
SurfaceOrientation.Rotation270 => DisplayRotation.Rotation270,
SurfaceOrientation.Rotation180 => DisplayRotation.Rotation180,
SurfaceOrientation.Rotation90 => DisplayRotation.Rotation90,
SurfaceOrientation.Rotation0 => DisplayRotation.Rotation0,
_ => DisplayRotation.Unknown,
};
}
DisplayOrientation CalculateOrientation()
{
return Platform.AppContext.Resources?.Configuration?.Orientation switch
{
Orientation.Landscape => DisplayOrientation.Landscape,
Orientation.Portrait => DisplayOrientation.Portrait,
Orientation.Square => DisplayOrientation.Portrait,
_ => DisplayOrientation.Unknown
};
}
Display? GetDefaultDisplay()
{
try
{
using var service = Platform.AppContext.GetSystemService(Context.WindowService);
using var windowManager = service?.JavaCast<IWindowManager>();
return windowManager?.DefaultDisplay;
}
catch (Exception ex)
{
Debug.WriteLine($"Unable to get default display: {ex}");
return null;
}
}
}
class Listener : OrientationEventListener
{
readonly Action onChanged;
internal Listener(Context context, Action handler)
: base(context) => onChanged = handler;
public override async void OnOrientationChanged(int orientation)
{
await Task.Delay(500);
onChanged();
}
}
}
| 26.161538 | 84 | 0.739782 | [
"MIT"
] | 41396/maui | src/Essentials/src/DeviceDisplay/DeviceDisplay.android.cs | 3,401 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("05. Teamwork projects")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("05. Teamwork projects")]
[assembly: System.Reflection.AssemblyTitleAttribute("05. Teamwork projects")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 43.166667 | 81 | 0.635135 | [
"MIT"
] | dradoslavov/Technology-Fundamentals | 07.Objects and Classes - Exercise/05. Teamwork projects/obj/Debug/netcoreapp2.1/05. Teamwork projects.AssemblyInfo.cs | 1,036 | 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;
namespace RunTests
{
internal sealed class ProcessTestExecutor
{
public TestExecutionOptions Options { get; }
internal ProcessTestExecutor(TestExecutionOptions options)
{
Options = options;
}
public string GetCommandLineArguments(AssemblyInfo assemblyInfo, bool useSingleQuotes)
{
// http://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html
// Single quotes are needed in bash to avoid the need to escape characters such as backtick (`) which are found in metadata names.
// Batch scripts don't need to worry about escaping backticks, but they don't support single quoted strings, so we have to use double quotes.
// We also need double quotes when building an arguments string for Process.Start in .NET Core so that splitting/unquoting works as expected.
var sep = useSingleQuotes ? "'" : @"""";
var builder = new StringBuilder();
builder.Append($@"test");
builder.Append($@" {sep}{assemblyInfo.AssemblyName}{sep}");
var typeInfoList = assemblyInfo.PartitionInfo.TypeInfoList;
if (typeInfoList.Length > 0 || !string.IsNullOrWhiteSpace(Options.TestFilter))
{
builder.Append($@" --filter {sep}");
var any = false;
foreach (var typeInfo in typeInfoList)
{
MaybeAddSeparator();
builder.Append(typeInfo.FullName);
}
builder.Append(sep);
if (Options.TestFilter is object)
{
MaybeAddSeparator();
builder.Append(Options.TestFilter);
}
void MaybeAddSeparator(char separator = '|')
{
if (any)
{
builder.Append(separator);
}
any = true;
}
}
builder.Append($@" --framework {assemblyInfo.TargetFramework}");
builder.Append($@" --logger {sep}xunit;LogFilePath={GetResultsFilePath(assemblyInfo, "xml")}{sep}");
if (Options.IncludeHtml)
{
builder.AppendFormat($@" --logger {sep}html;LogFileName={GetResultsFilePath(assemblyInfo, "html")}{sep}");
}
// The 25 minute timeout accounts for the fact that VSIX deployment and/or experimental hive reset and
// configuration can take significant time (seems to vary from ~10 seconds to ~15 minutes), and the blame
// functionality cannot separate this configuration overhead from the first test which will eventually run.
// https://github.com/dotnet/roslyn/issues/59851
builder.Append(" --blame-crash --blame-hang-dump-type full --blame-hang-timeout 25minutes");
return builder.ToString();
}
private string GetResultsFilePath(AssemblyInfo assemblyInfo, string suffix = "xml")
{
var fileName = $"{assemblyInfo.DisplayName}_{assemblyInfo.TargetFramework}_{assemblyInfo.Platform}_test_results.{suffix}";
return Path.Combine(Options.TestResultsDirectory, fileName);
}
public async Task<TestResult> RunTestAsync(AssemblyInfo assemblyInfo, CancellationToken cancellationToken)
{
var result = await RunTestAsyncInternal(assemblyInfo, retry: false, cancellationToken);
// For integration tests (TestVsi), we make one more attempt to re-run failed tests.
if (Options.Retry && !Options.IncludeHtml && !result.Succeeded)
{
return await RunTestAsyncInternal(assemblyInfo, retry: true, cancellationToken);
}
return result;
}
private async Task<TestResult> RunTestAsyncInternal(AssemblyInfo assemblyInfo, bool retry, CancellationToken cancellationToken)
{
try
{
var commandLineArguments = GetCommandLineArguments(assemblyInfo, useSingleQuotes: false);
var resultsFilePath = GetResultsFilePath(assemblyInfo);
var resultsDir = Path.GetDirectoryName(resultsFilePath);
var htmlResultsFilePath = Options.IncludeHtml ? GetResultsFilePath(assemblyInfo, "html") : null;
var processResultList = new List<ProcessResult>();
ProcessInfo? procDumpProcessInfo = null;
// NOTE: xUnit doesn't always create the log directory
Directory.CreateDirectory(resultsDir!);
// Define environment variables for processes started via ProcessRunner.
var environmentVariables = new Dictionary<string, string>();
Options.ProcDumpInfo?.WriteEnvironmentVariables(environmentVariables);
if (retry && File.Exists(resultsFilePath))
{
ConsoleUtil.WriteLine("Starting a retry. Tests which failed will run a second time to reduce flakiness.");
try
{
var doc = XDocument.Load(resultsFilePath);
foreach (var test in doc.XPathSelectElements("/assemblies/assembly/collection/test[@result='Fail']"))
{
ConsoleUtil.WriteLine($" {test.Attribute("name")!.Value}: {test.Attribute("result")!.Value}");
}
}
catch
{
ConsoleUtil.WriteLine(" ...Failed to identify the list of specific failures.");
}
// Copy the results file path, since the new xunit run will overwrite it
var backupResultsFilePath = Path.ChangeExtension(resultsFilePath, ".old");
File.Copy(resultsFilePath, backupResultsFilePath, overwrite: true);
// If running the process with this varialbe added, we assume that this file contains
// xml logs from the first attempt.
environmentVariables.Add("OutputXmlFilePath", backupResultsFilePath);
}
// NOTE: xUnit seems to have an occasional issue creating logs create
// an empty log just in case, so our runner will still fail.
File.Create(resultsFilePath).Close();
var start = DateTime.UtcNow;
var dotnetProcessInfo = ProcessRunner.CreateProcess(
ProcessRunner.CreateProcessStartInfo(
Options.DotnetFilePath,
commandLineArguments,
workingDirectory: Path.GetDirectoryName(assemblyInfo.AssemblyPath),
displayWindow: false,
captureOutput: true,
environmentVariables: environmentVariables),
lowPriority: false,
cancellationToken: cancellationToken);
Logger.Log($"Create xunit process with id {dotnetProcessInfo.Id} for test {assemblyInfo.DisplayName}");
var xunitProcessResult = await dotnetProcessInfo.Result;
var span = DateTime.UtcNow - start;
Logger.Log($"Exit xunit process with id {dotnetProcessInfo.Id} for test {assemblyInfo.DisplayName} with code {xunitProcessResult.ExitCode}");
processResultList.Add(xunitProcessResult);
if (procDumpProcessInfo != null)
{
var procDumpProcessResult = await procDumpProcessInfo.Value.Result;
Logger.Log($"Exit procdump process with id {procDumpProcessInfo.Value.Id} for {dotnetProcessInfo.Id} for test {assemblyInfo.DisplayName} with code {procDumpProcessResult.ExitCode}");
processResultList.Add(procDumpProcessResult);
}
if (xunitProcessResult.ExitCode != 0)
{
// On occasion we get a non-0 output but no actual data in the result file. The could happen
// if xunit manages to crash when running a unit test (a stack overflow could cause this, for instance).
// To avoid losing information, write the process output to the console. In addition, delete the results
// file to avoid issues with any tool attempting to interpret the (potentially malformed) text.
var resultData = string.Empty;
try
{
resultData = File.ReadAllText(resultsFilePath).Trim();
}
catch
{
// Happens if xunit didn't produce a log file
}
if (resultData.Length == 0)
{
// Delete the output file.
File.Delete(resultsFilePath);
resultsFilePath = null;
htmlResultsFilePath = null;
}
}
Logger.Log($"Command line {assemblyInfo.DisplayName} completed in {span.TotalSeconds} seconds: {Options.DotnetFilePath} {commandLineArguments}");
var standardOutput = string.Join(Environment.NewLine, xunitProcessResult.OutputLines) ?? "";
var errorOutput = string.Join(Environment.NewLine, xunitProcessResult.ErrorLines) ?? "";
var testResultInfo = new TestResultInfo(
exitCode: xunitProcessResult.ExitCode,
resultsFilePath: resultsFilePath,
htmlResultsFilePath: htmlResultsFilePath,
elapsed: span,
standardOutput: standardOutput,
errorOutput: errorOutput);
return new TestResult(
assemblyInfo,
testResultInfo,
commandLineArguments,
processResults: ImmutableArray.CreateRange(processResultList));
}
catch (Exception ex)
{
throw new Exception($"Unable to run {assemblyInfo.AssemblyPath} with {Options.DotnetFilePath}. {ex}");
}
}
}
}
| 47.929825 | 202 | 0.581168 | [
"MIT"
] | Ruffo324/roslyn | src/Tools/Source/RunTests/ProcessTestExecutor.cs | 10,930 | C# |
/*
* Copyright 2012-2017 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI81;
using NUnit.Framework;
using NativeULong = System.UInt64;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI81
{
/// <summary>
/// C_Login and C_Logout tests.
/// </summary>
[TestFixture()]
public class _08_LoginTest
{
/// <summary>
/// Normal user C_Login and C_Logout test.
/// </summary>
[Test()]
public void _01_NormalUserLoginTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs81);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, CKF.CKF_SERIAL_SESSION, IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, NativeLongUtils.ConvertFromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting as normal user
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// Security officer C_Login and C_Logout test.
/// </summary>
[Test()]
public void _02_SecurityOfficerLoginTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs81);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as SO (security officer)
rv = pkcs11.C_Login(session, CKU.CKU_SO, Settings.SecurityOfficerPinArray, NativeLongUtils.ConvertFromInt32(Settings.SecurityOfficerPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting as security officer
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| 37.125 | 166 | 0.539562 | [
"Apache-2.0"
] | arkkadin/pkcs11Interop | src/Pkcs11Interop/Pkcs11InteropTests/LowLevelAPI81/_08_LoginTest.cs | 4,752 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
using Pulumi.Utilities;
namespace Pulumi.Yandex
{
public static class GetMdbSqlserverCluster
{
/// <summary>
/// Get information about a Yandex Managed SQLServer cluster. For more information, see
/// [the official documentation](https://cloud.yandex.com/docs/managed-sqlserver/).
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Yandex = Pulumi.Yandex;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var foo = Output.Create(Yandex.GetMdbSqlserverCluster.InvokeAsync(new Yandex.GetMdbSqlserverClusterArgs
/// {
/// Name = "test",
/// }));
/// this.NetworkId = foo.Apply(foo => foo.NetworkId);
/// }
///
/// [Output("networkId")]
/// public Output<string> NetworkId { get; set; }
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetMdbSqlserverClusterResult> InvokeAsync(GetMdbSqlserverClusterArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetMdbSqlserverClusterResult>("yandex:index/getMdbSqlserverCluster:getMdbSqlserverCluster", args ?? new GetMdbSqlserverClusterArgs(), options.WithVersion());
/// <summary>
/// Get information about a Yandex Managed SQLServer cluster. For more information, see
/// [the official documentation](https://cloud.yandex.com/docs/managed-sqlserver/).
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Yandex = Pulumi.Yandex;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var foo = Output.Create(Yandex.GetMdbSqlserverCluster.InvokeAsync(new Yandex.GetMdbSqlserverClusterArgs
/// {
/// Name = "test",
/// }));
/// this.NetworkId = foo.Apply(foo => foo.NetworkId);
/// }
///
/// [Output("networkId")]
/// public Output<string> NetworkId { get; set; }
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Output<GetMdbSqlserverClusterResult> Invoke(GetMdbSqlserverClusterInvokeArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetMdbSqlserverClusterResult>("yandex:index/getMdbSqlserverCluster:getMdbSqlserverCluster", args ?? new GetMdbSqlserverClusterInvokeArgs(), options.WithVersion());
}
public sealed class GetMdbSqlserverClusterArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The ID of the SQLServer cluster.
/// </summary>
[Input("clusterId")]
public string? ClusterId { get; set; }
[Input("deletionProtection")]
public bool? DeletionProtection { get; set; }
/// <summary>
/// The ID of the folder that the resource belongs to. If it is not provided, the default provider folder is used.
/// </summary>
[Input("folderId")]
public string? FolderId { get; set; }
/// <summary>
/// The name of the SQLServer cluster.
/// </summary>
[Input("name")]
public string? Name { get; set; }
[Input("sqlserverConfig")]
private Dictionary<string, string>? _sqlserverConfig;
/// <summary>
/// SQLServer cluster config.
/// </summary>
public Dictionary<string, string> SqlserverConfig
{
get => _sqlserverConfig ?? (_sqlserverConfig = new Dictionary<string, string>());
set => _sqlserverConfig = value;
}
public GetMdbSqlserverClusterArgs()
{
}
}
public sealed class GetMdbSqlserverClusterInvokeArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The ID of the SQLServer cluster.
/// </summary>
[Input("clusterId")]
public Input<string>? ClusterId { get; set; }
[Input("deletionProtection")]
public Input<bool>? DeletionProtection { get; set; }
/// <summary>
/// The ID of the folder that the resource belongs to. If it is not provided, the default provider folder is used.
/// </summary>
[Input("folderId")]
public Input<string>? FolderId { get; set; }
/// <summary>
/// The name of the SQLServer cluster.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("sqlserverConfig")]
private InputMap<string>? _sqlserverConfig;
/// <summary>
/// SQLServer cluster config.
/// </summary>
public InputMap<string> SqlserverConfig
{
get => _sqlserverConfig ?? (_sqlserverConfig = new InputMap<string>());
set => _sqlserverConfig = value;
}
public GetMdbSqlserverClusterInvokeArgs()
{
}
}
[OutputType]
public sealed class GetMdbSqlserverClusterResult
{
public readonly ImmutableArray<Outputs.GetMdbSqlserverClusterBackupWindowStartResult> BackupWindowStarts;
public readonly string ClusterId;
/// <summary>
/// Creation timestamp of the key.
/// </summary>
public readonly string CreatedAt;
/// <summary>
/// A database of the SQLServer cluster. The structure is documented below.
/// </summary>
public readonly ImmutableArray<Outputs.GetMdbSqlserverClusterDatabaseResult> Databases;
public readonly bool DeletionProtection;
/// <summary>
/// Description of the SQLServer cluster.
/// </summary>
public readonly string Description;
/// <summary>
/// Deployment environment of the SQLServer cluster.
/// </summary>
public readonly string Environment;
public readonly string FolderId;
/// <summary>
/// Aggregated health of the cluster.
/// </summary>
public readonly string Health;
/// <summary>
/// A host of the SQLServer cluster. The structure is documented below.
/// </summary>
public readonly ImmutableArray<Outputs.GetMdbSqlserverClusterHostResult> Hosts;
/// <summary>
/// The provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
/// <summary>
/// A set of key/value label pairs to assign to the SQLServer cluster.
/// </summary>
public readonly ImmutableDictionary<string, string> Labels;
/// <summary>
/// The name of the database.
/// </summary>
public readonly string Name;
/// <summary>
/// ID of the network, to which the SQLServer cluster belongs.
/// </summary>
public readonly string NetworkId;
/// <summary>
/// Resources allocated to hosts of the SQLServer cluster. The structure is documented below.
/// </summary>
public readonly ImmutableArray<Outputs.GetMdbSqlserverClusterResourceResult> Resources;
/// <summary>
/// A set of ids of security groups assigned to hosts of the cluster.
/// </summary>
public readonly ImmutableArray<string> SecurityGroupIds;
/// <summary>
/// SQLServer cluster config.
/// </summary>
public readonly ImmutableDictionary<string, string> SqlserverConfig;
/// <summary>
/// Status of the cluster.
/// </summary>
public readonly string Status;
/// <summary>
/// A user of the SQLServer cluster. The structure is documented below.
/// </summary>
public readonly ImmutableArray<Outputs.GetMdbSqlserverClusterUserResult> Users;
/// <summary>
/// Version of the SQLServer cluster.
/// </summary>
public readonly string Version;
[OutputConstructor]
private GetMdbSqlserverClusterResult(
ImmutableArray<Outputs.GetMdbSqlserverClusterBackupWindowStartResult> backupWindowStarts,
string clusterId,
string createdAt,
ImmutableArray<Outputs.GetMdbSqlserverClusterDatabaseResult> databases,
bool deletionProtection,
string description,
string environment,
string folderId,
string health,
ImmutableArray<Outputs.GetMdbSqlserverClusterHostResult> hosts,
string id,
ImmutableDictionary<string, string> labels,
string name,
string networkId,
ImmutableArray<Outputs.GetMdbSqlserverClusterResourceResult> resources,
ImmutableArray<string> securityGroupIds,
ImmutableDictionary<string, string> sqlserverConfig,
string status,
ImmutableArray<Outputs.GetMdbSqlserverClusterUserResult> users,
string version)
{
BackupWindowStarts = backupWindowStarts;
ClusterId = clusterId;
CreatedAt = createdAt;
Databases = databases;
DeletionProtection = deletionProtection;
Description = description;
Environment = environment;
FolderId = folderId;
Health = health;
Hosts = hosts;
Id = id;
Labels = labels;
Name = name;
NetworkId = networkId;
Resources = resources;
SecurityGroupIds = securityGroupIds;
SqlserverConfig = sqlserverConfig;
Status = status;
Users = users;
Version = version;
}
}
}
| 34.671096 | 212 | 0.575891 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-yandex | sdk/dotnet/GetMdbSqlserverCluster.cs | 10,436 | 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("CircleSelection")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CircleSelection")]
[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("a3e0a0da-f2da-483a-bd8f-04cf0acfc112")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.783784 | 84 | 0.748927 | [
"MIT"
] | PacktPublishing/Improving-your-C-Sharp-Skills | Chapter15/CircleSelection/Properties/AssemblyInfo.cs | 1,401 | C# |
using MySql.Data.MySqlClient;
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 Painel
{
public partial class FormProdutos : Form
{
public FormProdutos()
{
InitializeComponent();
}
private void FormProdutos_Load(object sender, EventArgs e)
{
string BancoDeDados = "server=localhost;user id=root;password=;database=loja_jadore";
MySqlConnection conexao = new MySqlConnection(BancoDeDados);
try
{
conexao.Open();
string sqlSelect = $"SELECT produtos.id, produtos.nome, produtos.preco, produtos.preco_antigo, produtos.descricao, produtos.cor, produtos.tamanho, categorias.categoria AS 'categoria', subcategorias.subcategoria AS 'subcategoria', produtos.quantidade_estoque, produtos.fotos FROM produtos INNER JOIN categorias ON produtos.id_categoria = categorias.id INNER JOIN subcategorias ON produtos.id_subcategoria = subcategorias.id";
MySqlDataAdapter da = new MySqlDataAdapter(sqlSelect, conexao);
DataTable dt = new DataTable();
da.Fill(dt);
GridProdutos.DataSource = dt;
}
catch (MySqlException erro)
{
MessageBox.Show("Ocorreu um erro. \nErro: " + erro.Message, "Erro", MessageBoxButtons.OK);
}
}
private void textBoxBusca_TextChanged(object sender, EventArgs e)
{
string BancoDeDados = "server=localhost;user id=root;password=;database=loja_jadore";
MySqlConnection conexao = new MySqlConnection(BancoDeDados);
try
{
string Busca = textBoxBusca.Text;
conexao.Open();
string sqlSelect = $"SELECT produtos.id, produtos.nome, produtos.preco, produtos.preco_antigo, produtos.descricao, produtos.cor, produtos.tamanho, categorias.categoria AS 'categoria', subcategorias.subcategoria AS 'subcategoria', produtos.quantidade_estoque, produtos.fotos FROM produtos INNER JOIN categorias ON produtos.id_categoria = categorias.id INNER JOIN subcategorias ON produtos.id_subcategoria = subcategorias.id WHERE produtos.nome LIKE '%{Busca}%'";
MySqlDataAdapter da = new MySqlDataAdapter(sqlSelect, conexao);
DataTable dt = new DataTable();
da.Fill(dt);
GridProdutos.DataSource = dt;
conexao.Close();
}
catch (MySqlException erro)
{
MessageBox.Show("Ocorreu um erro. \nErro: " + erro.Message, "Erro", MessageBoxButtons.OK);
}
}
}
}
| 45.870968 | 477 | 0.644515 | [
"MIT"
] | jhenifferaraujo20/projeto-integrador-desktop | Painel/FormProdutos.cs | 2,846 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// DispatchInterface IHTMLAnchorElement3
/// SupportByVersion MSHTML, 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsDispatchInterface)]
public class IHTMLAnchorElement3 : IHTMLAnchorElement2
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IHTMLAnchorElement3);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public IHTMLAnchorElement3(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IHTMLAnchorElement3(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLAnchorElement3(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLAnchorElement3(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLAnchorElement3(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLAnchorElement3(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLAnchorElement3() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLAnchorElement3(string progId) : base(progId)
{
}
#endregion
#region Properties
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| 31.966387 | 174 | 0.703733 | [
"MIT"
] | DominikPalo/NetOffice | Source/MSHTML/DispatchInterfaces/IHTMLAnchorElement3.cs | 3,806 | C# |
// Copyright (C) 2003-2010 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alexis Kochetov
// Created: 2009.06.22
using System.Linq.Expressions;
namespace Xtensive.Orm.Linq.Expressions
{
internal class MarkerExpression : ExtendedExpression
{
public Expression Target { get; private set; }
public MarkerType MarkerType { get; private set; }
// Constructors
/// <summary>
/// Initializes a new instance of this class.
/// </summary>
public MarkerExpression(Expression target, MarkerType markerType)
: base(ExtendedExpressionType.Marker, target.Type)
{
Target = target;
MarkerType = markerType;
}
}
} | 24.233333 | 69 | 0.689133 | [
"MIT"
] | DataObjects-NET/dataobjects-net | Orm/Xtensive.Orm/Orm/Linq/Expressions/MarkerExpression.cs | 727 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Newtonsoft.Json.Linq;
using POESKillTree.Common.ViewModels;
using POESKillTree.Controls;
using POESKillTree.Controls.Dialogs;
using POESKillTree.Localization;
using POESKillTree.Model;
using POESKillTree.Model.Builds;
using POESKillTree.Model.Items;
using POESKillTree.Utils;
namespace POESKillTree.ViewModels.Equipment
{
public class DownloadStashViewModel : CloseableViewModel
{
private readonly StashViewModel _stash;
private readonly IPersistentData _persistenData;
private readonly IDialogCoordinator _dialogCoordinator;
private readonly TaskCompletionSource<object> _viewLoadedCompletionSource;
private PoEBuild _build;
public PoEBuild Build
{
get { return _build; }
private set { SetProperty(ref _build, value); }
}
private string _tabsLink;
public string TabsLink
{
get { return _tabsLink; }
private set { SetProperty(ref _tabsLink, value);}
}
private string _tabLink;
public string TabLink
{
get { return _tabLink; }
private set { SetProperty(ref _tabLink, value); }
}
private readonly List<StashBookmark> _tabs = new List<StashBookmark>();
public ICollectionView TabsView { get; }
public static NotifyingTask<IReadOnlyList<string>> CurrentLeagues { get; private set; }
private RelayCommand<string> _openInBrowserCommand;
public ICommand OpenInBrowserCommand
{
get
{
return _openInBrowserCommand ?? (_openInBrowserCommand = new RelayCommand<string>(
param => Process.Start(param),
param => !string.IsNullOrEmpty(param)));
}
}
private ICommand _loadTabsCommand;
public ICommand LoadTabsCommand
{
get { return _loadTabsCommand ?? (_loadTabsCommand = new AsyncRelayCommand(LoadTabs)); }
}
private ICommand _loadTabContentsCommand;
public ICommand LoadTabContentsCommand
{
get { return _loadTabContentsCommand ?? (_loadTabContentsCommand = new AsyncRelayCommand(LoadTabContents)); }
}
public DownloadStashViewModel(IDialogCoordinator dialogCoordinator, IPersistentData persistentData, StashViewModel stash)
{
_stash = stash;
_persistenData = persistentData;
_dialogCoordinator = dialogCoordinator;
DisplayName = L10n.Message("Download & Import Stash");
Build = persistentData.CurrentBuild;
if (Build.League != null && _persistenData.LeagueStashes.ContainsKey(Build.League))
_tabs = new List<StashBookmark>(_persistenData.LeagueStashes[Build.League]);
TabsView = new ListCollectionView(_tabs);
TabsView.CurrentChanged += (sender, args) => UpdateTabLink();
Build.PropertyChanged += BuildOnPropertyChanged;
BuildOnPropertyChanged(this, null);
_viewLoadedCompletionSource = new TaskCompletionSource<object>();
if (CurrentLeagues == null)
{
CurrentLeagues = new NotifyingTask<IReadOnlyList<string>>(LoadCurrentLeaguesAsync(),
async e =>
{
await _viewLoadedCompletionSource.Task;
await _dialogCoordinator.ShowWarningAsync(this,
L10n.Message("Could not load the currently running leagues."), e.Message);
});
}
}
// Errors in CurrentLeagues task may only be shown when the dialog coordinator context is registered,
// which requires the view to be loaded.
public void ViewLoaded()
{
_viewLoadedCompletionSource.SetResult(null);
}
private static async Task<IReadOnlyList<string>> LoadCurrentLeaguesAsync()
{
using (var client = new HttpClient())
{
var file = await client.GetStringAsync("http://api.pathofexile.com/leagues?type=main&compact=1")
.ConfigureAwait(false);
return JArray.Parse(file).Select(t => t["id"].Value<string>()).ToList();
}
}
protected override void OnClose()
{
Build.PropertyChanged -= BuildOnPropertyChanged;
}
private void BuildOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
if (propertyChangedEventArgs != null && propertyChangedEventArgs.PropertyName == "League")
{
_tabs.Clear();
if (Build.League != null && _persistenData.LeagueStashes.ContainsKey(Build.League))
{
_tabs.AddRange(_persistenData.LeagueStashes[Build.League]);
}
TabsView.Refresh();
TabsView.MoveCurrentToFirst();
}
TabsLink =
string.Format(
"https://www.pathofexile.com/character-window/get-stash-items?tabs=1&tabIndex=0&league={0}&accountName={1}",
Build.League, Build.AccountName);
UpdateTabLink();
}
private void UpdateTabLink()
{
var selectedTab = TabsView.CurrentItem as StashBookmark;
if (selectedTab == null)
{
TabLink = "";
return;
}
TabLink =
string.Format(
"https://www.pathofexile.com/character-window/get-stash-items?tabs=0&tabIndex={2}&league={0}&accountName={1}",
Build.League, Build.AccountName, selectedTab.Position);
}
private async Task LoadTabs()
{
var stashData = Clipboard.GetText();
_tabs.Clear();
try
{
var tabs = (JArray)JObject.Parse(stashData)["tabs"];
foreach (var tab in tabs)
{
if (tab["hidden"].Value<bool>())
continue;
var name = tab["n"].Value<string>();
var index = tab["i"].Value<int>();
var c = tab["colour"].Value<JObject>();
var color = Color.FromArgb(0xFF, c["r"].Value<byte>(), c["g"].Value<byte>(), c["b"].Value<byte>());
_tabs.Add(new StashBookmark(name, index, color));
}
if (Build.League != null)
{
_persistenData.LeagueStashes[Build.League] = new List<StashBookmark>(_tabs);
}
}
catch (Exception e)
{
await _dialogCoordinator.ShowErrorAsync(this,
L10n.Message("An error occurred while attempting to load stash data."), e.Message);
}
TabsView.Refresh();
TabsView.MoveCurrentToFirst();
}
private async Task LoadTabContents()
{
var tabContents = Clipboard.GetText();
try
{
var json = JObject.Parse(tabContents);
var isQuadTab = json.Value<bool>("quadLayout");
var items = new List<Item>();
foreach (JObject jItem in json["items"])
{
if (isQuadTab)
{
// icons of quad tabs are downsized and their url doesn't allow inferring the normal-sized url
jItem.Remove("icon");
}
items.Add(new Item(_persistenData, jItem));
}
var yStart = _stash.LastOccupiedRow + 3;
var selectedBookmark = TabsView.CurrentItem as StashBookmark;
var sb = selectedBookmark != null
? new StashBookmark(selectedBookmark.Name, yStart, selectedBookmark.Color)
: new StashBookmark("imported", yStart);
_stash.BeginUpdate();
_stash.AddStashTab(sb);
var yOffsetInImported = items.Min(i => i.Y);
var yMax = items.Max(i => i.Y + i.Height);
foreach (var item in items)
{
item.Y += yStart - yOffsetInImported;
if (item.X + item.Width > StashViewModel.Columns)
{
// Mostly for quad stash tabs:
// - add items on the right side below those on the left side
// - items crossing both sides have to be moved to one side, which might lead to stacked items
// Also makes sure items are not added outside the stash when importing other special tabs.
item.X = Math.Max(0, Math.Min(item.X - StashViewModel.Columns, StashViewModel.Columns - 1));
item.Y += yMax;
}
_stash.AddItem(item, true);
}
await _dialogCoordinator.ShowInfoAsync(this, L10n.Message("New tab added"),
string.Format(L10n.Message("New tab with {0} items was added to stash."), items.Count));
}
catch (Exception e)
{
await _dialogCoordinator.ShowErrorAsync(this,
L10n.Message("An error occurred while attempting to load stash data."), e.Message);
}
finally
{
_stash.EndUpdate();
}
}
}
} | 40.113725 | 131 | 0.542966 | [
"MIT"
] | ManuelOTuga/PoE | WPFSKillTree/ViewModels/Equipment/DownloadStashViewModel.cs | 9,977 | C# |
namespace PcSoft.ExtendedEditor._90_Scripts._00_Runtime
{
internal static class ExtendedEditorConstants
{
}
}
| 17.571429 | 56 | 0.756098 | [
"Apache-2.0"
] | KleinerHacker/unity.extensions | Assets/PcSoft/ExtendedEditor/90 Scripts/00 Runtime/ExtendedEditorConstants.cs | 125 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// MybankCreditSceneprodSignConsultResponse.
/// </summary>
public class MybankCreditSceneprodSignConsultResponse : AlipayResponse
{
/// <summary>
/// 是否允许签约
/// </summary>
[JsonPropertyName("approved")]
public string Approved { get; set; }
/// <summary>
/// 拒绝原因,当approved为false的时候透出
/// </summary>
[JsonPropertyName("reject_reason")]
public string RejectReason { get; set; }
/// <summary>
/// 网商traceId,便于查询日志内容
/// </summary>
[JsonPropertyName("trace_id")]
public string TraceId { get; set; }
}
}
| 25.758621 | 74 | 0.585007 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/MybankCreditSceneprodSignConsultResponse.cs | 807 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MayerControl : MonoBehaviour
{
// Variables del movimiento del personaje
public float jumpForce;
Rigidbody2D playerRigidBody;
public LayerMask groundMask;
Animator animator;
const string STATE_ALIVE = "isAlive";
const string STATE_ON_THE_GROUND = "isOnTheGround";
// Awake is called before Start
private void Awake()
{
// Se encarga de buscar y de extraer los elementos del Rigidbody 2D a la variable playerRigidBody
playerRigidBody = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
jumpForce = 8f;
animator.SetBool(STATE_ALIVE, true);
animator.SetBool(STATE_ON_THE_GROUND, false);
}
// Update is called once per frame
void Update()
{
// Si se preciona el espacio o click del mouse entonces...
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(1))
{
Jump();
}
animator.SetBool(STATE_ON_THE_GROUND,IsTouchingTheGround());
//Debug.DrawRay(this.transform.position, Vector2.down*1.4f,Color.red);
}
// Metodo para que el personaje salte
void Jump()
{
if (IsTouchingTheGround())
{
// Vector2 es un metodo para cambiar la posicion de un objeto 2D, lo que sigue es el tipo de fuerza, en este caso es tipo impulso
playerRigidBody.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
// Metodo para saber si esta o no tocando el suelo
bool IsTouchingTheGround()
{ // 0.1 f = 10 cm
if (Physics2D.Raycast(this.transform.position, Vector2.down,1.4f,groundMask))
{
// To do: Programar logica de contacto con el suelo
animator.speed = 1.0f; // Velocidad de animacion normal
return true;
}
else
{
// To do: programar logica de no contacto
animator.speed = 0.85f; // Velocidad de animacion reducida (para el salto)
return false;
}
}
}
| 31.616438 | 142 | 0.60312 | [
"MIT"
] | Alex99-bit/Space-man | Assets/Scripts/MayerControl.cs | 2,308 | C# |
using Microsoft.AspNetCore.Mvc;
namespace WebApplication5.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
} | 30.818182 | 106 | 0.593904 | [
"MIT"
] | 220328-uta-sh-net-ext/Steve-Burgos | WebApplication5/WebApplication5/Controllers/WeatherForecastController.cs | 1,017 | C# |
using System;
using UnityEngine;
// Token: 0x0200043B RID: 1083
public class IntroYandereScript : MonoBehaviour
{
// Token: 0x06001D0B RID: 7435 RVA: 0x0010FE7C File Offset: 0x0010E27C
private void LateUpdate()
{
this.Hips.localEulerAngles = new Vector3(this.Hips.localEulerAngles.x + this.X, this.Hips.localEulerAngles.y, this.Hips.localEulerAngles.z);
this.Spine.localEulerAngles = new Vector3(this.Spine.localEulerAngles.x + this.X, this.Spine.localEulerAngles.y, this.Spine.localEulerAngles.z);
this.Spine1.localEulerAngles = new Vector3(this.Spine1.localEulerAngles.x + this.X, this.Spine1.localEulerAngles.y, this.Spine1.localEulerAngles.z);
this.Spine2.localEulerAngles = new Vector3(this.Spine2.localEulerAngles.x + this.X, this.Spine2.localEulerAngles.y, this.Spine2.localEulerAngles.z);
this.Spine3.localEulerAngles = new Vector3(this.Spine3.localEulerAngles.x + this.X, this.Spine3.localEulerAngles.y, this.Spine3.localEulerAngles.z);
this.Neck.localEulerAngles = new Vector3(this.Neck.localEulerAngles.x + this.X, this.Neck.localEulerAngles.y, this.Neck.localEulerAngles.z);
this.Head.localEulerAngles = new Vector3(this.Head.localEulerAngles.x + this.X, this.Head.localEulerAngles.y, this.Head.localEulerAngles.z);
this.RightUpLeg.localEulerAngles = new Vector3(this.RightUpLeg.localEulerAngles.x - this.X, this.RightUpLeg.localEulerAngles.y, this.RightUpLeg.localEulerAngles.z);
this.RightLeg.localEulerAngles = new Vector3(this.RightLeg.localEulerAngles.x - this.X, this.RightLeg.localEulerAngles.y, this.RightLeg.localEulerAngles.z);
this.RightFoot.localEulerAngles = new Vector3(this.RightFoot.localEulerAngles.x - this.X, this.RightFoot.localEulerAngles.y, this.RightFoot.localEulerAngles.z);
this.LeftUpLeg.localEulerAngles = new Vector3(this.LeftUpLeg.localEulerAngles.x - this.X, this.LeftUpLeg.localEulerAngles.y, this.LeftUpLeg.localEulerAngles.z);
this.LeftLeg.localEulerAngles = new Vector3(this.LeftLeg.localEulerAngles.x - this.X, this.LeftLeg.localEulerAngles.y, this.LeftLeg.localEulerAngles.z);
this.LeftFoot.localEulerAngles = new Vector3(this.LeftFoot.localEulerAngles.x - this.X, this.LeftFoot.localEulerAngles.y, this.LeftFoot.localEulerAngles.z);
}
// Token: 0x04002382 RID: 9090
public Transform Hips;
// Token: 0x04002383 RID: 9091
public Transform Spine;
// Token: 0x04002384 RID: 9092
public Transform Spine1;
// Token: 0x04002385 RID: 9093
public Transform Spine2;
// Token: 0x04002386 RID: 9094
public Transform Spine3;
// Token: 0x04002387 RID: 9095
public Transform Neck;
// Token: 0x04002388 RID: 9096
public Transform Head;
// Token: 0x04002389 RID: 9097
public Transform RightUpLeg;
// Token: 0x0400238A RID: 9098
public Transform RightLeg;
// Token: 0x0400238B RID: 9099
public Transform RightFoot;
// Token: 0x0400238C RID: 9100
public Transform LeftUpLeg;
// Token: 0x0400238D RID: 9101
public Transform LeftLeg;
// Token: 0x0400238E RID: 9102
public Transform LeftFoot;
// Token: 0x0400238F RID: 9103
public float X;
}
| 45.41791 | 166 | 0.784095 | [
"Unlicense"
] | larryeedwards/openyan | Assembly-CSharp/IntroYandereScript.cs | 3,045 | C# |
// <copyright file="AssemblyInfo.cs" company="Team B">
// Team B. All rights reserved.
// </copyright>
using System.Reflection;
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("UseCaseCore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UseCaseCore")]
[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("f452a6cb-6f8d-41a6-b580-65751ec08523")]
// 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")]
| 36.625 | 84 | 0.733788 | [
"MIT"
] | WowItsDoge/AI-SWP | 03_Implementierung/UseCaseTool/UseCaseCore/Properties/AssemblyInfo.cs | 1,468 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ManagedIrbis.Search;
namespace UnitTests.ManagedIrbis.Search
{
[TestClass]
public class SearchExceptionTest
{
[TestMethod]
public void SearchException_Construction_1()
{
SearchException exception = new SearchException();
Assert.IsNotNull(exception);
}
[TestMethod]
public void SearchException_Construction_2()
{
string message = "Message";
SearchException exception = new SearchException(message);
Assert.AreSame(message, exception.Message);
}
[TestMethod]
public void SearchException_Construction_3()
{
string message = "Message";
Exception innerException = new Exception();
SearchException exception = new SearchException(message, innerException);
Assert.AreSame(message, exception.Message);
Assert.AreSame(innerException, exception.InnerException);
}
}
}
| 28.105263 | 85 | 0.636704 | [
"MIT"
] | amironov73/ManagedClient.45 | Source/UnitTests/ManagedIrbis/Search/SearchExceptionTest.cs | 1,070 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using TygaSoft.IDAL;
using TygaSoft.Model;
using TygaSoft.DBUtility;
namespace TygaSoft.SqlServerDAL
{
public partial class StockLocation : IStockLocation
{
#region IStockLocation Member
public int Insert(StockLocationInfo model)
{
StringBuilder sb = new StringBuilder(300);
sb.Append(@"insert into StockLocation (UserId,ZoneId,Code,Named,Width,Wide,High,Volume,Cubage,Row,Layer,Col,Passway,Xc,Yc,Zc,Orientation,StockLocationType,StackLimit,GroundTrayQty,StockLocationDeal,CarryWeight,UseStatus,Remark,LastUpdatedDate)
values
(@UserId,@ZoneId,@Code,@Named,@Width,@Wide,@High,@Volume,@Cubage,@Row,@Layer,@Col,@Passway,@Xc,@Yc,@Zc,@Orientation,@StockLocationType,@StackLimit,@GroundTrayQty,@StockLocationDeal,@CarryWeight,@UseStatus,@Remark,@LastUpdatedDate)
");
SqlParameter[] parms = {
new SqlParameter("@UserId",SqlDbType.UniqueIdentifier),
new SqlParameter("@ZoneId",SqlDbType.UniqueIdentifier),
new SqlParameter("@Code",SqlDbType.VarChar,30),
new SqlParameter("@Named",SqlDbType.NVarChar,50),
new SqlParameter("@Width",SqlDbType.Float),
new SqlParameter("@Wide",SqlDbType.Float),
new SqlParameter("@High",SqlDbType.Float),
new SqlParameter("@Volume",SqlDbType.Float),
new SqlParameter("@Cubage",SqlDbType.Float),
new SqlParameter("@Row",SqlDbType.Float),
new SqlParameter("@Layer",SqlDbType.Float),
new SqlParameter("@Col",SqlDbType.Float),
new SqlParameter("@Passway",SqlDbType.Float),
new SqlParameter("@Xc",SqlDbType.Float),
new SqlParameter("@Yc",SqlDbType.Float),
new SqlParameter("@Zc",SqlDbType.Float),
new SqlParameter("@Orientation",SqlDbType.Float),
new SqlParameter("@StockLocationType",SqlDbType.NVarChar,20),
new SqlParameter("@StackLimit",SqlDbType.Float),
new SqlParameter("@GroundTrayQty",SqlDbType.Float),
new SqlParameter("@StockLocationDeal",SqlDbType.NVarChar,20),
new SqlParameter("@CarryWeight",SqlDbType.Float),
new SqlParameter("@UseStatus",SqlDbType.NVarChar,20),
new SqlParameter("@Remark",SqlDbType.NVarChar,100),
new SqlParameter("@LastUpdatedDate",SqlDbType.DateTime)
};
parms[0].Value = model.UserId;
parms[1].Value = model.ZoneId;
parms[2].Value = model.Code;
parms[3].Value = model.Named;
parms[4].Value = model.Width;
parms[5].Value = model.Wide;
parms[6].Value = model.High;
parms[7].Value = model.Volume;
parms[8].Value = model.Cubage;
parms[9].Value = model.Row;
parms[10].Value = model.Layer;
parms[11].Value = model.Col;
parms[12].Value = model.Passway;
parms[13].Value = model.Xc;
parms[14].Value = model.Yc;
parms[15].Value = model.Zc;
parms[16].Value = model.Orientation;
parms[17].Value = model.StockLocationType;
parms[18].Value = model.StackLimit;
parms[19].Value = model.GroundTrayQty;
parms[20].Value = model.StockLocationDeal;
parms[21].Value = model.CarryWeight;
parms[22].Value = model.UseStatus;
parms[23].Value = model.Remark;
parms[24].Value = model.LastUpdatedDate;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public int InsertByOutput(StockLocationInfo model)
{
StringBuilder sb = new StringBuilder(300);
sb.Append(@"insert into StockLocation (Id,UserId,ZoneId,Code,Named,Width,Wide,High,Volume,Cubage,Row,Layer,Col,Passway,Xc,Yc,Zc,Orientation,StockLocationType,StackLimit,GroundTrayQty,StockLocationDeal,CarryWeight,UseStatus,Remark,LastUpdatedDate)
values
(@Id,@UserId,@ZoneId,@Code,@Named,@Width,@Wide,@High,@Volume,@Cubage,@Row,@Layer,@Col,@Passway,@Xc,@Yc,@Zc,@Orientation,@StockLocationType,@StackLimit,@GroundTrayQty,@StockLocationDeal,@CarryWeight,@UseStatus,@Remark,@LastUpdatedDate)
");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier),
new SqlParameter("@UserId",SqlDbType.UniqueIdentifier),
new SqlParameter("@ZoneId",SqlDbType.UniqueIdentifier),
new SqlParameter("@Code",SqlDbType.VarChar,30),
new SqlParameter("@Named",SqlDbType.NVarChar,50),
new SqlParameter("@Width",SqlDbType.Float),
new SqlParameter("@Wide",SqlDbType.Float),
new SqlParameter("@High",SqlDbType.Float),
new SqlParameter("@Volume",SqlDbType.Float),
new SqlParameter("@Cubage",SqlDbType.Float),
new SqlParameter("@Row",SqlDbType.Float),
new SqlParameter("@Layer",SqlDbType.Float),
new SqlParameter("@Col",SqlDbType.Float),
new SqlParameter("@Passway",SqlDbType.Float),
new SqlParameter("@Xc",SqlDbType.Float),
new SqlParameter("@Yc",SqlDbType.Float),
new SqlParameter("@Zc",SqlDbType.Float),
new SqlParameter("@Orientation",SqlDbType.Float),
new SqlParameter("@StockLocationType",SqlDbType.NVarChar,20),
new SqlParameter("@StackLimit",SqlDbType.Float),
new SqlParameter("@GroundTrayQty",SqlDbType.Float),
new SqlParameter("@StockLocationDeal",SqlDbType.NVarChar,20),
new SqlParameter("@CarryWeight",SqlDbType.Float),
new SqlParameter("@UseStatus",SqlDbType.NVarChar,20),
new SqlParameter("@Remark",SqlDbType.NVarChar,100),
new SqlParameter("@LastUpdatedDate",SqlDbType.DateTime)
};
parms[0].Value = model.Id;
parms[1].Value = model.UserId;
parms[2].Value = model.ZoneId;
parms[3].Value = model.Code;
parms[4].Value = model.Named;
parms[5].Value = model.Width;
parms[6].Value = model.Wide;
parms[7].Value = model.High;
parms[8].Value = model.Volume;
parms[9].Value = model.Cubage;
parms[10].Value = model.Row;
parms[11].Value = model.Layer;
parms[12].Value = model.Col;
parms[13].Value = model.Passway;
parms[14].Value = model.Xc;
parms[15].Value = model.Yc;
parms[16].Value = model.Zc;
parms[17].Value = model.Orientation;
parms[18].Value = model.StockLocationType;
parms[19].Value = model.StackLimit;
parms[20].Value = model.GroundTrayQty;
parms[21].Value = model.StockLocationDeal;
parms[22].Value = model.CarryWeight;
parms[23].Value = model.UseStatus;
parms[24].Value = model.Remark;
parms[25].Value = model.LastUpdatedDate;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public int Update(StockLocationInfo model)
{
StringBuilder sb = new StringBuilder(500);
sb.Append(@"update StockLocation set UserId = @UserId,ZoneId = @ZoneId,Code = @Code,Named = @Named,Width = @Width,Wide = @Wide,High = @High,Volume = @Volume,Cubage = @Cubage,Row = @Row,Layer = @Layer,Col = @Col,Passway = @Passway,Xc = @Xc,Yc = @Yc,Zc = @Zc,Orientation = @Orientation,StockLocationType = @StockLocationType,StackLimit = @StackLimit,GroundTrayQty = @GroundTrayQty,StockLocationDeal = @StockLocationDeal,CarryWeight = @CarryWeight,UseStatus = @UseStatus,Remark = @Remark,LastUpdatedDate = @LastUpdatedDate
where Id = @Id
");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier),
new SqlParameter("@UserId",SqlDbType.UniqueIdentifier),
new SqlParameter("@ZoneId",SqlDbType.UniqueIdentifier),
new SqlParameter("@Code",SqlDbType.VarChar,30),
new SqlParameter("@Named",SqlDbType.NVarChar,50),
new SqlParameter("@Width",SqlDbType.Float),
new SqlParameter("@Wide",SqlDbType.Float),
new SqlParameter("@High",SqlDbType.Float),
new SqlParameter("@Volume",SqlDbType.Float),
new SqlParameter("@Cubage",SqlDbType.Float),
new SqlParameter("@Row",SqlDbType.Float),
new SqlParameter("@Layer",SqlDbType.Float),
new SqlParameter("@Col",SqlDbType.Float),
new SqlParameter("@Passway",SqlDbType.Float),
new SqlParameter("@Xc",SqlDbType.Float),
new SqlParameter("@Yc",SqlDbType.Float),
new SqlParameter("@Zc",SqlDbType.Float),
new SqlParameter("@Orientation",SqlDbType.Float),
new SqlParameter("@StockLocationType",SqlDbType.NVarChar,20),
new SqlParameter("@StackLimit",SqlDbType.Float),
new SqlParameter("@GroundTrayQty",SqlDbType.Float),
new SqlParameter("@StockLocationDeal",SqlDbType.NVarChar,20),
new SqlParameter("@CarryWeight",SqlDbType.Float),
new SqlParameter("@UseStatus",SqlDbType.NVarChar,20),
new SqlParameter("@Remark",SqlDbType.NVarChar,100),
new SqlParameter("@LastUpdatedDate",SqlDbType.DateTime)
};
parms[0].Value = model.Id;
parms[1].Value = model.UserId;
parms[2].Value = model.ZoneId;
parms[3].Value = model.Code;
parms[4].Value = model.Named;
parms[5].Value = model.Width;
parms[6].Value = model.Wide;
parms[7].Value = model.High;
parms[8].Value = model.Volume;
parms[9].Value = model.Cubage;
parms[10].Value = model.Row;
parms[11].Value = model.Layer;
parms[12].Value = model.Col;
parms[13].Value = model.Passway;
parms[14].Value = model.Xc;
parms[15].Value = model.Yc;
parms[16].Value = model.Zc;
parms[17].Value = model.Orientation;
parms[18].Value = model.StockLocationType;
parms[19].Value = model.StackLimit;
parms[20].Value = model.GroundTrayQty;
parms[21].Value = model.StockLocationDeal;
parms[22].Value = model.CarryWeight;
parms[23].Value = model.UseStatus;
parms[24].Value = model.Remark;
parms[25].Value = model.LastUpdatedDate;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public int Delete(Guid id)
{
StringBuilder sb = new StringBuilder(250);
sb.Append("delete from StockLocation where Id = @Id ");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier)
};
parms[0].Value = id;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public bool DeleteBatch(IList<object> list)
{
StringBuilder sb = new StringBuilder(500);
ParamsHelper parms = new ParamsHelper();
int n = 0;
foreach (string item in list)
{
n++;
sb.Append(@"delete from StockLocation where Id = @Id" + n + " ;");
SqlParameter parm = new SqlParameter("@Id" + n + "", SqlDbType.UniqueIdentifier);
parm.Value = Guid.Parse(item);
parms.Add(parm);
}
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms != null ? parms.ToArray() : null) > 0;
}
public StockLocationInfo GetModel(Guid id)
{
StockLocationInfo model = null;
StringBuilder sb = new StringBuilder(300);
sb.Append(@"select top 1 Id,UserId,ZoneId,Code,Named,Width,Wide,High,Volume,Cubage,Row,Layer,Col,Passway,Xc,Yc,Zc,Orientation,StockLocationType,StackLimit,GroundTrayQty,StockLocationDeal,CarryWeight,UseStatus,Remark,LastUpdatedDate
from StockLocation
where Id = @Id ");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier)
};
parms[0].Value = id;
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms))
{
if (reader != null)
{
if (reader.Read())
{
model = new StockLocationInfo();
model.Id = reader.GetGuid(0);
model.UserId = reader.GetGuid(1);
model.ZoneId = reader.GetGuid(2);
model.Code = reader.GetString(3);
model.Named = reader.GetString(4);
model.Width = reader.GetDouble(5);
model.Wide = reader.GetDouble(6);
model.High = reader.GetDouble(7);
model.Volume = reader.GetDouble(8);
model.Cubage = reader.GetDouble(9);
model.Row = reader.GetDouble(10);
model.Layer = reader.GetDouble(11);
model.Col = reader.GetDouble(12);
model.Passway = reader.GetDouble(13);
model.Xc = reader.GetDouble(14);
model.Yc = reader.GetDouble(15);
model.Zc = reader.GetDouble(16);
model.Orientation = reader.GetDouble(17);
model.StockLocationType = reader.GetString(18);
model.StackLimit = reader.GetDouble(19);
model.GroundTrayQty = reader.GetDouble(20);
model.StockLocationDeal = reader.GetString(21);
model.CarryWeight = reader.GetDouble(22);
model.UseStatus = reader.GetString(23);
model.Remark = reader.GetString(24);
model.LastUpdatedDate = reader.GetDateTime(25);
}
}
}
return model;
}
public IList<StockLocationInfo> GetList(int pageIndex, int pageSize, out int totalRecords, string sqlWhere, params SqlParameter[] cmdParms)
{
StringBuilder sb = new StringBuilder(500);
sb.Append(@"select count(*) from StockLocation ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
totalRecords = (int)SqlHelper.ExecuteScalar(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms);
if (totalRecords == 0) return new List<StockLocationInfo>();
sb.Clear();
int startIndex = (pageIndex - 1) * pageSize + 1;
int endIndex = pageIndex * pageSize;
sb.Append(@"select * from(select row_number() over(order by LastUpdatedDate desc) as RowNumber,
Id,UserId,ZoneId,Code,Named,Width,Wide,High,Volume,Cubage,Row,Layer,Col,Passway,Xc,Yc,Zc,Orientation,StockLocationType,StackLimit,GroundTrayQty,StockLocationDeal,CarryWeight,UseStatus,Remark,LastUpdatedDate
from StockLocation ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
sb.AppendFormat(@")as objTable where RowNumber between {0} and {1} ", startIndex, endIndex);
IList<StockLocationInfo> list = new List<StockLocationInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
StockLocationInfo model = new StockLocationInfo();
model.Id = reader.GetGuid(1);
model.UserId = reader.GetGuid(2);
model.ZoneId = reader.GetGuid(3);
model.Code = reader.GetString(4);
model.Named = reader.GetString(5);
model.Width = reader.GetDouble(6);
model.Wide = reader.GetDouble(7);
model.High = reader.GetDouble(8);
model.Volume = reader.GetDouble(9);
model.Cubage = reader.GetDouble(10);
model.Row = reader.GetDouble(11);
model.Layer = reader.GetDouble(12);
model.Col = reader.GetDouble(13);
model.Passway = reader.GetDouble(14);
model.Xc = reader.GetDouble(15);
model.Yc = reader.GetDouble(16);
model.Zc = reader.GetDouble(17);
model.Orientation = reader.GetDouble(18);
model.StockLocationType = reader.GetString(19);
model.StackLimit = reader.GetDouble(20);
model.GroundTrayQty = reader.GetDouble(21);
model.StockLocationDeal = reader.GetString(22);
model.CarryWeight = reader.GetDouble(23);
model.UseStatus = reader.GetString(24);
model.Remark = reader.GetString(25);
model.LastUpdatedDate = reader.GetDateTime(26);
list.Add(model);
}
}
}
return list;
}
public IList<StockLocationInfo> GetList(int pageIndex, int pageSize, string sqlWhere, params SqlParameter[] cmdParms)
{
StringBuilder sb = new StringBuilder(500);
int startIndex = (pageIndex - 1) * pageSize + 1;
int endIndex = pageIndex * pageSize;
sb.Append(@"select * from(select row_number() over(order by LastUpdatedDate desc) as RowNumber,
Id,UserId,ZoneId,Code,Named,Width,Wide,High,Volume,Cubage,Row,Layer,Col,Passway,Xc,Yc,Zc,Orientation,StockLocationType,StackLimit,GroundTrayQty,StockLocationDeal,CarryWeight,UseStatus,Remark,LastUpdatedDate
from StockLocation ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
sb.AppendFormat(@")as objTable where RowNumber between {0} and {1} ", startIndex, endIndex);
IList<StockLocationInfo> list = new List<StockLocationInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
StockLocationInfo model = new StockLocationInfo();
model.Id = reader.GetGuid(1);
model.UserId = reader.GetGuid(2);
model.ZoneId = reader.GetGuid(3);
model.Code = reader.GetString(4);
model.Named = reader.GetString(5);
model.Width = reader.GetDouble(6);
model.Wide = reader.GetDouble(7);
model.High = reader.GetDouble(8);
model.Volume = reader.GetDouble(9);
model.Cubage = reader.GetDouble(10);
model.Row = reader.GetDouble(11);
model.Layer = reader.GetDouble(12);
model.Col = reader.GetDouble(13);
model.Passway = reader.GetDouble(14);
model.Xc = reader.GetDouble(15);
model.Yc = reader.GetDouble(16);
model.Zc = reader.GetDouble(17);
model.Orientation = reader.GetDouble(18);
model.StockLocationType = reader.GetString(19);
model.StackLimit = reader.GetDouble(20);
model.GroundTrayQty = reader.GetDouble(21);
model.StockLocationDeal = reader.GetString(22);
model.CarryWeight = reader.GetDouble(23);
model.UseStatus = reader.GetString(24);
model.Remark = reader.GetString(25);
model.LastUpdatedDate = reader.GetDateTime(26);
list.Add(model);
}
}
}
return list;
}
public IList<StockLocationInfo> GetList(string sqlWhere, params SqlParameter[] cmdParms)
{
StringBuilder sb = new StringBuilder(500);
sb.Append(@"select Id,UserId,ZoneId,Code,Named,Width,Wide,High,Volume,Cubage,Row,Layer,Col,Passway,Xc,Yc,Zc,Orientation,StockLocationType,StackLimit,GroundTrayQty,StockLocationDeal,CarryWeight,UseStatus,Remark,LastUpdatedDate
from StockLocation ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
sb.Append("order by LastUpdatedDate desc ");
IList<StockLocationInfo> list = new List<StockLocationInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
StockLocationInfo model = new StockLocationInfo();
model.Id = reader.GetGuid(0);
model.UserId = reader.GetGuid(1);
model.ZoneId = reader.GetGuid(2);
model.Code = reader.GetString(3);
model.Named = reader.GetString(4);
model.Width = reader.GetDouble(5);
model.Wide = reader.GetDouble(6);
model.High = reader.GetDouble(7);
model.Volume = reader.GetDouble(8);
model.Cubage = reader.GetDouble(9);
model.Row = reader.GetDouble(10);
model.Layer = reader.GetDouble(11);
model.Col = reader.GetDouble(12);
model.Passway = reader.GetDouble(13);
model.Xc = reader.GetDouble(14);
model.Yc = reader.GetDouble(15);
model.Zc = reader.GetDouble(16);
model.Orientation = reader.GetDouble(17);
model.StockLocationType = reader.GetString(18);
model.StackLimit = reader.GetDouble(19);
model.GroundTrayQty = reader.GetDouble(20);
model.StockLocationDeal = reader.GetString(21);
model.CarryWeight = reader.GetDouble(22);
model.UseStatus = reader.GetString(23);
model.Remark = reader.GetString(24);
model.LastUpdatedDate = reader.GetDateTime(25);
list.Add(model);
}
}
}
return list;
}
public IList<StockLocationInfo> GetList()
{
StringBuilder sb = new StringBuilder(300);
sb.Append(@"select Id,UserId,ZoneId,Code,Named,Width,Wide,High,Volume,Cubage,Row,Layer,Col,Passway,Xc,Yc,Zc,Orientation,StockLocationType,StackLimit,GroundTrayQty,StockLocationDeal,CarryWeight,UseStatus,Remark,LastUpdatedDate
from StockLocation
order by LastUpdatedDate desc ");
IList<StockLocationInfo> list = new List<StockLocationInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString()))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
StockLocationInfo model = new StockLocationInfo();
model.Id = reader.GetGuid(0);
model.UserId = reader.GetGuid(1);
model.ZoneId = reader.GetGuid(2);
model.Code = reader.GetString(3);
model.Named = reader.GetString(4);
model.Width = reader.GetDouble(5);
model.Wide = reader.GetDouble(6);
model.High = reader.GetDouble(7);
model.Volume = reader.GetDouble(8);
model.Cubage = reader.GetDouble(9);
model.Row = reader.GetDouble(10);
model.Layer = reader.GetDouble(11);
model.Col = reader.GetDouble(12);
model.Passway = reader.GetDouble(13);
model.Xc = reader.GetDouble(14);
model.Yc = reader.GetDouble(15);
model.Zc = reader.GetDouble(16);
model.Orientation = reader.GetDouble(17);
model.StockLocationType = reader.GetString(18);
model.StackLimit = reader.GetDouble(19);
model.GroundTrayQty = reader.GetDouble(20);
model.StockLocationDeal = reader.GetString(21);
model.CarryWeight = reader.GetDouble(22);
model.UseStatus = reader.GetString(23);
model.Remark = reader.GetString(24);
model.LastUpdatedDate = reader.GetDateTime(25);
list.Add(model);
}
}
}
return list;
}
#endregion
}
}
| 55.545279 | 532 | 0.514326 | [
"MIT"
] | Arainsd/Wms | src/TygaSoft/SqlServerDAL/AutoCode/StockLocation.cs | 28,830 | C# |
/*******************************************************************************
* Copyright 2009-2018 Amazon Services. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*******************************************************************************
* Pay With Amazon Event
* API Version: 2015-05-01
* Library Version: 2018-02-07
* Generated: Fri Jan 19 15:01:20 PST 2018
*/
using System;
using System.Collections.Generic;
using Claytondus.AmazonMWS.Runtime;
namespace Claytondus.AmazonMWS.Finances.Model
{
public class PayWithAmazonEvent : AbstractMwsObject
{
private string _sellerOrderId;
private DateTime? _transactionPostedDate;
private string _businessObjectType;
private string _salesChannel;
private ChargeComponent _charge;
private List<FeeComponent> _feeList;
private string _paymentAmountType;
private string _amountDescription;
private string _fulfillmentChannel;
private string _storeName;
/// <summary>
/// Gets and sets the SellerOrderId property.
/// </summary>
public string SellerOrderId
{
get { return this._sellerOrderId; }
set { this._sellerOrderId = value; }
}
/// <summary>
/// Sets the SellerOrderId property.
/// </summary>
/// <param name="sellerOrderId">SellerOrderId property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithSellerOrderId(string sellerOrderId)
{
this._sellerOrderId = sellerOrderId;
return this;
}
/// <summary>
/// Checks if SellerOrderId property is set.
/// </summary>
/// <returns>true if SellerOrderId property is set.</returns>
public bool IsSetSellerOrderId()
{
return this._sellerOrderId != null;
}
/// <summary>
/// Gets and sets the TransactionPostedDate property.
/// </summary>
public DateTime TransactionPostedDate
{
get { return this._transactionPostedDate.GetValueOrDefault(); }
set { this._transactionPostedDate = value; }
}
/// <summary>
/// Sets the TransactionPostedDate property.
/// </summary>
/// <param name="transactionPostedDate">TransactionPostedDate property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithTransactionPostedDate(DateTime transactionPostedDate)
{
this._transactionPostedDate = transactionPostedDate;
return this;
}
/// <summary>
/// Checks if TransactionPostedDate property is set.
/// </summary>
/// <returns>true if TransactionPostedDate property is set.</returns>
public bool IsSetTransactionPostedDate()
{
return this._transactionPostedDate != null;
}
/// <summary>
/// Gets and sets the BusinessObjectType property.
/// </summary>
public string BusinessObjectType
{
get { return this._businessObjectType; }
set { this._businessObjectType = value; }
}
/// <summary>
/// Sets the BusinessObjectType property.
/// </summary>
/// <param name="businessObjectType">BusinessObjectType property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithBusinessObjectType(string businessObjectType)
{
this._businessObjectType = businessObjectType;
return this;
}
/// <summary>
/// Checks if BusinessObjectType property is set.
/// </summary>
/// <returns>true if BusinessObjectType property is set.</returns>
public bool IsSetBusinessObjectType()
{
return this._businessObjectType != null;
}
/// <summary>
/// Gets and sets the SalesChannel property.
/// </summary>
public string SalesChannel
{
get { return this._salesChannel; }
set { this._salesChannel = value; }
}
/// <summary>
/// Sets the SalesChannel property.
/// </summary>
/// <param name="salesChannel">SalesChannel property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithSalesChannel(string salesChannel)
{
this._salesChannel = salesChannel;
return this;
}
/// <summary>
/// Checks if SalesChannel property is set.
/// </summary>
/// <returns>true if SalesChannel property is set.</returns>
public bool IsSetSalesChannel()
{
return this._salesChannel != null;
}
/// <summary>
/// Gets and sets the Charge property.
/// </summary>
public ChargeComponent Charge
{
get { return this._charge; }
set { this._charge = value; }
}
/// <summary>
/// Sets the Charge property.
/// </summary>
/// <param name="charge">Charge property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithCharge(ChargeComponent charge)
{
this._charge = charge;
return this;
}
/// <summary>
/// Checks if Charge property is set.
/// </summary>
/// <returns>true if Charge property is set.</returns>
public bool IsSetCharge()
{
return this._charge != null;
}
/// <summary>
/// Gets and sets the FeeList property.
/// </summary>
public List<FeeComponent> FeeList
{
get
{
if(this._feeList == null)
{
this._feeList = new List<FeeComponent>();
}
return this._feeList;
}
set { this._feeList = value; }
}
/// <summary>
/// Sets the FeeList property.
/// </summary>
/// <param name="feeList">FeeList property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithFeeList(FeeComponent[] feeList)
{
this._feeList.AddRange(feeList);
return this;
}
/// <summary>
/// Checks if FeeList property is set.
/// </summary>
/// <returns>true if FeeList property is set.</returns>
public bool IsSetFeeList()
{
return this.FeeList.Count > 0;
}
/// <summary>
/// Gets and sets the PaymentAmountType property.
/// </summary>
public string PaymentAmountType
{
get { return this._paymentAmountType; }
set { this._paymentAmountType = value; }
}
/// <summary>
/// Sets the PaymentAmountType property.
/// </summary>
/// <param name="paymentAmountType">PaymentAmountType property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithPaymentAmountType(string paymentAmountType)
{
this._paymentAmountType = paymentAmountType;
return this;
}
/// <summary>
/// Checks if PaymentAmountType property is set.
/// </summary>
/// <returns>true if PaymentAmountType property is set.</returns>
public bool IsSetPaymentAmountType()
{
return this._paymentAmountType != null;
}
/// <summary>
/// Gets and sets the AmountDescription property.
/// </summary>
public string AmountDescription
{
get { return this._amountDescription; }
set { this._amountDescription = value; }
}
/// <summary>
/// Sets the AmountDescription property.
/// </summary>
/// <param name="amountDescription">AmountDescription property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithAmountDescription(string amountDescription)
{
this._amountDescription = amountDescription;
return this;
}
/// <summary>
/// Checks if AmountDescription property is set.
/// </summary>
/// <returns>true if AmountDescription property is set.</returns>
public bool IsSetAmountDescription()
{
return this._amountDescription != null;
}
/// <summary>
/// Gets and sets the FulfillmentChannel property.
/// </summary>
public string FulfillmentChannel
{
get { return this._fulfillmentChannel; }
set { this._fulfillmentChannel = value; }
}
/// <summary>
/// Sets the FulfillmentChannel property.
/// </summary>
/// <param name="fulfillmentChannel">FulfillmentChannel property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithFulfillmentChannel(string fulfillmentChannel)
{
this._fulfillmentChannel = fulfillmentChannel;
return this;
}
/// <summary>
/// Checks if FulfillmentChannel property is set.
/// </summary>
/// <returns>true if FulfillmentChannel property is set.</returns>
public bool IsSetFulfillmentChannel()
{
return this._fulfillmentChannel != null;
}
/// <summary>
/// Gets and sets the StoreName property.
/// </summary>
public string StoreName
{
get { return this._storeName; }
set { this._storeName = value; }
}
/// <summary>
/// Sets the StoreName property.
/// </summary>
/// <param name="storeName">StoreName property.</param>
/// <returns>this instance.</returns>
public PayWithAmazonEvent WithStoreName(string storeName)
{
this._storeName = storeName;
return this;
}
/// <summary>
/// Checks if StoreName property is set.
/// </summary>
/// <returns>true if StoreName property is set.</returns>
public bool IsSetStoreName()
{
return this._storeName != null;
}
public override void ReadFragmentFrom(IMwsReader reader)
{
_sellerOrderId = reader.Read<string>("SellerOrderId");
_transactionPostedDate = reader.Read<DateTime?>("TransactionPostedDate");
_businessObjectType = reader.Read<string>("BusinessObjectType");
_salesChannel = reader.Read<string>("SalesChannel");
_charge = reader.Read<ChargeComponent>("Charge");
_feeList = reader.ReadList<FeeComponent>("FeeList", "FeeComponent");
_paymentAmountType = reader.Read<string>("PaymentAmountType");
_amountDescription = reader.Read<string>("AmountDescription");
_fulfillmentChannel = reader.Read<string>("FulfillmentChannel");
_storeName = reader.Read<string>("StoreName");
}
public override void WriteFragmentTo(IMwsWriter writer)
{
writer.Write("SellerOrderId", _sellerOrderId);
writer.Write("TransactionPostedDate", _transactionPostedDate);
writer.Write("BusinessObjectType", _businessObjectType);
writer.Write("SalesChannel", _salesChannel);
writer.Write("Charge", _charge);
writer.WriteList("FeeList", "FeeComponent", _feeList);
writer.Write("PaymentAmountType", _paymentAmountType);
writer.Write("AmountDescription", _amountDescription);
writer.Write("FulfillmentChannel", _fulfillmentChannel);
writer.Write("StoreName", _storeName);
}
public override void WriteTo(IMwsWriter writer)
{
writer.Write("http://mws.amazonservices.com/Finances/2015-05-01", "PayWithAmazonEvent", this);
}
public PayWithAmazonEvent() : base()
{
}
}
}
| 33.733333 | 106 | 0.571621 | [
"Apache-2.0"
] | claytondus/Claytondus.AmazonMWS | Claytondus.AmazonMWS.Finances/Model/PayWithAmazonEvent.cs | 12,650 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Globalization;
namespace System
{
class Program
{
static void PrintUsage()
{
Console.WriteLine(
"This utility sorts text file in order to fulfill GDAL ASCII Gridded XYZ specification. \n" +
"It places cells with same Y coordinates on consecutive lines. \n" +
"For a same Y coordinate value it organizes the lines in the dataset by increasing X values. \n" +
"The supported column separators are: space, comma, semicolon and tabulations.\n" +
"\n" +
"Usage: \n" +
" xyz_sort <source.xyz> [sorted.xyz]\n");
}
static void Main(string[] args)
{
if (args.Length < 1)
{
PrintUsage();
Console.ReadKey();
return;
}
var srcFilePath = args[0];
if (!File.Exists(srcFilePath))
{
Console.WriteLine("File does not exists: " + srcFilePath);
return;
}
var dstFilePath = Path.ChangeExtension(srcFilePath, "sorted" + Path.GetExtension(srcFilePath));
if (args.Length > 1)
dstFilePath = args[1];
try
{
using (var xyzLines = new XYZGridLines(srcFilePath))
{
Console.Write("Loading source file... ");
var lnCount = xyzLines.InitReader();
Console.WriteLine(lnCount.ToString() + " lines loaded. ");
Console.WriteLine("Writing sorted file...");
xyzLines.DuplicateFound += XyzReader_DuplicateFound;
xyzLines.SortAndWriteLines(dstFilePath);
var summaryText = xyzLines.WritedLines.ToString() + " lines saved. ";
if (xyzLines.Duplicates > 0)
summaryText += "(" + xyzLines.Duplicates.ToString() + " duplicates filtered out)";
Console.WriteLine(summaryText);
}
}
catch (LineException lex)
{
Console.WriteLine("Invalid file format, line number " + lex.LineNumber.ToString() + ": ");
Console.WriteLine(lex.LineText);
Console.WriteLine(lex.Message);
if (lex.InnerException != null)
Console.WriteLine(lex.InnerException.Message);
Console.ReadKey();
return;
}
}
private static void XyzReader_DuplicateFound(object sender, XLineEventArgs e)
{
var duplicatesAreTheSame = true;
var firstLn = e.Lines.First();
foreach (var lnItem in e.Lines)
{
duplicatesAreTheSame = duplicatesAreTheSame && (firstLn.Text == lnItem.Text);
}
if (!duplicatesAreTheSame)
{
Console.WriteLine("Multiple lines with the same XY coordinates found:");
foreach (var lnItem in e.Lines)
{
Console.WriteLine("#{0, -10}: {1}", lnItem.LineNumber, lnItem.Text);
}
Console.WriteLine("Saved line : " + e.UsedLine);
Console.WriteLine();
}
}
}
}
| 34.8 | 113 | 0.509195 | [
"MIT"
] | KubaSzostak/gdal-dragndrop | src/xyz_sort/xyz_sort.cs | 3,482 | C# |
namespace Bau.Data
{
using Bau.Data.Entities;
using Bau.Planning;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
public class BauSeeder
{
private readonly BauDbContext ctx;
private readonly IHostingEnvironment hosting;
private readonly UserManager<StoreUser> userManager;
private readonly IPlanningService planningService;
public BauSeeder(
BauDbContext ctx,
IHostingEnvironment hosting,
UserManager<StoreUser> userManager,
IPlanningService planningService)
{
this.ctx = ctx;
this.hosting = hosting;
this.userManager = userManager;
this.planningService = planningService;
}
public async Task Seed()
{
ctx.Database.EnsureCreated();
var user = await userManager.FindByEmailAsync("bau@bau.bau");
if (user == null)
{
user = new StoreUser()
{
FirstName = "Bau",
LastName = "Bau",
UserName = "bau@bau.bau",
Email = "bau@bau.bau"
};
var result = await userManager.CreateAsync(user, "P@ssw0rd!");
if (result != IdentityResult.Success)
{
throw new InvalidOperationException("Failed to create default user");
}
}
if (!ctx.Engineers.Any())
{
var filePath = Path.Combine(hosting.ContentRootPath, "../Bau.Data/engineers.json");
var json = File.ReadAllText(filePath);
var engineers = JsonConvert.DeserializeObject<IEnumerable<Engineer>>(json);
ctx.Engineers.AddRange(engineers);
ctx.SaveChanges();
planningService.GeneratePlanForDateRagne(
ctx,
new DateTime(2018, 2, 1),
new DateTime(2018, 2, 28));
}
}
}
}
| 29.973684 | 99 | 0.533363 | [
"MIT"
] | zbigniew-gajewski/asp-net-core-mvc-ef-core-angular | Bau/Data/BauSeeder.cs | 2,280 | C# |
///////////////////////////////////////////////////////////////////////////////////
/// ///
/// This file is part of the OpenDriveSimulator project ///
/// (www.github.com/TUMMMK/OpenDrive) ///
/// ///
/// Copyright (c) 2016 Simon Schenk (simon.schenk@tum.de) ///
/// ///
///////////////////////////////////////////////////////////////////////////////////
/// The MIT License ///
/// ///
/// Permission is hereby granted, free of charge, to any person obtaining a ///
/// copy of this software and associated documentation files (the "Software"), ///
/// to deal in the Software without restriction, including without limitation ///
/// the rights to use, copy, modify, merge, publish, distribute, sublicense, ///
/// and/or sell copies of the Software, and to permit persons to whom the ///
/// Software is furnished to do so, subject to the following conditions: ///
/// ///
/// The above copyright notice and this permission notice shall be included ///
/// in all copies or substantial portions of the Software. ///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ///
/// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ///
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ///
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ///
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ///
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ///
/// DEALINGS IN THE SOFTWARE. ///
///////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.IO;
namespace OpenDriveSimulator.Scripting
{
class DebugLogger : SimScriptBase
{
string logFilePath;
List<string> m_linesToStore = new List<string>();
public override void Start()
{
Interval = 5000;
base.Start();
logFilePath = Path.Combine(Application.RootFolder, "DebugLogs");
if (!Directory.Exists(logFilePath))
Directory.CreateDirectory(logFilePath);
string filename = DateTime.Now.Date.Year + "_" + DateTime.Now.Date.Month + "_" + DateTime.Now.Date.Day + ".log";
logFilePath = Path.Combine(logFilePath, filename);
}
public void AddLine(string line)
{
m_linesToStore.Add(line);
}
void PrintLines()
{
File.AppendAllLines(logFilePath, m_linesToStore);
m_linesToStore.Clear();
}
protected override void OnTick(object sender, EventArgs e)
{
PrintLines();
}
protected override void OnAbort(object sender, EventArgs e)
{
PrintLines();
}
}
}
| 47.166667 | 121 | 0.48351 | [
"MIT"
] | TUMMMK/OpenDrive | OpenDriveSimulator/Scripts/GeneralScripting/DebugLogger.cs | 3,398 | C# |
using Autofac;
using Autofac.Extras.DynamicProxy;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Linq;
using System.Reflection;
using EasyCaching.Core.Configurations;
using EasyCaching.Core.Interceptor;
namespace Adnc.Infr.EasyCaching.Interceptor.Castle
{
/// <summary>
/// Castle interceptor service collection extensions.
/// </summary>
public static class CastleInterceptorServiceCollectionExtensions
{
/// <summary>
/// Configures the castle interceptor.
/// </summary>
/// <returns>The castle interceptor.</returns>
/// <param name="services">Services.</param>
/// <param name="options">Easycaching Interceptor config</param>
public static void ConfigureCastleInterceptor(this IServiceCollection services, Action<EasyCachingInterceptorOptions> options)
{
services.TryAddSingleton<IEasyCachingKeyGenerator, CustomEasyCachingKeyGenerator>();
services.Configure(options);
}
/// <summary>
/// Configures the castle interceptor.
/// </summary>
/// <param name="builder">Container Builder.</param>
public static void ConfigureCastleInterceptor(this ContainerBuilder builder)
{
//var assembly = isCalling ? Assembly.GetCallingAssembly() : Assembly.GetExecutingAssembly();
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
builder.RegisterType<EasyCachingInterceptor>();
builder.RegisterAssemblyTypes(assemblies)
.Where(t => !t.IsAbstract && t.GetInterfaces().SelectMany(x => x.GetMethods()).Any(
y => y.CustomAttributes.Any(data =>
typeof(EasyCachingInterceptorAttribute).GetTypeInfo().IsAssignableFrom(data.AttributeType)
)))
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(EasyCachingInterceptor));
}
internal static void ConfigureCastleInterceptorForTest(this ContainerBuilder builder)
{
var assembly = Assembly.GetCallingAssembly();
builder.RegisterType<EasyCachingInterceptor>();
builder.RegisterAssemblyTypes(assembly)
.Where(t => !t.IsAbstract && t.GetInterfaces().SelectMany(x => x.GetMethods()).Any(
y => y.CustomAttributes.Any(data =>
typeof(EasyCachingInterceptorAttribute).GetTypeInfo().IsAssignableFrom(data.AttributeType)
)))
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(EasyCachingInterceptor));
}
}
}
| 41.830986 | 134 | 0.63367 | [
"MIT"
] | JavaScript-zt/Adnc | src/ServerApi/Adnc.Infr.EasyCaching/Interceptor/CastleInterceptorServiceCollectionExtensions.cs | 2,972 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace NeoCortexApi.Entities
{
public class DistributedMemory
{
public IDistributedDictionary<int, Column> ColumnDictionary { get; set; }
//public IDistributedDictionary<int, Pool> PoolDictionary { get; set; }
}
}
| 21.066667 | 81 | 0.71519 | [
"Apache-2.0"
] | PrasadSahana/Implementation-of-Scalar-Encoders-in-HTM | Source/HTM/NeoCortexEntities/Entities/DistributedMemory.cs | 318 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.34014
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Game2048.Properties
{
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[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>
/// 返回此类使用的、缓存的 ResourceManager 实例。
/// </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("Game2048.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 为所有资源查找重写当前线程的 CurrentUICulture 属性,
/// 方法是使用此强类型资源类。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 33.902778 | 174 | 0.575174 | [
"MIT"
] | zc910704/C--homework | resource/Game2048/Game2048/Properties/Resources.Designer.cs | 2,797 | C# |
#region Using directives
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
#endregion
namespace Blazorise.Markdown
{
/// <summary>
/// Component for acts as a wrapper around the EasyMDE, a markdown editor.
/// </summary>
public partial class Markdown : BaseComponent
{
#region Members
private DotNetObjectReference<Markdown> dotNetObjectRef;
#endregion
#region Methods
/// <inheritdoc/>
public override async Task SetParametersAsync( ParameterView parameters )
{
if ( Initialized && parameters.TryGetValue<string>( nameof( Value ), out var newValue ) && newValue != Value )
{
ExecuteAfterRender( () => SetValueAsync( newValue ) );
}
await base.SetParametersAsync( parameters );
}
/// <inheritdoc/>
protected override async Task OnAfterRenderAsync( bool firstRender )
{
await base.OnAfterRenderAsync( firstRender );
if ( firstRender )
{
dotNetObjectRef ??= DotNetObjectReference.Create( this );
await JSRuntime.InvokeVoidAsync( "blazoriseMarkdown.initialize", dotNetObjectRef, ElementId, Value );
Initialized = true;
}
}
/// <inheritdoc/>
protected override async ValueTask DisposeAsync( bool disposing )
{
if ( disposing )
{
await JSRuntime.InvokeVoidAsync( "blazoriseMarkdown.destroy", ElementId );
dotNetObjectRef?.Dispose();
dotNetObjectRef = null;
}
await base.DisposeAsync( disposing );
}
/// <summary>
/// Gets the markdown value.
/// </summary>
/// <returns>Markdown value.</returns>
public async Task<string> GetValueAsync()
{
if ( !Initialized )
return null;
return await JSRuntime.InvokeAsync<string>( "blazoriseMarkdown.getValue", ElementId );
}
/// <summary>
/// Sets the markdown value.
/// </summary>
/// <param name="value">Value to set.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task SetValueAsync( string value )
{
if ( !Initialized )
return;
await JSRuntime.InvokeAsync<string>( "blazoriseMarkdown.setValue", ElementId, value );
}
/// <summary>
/// Updates the internal markdown value. This method should only be called internally!
/// </summary>
/// <param name="value">New value.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[JSInvokable]
public Task UpdateInternalValue( string value )
{
Value = value;
return ValueChanged.InvokeAsync( Value );
}
#endregion
#region Properties
/// <inheritdoc/>
protected override bool ShouldAutoGenerateId => true;
/// <summary>
/// Indicates if markdown editor is properly initialized.
/// </summary>
protected bool Initialized { get; set; }
/// <summary>
/// Gets or set the javascript runtime.
/// </summary>
[Inject] public IJSRuntime JSRuntime { get; set; }
/// <summary>
/// Gets or sets the markdown value.
/// </summary>
[Parameter] public string Value { get; set; }
/// <summary>
/// An event that occurs after the markdown value has changed.
/// </summary>
[Parameter] public EventCallback<string> ValueChanged { get; set; }
#endregion
}
}
| 29.546154 | 122 | 0.568081 | [
"Apache-2.0"
] | Luk164/Blazorise | Source/Extensions/Blazorise.Markdown/Markdown.razor.cs | 3,843 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.