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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using System;
using CoreLocation;
using UIKit;
using Foundation;
namespace Location.iOS
{
public class LocationManager
{
protected CLLocationManager locMgr;
// event for the location changing
public event EventHandler<LocationUpdatedEventArgs> LocationUpdated = delegate { };
public LocationManager ()
{
this.locMgr = new CLLocationManager ();
this.locMgr.PausesLocationUpdatesAutomatically = false;
// iOS 8 has additional permissions requirements
if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
locMgr.RequestAlwaysAuthorization (); // works in background
//locMgr.RequestWhenInUseAuthorization (); // only in foreground
}
if (UIDevice.CurrentDevice.CheckSystemVersion (9, 0)) {
locMgr.AllowsBackgroundLocationUpdates = true;
}
LocationUpdated += PrintLocation;
}
// create a location manager to get system location updates to the application
public CLLocationManager LocMgr {
get { return this.locMgr; }
}
public void StartLocationUpdates ()
{
// We need the user's permission for our app to use the GPS in iOS. This is done either by the user accepting
// the popover when the app is first launched, or by changing the permissions for the app in Settings
if (CLLocationManager.LocationServicesEnabled) {
LocMgr.DesiredAccuracy = 1; // sets the accuracy that we want in meters
// Location updates are handled differently pre-iOS 6. If we want to support older versions of iOS,
// we want to do perform this check and let our LocationManager know how to handle location updates.
if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
LocMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
// fire our custom Location Updated event
this.LocationUpdated (this, new LocationUpdatedEventArgs (e.Locations [e.Locations.Length - 1]));
};
} else {
// this won't be called on iOS 6 (deprecated). We will get a warning here when we build.
LocMgr.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
this.LocationUpdated (this, new LocationUpdatedEventArgs (e.NewLocation));
};
}
// Start our location updates
LocMgr.StartUpdatingLocation ();
// Get some output from our manager in case of failure
LocMgr.Failed += (object sender, NSErrorEventArgs e) => {
Console.WriteLine (e.Error);
};
} else {
//Let the user know that they need to enable LocationServices
Console.WriteLine ("Location services not enabled, please enable this in your Settings");
}
}
//This will keep going in the background and the foreground
public void PrintLocation (object sender, LocationUpdatedEventArgs e)
{
CLLocation location = e.Location;
Console.WriteLine ("Altitude: " + location.Altitude + " meters");
Console.WriteLine ("Longitude: " + location.Coordinate.Longitude);
Console.WriteLine ("Latitude: " + location.Coordinate.Latitude);
Console.WriteLine ("Course: " + location.Course);
Console.WriteLine ("Speed: " + location.Speed);
}
}
} | 32.333333 | 112 | 0.715851 | [
"Apache-2.0"
] | G3r3rd/mobile-samples | BackgroundLocationDemo/location.iOS/LocationManager.cs | 3,104 | C# |
/////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Forge Partner Development
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Diagnostics;
using System.IO.Compression;
using Newtonsoft.Json;
using Autodesk.Max;
namespace Autodesk.Forge.Sample.DesignAutomation.Max
{
/// <summary>
/// Used to hold the parameters to change
/// </summary>
public class InputParams
{
public List<float> VertexPercents { get; set; }
public bool KeepNormals { get; set; }
public bool CollapseStack { get; set; }
}
/// <summary>
/// Iterate entire scene to get all nodes
/// Adds ProOptimizer modifier to each node
/// </summary>
static public class ParameterChanger
{
static List<IINode> m_sceneNodes = new List<IINode> { };
/// <summary>
/// This will return a modifier from the stack
/// </summary>
/// <param name="nodeToSearch"> Input node to search. </param>
/// <param name="cid"> Input the class id of the modifier to find. </param>
/// <returns> The found modifier or null if not found. </returns>
static public IModifier GetModifier(IINode nodeToSearch, IClass_ID cid)
{
IGlobal global = Autodesk.Max.GlobalInterface.Instance;
IIDerivedObject dobj = nodeToSearch.ObjectRef as IIDerivedObject;
while (dobj != null)
{
int nmods = dobj.NumModifiers;
for (int i = 0; i < nmods; i++)
{
IModifier mod = dobj.GetModifier(i);
// have to compare ClassID Parts A and B separately. The equals operator is not
// implemented so it will return false even when they are equal.
if ((mod.ClassID.PartA == cid.PartA) && (mod.ClassID.PartB == cid.PartB))
return mod;
}
dobj = dobj.ObjRef as IIDerivedObject;
}
return null;
}
//
/// <summary>
/// Adds an object space modifier to provided node (by handle).
/// </summary>
/// <param name="nodeHandle"> Input the node handle to add the modifier to. </param>
/// <param name="cid"> Input the class id of the modifier add. </param>
/// <returns> Returns 1 if successful or -1 if not. </returns>
static public int AddOsmModifier(IINode node, IClass_ID cid)
{
try
{
IGlobal global = Autodesk.Max.GlobalInterface.Instance;
IInterface14 ip = global.COREInterface14;
IObject obj = node.ObjectRef;
IIDerivedObject dobj = global.CreateDerivedObject(obj);
object objMod = ip.CreateInstance(SClass_ID.Osm, cid as IClass_ID);
IModifier mod = (IModifier)objMod;
dobj.AddModifier(mod, null, 0); // top of stack
node.ObjectRef = dobj;
}
catch (Exception ex)
{
Debug.Print(ex.Message);
return -1;
}
return 1;
}
public enum ProOptimizerPBValues
{
optimizer_main_ratio = 0,
optimizer_main_vertexcount,
optimizer_main_calculate,
optimizer_options_optmode,
optimizer_options_keep_materials,
optimizer_options_keep_uv,
optimizer_options_lock_uv,
optimizer_options_tolerance_uv,
optimizer_options_keep_vc,
optimizer_options_lock_vc,
optimizer_options_merge_faces,
optimizer_options_merge_faces_angle,
optimizer_options_merge_points,
optimizer_options_merge_points_threshold,
optimizer_options_preserve_selection,
optimizer_options_invert_selection,
optimizer_options_tolerance_vc,
optimizer_symmetry_mode,
optimizer_symmetry_tolerance,
optimizer_advanced_compact,
optimizer_advanced_flip,
optimizer_options_keep_normals,
optimizer_options_normal_mode,
optimizer_options_normal_threshold,
optimizer_advanced_lock_points
}
/// <summary>
/// Adds the Shell modifier to the provided node (by handle).
/// </summary>
/// <param name="nodeHandle"> Input the node handle to add the modifier to. </param>
/// <param name="shellAmount"> Input the amount of shell thickness as float. </param>
/// <returns> Returns 1 if successful or -1 if not. </returns>
static public int AddOsmProoptimizer(IINode node, float VertexPercent, bool KeepNormals)
{
try
{
IGlobal global = Autodesk.Max.GlobalInterface.Instance;
IInterface14 ip = global.COREInterface14;
int t = ip.Time;
// classID:#(1056067556, 1496462090)
IClass_ID cidOsmProoptimizer = global.Class_ID.Create(0x3EF24FE4, 0x5932330A);
AddOsmModifier(node, cidOsmProoptimizer);
IModifier mod = GetModifier(node, cidOsmProoptimizer);
if (mod != null)
{
// In order to get the "Calculate" parameter to trigger the modifier to execute, we have to enable some UI elements.
ip.CmdPanelOpen = true; // ensures the command panel in general is open
ip.SelectNode(node, true); // Select the node to make it active
ip.CommandPanelTaskMode = 2; // TASK_MODE_MODIFY. This makes the modifier panel active.
// Now we can set the parameters on the modifier, and at end "calculate" the results.
IIParamBlock2 pb = mod.GetParamBlock(0);
pb.SetValue((int)ProOptimizerPBValues.optimizer_main_ratio, t, VertexPercent, 0);
pb.SetValue((int)ProOptimizerPBValues.optimizer_options_keep_uv, t, 1, 0);
pb.SetValue((int)ProOptimizerPBValues.optimizer_options_keep_normals, t, 0, 0);
// There is no true way to know if this was valid/invalid for the mesh, so we check the outer level routine on triobject for changes. **
pb.SetValue((int)ProOptimizerPBValues.optimizer_main_calculate, t, 1, 0);
ip.ClearNodeSelection(false);
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
return -1;
}
return 1;
}
//
/// <summary>
/// Recursively go through the scene and get all nodes
/// Use the Autodesk.Max APIs to get the children nodes
/// </summary>
static private void GetSceneNodes(IINode node)
{
m_sceneNodes.Add(node);
for (int i = 0; i < node.NumberOfChildren; i++)
GetSceneNodes(node.GetChildNode(i));
}
static public string UpdateNodes(float vertexPercent, bool keepNormals, bool collapseStack)
{
IGlobal globalInterface = Autodesk.Max.GlobalInterface.Instance;
IInterface14 coreInterface = globalInterface.COREInterface14;
// start the scene process
globalInterface.TheHold.Begin();
IINode nodeRoot = coreInterface.RootNode;
m_sceneNodes.Clear();
GetSceneNodes(nodeRoot);
List<IINode> optimizedNodes = new List<IINode> { };
// Iterate each node in the scene file and process all meshes into ProOptimized meshes.
foreach (IINode node in m_sceneNodes)
{
// Check for object assigned to node (could be something other than object)
if (node.ObjectRef != null) {
IObjectState os = node.ObjectRef.Eval(coreInterface.Time);
IObject objOriginal = os.Obj;
if (!objOriginal.IsSubClassOf(globalInterface.TriObjectClassID))
{
// If it is NOT, see if we can convert it...
if (objOriginal.CanConvertToType(globalInterface.TriObjectClassID) == 1)
{
objOriginal = objOriginal.ConvertToType(coreInterface.Time, globalInterface.TriObjectClassID);
}
else
{
RuntimeExecute.LogTrace("\nNode {0} Object Not Converted Error: {1}", node.NodeName, objOriginal.ObjectName);
continue;
}
}
ITriObject tri = objOriginal as ITriObject;
if (tri == null)
{
RuntimeExecute.LogTrace("\nNode {0} Object Not Converted Error: {1}", node.NodeName, objOriginal.ObjectName);
continue;
}
int val = tri.Mesh.NumVerts;
AddOsmProoptimizer(node, vertexPercent, keepNormals);
// get new mesh state
os = node.ObjectRef.Eval(coreInterface.Time);
tri = os.Obj as ITriObject;
// ** after modifier operation we can see if success by checking if the mesh size is different than before
if (val != tri.Mesh.NumVerts)
{
if (collapseStack)
coreInterface.CollapseNode(node, true);
optimizedNodes.Add(node);
}
}
}
int status;
if (optimizedNodes.Count() > 0)
{
// Build result file name based on percentage used
string full_filename = coreInterface.CurFilePath;
string filename = coreInterface.CurFileName;
vertexPercent = vertexPercent * 100;
string stringVertexPercent = vertexPercent.ToString("F1");
stringVertexPercent = stringVertexPercent.Replace('.', '_');
string output = "outputFile-" + stringVertexPercent + ".max";
string new_filename = full_filename.Replace(filename, output);
status = coreInterface.SaveToFile(new_filename, true, false);
// setup to export as FBX as well
string outputFBX = new_filename.Replace(".max", ".fbx");
string msCmdFbxExport = "exportFile \"" + outputFBX + "\" #noPrompt using:FBXEXP";
bool fbxOk = globalInterface.ExecuteMAXScriptScript(msCmdFbxExport, false, null, false);
// If we changed something, put scene back for next iteration
globalInterface.TheHold.Cancel();
if ((status == 0) || (fbxOk == false)) // error saving max or fbx file
return null;
return new_filename;
}
return null;
}
}
/// <summary>
/// This class is used to execute the automation. Above class could be connected to UI elements, or run by scripts directly.
/// This class takes the input from JSON input and uses those values. This way it is more cohesive to web development.
/// </summary>
static public class RuntimeExecute
{
static public int ProOptimizeMesh()
{
int count = 0;
// Run entire code block with try/catch to help determine errors
try
{
// read input parameters from JSON file
InputParams inputParams = JsonConvert.DeserializeObject<InputParams>(File.ReadAllText("params.json"));
/*InputParams inputParams = new InputParams
{
VertexPercents = new List<float> { 0.225F, 0.426F, 0.752F, 0.895F },
KeepNormals = false,
CollapseStack = false
};*/
List<string> solution_files = new List <string> { };
foreach (float n in inputParams.VertexPercents)
{
string status = ParameterChanger.UpdateNodes(n, inputParams.KeepNormals, inputParams.CollapseStack);
if (status != null)
{
count += 1; // number of solutions successfully created as new scene files.
// add MAX files
solution_files.Add(status);
// add FBX files
status = status.Replace(".max", ".fbx");
solution_files.Add(status);
}
}
if (solution_files.Count > 0)
{
string zipName = @".\output.zip";
using (ZipArchive newZipFile = ZipFile.Open(zipName, ZipArchiveMode.Create))
{
foreach (string file in solution_files)
{
newZipFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
}
}
}
}
catch (Exception e)
{
LogTrace("Exception Error: " + e.Message);
return -1; //fail
}
LogTrace("Changed {0} scenes.", count);
return count; // 0+ means success, and how many objects were changed.
}
/// <summary>
/// Information sent to this LogTrace will appear on the Design Automation output
/// </summary>
public static void LogTrace(string format, params object[] args)
{
IGlobal globalInterface = Autodesk.Max.GlobalInterface.Instance;
IInterface14 coreInterface = globalInterface.COREInterface14;
ILogSys log = coreInterface.Log;
// Note flags are necessary to produce Design Automation output. This is same as C++:
// SYSLOG_INFO | SYSLOG_IGNORE_VERBOSITY | SYSLOG_BROADCAST
log.LogEntry(0x00000004 | 0x00040000 | 0x00010000, false, "", string.Format(format, args));
}
}
} | 42.663866 | 156 | 0.55538 | [
"MIT"
] | kevinvandecar/design.automation.3dsmax-csharp-meshoptimizer | ProOptimizerAutomation/Command.cs | 15,233 | C# |
using System;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
namespace XamarinFormsDemo.Views {
public partial class NewItemPage : ContentPage {
public Item Item { get; set; }
public NewItemPage() {
InitializeComponent();
Item = new Item {
Id = Guid.NewGuid().ToString(),
Text = "Item name",
Description = "This is an item description."
};
BindingContext = this;
}
async void Save_Clicked(object sender, EventArgs e) {
MessagingCenter.Send(this, "AddItem", Item);
await Navigation.PopToRootAsync();
}
}
}
| 24.464286 | 61 | 0.559124 | [
"MIT"
] | DevExpress/XPO | Tutorials/Xamarin.Forms/XamarinFormsDemo/Views/NewItemPage.xaml.cs | 687 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// alipay.overseas.transfer.consult
/// </summary>
public class AlipayOverseasTransferConsultRequest : IAlipayRequest<AlipayOverseasTransferConsultResponse>
{
/// <summary>
/// 跨境汇款
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest 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 AlipayObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.overseas.transfer.consult";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if (udfParams == null)
{
udfParams = new Dictionary<string, string>();
}
udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
if (udfParams != null)
{
parameters.AddAll(udfParams);
}
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.456522 | 109 | 0.538462 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Request/AlipayOverseasTransferConsultRequest.cs | 3,247 | C# |
using System;
using System.Collections.Generic;
namespace Agence.Domain.Entities
{
public partial class CaoOsStatus
{
public long CoStatusAtual { get; set; }
public string DsStatus { get; set; }
}
}
| 19.083333 | 47 | 0.668122 | [
"Apache-2.0"
] | MoyaSoftInk/Sputnik | Agence/Agence.Domain/Entities/CaoOsStatus.cs | 231 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using DEM_MVC_BL.Interfaces.IServices.Conference;
using DEM_MVC_BL.Models.PollModels;
using DEM_MVC_BL.Models.PollOptionModels;
using DEM_MVC_DAL.Entities.PollEntities;
using DEM_MVC_DAL.Entities.PollOptionEntities;
using DEM_MVC_DAL.Interfaces.IFactory;
using DEM_MVC_DAL.Interfaces.IRepositories;
using DEM_MVC_Infrastructure.Models;
namespace DEM_MVC_BL.Services.Conference
{
public class PollReadService : IPollReadService
{
private readonly IConnectionFactory _connectionFactory;
private readonly IPollRepository _pollRepository;
private readonly IPollOptionRepository _pollOptionRepository;
public PollReadService(IConnectionFactory connectionFactory,
IPollRepository pollRepository,
IPollOptionRepository pollOptionRepository)
{
_connectionFactory = connectionFactory;
_pollRepository = pollRepository;
_pollOptionRepository = pollOptionRepository;
}
public List<PollViewModel> GetPollViewModelWithOptionsByTopicId(int topicId)
{
var pollViewModels = new List<PollViewModel>();
var pollOptionsViewModels = new List<PollOptionViewModel>();
try
{
var pollEntities = _pollRepository.GetPollsByTopicId(topicId, _connectionFactory);
var pollOptionEntities = _pollOptionRepository.GetPollOptionsByPollsId(pollEntities.Select(x => x.PollId).ToList(), _connectionFactory);
pollViewModels = Mapper.Map<List<PollEntity>, List<PollViewModel>>(pollEntities);
pollOptionsViewModels = Mapper.Map<List<PollOptionEntity>, List<PollOptionViewModel>>(pollOptionEntities);
foreach (var pollViewModel in pollViewModels)
{
var pollsOptionViewModels = pollOptionsViewModels.Where(x => x.PollId == pollViewModel.PollId).OrderBy(x => x.PollOptionId).ToList();
pollsOptionViewModels = CalculatePollOptionTotalPercent(pollsOptionViewModels);
pollViewModel.PollOptionList = pollsOptionViewModels;
}
}
catch (Exception exception)
{
DemLogger.Current.Error(exception, $"{nameof(PollReadService)}. Error in function {DemLogger.GetCallerInfo()}");
}
return pollViewModels;
}
private List<PollOptionViewModel> CalculatePollOptionTotalPercent(List<PollOptionViewModel> pollsOptionViewModels)
{
double totalVotes = pollsOptionViewModels.Sum(x => x.PollOptionTotal);
foreach (var pollsOptionViewModel in pollsOptionViewModels)
{
pollsOptionViewModel.PollOptionTotalPercent = (100 * pollsOptionViewModel.PollOptionTotal) / totalVotes;
}
return pollsOptionViewModels;
}
}
} | 43.764706 | 153 | 0.691868 | [
"MIT"
] | AndreyShpilevoy/DemProject | DEM_MVC_BL/Services/Conference/PollReadService.cs | 2,978 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.GameLift;
using Amazon.GameLift.Model;
namespace Amazon.PowerShell.Cmdlets.GML
{
/// <summary>
/// Removes locations from a multi-location fleet. When deleting a location, all game
/// server process and all instances that are still active in the location are shut down.
///
///
///
/// <para>
/// To delete fleet locations, identify the fleet ID and provide a list of the locations
/// to be deleted.
/// </para><para>
/// If successful, GameLift sets the location status to <code>DELETING</code>, and begins
/// to shut down existing server processes and terminate instances in each location being
/// deleted. When completed, the location status changes to <code>TERMINATED</code>.
/// </para><para><b>Learn more</b></para><para><a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-intro.html">Setting
/// up GameLift fleets</a></para><para><b>Related actions</b></para><para><a>CreateFleetLocations</a> | <a>DescribeFleetLocationAttributes</a> | <a>DescribeFleetLocationCapacity</a>
/// | <a>DescribeFleetLocationUtilization</a> | <a>DescribeFleetAttributes</a> | <a>DescribeFleetCapacity</a>
/// | <a>DescribeFleetUtilization</a> | <a>UpdateFleetCapacity</a> | <a>StopFleetActions</a>
/// | <a>DeleteFleetLocations</a> | <a href="https://docs.aws.amazon.com/gamelift/latest/developerguide/reference-awssdk.html#reference-awssdk-resources-fleets">All
/// APIs by task</a></para>
/// </summary>
[Cmdlet("Remove", "GMLFleetLocation", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]
[OutputType("Amazon.GameLift.Model.DeleteFleetLocationsResponse")]
[AWSCmdlet("Calls the Amazon GameLift Service DeleteFleetLocations API operation.", Operation = new[] {"DeleteFleetLocations"}, SelectReturnType = typeof(Amazon.GameLift.Model.DeleteFleetLocationsResponse))]
[AWSCmdletOutput("Amazon.GameLift.Model.DeleteFleetLocationsResponse",
"This cmdlet returns an Amazon.GameLift.Model.DeleteFleetLocationsResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class RemoveGMLFleetLocationCmdlet : AmazonGameLiftClientCmdlet, IExecutor
{
#region Parameter FleetId
/// <summary>
/// <para>
/// <para>A unique identifier for the fleet to delete locations for. You can use either the
/// fleet ID or ARN value.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String FleetId { get; set; }
#endregion
#region Parameter Location
/// <summary>
/// <para>
/// <para>The list of fleet locations to delete. Specify locations in the form of an AWS Region
/// code, such as <code>us-west-2</code>.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyCollection]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[Alias("Locations")]
public System.String[] Location { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.GameLift.Model.DeleteFleetLocationsResponse).
/// Specifying the name of a property of type Amazon.GameLift.Model.DeleteFleetLocationsResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the FleetId parameter.
/// The -PassThru parameter is deprecated, use -Select '^FleetId' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^FleetId' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.FleetId), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-GMLFleetLocation (DeleteFleetLocations)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.GameLift.Model.DeleteFleetLocationsResponse, RemoveGMLFleetLocationCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.FleetId;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.FleetId = this.FleetId;
#if MODULAR
if (this.FleetId == null && ParameterWasBound(nameof(this.FleetId)))
{
WriteWarning("You are passing $null as a value for parameter FleetId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
if (this.Location != null)
{
context.Location = new List<System.String>(this.Location);
}
#if MODULAR
if (this.Location == null && ParameterWasBound(nameof(this.Location)))
{
WriteWarning("You are passing $null as a value for parameter Location which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.GameLift.Model.DeleteFleetLocationsRequest();
if (cmdletContext.FleetId != null)
{
request.FleetId = cmdletContext.FleetId;
}
if (cmdletContext.Location != null)
{
request.Locations = cmdletContext.Location;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.GameLift.Model.DeleteFleetLocationsResponse CallAWSServiceOperation(IAmazonGameLift client, Amazon.GameLift.Model.DeleteFleetLocationsRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon GameLift Service", "DeleteFleetLocations");
try
{
#if DESKTOP
return client.DeleteFleetLocations(request);
#elif CORECLR
return client.DeleteFleetLocationsAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String FleetId { get; set; }
public List<System.String> Location { get; set; }
public System.Func<Amazon.GameLift.Model.DeleteFleetLocationsResponse, RemoveGMLFleetLocationCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 47.464419 | 279 | 0.620769 | [
"Apache-2.0"
] | QPC-database/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/GameLift/Basic/Remove-GMLFleetLocation-Cmdlet.cs | 12,673 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Wexflow.Tasks.TextsDecryptor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Wexflow.Tasks.TextsDecryptor")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("6fd67ff8-eeda-41b1-bf5e-073d6039ba59")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("5.7.0.0")]
[assembly: AssemblyFileVersion("5.7.0.0")]
| 41.222222 | 102 | 0.752695 | [
"MIT"
] | drewfreyling/Wexflow | src/net/Wexflow.Tasks.TextsDecryptor/Properties/AssemblyInfo.cs | 1,509 | C# |
//
// Copyright (c) Microsoft and contributors. 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://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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Management.Network
{
/// <summary>
/// The Network Resource Provider API includes operations for managing the
/// subnets for your subscription.
/// </summary>
public partial interface INetworkInterfaceOperations
{
/// <summary>
/// The Put NetworkInterface operation creates/updates a
/// networkInterface
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update NetworkInterface operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for PutNetworkInterface Api servive call
/// </returns>
Task<NetworkInterfacePutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken);
/// <summary>
/// The delete netwokInterface operation deletes the specified
/// netwokInterface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken);
/// <summary>
/// The Put NetworkInterface operation creates/updates a
/// networkInterface
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update NetworkInterface operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken);
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken);
/// <summary>
/// The Get ntework interface operation retreives information about the
/// specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for GetNetworkInterface Api service call
/// </returns>
Task<NetworkInterfaceGetResponse> GetAsync(string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken);
/// <summary>
/// The Get ntework interface operation retreives information about the
/// specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for GetNetworkInterface Api service call
/// </returns>
Task<NetworkInterfaceGetResponse> GetVirtualMachineScaleSetNetworkInterfaceAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, CancellationToken cancellationToken);
/// <summary>
/// The List networkInterfaces opertion retrieves all the
/// networkInterfaces in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for ListNetworkInterface Api service call
/// </returns>
Task<NetworkInterfaceListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken);
/// <summary>
/// The List networkInterfaces opertion retrieves all the
/// networkInterfaces in a subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for ListNetworkInterface Api service call
/// </returns>
Task<NetworkInterfaceListResponse> ListAllAsync(CancellationToken cancellationToken);
/// <summary>
/// The list network interface operation retrieves information about
/// all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for ListNetworkInterface Api service call
/// </returns>
Task<NetworkInterfaceListResponse> ListVirtualMachineScaleSetNetworkInterfacesAsync(string resourceGroupName, string virtualMachineScaleSetName, CancellationToken cancellationToken);
}
}
| 42.608491 | 244 | 0.629248 | [
"Apache-2.0"
] | cwickham3/azure-sdk-for-net | src/ResourceManagement/Network/NetworkManagement/Generated/INetworkInterfaceOperations.cs | 9,033 | C# |
using System.Collections.Generic;
using System.Data.SqlClient;
using Dapper;
using Universe.Dashboard.DAL.MultiProvider;
namespace Universe.Dashboard.DAL.Tests.MultiProvider
{
public class SqlServerProvider4Tests : IProvider4Tests
{
private const string SERVERS_PATTERN = "MSSQL_TEST_SERVER";
public string EnvVarName => DashboardContextOptionsFactory.EnvNames.MSSqlDb;
public IProvider4Runtime Provider4Runtime => Providers4Runtime.SqlServer;
public List<string> GetServerConnectionStrings()
{
return MultiProviderExtensions.GetServerConnectionStrings(SERVERS_PATTERN);
}
public string CreateDatabase(string serverConnectionString, string dbName)
{
SqlConnectionStringBuilder b = new SqlConnectionStringBuilder(serverConnectionString);
var artifact = $"MS SQL Server database `{dbName}` on server {b.DataSource}";
MultiProviderExtensions.RiskyAction($"Creating {artifact}", () =>
{
using (var con = new SqlConnection(serverConnectionString))
{
con.Execute($"Create Database [{dbName}];");
}
});
b.InitialCatalog = dbName;
return b.ConnectionString;
}
public void DropDatabase(string serverConnectionString, string dbName)
{
using (SqlConnection con = new SqlConnection(serverConnectionString))
{
con.Execute($"Drop Database [{dbName}];");
}
}
}
} | 35.688889 | 98 | 0.63076 | [
"MIT"
] | devizer/KernelManagementLab | Universe.Dashboard.DAL.Tests/MultiProvider/SqlServerProvider4Tests.cs | 1,606 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using SFA.DAS.QnA.Api.Infrastructure;
using SFA.DAS.QnA.Api.Types;
using SFA.DAS.QnA.Application.Queries.Sequences.GetCurrentSequence;
using SFA.DAS.QnA.Application.Queries.Sequences.GetSequence;
using SFA.DAS.QnA.Application.Queries.Sequences.GetSequences;
namespace SFA.DAS.QnA.Api.Controllers
{
[Route("applications")]
[Produces("application/json")]
public class SequencesController : Controller
{
private readonly IMediator _mediator;
public SequencesController(IMediator mediator)
{
_mediator = mediator;
}
/// <summary>
/// Returns all of the Sequences for the Application
/// </summary>
/// <returns>An array of Sequences</returns>
/// <response code="200">Returns the Application's Sequences</response>
/// <response code="204">If there are no Sequences for the given Application Id</response>
/// <response code="404">If there is no Application for the given Application Id</response>
[HttpGet("{applicationId}/sequences")]
[ProducesResponseType(200)]
[ProducesResponseType(204)]
[ProducesResponseType(404)]
public async Task<ActionResult<List<Sequence>>> GetSequences(Guid applicationId)
{
var sequences = await _mediator.Send(new GetSequencesRequest(applicationId), CancellationToken.None);
if (!sequences.Success) return NotFound(new NotFoundError(sequences.Message));
if (sequences.Value.Count == 0) return NoContent();
return sequences.Value;
}
/// <summary>
/// Returns the requested Sequence
/// </summary>
/// <returns>The requested Sequence</returns>
/// <response code="200">Returns the requested sequence</response>
/// <response code="404">If the ApplicationId or SequenceId are not found</response>
[HttpGet("{applicationId}/sequences/{sequenceId:guid}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<ActionResult<Sequence>> GetSequence(Guid applicationId, Guid sequenceId)
{
var sequence = await _mediator.Send(new GetSequenceRequest(applicationId, sequenceId), CancellationToken.None);
if (!sequence.Success) return NotFound(new NotFoundError(sequence.Message));
return sequence.Value;
}
/// <summary>
/// Returns the requested Sequence
/// </summary>
/// <returns>The requested Sequence</returns>
/// <response code="200">Returns the requested sequence</response>
/// <response code="404">If the ApplicationId or SequenceNo are not found</response>
[HttpGet("{applicationId}/sequences/{sequenceNo:int}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public async Task<ActionResult<Sequence>> GetSequenceBySequenceNo(Guid applicationId, int sequenceNo)
{
var sequence = await _mediator.Send(new GetSequenceBySequenceNoRequest(applicationId, sequenceNo), CancellationToken.None);
if (!sequence.Success) return NotFound(new NotFoundError(sequence.Message));
return sequence.Value;
}
}
} | 42.6625 | 135 | 0.667448 | [
"MIT"
] | SkillsFundingAgency/das-qna-api | src/SFA.DAS.QnA.Api/Controllers/SequencesController.cs | 3,413 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lokanta_Otomasyonu
{
public abstract class Tutar
{
public static int tutar=0;
public abstract void tutarHesapla();
}
} | 19.571429 | 44 | 0.718978 | [
"MIT"
] | BurakErenCatal/Restaurant-Automation | Tutar.cs | 276 | C# |
using Honeydukes.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
namespace Honeydukes.Controllers
{
public class FlavorsController : Controller
{
private readonly HoneydukesContext _db;
public FlavorsController(HoneydukesContext db)
{
_db = db;
}
[HttpGet]
public ActionResult Index()
{
List<Flavor> model = _db.Flavors.ToList();
return View(model);
}
[Authorize]
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Flavor flavor)
{
_db.Flavors.Add(flavor);
_db.SaveChanges();
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Details(int id)
{
var thisFlavor = _db.Flavors
.Include(flavor => flavor.Treats)
.ThenInclude(join => join.Treat)
.FirstOrDefault(flavor => flavor.FlavorId == id);
return View(thisFlavor);
}
[Authorize]
[HttpGet]
public ActionResult Edit(int id)
{
var thisFlavor = _db.Flavors.FirstOrDefault(flavor => flavor.FlavorId == id);
return View(thisFlavor);
}
[HttpPost]
public ActionResult Edit(Flavor flavor)
{
_db.Entry(flavor).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Details", new { id = flavor.FlavorId });
}
[Authorize]
[HttpGet]
public ActionResult Delete(int id)
{
var thisFlavor = _db.Flavors.FirstOrDefault(flavor => flavor.FlavorId == id);
return View(thisFlavor);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
var thisFlavor = _db.Flavors.FirstOrDefault(flavor => flavor.FlavorId == id);
_db.Flavors.Remove(thisFlavor);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
} | 23.831325 | 83 | 0.648635 | [
"MIT"
] | jhvozdovich/candy-store | Honeydukes/Controllers/FlavorsController.cs | 1,978 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Engineering.DataSource;
using Engineering.DataSource.CoordinateSystems;
using Engineering.DataSource.OilGas;
using Engineering.DataSource.Tools;
using Kokkos;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Npgsql;
using NpgsqlTypes;
namespace OilGas.Data
{
public sealed class OilGasDbException : Exception
{
public OilGasDbException()
{
}
public OilGasDbException(string message)
: base(message)
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
internal static void Throw()
{
throw new OilGasDbException();
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
internal static void Throw(string message)
{
throw new OilGasDbException(message);
}
}
/// <summary>
/// New Mexico https://wwwapps.emnrd.state.nm.us/ocd/ocdpermitting/Data/Wells.aspx
/// </summary>
public sealed class OilGasDbContext : DbContext
{
public const string Host = "timothyrmcnealy.com";
public const string Port = "15432";
public const string DefaultDbName = "C:\\OilGas.db";
//public const string InMemoryName = ":memory:";
private static readonly IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
public DbSet<ShapeFileLocation> ShapeFileLocations { get; set; }
public DbSet<Company> Companys { get; set; }
public DbSet<DrillingPermit> DrillingPermits { get; set; }
public DbSet<DirectionalSurvey> DirectionalSurveys { get; set; }
public DbSet<Field> Fields { get; set; }
public DbSet<Lease> Leases { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<WellboreDetails> WellboreDetails { get; set; }
public DbSet<CompletionDetails> CompletionDetails { get; set; }
public DbSet<ReservoirData> ReservoirData { get; set; }
public DbSet<PerforationInterval> PerforationIntervals { get; set; }
public DbSet<OilProperties> OilProperties { get; set; }
public DbSet<GasProperties> GasProperties { get; set; }
public DbSet<WaterProperties> WaterProperties { get; set; }
public DbSet<ReservoirProperties> ReservoirProperties { get; set; }
public DbSet<DailyProduction> DailyProduction { get; set; }
public DbSet<MonthlyProduction> MonthlyProduction { get; set; }
public DbSet<CumulativeProduction> CumulativeProduction { get; set; }
public DbSet<Well> Wells { get; set; }
public NpgsqlConnection Connection { get; }
public static readonly ILoggerFactory DbLoggerFactory = LoggerFactory.Create(builder => { builder.AddFilter((category, level) =>
category == DbLoggerCategory.Database.Command.Name
&& level == LogLevel.Information)
.AddConsole(); });
/// <summary>var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";</summary>
public OilGasDbContext()
: this(CreateAndOpen())
{
}
public OilGasDbContext(NpgsqlConnection connection)
: base(new DbContextOptionsBuilder<OilGasDbContext>().UseLazyLoadingProxies()
.UseMemoryCache(_cache)
.UseNpgsql(connection)
//.EnableSensitiveDataLogging()
//.UseLoggerFactory(DbLoggerFactory)
.Options)
{
Connection = connection;
//command.ExecuteNonQuery();
//command.CommandText = $"PRAGMA foreign_keys = ON;";
//command.ExecuteNonQuery();
//command.CommandText = $"PRAGMA mmap_size={100 * 1024 * 1024};";
//command.ExecuteNonQuery();
//Database.EnsureCreated();
}
private static NpgsqlConnection CreateAndOpen()
{
//NpgsqlConnection connection = new NpgsqlConnection($"Host={Host};Port={Port};Username={Encryption.Username};Password={Encryption.Password};Database=OilGas");
NpgsqlConnection connection;
try
{
connection = new NpgsqlConnection($"Host={Host};Port={Port};Username={Encryption.Username};Password={Encryption.Password};Database=OilGas");
connection.Open();
}
catch(Exception)
{
connection = new NpgsqlConnection($"Host={Host};Port={Port};Username=db_user;Password=dbAccess;Database=OilGas");
connection.Open();
}
//NpgsqlCommand command = connection.CreateCommand();
//command.CommandText = $"PRAGMA automatic_index = ON;";
//command.ExecuteNonQuery();
//command.CommandText = $"PRAGMA foreign_keys = ON;";
//command.ExecuteNonQuery();
//command.CommandText = $"PRAGMA mmap_size={100 * 1024 * 1024};";
//command.ExecuteNonQuery();
//connection.Close();
//connection.Open();
return connection;
}
public void CloseConnection()
{
Connection.Close();
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
//}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ShapeFileLocation>().HasIndex(dp => new {dp.Id, dp.Api}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<WellboreDetails>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<CompletionDetails>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<ReservoirData>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<PerforationInterval>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently();
modelBuilder.Entity<CumulativeProduction>().HasIndex(dp => new {dp.Id, dp.Date}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<DailyProduction>().HasIndex(dp => new {dp.Id, dp.Date}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<DirectionalSurvey>().HasIndex(dp => new {dp.Id});
modelBuilder.Entity<DrillingPermit>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<Lease>().HasIndex(dp => new {dp.Number, dp.District}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<Field>().HasIndex(dp => new {dp.Number, dp.District}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<Location>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<GasProperties>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<MonthlyProduction>().HasIndex(dp => new {dp.Id, dp.Date}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<OilProperties>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<Company>().HasIndex(dp => dp.Number).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<ReservoirProperties>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<WaterProperties>().HasIndex(dp => new {dp.Id}).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<Well>().HasIndex(dp => dp.Api).IsCreatedConcurrently().IsUnique();
modelBuilder.Entity<ShapeFileLocation>().Property(p => p.Api).HasConversion(v => v.ToString(), v => new ApiNumber(v));
modelBuilder.Entity<DrillingPermit>().Property(p => p.Api).HasConversion(v => v.ToString(), v => new ApiNumber(v));
modelBuilder.Entity<Well>().Property(p => p.Api).HasConversion(v => v.ToString(), v => new ApiNumber(v));
modelBuilder.Entity<CumulativeProduction>().Property(p => p.Date).HasConversion(v => (DateTime)v, v => (ProductionDate)v);
modelBuilder.Entity<DailyProduction>().Property(p => p.Date).HasConversion(v => (DateTime)v, v => (ProductionDate)v);
modelBuilder.Entity<MonthlyProduction>().Property(p => p.Date).HasConversion(v => (DateTime)v, v => (ProductionDate)v);
//modelBuilder.HasPostgresExtension("hstore");
//HasPostgresExtension("uuid-ossp")
}
public override void Dispose()
{
base.Dispose();
if(Connection.State != ConnectionState.Closed)
{
Connection.Close();
Connection.Dispose();
}
}
//public void AutomaticIndex()
//{
// NpgsqlCommand command = Connection.CreateCommand();
// command.CommandText = $"PRAGMA automatic_index = ON;";
// command.ExecuteNonQuery();
//}
//public void ForeignKey()
//{
// NpgsqlCommand command = Connection.CreateCommand();
// command.CommandText = $"PRAGMA foreign_keys = ON;";
// command.ExecuteNonQuery();
//}
//public void MmapSize()
//{
// NpgsqlCommand command = Connection.CreateCommand();
// command.CommandText = $"PRAGMA mmap_size={100 * 1024 * 1024};";
// command.ExecuteNonQuery();
//}
//public void Compact()
//{
// NpgsqlCommand command = Connection.CreateCommand();
// command.CommandText = "PRAGMA auto_vacuum = FULL;";
// //VACUUM main INTO filename;
// command.ExecuteNonQuery();
//}
public void DropAllTables()
{
NpgsqlCommand command = Connection.CreateCommand();
command.CommandText =
"DROP TABLE \"Well\",\"WaterProperties\",\"ReservoirProperties\",\"Companys\",\"OilProperties\",\"MonthlyProduction\",\"Location\",\"GasProperties\",\"Field\",\"DrillingPermit\",\"DirectionalSurvey\",\"DailyProduction\",\"CumulativeProduction\",\"CompletionDetails\" CASCADE;";
command.ExecuteNonQuery();
SaveChanges();
}
public void Restore()
{
//SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
}
public void Backup()
{
NpgsqlCommand command = Connection.CreateCommand();
command.CommandText = $"BACKUP DATABASE databasename TO DISK = \"{DefaultDbName}\";";
command.ExecuteNonQuery();
}
public void LoadRelationalProperties(Well well)
{
//Entry(well).Reference(nameof(Well.Company)).Load();
//Entry(well).Reference(nameof(Well.Field)).Load();
//Entry(well).Reference(nameof(Well.Lease)).Load();
//Entry(well).Reference(nameof(Well.Location)).Load();
//Entry(well).Reference(nameof(Well.WellboreDetails)).Load();
//Entry(well).Collection(nameof(Well.CompletionDetails)).Load();
//Entry(well).Collection(nameof(Well.DirectionalSurvey)).Load();
//Entry(well).Collection(nameof(Well.DailyProduction)).Load();
//Entry(well).Collection(nameof(Well.MonthlyProduction)).Load();
//Entry(well).Collection(nameof(Well.CumulativeProduction)).Load();
//Entry(well).Collection(nameof(Well.ReservoirData)).Load();
//foreach(ReservoirData reservoirData in well.ReservoirData)
//{
// Entry(reservoirData).Reference(nameof(Engineering.DataSource.OilGas.ReservoirData.GasProperties)).Load();
// Entry(reservoirData).Reference(nameof(Engineering.DataSource.OilGas.ReservoirData.OilProperties)).Load();
// Entry(reservoirData).Reference(nameof(Engineering.DataSource.OilGas.ReservoirData.WaterProperties)).Load();
// Entry(reservoirData).Reference(nameof(Engineering.DataSource.OilGas.ReservoirData.ReservoirProperties)).Load();
//}
}
public void LoadDb(string filePath)
{
NpgsqlConnection dbFile = new NpgsqlConnection($"Data Source={filePath}");
dbFile.Open();
//dbFile.BackupDatabase(Connection);
dbFile.Close();
Console.WriteLine($"{filePath} loaded.");
}
public void LoadOperatorsCsv(string filePath)
{
int num_threads = 4;
int num_numa = 1;
int device_id = 0;
int ndevices = 1;
int skip_device = 9999;
InitArguments arguments = new InitArguments(num_threads, num_numa, device_id, ndevices, skip_device, false);
List<string[]> rows;
using(ScopeGuard.Get(arguments))
{
using(MemoryMapped mm = new MemoryMapped(filePath))
{
MappedCsvReader csvReader = new MappedCsvReader(mm);
(_, rows) = csvReader.ReadFile(1);
}
}
Company[] entries = new Company[rows.Count];
Parallel.ForEach(Partitioner.Create(0, rows.Count),
(row,
loopState) =>
{
string number;
string name;
for(int i = row.Item1; i < row.Item2; i++)
{
number = rows[i][0];
name = rows[i][1];
entries[i] = new Company(name, number);
}
});
using(NpgsqlTransaction transaction = Connection.BeginTransaction(IsolationLevel.ReadCommitted))
{
Companys.AddRange(entries);
transaction.Commit();
SaveChanges();
}
}
//@"C:\Users\tehgo\Desktop\DrillingPermits_STX_2000_2020.csv"
public void LoadDrillingPermitsCsv(string filePath)
{
int num_threads = 4;
int num_numa = 1;
int device_id = 0;
int ndevices = 1;
int skip_device = 9999;
InitArguments arguments = new InitArguments(num_threads, num_numa, device_id, ndevices, skip_device, false);
List<string[]> rows;
using(ScopeGuard.Get(arguments))
{
using(MemoryMapped mm = new MemoryMapped(filePath))
{
MappedCsvReader csvReader = new MappedCsvReader(mm);
(_, rows) = csvReader.ReadFile(1);
}
}
int OperatorNumber(string operatorNameNumber)
{
operatorNameNumber = operatorNameNumber.Substring(0, operatorNameNumber.Length - 1);
int last = operatorNameNumber.LastIndexOf("(", StringComparison.InvariantCulture);
return int.Parse(operatorNameNumber.Substring(last + 1));
}
Well[] entries = new Well[rows.Count];
List<Company> companies = Companys.ToList();
Parallel.ForEach(Partitioner.Create(0, rows.Count),
(row,
loopState) =>
{
int index;
string statusDate;
int? status;
ApiNumber api;
string operatorNameNumber;
string leaseName;
string wellNumber;
string dist;
string county;
string wellboreProfile;
string filingPurpose;
string amend;
string totalDepth;
string stackedLateralParentWellDp;
string currentQueue;
int operatorNumber;
Company company;
//for(int i = 0; i < rows.Count; i++)
for(int i = row.Item1; i < row.Item2; i++)
{
index = 0;
statusDate = rows[i][index++];
status = int.Parse(rows[i][index++]);
api = new ApiNumber("42" + rows[i][index++]);
operatorNameNumber = rows[i][index++];
leaseName = rows[i][index++];
wellNumber = rows[i][index++];
dist = rows[i][index++];
county = rows[i][index++];
wellboreProfile = rows[i][index++];
filingPurpose = rows[i][index++];
amend = rows[i][index++];
totalDepth = rows[i][index++];
stackedLateralParentWellDp = rows[i][index++];
currentQueue = rows[i][index];
operatorNumber = OperatorNumber(operatorNameNumber);
company = companies.FirstOrDefault(o => o.Number == operatorNumber);
entries[i] = new Well(api, leaseName, wellNumber, new Location(county, "Texas"), company);
}
});
using(NpgsqlTransaction transaction = Connection.BeginTransaction(IsolationLevel.ReadCommitted))
{
Wells.AddRange(entries);
transaction.Commit();
SaveChanges();
}
}
public void LoadFracFocusRegistryCsv(string filePath)
{
//CsvReader csvReader = new CsvReader(File.ReadAllBytes(filePath));
//(List<string[]> header, List<string[]> rows) = csvReader.ReadFile(1);
//Registry[] entries = new Registry[rows.Count];
//Parallel.ForEach(Partitioner.Create(0, rows.Count),
// (row,
// loopState) =>
// {
// for(int i = row.Item1; i < row.Item2; i++)
// {
// entries[i] = new Registry(rows[i]);
// }
// });
//using(NpgsqlTransaction transaction = Connection.BeginTransaction(IsolationLevel.ReadCommitted))
//{
// FracFocusRegistry.AddRange(entries);
// transaction.Commit();
// SaveChanges();
//}
}
public void AddRange(List<ShapeFileLocation> locations)
{
ShapeFileLocations.AddRange(locations);
}
public void ConvertLocations()
{
List<ShapeFileLocation> shapeFileLocations = ShapeFileLocations.ToList();
double surfaceEasting;
double surfaceNorthing;
double bottomEasting;
double bottomNorthing;
ShapeFileLocation shapeFileLocation;
for(int i = 0; i < shapeFileLocations.Count(); ++i)
{
shapeFileLocation = shapeFileLocations[i];
if(!shapeFileLocation.SurfaceLatitude83.HasValue ||
!shapeFileLocation.SurfaceLongitude83.HasValue ||
!shapeFileLocation.BottomLatitude83.HasValue ||
!shapeFileLocation.BottomLongitude83.HasValue)
{
continue;
}
(surfaceEasting, surfaceNorthing) = CoordinateConverter.toWebMercator(shapeFileLocation.SurfaceLongitude83.Value, shapeFileLocation.SurfaceLatitude83.Value);
(bottomEasting, bottomNorthing) = CoordinateConverter.toWebMercator(shapeFileLocation.BottomLongitude83.Value, shapeFileLocation.BottomLatitude83.Value);
shapeFileLocation.SurfaceEasting83 = surfaceEasting;
shapeFileLocation.SurfaceNorthing83 = surfaceNorthing;
shapeFileLocation.BottomEasting83 = bottomEasting;
shapeFileLocation.BottomNorthing83 = bottomNorthing;
ShapeFileLocations.Update(shapeFileLocation);
}
SaveChanges();
}
public void Add(Well well)
{
Wells.Add(well);
}
public async Task AddAsync(Well well)
{
await Wells.AddAsync(well);
}
public void AddRange(List<Well> wells)
{
Wells.AddRange(wells);
}
public async Task AddRangeAsync(List<Well> wells)
{
await Wells.AddRangeAsync(wells);
}
public void Update(Well well)
{
Wells.Update(well);
}
public void Remove(Well well)
{
Wells.Remove(well);
}
public async Task RemoveAsync(Well well)
{
await Task.FromResult(Wells.Remove(well));
}
public void RemoveRange(List<Well> wells)
{
Wells.RemoveRange(wells);
}
public void Commit()
{
SaveChanges();
}
public async Task CommitAsync()
{
await SaveChangesAsync();
}
private IQueryable<Well> GetAllWellsIncluding()
{
return Wells;
//.Include(w => w.Location)
//.Include(w => w.Lease)
//.Include(w => w.Field)
//.Include(w => w.Company)
//.Include(w => w.WellboreDetails)
//.Include(w => w.CompletionDetails).ThenInclude(c => c.PerforationIntervals)
//.Include(w => w.ReservoirData).ThenInclude(r => r.ReservoirProperties)
//.Include(w => w.ReservoirData).ThenInclude(r => r.GasProperties)
//.Include(w => w.ReservoirData).ThenInclude(r => r.OilProperties)
//.Include(w => w.ReservoirData).ThenInclude(r => r.WaterProperties)
//.Include(w => w.DirectionalSurvey)
//.Include(w => w.DailyProduction)
//.Include(w => w.MonthlyProduction)
//.Include(w => w.CumulativeProduction);
}
private async Task<IQueryable<Well>> GetAllWellsIncludingAsync()
{
return await Task.FromResult(Wells.AsQueryable());
}
public List<Well> GetAllWells()
{
List<Well> wells = GetAllWellsIncluding().ToList();
return wells;
}
public async Task<List<Well>> GetAllWellsAsync()
{
List<Well> wells = (await GetAllWellsIncludingAsync()).ToList();
return wells;
}
public List<Well> GetWellsByOperator(string name)
{
List<Well> wells = GetAllWellsIncluding().Where(w => w.Company.Name.Contains(name)).ToList();
return wells;
}
public async Task<List<Well>> GetWellsByOperatorAsync(string name)
{
List<Well> wells = (await GetAllWellsIncludingAsync()).Where(w => w.Company.Name.Contains(name)).ToList();
return wells;
}
public List<Well> GetWellsByCounty(string county)
{
List<Well> wells = Wells.Where(w => w.Location.County.ToUpper() == county.ToUpper()).ToList();
return wells;
}
public async Task<List<Well>> GetWellsByCountyAsync(string county)
{
List<Well> wells = (await GetAllWellsIncludingAsync()).Where(w => w.Location.County == county.ToUpper()).ToList();
return wells;
}
public Well GetWellByApi(ApiNumber api)
{
Well well = Wells.SingleOrDefault(w => w.Api == api);
return well;
}
public async Task<Well> GetWellByApiAsync(ApiNumber api)
{
Well well = await Wells.SingleOrDefaultAsync(w => w.Api == api);
return well;
}
public Lease GetLease(long number, int district)
{
return Leases.FirstOrDefault(f => f.Number == number && f.District == district);
}
public async Task<Lease> GetLeaseAsync(long number, int district)
{
return await Leases.FirstOrDefaultAsync(f => f.Number == number && f.District == district);
}
public Field GetField(long number, int district)
{
return Fields.FirstOrDefault(f => f.Number == number && f.District == district);
}
public async Task<Field> GetFieldAsync(long number, int district)
{
return await Fields.FirstOrDefaultAsync(f => f.Number == number && f.District == district);
}
public Field GetField(string name)
{
return Fields.FirstOrDefault(f => f.Name.Contains(name));
}
public async Task<Field> GetFieldAsync(string name)
{
return await Fields.FirstOrDefaultAsync(f => f.Name.Contains(name));
}
public Company GetOperator(long number)
{
return Companys.FirstOrDefault(o => o.Number == number);
}
public async Task<Company> GetOperatorAsync(long number)
{
return await Companys.FirstOrDefaultAsync(o => o.Number == number);
}
public Company GetOperator(string name)
{
return Companys.FirstOrDefault(f => f.Name.Contains(name));
}
public async Task<Company> GetOperatorAsync(string name)
{
return await Companys.FirstOrDefaultAsync(f => f.Name.Contains(name));
}
#region AddorUpdate
public Well AddorUpdate(Well entity)
{
Well existing = Wells.FirstOrDefault(e => e.Api == entity.Api);
if(existing != null)
{
return Wells.Update(entity).Entity;
}
return Wells.Add(entity).Entity;
}
public async Task<Well> AddorUpdateAsync(Well entity)
{
Well existing = await Wells.FirstOrDefaultAsync(e => e.Api == entity.Api);
if(existing != null)
{
return Wells.Update(entity).Entity;
}
return (await Wells.AddAsync(entity)).Entity;
}
#endregion
}
}
| 36.731114 | 293 | 0.538293 | [
"MIT"
] | trmcnealy/OilGas.Data | OilGas.Data/Data/OilGasDbContext.cs | 28,697 | C# |
using System.Security.Cryptography;
namespace Dalion.HttpMessageSigning.Signing {
public class CustomSignatureAlgorithm : ISignatureAlgorithm {
private bool _verificationResult;
private bool _isDisposed;
public CustomSignatureAlgorithm(string name) {
if (string.IsNullOrEmpty(name)) name = "NOTSUPPORTED";
Name = name;
_verificationResult = true;
_isDisposed = false;
}
public void Dispose() {
_isDisposed = true;
}
public string Name { get; }
public HashAlgorithmName HashAlgorithm { get; set; }
public void SetVerificationResult(bool result) {
_verificationResult = result;
}
public byte[] ComputeHash(string contentToSign) {
return new byte[] {1, 2, 3};
}
public bool VerifySignature(string contentToSign, byte[] signature) {
return _verificationResult;
}
public bool IsDisposed() {
return _isDisposed;
}
}
} | 27.487179 | 77 | 0.596082 | [
"MIT"
] | DavidLievrouw/HttpMessageSigning | src/HttpMessageSigning.Signing.Tests/CustomSignatureAlgorithm.cs | 1,072 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Tempest.Language;
namespace Tests.Tempest.Language
{
[TestFixture]
public class IdentifierTests
{
[Test]
public void DefaultInitialization()
{
Identifier name = default;
Assert.That(name.IsInvalid, Is.True);
}
[Test]
public void Initialization()
{
Identifier name = new("Sawyer");
Assert.That(name.IsInvalid, Is.False);
Assert.That(name.Name, Is.EqualTo("Sawyer"));
}
[Test]
public void Initialization_Null()
{
Assert.Catch(() => new Identifier(null!));
}
[Test]
public void Equality()
{
Identifier x = new("Jack");
Identifier y = new("Jack");
Assert.That(x, Is.EqualTo(y));
Assert.That(x == y, Is.True);
Assert.That(x.Equals(y), Is.True);
Assert.That(x.Equals((object)y), Is.True);
Identifier z = default;
Assert.That(z, Is.EqualTo(z));
Assert.That(z.Equals(z), Is.True);
Assert.That(x, Is.Not.EqualTo(z));
Assert.That(x == z, Is.False);
Assert.That(x.Equals(z), Is.False);
Assert.That(x.Equals((object)z), Is.False);
}
[Test]
public void Inequality()
{
Identifier x = new("Jack");
Identifier y = new("Kate");
Assert.That(x, Is.Not.EqualTo(y));
Assert.That(x == y, Is.False);
Assert.That(x.Equals(y), Is.False);
Assert.That(x.Equals((object)y), Is.False);
Identifier z = default;
Assert.That(x, Is.Not.EqualTo(z));
Assert.That(x != z, Is.True);
}
[Test]
public void HashCode()
{
Identifier x = new("Jack");
Identifier y = new("Jack");
Assert.That(x.GetHashCode(), Is.EqualTo(y.GetHashCode()));
}
[Test]
public void HashCodeOnDefault()
{
Identifier x = default;
Identifier y = default;
Assert.That(x.GetHashCode(), Is.EqualTo(y.GetHashCode()));
}
[Test]
public void AsString()
{
Identifier x = default;
Assert.That(x.ToString(), Is.Not.Null & Has.Length.GreaterThan(0));
Identifier y = new("Jack");
Assert.That(y.ToString(), Is.Not.Null & Has.Length.GreaterThan(0));
}
}
}
| 26.117647 | 79 | 0.510135 | [
"MIT"
] | foxesknow/Tempest | Tests.Tempest.Language/IdentifierTests.cs | 2,666 | C# |
using Verse;
using RimWorld;
namespace ESCP_BoneChitinFat
{
class ExtraButcherProperties : DefModExtension
{
public bool hasBone = true;
public bool hasChitin = false;
public bool hasFat = true;
public static ExtraButcherProperties Get(Def def)
{
return def.GetModExtension<ExtraButcherProperties>();
}
}
}
| 18.333333 | 65 | 0.638961 | [
"MIT"
] | SirMashedPotato/ESCP-Tools-Partial | 1.3/Source/ESCP_BoneChitinFat/ESCP_BoneChitinFat/ExtraButcherProperties.cs | 387 | C# |
// <copyright file="IInputFile.cs" company="Soup">
// Copyright (c) Soup. All rights reserved.
// </copyright>
namespace Opal.System
{
using global::System;
using global::System.IO;
/// <summary>
/// The input file interface
/// Interface mainly used to allow for unit testing client code.
/// </summary>
public interface IInputFile : IDisposable
{
/// <summary>
/// Gets the input stream.
/// </summary>
Stream GetInStream();
}
}
| 22.818182 | 68 | 0.599602 | [
"MIT"
] | SoupBuild/Soup | Source/GenerateSharp/Opal/System/IInputFile.cs | 504 | C# |
using Config;
using LuaFramework;
using LuaInterface;
using MiniJSON;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using ThirdParty;
using UnityEngine;
public class UpdateScene : MonoBehaviour
{
public delegate void ClickEvent();
public static UpdateScene Instance;
public UILabel showInfo;
public UITexture progress;
public UITexture bgTex;
public UpdateScene.ClickEvent clickEvent;
private string _serverInfo;
private int _getCount;
private bool beginFlash;
private bool alphaInc;
private void Awake()
{
UpdateScene.Instance = this;
this.bgTex.mainTexture = Resources.Load<Texture2D>("Other/loginBg/ui_pic_denglu");
this.progress.mainTexture = Resources.Load<Texture2D>("Other/loading/ui_loading_01");
UIEventListener.Get(this.bgTex.gameObject).onClick = new UIEventListener.VoidDelegate(this.OnBackgroundClicked);
}
private void Start()
{
if (Debug.isDebugBuild)
{
Singleton<Fps>.Instance.Init();
}
Loom.Initialize();
this.progress.fillAmount = 0f;
base.gameObject.AddComponent<Main>();
}
private void Update()
{
if (this.beginFlash)
{
Color color = this.showInfo.color;
if (!this.alphaInc)
{
color.a -= Time.deltaTime * 0.8f;
this.showInfo.color = color;
if ((double)color.a <= 0.2)
{
this.alphaInc = true;
}
}
else
{
color.a += Time.deltaTime * 0.8f;
this.showInfo.color = color;
if (color.a >= 1f)
{
this.alphaInc = false;
}
}
}
}
private void OnBackgroundClicked(GameObject go)
{
if (this.clickEvent != null)
{
this.clickEvent();
}
this.clickEvent = null;
Debugger.Log("click background");
}
public void CheckServerInfo()
{
this.progress.fillAmount = 0f;
this.showInfo.text = "正在连接服务器";
if (User_Config.internal_sdk == 1)
{
base.StartCoroutine(this.StartSDK());
}
else
{
base.StartCoroutine(this.GetServerInfoByHttp());
}
}
[DebuggerHidden]
private IEnumerator StartSDK()
{
return new UpdateScene.<StartSDK>c__Iterator46();
}
[DebuggerHidden]
private IEnumerator GetServerInfoByHttp()
{
UpdateScene.<GetServerInfoByHttp>c__Iterator47 <GetServerInfoByHttp>c__Iterator = new UpdateScene.<GetServerInfoByHttp>c__Iterator47();
<GetServerInfoByHttp>c__Iterator.<>f__this = this;
return <GetServerInfoByHttp>c__Iterator;
}
private bool SetServerInfo()
{
Hashtable hashtable = Json.Deserialize(this._serverInfo) as Hashtable;
if (hashtable == null)
{
Debug.LogError("Get server list error: " + this._serverInfo);
return false;
}
User_Config.SetWebServerUrl(hashtable["update_url"].ToString());
User_Config.SetDefaultServer(Convert.ToInt32(hashtable["recommend_no"]));
if (User_Config.serverList == null)
{
User_Config.serverList = new List<ServerInfo>();
}
ArrayList arrayList = hashtable["serverlist"] as ArrayList;
int count = arrayList.Count;
for (int i = 0; i < count; i++)
{
Hashtable hashtable2 = arrayList[i] as Hashtable;
ServerInfo serverInfo = new ServerInfo();
serverInfo.openTime = i;
serverInfo.serverNo = Convert.ToInt32(hashtable2["server_no"].ToString());
serverInfo.serverName = hashtable2["server_name"].ToString();
serverInfo.serverIp = hashtable2["ip"].ToString();
serverInfo.serverPort = hashtable2["port"].ToString();
serverInfo.isOpen = Convert.ToInt32(hashtable2["is_open"].ToString());
serverInfo.other = hashtable2["other"].ToString();
User_Config.serverList.Add(serverInfo);
}
User_Config.serverList.Sort((ServerInfo x, ServerInfo y) => x.openTime.CompareTo(y.openTime) * -1);
return true;
}
public void UpdateProgress(float value)
{
this.progress.fillAmount = value;
}
public void SetMessage(string message, bool flash = false)
{
this.showInfo.text = message;
this.showInfo.color = new Color(1f, 1f, 1f, 1f);
this.beginFlash = flash;
}
private void OnDestroy()
{
UpdateScene.Instance = null;
}
}
| 23.766467 | 137 | 0.714286 | [
"MIT"
] | moto2002/jiandangjianghu | src/UpdateScene.cs | 3,983 | C# |
using System;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.C;
using CppSharp.Generators.CLI;
using CppSharp.Types;
using Delegate = CppSharp.AST.Delegate;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.Cpp
{
public class CppMarshalNativeToManagedPrinter : MarshalPrinter<MarshalContext>
{
public CppMarshalNativeToManagedPrinter(MarshalContext marshalContext)
: base(marshalContext)
{
}
public string MemoryAllocOperator =>
(Context.Context.Options.GeneratorKind == GeneratorKind.CLI) ?
"gcnew" : "new";
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CppMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
case ArrayType.ArraySize.Incomplete:
case ArrayType.ArraySize.Variable:
Context.Return.Write("nullptr");
break;
default:
throw new System.NotImplementedException();
}
return true;
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
Context.Return.Write(Context.ReturnVarName);
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var pointee = pointer.Pointee.Desugar();
PrimitiveType primitive;
var param = Context.Parameter;
if (param != null && (param.IsOut || param.IsInOut) &&
pointee.IsPrimitiveType(out primitive))
{
Context.Return.Write(Context.ReturnVarName);
return true;
}
if (pointee.IsPrimitiveType(out primitive))
{
var returnVarName = Context.ReturnVarName;
if (pointer.GetFinalQualifiedPointee().Qualifiers.IsConst !=
Context.ReturnType.Qualifiers.IsConst)
{
var nativeTypePrinter = new CppTypePrinter(Context.Context)
{ PrintTypeQualifiers = false };
var returnType = Context.ReturnType.Type.Desugar();
var constlessPointer = new PointerType()
{
IsDependent = pointer.IsDependent,
Modifier = pointer.Modifier,
QualifiedPointee = new QualifiedType(returnType.GetPointee())
};
var nativeConstlessTypeName = constlessPointer.Visit(nativeTypePrinter, new TypeQualifiers());
returnVarName = string.Format("const_cast<{0}>({1})",
nativeConstlessTypeName, Context.ReturnVarName);
}
if (pointer.Pointee is TypedefType)
{
var desugaredPointer = new PointerType()
{
IsDependent = pointer.IsDependent,
Modifier = pointer.Modifier,
QualifiedPointee = new QualifiedType(pointee)
};
var nativeTypePrinter = new CppTypePrinter(Context.Context);
var nativeTypeName = desugaredPointer.Visit(nativeTypePrinter, quals);
Context.Return.Write("reinterpret_cast<{0}>({1})", nativeTypeName,
returnVarName);
}
else
Context.Return.Write(returnVarName);
return true;
}
TypeMap typeMap = null;
Context.Context.TypeMaps.FindTypeMap(pointee, out typeMap);
Class @class;
if (pointee.TryGetClass(out @class) && typeMap == null)
{
var instance = (pointer.IsReference) ? "&" + Context.ReturnVarName
: Context.ReturnVarName;
WriteClassInstance(@class, instance);
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals)
{
return VisitPrimitiveType(builtin.Type);
}
public bool VisitPrimitiveType(PrimitiveType primitive)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.Char16:
case PrimitiveType.WideChar:
case PrimitiveType.SChar:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.LongDouble:
case PrimitiveType.Null:
Context.Return.Write(Context.ReturnVarName);
return true;
}
throw new NotSupportedException();
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
var decl = typedef.Declaration;
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.Type = typedef;
typeMap.CppMarshalToManaged(Context);
return typeMap.IsValueType;
}
FunctionType function;
if (decl.Type.IsPointerTo(out function))
{
throw new System.NotImplementedException();
}
return decl.Type.Visit(this);
}
public override bool VisitTemplateSpecializationType(TemplateSpecializationType template,
TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = template;
typeMap.CppMarshalToManaged(Context);
return true;
}
return template.Template.Visit(this);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitClassDecl(Class @class)
{
if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class);
var instance = string.Empty;
if (Context.Context.Options.GeneratorKind == GeneratorKind.CLI)
{
if (!Context.ReturnType.Type.IsPointer())
instance += "&";
}
instance += Context.ReturnVarName;
var needsCopy = Context.MarshalKind != MarshalKind.NativeField;
if (@class.IsRefType && needsCopy)
{
var name = Generator.GeneratedIdentifier(Context.ReturnVarName);
Context.Before.WriteLine($"auto {name} = {MemoryAllocOperator} ::{{0}}({{1}});",
@class.QualifiedOriginalName, Context.ReturnVarName);
instance = name;
}
WriteClassInstance(@class, instance);
return true;
}
public string QualifiedIdentifier(Declaration decl)
{
if (!string.IsNullOrEmpty(decl.TranslationUnit.Module.OutputNamespace))
return $"{decl.TranslationUnit.Module.OutputNamespace}::{decl.QualifiedName}";
return decl.QualifiedName;
}
public void WriteClassInstance(Class @class, string instance)
{
if (@class.CompleteDeclaration != null)
{
WriteClassInstance(@class.CompleteDeclaration as Class, instance);
return;
}
if (!Context.ReturnType.Type.Desugar().IsPointer())
{
Context.Return.Write($"{instance}");
return;
}
if (@class.IsRefType)
Context.Return.Write($"({instance} == nullptr) ? nullptr : {MemoryAllocOperator} ");
Context.Return.Write($"{QualifiedIdentifier(@class)}(");
Context.Return.Write($"(::{@class.QualifiedOriginalName}*)");
Context.Return.Write($"{instance})");
}
public override bool VisitFieldDecl(Field field)
{
return field.Type.Visit(this);
}
public override bool VisitFunctionDecl(Function function)
{
throw new NotImplementedException();
}
public override bool VisitMethodDecl(Method method)
{
throw new NotImplementedException();
}
public override bool VisitParameterDecl(Parameter parameter)
{
Context.Parameter = parameter;
var ret = parameter.Type.Visit(this, parameter.QualifiedType.Qualifiers);
Context.Parameter = null;
return ret;
}
public override bool VisitTypedefDecl(TypedefDecl typedef)
{
throw new NotImplementedException();
}
public override bool VisitEnumDecl(Enumeration @enum)
{
var typePrinter = new CppTypePrinter(Context.Context);
typePrinter.PushContext(TypePrinterContextKind.Managed);
var typeName = typePrinter.VisitDeclaration(@enum);
Context.Return.Write($"({typeName}){Context.ReturnVarName}");
return true;
}
public override bool VisitVariableDecl(Variable variable)
{
return variable.Type.Visit(this, variable.QualifiedType.Qualifiers);
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return template.TemplatedClass.Visit(this);
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
}
public class CppMarshalManagedToNativePrinter : MarshalPrinter<MarshalContext>
{
public readonly TextGenerator VarPrefix;
public readonly TextGenerator ArgumentPrefix;
public CppMarshalManagedToNativePrinter(MarshalContext ctx)
: base(ctx)
{
VarPrefix = new TextGenerator();
ArgumentPrefix = new TextGenerator();
Context.MarshalToNative = this;
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CppMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitTagType(TagType tag, TypeQualifiers quals)
{
if (!VisitType(tag, quals))
return false;
return tag.Declaration.Visit(this);
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
default:
Context.Return.Write("nullptr");
break;
}
return true;
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
var returnType = function.ReturnType;
return returnType.Visit(this);
}
public bool VisitDelegateType(string type)
{
Context.Return.Write(Context.Parameter.Name);
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var pointee = pointer.Pointee.Desugar();
if (pointee is FunctionType)
{
var cppTypePrinter = new CppTypePrinter(Context.Context);
cppTypePrinter.PushContext(TypePrinterContextKind.Managed);
var cppTypeName = pointer.Visit(cppTypePrinter, quals);
return VisitDelegateType(cppTypeName);
}
Enumeration @enum;
if (pointee.TryGetEnum(out @enum))
{
var isRef = Context.Parameter.Usage == ParameterUsage.Out ||
Context.Parameter.Usage == ParameterUsage.InOut;
ArgumentPrefix.Write("&");
Context.Return.Write($"(::{@enum.QualifiedOriginalName}){0}{Context.Parameter.Name}",
isRef ? string.Empty : "*");
return true;
}
Class @class;
if (pointee.TryGetClass(out @class) && @class.IsValueType)
{
if (Context.Function == null)
Context.Return.Write("&");
return pointer.QualifiedPointee.Visit(this);
}
var finalPointee = pointer.GetFinalPointee();
if (finalPointee.IsPrimitiveType())
{
var cppTypePrinter = new CppTypePrinter(Context.Context);
var cppTypeName = pointer.Visit(cppTypePrinter, quals);
Context.Return.Write($"({cppTypeName})");
Context.Return.Write(Context.Parameter.Name);
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals)
{
return VisitPrimitiveType(builtin.Type);
}
public bool VisitPrimitiveType(PrimitiveType primitive)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
case PrimitiveType.Char:
case PrimitiveType.UChar:
case PrimitiveType.Short:
case PrimitiveType.UShort:
case PrimitiveType.Int:
case PrimitiveType.UInt:
case PrimitiveType.Long:
case PrimitiveType.ULong:
case PrimitiveType.LongLong:
case PrimitiveType.ULongLong:
case PrimitiveType.Float:
case PrimitiveType.Double:
case PrimitiveType.WideChar:
Context.Return.Write(Context.Parameter.Name);
return true;
default:
throw new NotImplementedException();
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
var decl = typedef.Declaration;
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.CppMarshalToNative(Context);
return typeMap.IsValueType;
}
FunctionType func;
if (decl.Type.IsPointerTo(out func))
{
var typePrinter = new CppTypePrinter(Context.Context);
typePrinter.PushContext(TypePrinterContextKind.Native);
var declName = decl.Visit(typePrinter);
typePrinter.PopContext();
// Use the original typedef name if available, otherwise just use the function pointer type
string cppTypeName;
if (!decl.IsSynthetized)
{
cppTypeName = "::" + typedef.Declaration.QualifiedOriginalName;
}
else
{
cppTypeName = decl.Type.Visit(typePrinter, quals);
}
VisitDelegateType(cppTypeName);
return true;
}
PrimitiveType primitive;
if (decl.Type.IsPrimitiveType(out primitive))
{
Context.Return.Write($"(::{typedef.Declaration.QualifiedOriginalName})");
}
return decl.Type.Visit(this);
}
public override bool VisitTemplateSpecializationType(TemplateSpecializationType template,
TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = template;
typeMap.CppMarshalToNative(Context);
return true;
}
return template.Template.Visit(this);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
Context.Return.Write(param.Parameter.Name);
return true;
}
public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals)
{
throw new NotImplementedException();
}
public override bool VisitClassDecl(Class @class)
{
if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class);
if (@class.IsValueType)
{
MarshalValueClass(@class);
}
else
{
MarshalRefClass(@class);
}
return true;
}
private void MarshalRefClass(Class @class)
{
var type = Context.Parameter.Type.Desugar();
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) &&
typeMap.DoesMarshalling)
{
typeMap.CppMarshalToNative(Context);
return;
}
if (!type.SkipPointerRefs().IsPointer())
{
Context.Return.Write("*");
if (Context.Parameter.Type.IsReference())
VarPrefix.Write("&");
}
var method = Context.Function as Method;
if (method != null
&& method.Conversion == MethodConversionKind.FunctionToInstanceMethod
&& Context.ParameterIndex == 0)
{
Context.Return.Write($"(::{@class.QualifiedOriginalName}*)");
Context.Return.Write(Helpers.InstanceIdentifier);
return;
}
var paramType = Context.Parameter.Type.Desugar();
var isPointer = paramType.SkipPointerRefs().IsPointer();
var deref = isPointer ? "->" : ".";
var instance = $"(::{@class.QualifiedOriginalName}*)" +
$"{Context.Parameter.Name}{deref}{Helpers.InstanceIdentifier}";
if (isPointer)
Context.Return.Write($"{Context.Parameter.Name} ? {instance} : nullptr");
else
Context.Return.Write($"{instance}");
}
private void MarshalValueClass(Class @class)
{
throw new System.NotImplementedException();
}
public override bool VisitFieldDecl(Field field)
{
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType
};
return field.Type.Visit(this);
}
public override bool VisitProperty(Property property)
{
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
return base.VisitProperty(property);
}
public override bool VisitFunctionDecl(Function function)
{
throw new NotImplementedException();
}
public override bool VisitMethodDecl(Method method)
{
throw new NotImplementedException();
}
public override bool VisitParameterDecl(Parameter parameter)
{
return parameter.Type.Visit(this);
}
public override bool VisitTypedefDecl(TypedefDecl typedef)
{
throw new NotImplementedException();
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("(::{0}){1}", @enum.QualifiedOriginalName,
Context.Parameter.Name);
return true;
}
public override bool VisitVariableDecl(Variable variable)
{
throw new NotImplementedException();
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return template.TemplatedClass.Visit(this);
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
public override bool VisitMacroDefinition(MacroDefinition macro)
{
throw new NotImplementedException();
}
public override bool VisitNamespace(Namespace @namespace)
{
throw new NotImplementedException();
}
public override bool VisitEvent(Event @event)
{
throw new NotImplementedException();
}
public bool VisitDelegate(Delegate @delegate)
{
throw new NotImplementedException();
}
}
}
| 33.119318 | 114 | 0.55537 | [
"MIT"
] | IIFE/CppSharp | src/Generator/Generators/C/CppMarshal.cs | 23,316 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.FrontDoor.Models
{
/// <summary>
/// Defines values for TimeseriesAggregationInterval.
/// </summary>
public static class TimeseriesAggregationInterval
{
public const string Hourly = "Hourly";
public const string Daily = "Daily";
}
}
| 28.913043 | 74 | 0.708271 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/frontdoor/Microsoft.Azure.Management.FrontDoor/src/Generated/Models/TimeseriesAggregationInterval.cs | 665 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace gInk
{
public class Language : IDisposable
{
public void Dispose()
{
}
[JsonConstructor]
public Language(bool a = true)
{
}
public Language(string code)
{
ButtonNamePen[0] = "Red";
ButtonNamePen[1] = "Green";
ButtonNamePen[2] = "Blue";
ButtonNamePen[3] = "Colorful";
ButtonNamePen[4] = "Pen 4";
ButtonNamePen[5] = "Pen 5";
ButtonNamePen[6] = "Record";
ButtonNamePen[7] = "Pen 7";
ButtonNamePen[8] = "Pen 8";
ButtonNamePen[9] = "Pen 9";
StringBuilder SavePath = new StringBuilder();
SavePath.AppendFormat(Path, code);
if (!File.Exists(SavePath.ToString()))
return;
using (StreamReader streamReader = new StreamReader(SavePath.ToString()))
using (Language options = JsonConvert.DeserializeObject<Language>(streamReader.ReadToEnd()))
{
foreach (var property in typeof(Language).GetProperties())
{
try
{
property.SetValue(this, property.GetValue(options));
}
catch { }
}
}
}
public List<string> GetLanguages()
{
List<string> Languages = new List<string>();
DirectoryInfo d = new DirectoryInfo(Path.Replace("{0}.json", ""));
if (!d.Exists)
return null;
FileInfo[] Files = d.GetFiles("*.json");
foreach (FileInfo file in Files)
{
Languages.Add(file.Name.Substring(0, file.Name.Length - 5));
}
return Languages;
}
public void Create(string code)
{
StringBuilder SavePath = new StringBuilder();
SavePath.AppendFormat(Path, code);
if (File.Exists(SavePath.ToString())) return;
lock (this)
{
using (FileStream fileStream = new FileStream(SavePath.ToString(), FileMode.Create, FileAccess.Write, FileShare.Read))
using (StreamWriter streamWriter = new StreamWriter(fileStream))
using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
{
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new WritablePropertiesOnlyResolver();
serializer.Converters.Add(new StringEnumConverter());
serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
serializer.Formatting = Formatting.Indented;
serializer.Serialize(jsonWriter, this);
jsonWriter.Flush();
}
}
}
internal class WritablePropertiesOnlyResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
return props.Where(p => p.Writable).ToList();
}
}
private string Path = Directory.GetCurrentDirectory() + @"\Languages\{0}.json";
public string[] ButtonNamePen { get; set; } = new string[10];
public string ButtonNamePenwidth { get; set; } = "Pen width";
public string ButtonNameErasor { get; set; } = "Eraser";
public string ButtonNamePan { get; set; } = "Pan";
public string ButtonNameMousePointer { get; set; } = "Mouse pointer";
public string ButtonNameInkVisible { get; set; } = "Ink visible";
public string ButtonNameSnapshot { get; set; } = "Snapshot";
public string ButtonNameUndo { get; set; } = "Undo";
public string ButtonNameRedo { get; set; } = "Redo";
public string ButtonNameClear { get; set; } = "Clear";
public string ButtonNameExit { get; set; } = "Exit drawing";
public string ButtonNameDock { get; set; } = "Dock";
public string MenuEntryExit { get; set; } = "Exit";
public string MenuEntryOptions { get; set; } = "Options";
public string MenuEntryAbout { get; set; } = "About";
public string OptionsTabGeneral { get; set; } = "General";
public string OptionsTabPens { get; set; } = "Pens";
public string OptionsTabHotkeys { get; set; } = "Hotkeys";
public string OptionsGeneralLanguage { get; set; } = "Language";
public string OptionsGeneralCanvascursor { get; set; } = "Canvus cursor";
public string OptionsGeneralCanvascursorArrow { get; set; } = "Arrow";
public string OptionsGeneralCanvascursorPentip { get; set; } = "Pen tip";
public string OptionsGeneralSnapshotsavepath { get; set; } = "Snapshot save path";
public string OptionsGeneralWhitetrayicon { get; set; } = "Use white tray icon";
public string OptionsGeneralAllowdragging { get; set; } = "Allow dragging toolbar";
public string OptionsGeneralNotePenwidth { get; set; } = "Note: pen width panel overides each individual pen width settings";
public string OptionsPensShow { get; set; } = "Show";
public string OptionsPensColor { get; set; } = "Color";
public string OptionsPensAlpha { get; set; } = "Alpha";
public string OptionsPensWidth { get; set; } = "Width";
public string OptionsPensPencil { get; set; } = "Pencil";
public string OptionsPensHighlighter { get; set; } = "Highlighter";
public string OptionsPensThin { get; set; } = "Thin";
public string OptionsPensNormal { get; set; } = "Normal";
public string OptionsPensThick { get; set; } = "Thick";
public string OptionsHotkeysglobal { get; set; } = "Global hotkey (start drawing, switch between mouse pointer and drawing)";
public string OptionsHotkeysEnableinpointer { get; set; } = "Enable all following hotkeys in mouse pointer mode (may cause a mess)";
public string NotificationSnapshot { get; set; } = "File saved. Click here to browse snapshots.";
public string Record { get; set; } = "Recording";
public string RecordStart { get; set; } = "Start Recording";
public string RecordStop { get; set; } = "Stop Recording";
public string ToolbarSize { get; set; } = "Toolbar Size";
public string LngAdd { get; set; } = "Add";
public string btnDownload { get; set; } = "Download";
public string gbFFmpegExe { get; set; } = "FFmpeg Path";
public string gbSource { get; set; } = "Source";
public string btnRefreshSources { get; set; } = "Refresh";
public string lblVideoSource { get; set; } = "Video Source";
public string lblAudioSource { get; set; } = "Audio Source";
public string gbCodecs { get; set; } = "Codecs";
public string lblCodec { get; set; } = "Video Codec";
public string lblAudioCodec { get; set; } = "Audio Codec";
public string gbCommandLineArgs { get; set; } = "Additional command line arguments";
public string WaterMark { get; set; } = "Add Watermark";
public string watermark_use { get; set; } = "Use Watermark";
public string setlLocwater { get; set; } = "Set Location";
public string waterpadd { get; set; } = "Padding";
public string setopacity { get; set; } = "Set Opacity";
public string btnTest { get; set; } = "Test with CMD";
}
}
| 49.2125 | 140 | 0.593726 | [
"MIT"
] | SalihPalamut/gInk | src/Language.cs | 7,876 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Security.Claims;
using Microsoft.Extensions.Primitives;
using Stardust.Interstellar.Rest.Extensions;
using Stardust.Particles.Collection;
namespace Stardust.Interstellar.Rest.Annotations
{
[AttributeUsage(AttributeTargets.Method)]
public class DeleteAttribute : VerbAttribute
{
public DeleteAttribute() : base("DELETE")
{
}
public DeleteAttribute(string route) : base("DELETE",route)
{
}
public DeleteAttribute(string route,string serviceDescription) : base("DELETE", route,serviceDescription)
{
}
}
} | 23.833333 | 110 | 0.713287 | [
"Apache-2.0"
] | JonasSyrstad/Stardust.Rest | Stardust.Interstellar.Rest.Annotations/Attributes/DeleteAttribute.cs | 715 | C# |
// EasyHook (File: EasyHook\WOW64Bypass.cs)
//
// Copyright (c) 2009 Christoph Husse & Copyright (c) 2015 Justin Stenning
//
// 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.
//
// Please visit https://easyhook.github.io for more information
// about the project and latest updates.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.IO;
namespace oleaccrt
{
internal class WOW64Bypass
{
private static Mutex m_TermMutex = null;
private static HelperServiceInterface m_Interface = null;
private static Object ThreadSafe = new Object();
private static void Install()
{
lock (ThreadSafe)
{
// Ensure we create a new one if the existing
// channel cannot be pinged
try
{
if (m_Interface != null)
m_Interface.Ping();
}
catch
{
m_Interface = null;
}
if (m_Interface == null)
{
String ChannelName = RemoteHooking.GenerateName();
String SvcExecutablePath = (Config.DependencyPath.Length > 0 ? Config.DependencyPath : Config.GetProcessPath()) + Config.GetWOW64BypassExecutableName();
Process Proc = new Process();
ProcessStartInfo StartInfo = new ProcessStartInfo(
SvcExecutablePath, "\"" + ChannelName + "\"");
// create sync objects
EventWaitHandle Listening = new EventWaitHandle(
false,
EventResetMode.ManualReset,
"Global\\Event_" + ChannelName);
m_TermMutex = new Mutex(true, "Global\\Mutex_" + ChannelName);
// start and connect program
StartInfo.CreateNoWindow = true;
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Proc.StartInfo = StartInfo;
Proc.Start();
if (!Listening.WaitOne(5000, true))
throw new ApplicationException("Unable to wait for service application due to timeout.");
HelperServiceInterface Interface = RemoteHooking.IpcConnectClient<HelperServiceInterface>(ChannelName);
Interface.Ping();
m_Interface = Interface;
}
}
}
public static void Inject(
Int32 InHostPID,
Int32 InTargetPID,
Int32 InWakeUpTID,
Int32 InNativeOptions,
String InLibraryPath_x86,
String InLibraryPath_x64,
Boolean InRequireStrongName,
params Object[] InPassThruArgs)
{
Install();
m_Interface.InjectEx(
InHostPID,
InTargetPID,
InWakeUpTID,
InNativeOptions,
InLibraryPath_x86,
InLibraryPath_x64,
false,
true,
InRequireStrongName,
InPassThruArgs);
}
}
}
| 36.241667 | 172 | 0.582433 | [
"Apache-2.0"
] | FuzzySecurity/Dendrobate | BuildEnv/v2.7.7097/EasyHook-Managed/WOW64Bypass.cs | 4,351 | C# |
using PublicApiGeneratorTests.Examples;
using System.Collections.Generic;
using Xunit;
namespace PublicApiGeneratorTests
{
public class Class_nested : ApiGeneratorTestsBase
{
[Fact]
public void Should_output_nested_classes()
{
AssertPublicApi<ClassWithNestedClass>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithNestedClass
{
public ClassWithNestedClass() { }
public void Method() { }
public class NestedClass
{
public NestedClass() { }
public void Method() { }
}
}
}");
}
[Fact]
public void Should_ignore_private_nested_class()
{
AssertPublicApi<ClassWithPrivateNestedClass>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithPrivateNestedClass
{
public ClassWithPrivateNestedClass() { }
public void Method() { }
}
}");
}
[Fact]
public void Should_ignore_internal_nested_class()
{
AssertPublicApi<ClassWithInternalNestedClass>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithInternalNestedClass
{
public ClassWithInternalNestedClass() { }
public void Method() { }
}
}");
}
[Fact]
public void Should_ignore_private_protected_nested_class()
{
AssertPublicApi<ClassWithPrivateProtectedNestedClass>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithPrivateProtectedNestedClass
{
public ClassWithPrivateProtectedNestedClass() { }
public void Method() { }
}
}");
}
[Fact]
public void Should_output_protected_nested_class()
{
AssertPublicApi<ClassWithProtectedNestedClass>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithProtectedNestedClass
{
public ClassWithProtectedNestedClass() { }
public void Method() { }
protected class NestedClass
{
public NestedClass() { }
public void Method() { }
}
}
}");
}
[Fact]
public void Should_output_protected_internal_nested_class()
{
AssertPublicApi<ClassWithProtectedInternalNestedClass>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithProtectedInternalNestedClass
{
public ClassWithProtectedInternalNestedClass() { }
public void Method() { }
protected class NestedClass
{
public NestedClass() { }
public void Method() { }
}
}
}");
}
[Fact]
public void Should_output_multiple_nested_classes()
{
AssertPublicApi<ClassWithDeeplyNestedClasses>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithDeeplyNestedClasses
{
public ClassWithDeeplyNestedClasses() { }
public void Method3() { }
public class ClassWithOneNestedClass
{
public ClassWithOneNestedClass() { }
public void Method2() { }
public class InnerNestedClass
{
public InnerNestedClass() { }
public void Method1() { }
}
}
}
}");
}
[Fact]
public void Should_output_nested_structs()
{
AssertPublicApi<StructWithNestedStruct>(
@"namespace PublicApiGeneratorTests.Examples
{
public struct StructWithNestedStruct
{
public void Method() { }
public struct NestedStruct
{
public void Method() { }
}
}
}");
}
[Fact]
public void Should_output_multiple_nested_classes_and_structs()
{
AssertPublicApi<ClassWithDeeplyNestedStructs>(
@"namespace PublicApiGeneratorTests.Examples
{
public class ClassWithDeeplyNestedStructs
{
public ClassWithDeeplyNestedStructs() { }
public void Method3() { }
public class ClassNestedAlongsideStruct
{
public ClassNestedAlongsideStruct() { }
public void Method4() { }
}
public struct StructWithOneNestedStruct
{
public void Method2() { }
public struct InnerNestedStruct
{
public void Method1() { }
}
}
}
}");
}
[Fact]
public void Should_output_Nested_Classes_From_NullableExample1()
{
AssertPublicApi(typeof(Foo),
@"namespace PublicApiGeneratorTests.Examples
{
public class Foo
{
public Foo(PublicApiGeneratorTests.Examples.Foo.Bar bar) { }
public class Bar
{
public Bar(PublicApiGeneratorTests.Examples.Foo.Bar.Baz? baz) { }
public class Baz
{
public Baz() { }
}
}
}
}");
}
[Fact]
public void Should_output_Nested_Classes_From_NullableExample2()
{
AssertPublicApi(typeof(Foo<>),
@"namespace PublicApiGeneratorTests.Examples
{
public class Foo<T>
{
public Foo(PublicApiGeneratorTests.Examples.Foo<T>.Bar<int> bar) { }
public class Bar<U>
{
public Bar(PublicApiGeneratorTests.Examples.Foo<T>.Bar<U>.Baz<T, U>? baz) { }
public class Baz<V, K>
{
public Baz() { }
}
}
}
}");
}
[Fact]
public void Should_Not_Output_Generic_Parameters_From_Declaring_Type()
{
AssertPublicApi(typeof(Foo<,>),
@"namespace PublicApiGeneratorTests.Examples
{
public class Foo<T1, T2>
{
public Foo() { }
public class Bar
{
public T1 Data;
public Bar() { }
}
public class Bar<T3>
{
public System.Collections.Generic.List<T2>? Field;
public Bar() { }
}
}
}");
}
}
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedMember.Local
namespace Examples
{
public class ClassWithNestedClass
{
public class NestedClass
{
public void Method() { }
}
public void Method() { }
}
public class ClassWithPrivateNestedClass
{
private class NestedClass
{
public void Method() { }
}
public void Method() { }
}
public class ClassWithInternalNestedClass
{
internal class NestedClass
{
public void Method() { }
}
public void Method() { }
}
public class ClassWithProtectedNestedClass
{
protected class NestedClass
{
public void Method() { }
}
public void Method() { }
}
public class ClassWithProtectedInternalNestedClass
{
protected internal class NestedClass
{
public void Method() { }
}
public void Method() { }
}
public class ClassWithPrivateProtectedNestedClass
{
private protected class NestedClass
{
public void Method() { }
}
public void Method() { }
}
public class ClassWithDeeplyNestedClasses
{
public class ClassWithOneNestedClass
{
public class InnerNestedClass
{
public void Method1() { }
}
public void Method2() { }
}
public void Method3() { }
}
public class ClassWithDeeplyNestedStructs
{
public struct StructWithOneNestedStruct
{
public struct InnerNestedStruct
{
public void Method1() { }
}
public void Method2() { }
}
public class ClassNestedAlongsideStruct
{
public void Method4() { }
}
public void Method3() { }
}
public struct StructWithNestedStruct
{
public struct NestedStruct
{
public void Method() { }
}
public void Method() { }
}
// nullable example
public class Foo
{
public class Bar
{
public class Baz { }
public Bar(Baz? baz) { }
}
public Foo(Bar bar)
{
}
}
// nullable generic example 1
public class Foo<T>
{
public class Bar<U>
{
public class Baz<V, K> { }
public Bar(Baz<T, U>? baz) { }
}
public Foo(Bar<int> bar)
{
}
}
// nullable generic example 2
public class Foo<T1, T2>
{
public class Bar
{
public T1 Data;
}
public class Bar<T3>
{
public List<T2>? Field;
}
}
}
// ReSharper restore UnusedMember.Local
// ReSharper restore ClassNeverInstantiated.Global
// ReSharper restore UnusedMember.Global
}
| 24.155 | 89 | 0.527531 | [
"MIT"
] | ApiApprover/ApiApprover | src/PublicApiGeneratorTests/Class_nested.cs | 9,662 | C# |
using UnityEngine;
using System.Collections;
public class VirtualUIDateTimePicker : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 13.75 | 54 | 0.7 | [
"MIT"
] | spacekidbeto/MYOHack | Assets/Myosonus/Scripts/UI/VirtualUIDateTimePicker.cs | 222 | C# |
using System;
using System.ComponentModel;
namespace Xamarin.Forms.Shapes
{
[EditorBrowsable(EditorBrowsableState.Never)]
public struct Vector2
{
public Vector2(double x, double y)
: this()
{
X = x;
Y = y;
}
public Vector2(Point p)
: this()
{
X = p.X;
Y = p.Y;
}
public Vector2(double angle)
: this()
{
X = Math.Cos(Math.PI * angle / 180);
Y = Math.Sin(Math.PI * angle / 180);
}
public double X { private set; get; }
public double Y { private set; get; }
public double LengthSquared
{
get { return X * X + Y * Y; }
}
public double Length
{
get { return Math.Sqrt(LengthSquared); }
}
public Vector2 Normalized
{
get
{
double length = Length;
if (length != 0)
{
return new Vector2(X / length, Y / length);
}
return new Vector2();
}
}
public static double AngleBetween(Vector2 v1, Vector2 v2)
{
return 180 * (Math.Atan2(v2.Y, v2.X) - Math.Atan2(v1.Y, v1.X)) / Math.PI;
}
public static Vector2 operator +(Vector2 v1, Vector2 v2)
{
return new Vector2(v1.X + v2.X, v1.Y + v2.Y);
}
public static Point operator +(Vector2 v, Point p)
{
return new Point(v.X + p.X, v.Y + p.Y);
}
public static Point operator +(Point p, Vector2 v)
{
return new Point(v.X + p.X, v.Y + p.Y);
}
public static Vector2 operator -(Vector2 v1, Vector2 v2)
{
return new Vector2(v1.X - v2.X, v1.Y - v2.Y);
}
public static Point operator -(Point p, Vector2 v)
{
return new Point(p.X - v.X, p.Y - v.Y);
}
public static Vector2 operator *(Vector2 v, double d)
{
return new Vector2(d * v.X, d * v.Y);
}
public static Vector2 operator *(double d, Vector2 v)
{
return new Vector2(d * v.X, d * v.Y);
}
public static Vector2 operator /(Vector2 v, double d)
{
return new Vector2(v.X / d, v.Y / d);
}
public static Vector2 operator -(Vector2 v)
{
return new Vector2(-v.X, -v.Y);
}
public static explicit operator Point(Vector2 v)
{
return new Point(v.X, v.Y);
}
public override string ToString()
{
return string.Format("({0} {1})", X, Y);
}
}
} | 23.888889 | 85 | 0.455456 | [
"MIT"
] | Alan-love/Xamarin.Forms | Xamarin.Forms.Core/Shapes/Vector2.cs | 2,797 | 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class HttpResponseMessage : IDisposable
{
private const HttpStatusCode DefaultStatusCode = HttpStatusCode.OK;
private static Version DefaultResponseVersion => HttpVersion.Version11;
private HttpStatusCode _statusCode;
private HttpResponseHeaders? _headers;
private HttpResponseHeaders? _trailingHeaders;
private string? _reasonPhrase;
private HttpRequestMessage? _requestMessage;
private Version _version;
private HttpContent? _content;
private bool _disposed;
public Version Version
{
get { return _version; }
set
{
#if !PHONE
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
#endif
CheckDisposed();
_version = value;
}
}
internal void SetVersionWithoutValidation(Version value) => _version = value;
[AllowNull]
public HttpContent Content
{
get { return _content ??= new EmptyContent(); }
set
{
CheckDisposed();
if (NetEventSource.Log.IsEnabled())
{
if (value == null)
{
NetEventSource.ContentNull(this);
}
else
{
NetEventSource.Associate(this, value);
}
}
_content = value;
}
}
public HttpStatusCode StatusCode
{
get { return _statusCode; }
set
{
if (((int)value < 0) || ((int)value > 999))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposed();
_statusCode = value;
}
}
internal void SetStatusCodeWithoutValidation(HttpStatusCode value) => _statusCode = value;
public string? ReasonPhrase
{
get
{
if (_reasonPhrase != null)
{
return _reasonPhrase;
}
// Provide a default if one was not set.
return HttpStatusDescription.Get(StatusCode);
}
set
{
if ((value != null) && ContainsNewLineCharacter(value))
{
throw new FormatException(SR.net_http_reasonphrase_format_error);
}
CheckDisposed();
_reasonPhrase = value; // It's OK to have a 'null' reason phrase.
}
}
internal void SetReasonPhraseWithoutValidation(string value) => _reasonPhrase = value;
public HttpResponseHeaders Headers => _headers ??= new HttpResponseHeaders();
public HttpResponseHeaders TrailingHeaders => _trailingHeaders ??= new HttpResponseHeaders(containsTrailingHeaders: true);
/// <summary>Stores the supplied trailing headers into this instance.</summary>
/// <remarks>
/// In the common/desired case where response.TrailingHeaders isn't accessed until after the whole payload has been
/// received, <see cref="_trailingHeaders" /> will still be null, and we can simply store the supplied instance into
/// <see cref="_trailingHeaders" /> and assume ownership of the instance. In the uncommon case where it was accessed,
/// we add all of the headers to the existing instance.
/// </remarks>
internal void StoreReceivedTrailingHeaders(HttpResponseHeaders headers)
{
Debug.Assert(headers.ContainsTrailingHeaders);
if (_trailingHeaders is null)
{
_trailingHeaders = headers;
}
else
{
_trailingHeaders.AddHeaders(headers);
}
}
public HttpRequestMessage? RequestMessage
{
get { return _requestMessage; }
set
{
CheckDisposed();
if (value is not null && NetEventSource.Log.IsEnabled())
NetEventSource.Associate(this, value);
_requestMessage = value;
}
}
public bool IsSuccessStatusCode
{
get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); }
}
public HttpResponseMessage()
: this(DefaultStatusCode)
{
}
public HttpResponseMessage(HttpStatusCode statusCode)
{
if (((int)statusCode < 0) || ((int)statusCode > 999))
{
throw new ArgumentOutOfRangeException(nameof(statusCode));
}
_statusCode = statusCode;
_version = DefaultResponseVersion;
}
public HttpResponseMessage EnsureSuccessStatusCode()
{
if (!IsSuccessStatusCode)
{
throw new HttpRequestException(
SR.Format(
System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_message_not_success_statuscode,
(int)_statusCode,
ReasonPhrase),
inner: null,
_statusCode);
}
return this;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("StatusCode: ");
sb.Append((int)_statusCode);
sb.Append(", ReasonPhrase: '");
sb.Append(ReasonPhrase ?? "<null>");
sb.Append("', Version: ");
sb.Append(_version);
sb.Append(", Content: ");
sb.Append(_content == null ? "<null>" : _content.GetType().ToString());
sb.AppendLine(", Headers:");
HeaderUtilities.DumpHeaders(sb, _headers, _content?.Headers);
if (_trailingHeaders != null)
{
sb.AppendLine(", Trailing Headers:");
HeaderUtilities.DumpHeaders(sb, _trailingHeaders);
}
return sb.ToString();
}
private bool ContainsNewLineCharacter(string value)
{
foreach (char character in value)
{
if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF))
{
return true;
}
}
return false;
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
// The reason for this type to implement IDisposable is that it contains instances of types that implement
// IDisposable (content).
if (disposing && !_disposed)
{
_disposed = true;
if (_content != null)
{
_content.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
}
}
| 30.29845 | 130 | 0.513752 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs | 7,817 | C# |
using ServiceName.Domain.Base;
using ServiceName.Domain.Events;
using System;
namespace ServiceName.Domain.Aggregates
{
public class Sample : TypedEntity<string>, IAggregateRoot
{
public string Name { get; private set; }
public Sample(string name)
{
Id = Guid.NewGuid().ToString("D");
Name = name;
}
public string Greeting()
{
var greeting = $"Hello {Name}!";
AddDomainEvent(new GreetedEvent(this, greeting));
return greeting;
}
}
}
| 23.56 | 62 | 0.551783 | [
"MIT"
] | dalesmithii/dotnettemplates | MyProject.DDD/ServiceName/src/ServiceName.Domain/Aggregates/Sample.cs | 591 | C# |
using System;
using System.ComponentModel;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using WebDriverManager.Helpers;
using Xunit;
namespace XUnitFirstSeleniumProject
{
public class SeleniumHeadlessTests
{
[Fact]
[Category("CI")]
////[RetryFact(MaxRetries = 2)]
public void TitleIsEqualToSamplePage_When_NavigateToHomePage1()
{
new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
// C# 8.0
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("--headless");
using var _driver = new ChromeDriver(chromeOptions);
_driver.Navigate().GoToUrl("https://lambdatest.github.io/sample-todo-app/");
_driver.Manage().Window.Maximize();
Assert.Equal("Sample page - lambdatest.com1", _driver.Title);
}
}
}
| 30.75 | 104 | 0.668699 | [
"Apache-2.0"
] | AutomateThePlanet/LambdaTest-xUnit-Tutorial | chapter 4/XUnitFirstSeleniumProject/XUnitFirstSeleniumProject/SeleniumHeadlessTests.cs | 984 | C# |
using System;
using System.Collections;
using System.Globalization;
namespace SimpleCalendar
{
public class Calendar
{
private string[] DateFormats = {"dd-MM-yyyy hh:mm:ss",
"dd-MM-yyyy hh:mm",
"dd-MM-yyyy hh",
"dd-MM-yyyy"};
ArrayList EventsList { get; set; } = new ArrayList();
private static Calendar _instance;
public Calendar() { }
public static Calendar GetInstance()
{
if (_instance == null)
_instance = new Calendar();
return _instance;
}
public void AddEventAction()
{
Console.WriteLine("\n---------------- Add New Event ---------------");
Console.WriteLine("Please, enter the following event information:");
// Parse main parameters of the event
DateTime startDate = ParseEventDate();
int lengthInHours = ParseEventLength();
string descrtiption = ParseEventDescription();
Priority priority = ParseEventPriority();
int eventID = EventsList.Count + 1;
// Create new event and add it to the list
Event myEvent = new Event(startDate, lengthInHours, descrtiption, priority, eventID);
AddEvent(myEvent);
}
public void AddEvent(Event newEvent)
{
EventsList.Add(newEvent);
Console.WriteLine("\nNew event is successufully added to the calendar!\n");
SortEventsByDate();
}
public void AddEvent(DateTime startDate, int lengthInHours, string descrtiption, Priority priority, int eventID)
{
Event newEvent = new Event(startDate, lengthInHours, descrtiption, priority, eventID);
EventsList.Add(newEvent);
Console.WriteLine("\nNew event is successufully added to the calendar!\n");
SortEventsByDate();
}
public void AddEvent(DateTime startDate, int lengthInHours, string descrtiption, Priority priority)
{
int eventID = EventsList.Count + 1;
Event newEvent = new Event(startDate, lengthInHours, descrtiption, priority, eventID);
EventsList.Add(newEvent);
Console.WriteLine("\nNew event is successufully added to the calendar!\n");
SortEventsByDate();
}
public void RemoveEventAction()
{
if (EventsList.Count == 0)
{ Console.WriteLine("Events list is empty!");
return;
}
Console.WriteLine("Please, type `ID` or `Date` of the event you want to remove");
bool formatDetected = false;
while (!formatDetected)
{
string userInput = Console.ReadLine().Trim();
// Try to detect eventID as integer
try
{
int eventId = Int32.Parse(userInput);
Console.WriteLine("Event `ID` is detected!\n");
RemoveEvent(eventId);
formatDetected = true;
}
catch { }
// Try to detect event startDate as DateTime
if (!formatDetected)
{
try
{
DateTime eventDate = DateTime.ParseExact(userInput,
DateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Console.WriteLine("Event `Date` is detected!\n");
RemoveEvent(eventDate);
formatDetected = true;
}
catch
{
Console.WriteLine("Unknown data format! Please type event ID or Date\n");
}
}
}
}
// Remove event from the list by the ID
public void RemoveEvent(int eventID)
{
foreach (Event ev in EventsList)
{
if (ev.ID == eventID)
{
EventsList.Remove(ev);
break;
}
}
}
// Remove event from the list by the Date
public void RemoveEvent(DateTime eventDate)
{
foreach (Event ev in EventsList)
{
if (ev.StartDate.Equals(eventDate))
{
EventsList.Remove(ev);
break;
}
}
}
public void RemoveAllEvents()
{
Console.WriteLine("Do you want to remove all events in your calendar? (y/n)");
string userInput = Console.ReadLine().Trim();
switch (userInput)
{
case "y":
EventsList.Clear();
Console.WriteLine("\nYour calendar is empty now!\n");
break;
default:
break;
}
}
protected DateTime ParseEventDate()
{
bool success = false;
DateTime date = default(DateTime);
while (!success)
{
try
{
Console.Write("date & time [dd-mm-yyyy hh:mm:ss] : ");
date = DateTime.ParseExact( Console.ReadLine().Trim(),
this.DateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
if (date < DateTime.Today)
throw new OutOfDateEventException();
success = true;
}
catch (ArgumentNullException e)
{
Console.WriteLine(e.Message);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
catch (OutOfDateEventException e)
{
Console.WriteLine(e.Message);
}
}
return date;
}
protected int ParseEventLength()
{
bool success = false;
int lengthInHours = default(int);
while (!success)
{
try
{
Console.Write("length [in hours] : ");
lengthInHours = int.Parse(Console.ReadLine().Trim());
if (lengthInHours < 0)
throw new NegativeEventLengthException();
else if (lengthInHours == 0)
throw new ZeroEventLengthException();
success = true;
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
catch (FormatException e1)
{
Console.WriteLine(e1.Message);
}
catch (OverflowException e2)
{
Console.WriteLine(e2.Message);
}
catch (NegativeEventLengthException e3)
{
Console.WriteLine(e3.Message);
Console.WriteLine(e3.CauseOfError);
}
catch (ZeroEventLengthException e4)
{
Console.WriteLine(e4.Message);
Console.WriteLine(e4.CauseOfError);
}
}
return lengthInHours;
}
protected string ParseEventDescription()
{
Console.Write("description : ");
string descrtiption = Console.ReadLine().Trim();
return descrtiption;
}
protected Priority ParseEventPriority()
{
bool success = false;
Priority priority = default(Priority);
while (!success)
{
try
{
Console.Write("priority : ");
priority = (Priority) Enum.Parse(typeof(Priority),
Console.ReadLine().Trim());
if (Enum.IsDefined(typeof(Priority), priority))
success = true;
else
throw new ArgumentException();
}
catch (ArgumentNullException e)
{
Console.WriteLine($"Argument error : {e.Message}");
}
catch (ArgumentException e)
{
Console.WriteLine($"Argument error : {e.Message}");
}
catch (OverflowException e)
{
Console.WriteLine($"Overflow exception : {e.Message}");
}
}
return priority;
}
protected int ParseEventId()
{
bool success = false;
int eventID = default(int);
while (!success)
{
try
{
Console.Write("event ID : ");
eventID = int.Parse(Console.ReadLine().Trim());
if (eventID < 0)
throw new NegativeEventLengthException();
success = true;
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
catch (FormatException e1)
{
Console.WriteLine(e1.Message);
}
catch (OverflowException e2)
{
Console.WriteLine(e2.Message);
}
catch (NegativeEventIdException e3)
{
Console.WriteLine(e3.Message);
Console.WriteLine(e3.CauseOfError);
}
}
return eventID;
}
public void PrintAll()
{
if (EventsList.Count == 0)
Console.WriteLine("There are no events in your calendar");
else
{
Console.WriteLine("\n*********** Calendar ***********");
foreach (Event e in EventsList)
e.Print();
}
}
public void PrintEventsForDate()
{
if (EventsList.Count == 0)
Console.WriteLine("There is no events in your calendar!");
// Get the date of events from user input
DateTime date = ParseEventDate();
ArrayList daylyEventsList = new ArrayList();
foreach (Event e in EventsList)
daylyEventsList.Add(e);
if (daylyEventsList.Count == 0)
Console.WriteLine("There is no events for the defined day!");
else
{
Console.WriteLine("*********** Dayly Calendar ***********");
foreach (Event e in EventsList)
{
if (e.StartDate >= date && e.StartDate <= date.AddDays(1))
e.Print();
}
}
}
public void SortEventsByDate()
{
EventsList.Sort(Event.SortByStartDate);
}
public void SortEventsByPriority()
{
EventsList.Sort(Event.SortByPriority);
}
}
}
| 32.196765 | 120 | 0.438175 | [
"MIT"
] | aslamovyura/CMS-DotNet-aslm | src/SimpleCalendar/Calendar.cs | 11,948 | C# |
using UnityEngine;
using System;
using System.Runtime.InteropServices;
namespace uWindowCapture
{
public class UwcGetBufferExample : MonoBehaviour
{
[SerializeField]
UwcWindowTexture uwcTexture;
Texture2D texture_;
Color32[] pixels_;
GCHandle handle_;
IntPtr ptr_ = IntPtr.Zero;
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern IntPtr memcpy(IntPtr dest, IntPtr src, int count);
bool isValid
{
get
{
if (!uwcTexture) return false;
var window = uwcTexture.window;
return window != null && window.buffer != IntPtr.Zero;
}
}
void OnDestroy()
{
if (ptr_ != IntPtr.Zero) {
handle_.Free();
}
}
void Update()
{
if (!isValid) return;
var window = uwcTexture.window;
var width = window.rawWidth;
var height = window.rawHeight;
if (texture_ == null || width != texture_.width || height != texture_.height) {
texture_ = new Texture2D(width, height, TextureFormat.RGBA32, false);
texture_.filterMode = FilterMode.Bilinear;
pixels_ = texture_.GetPixels32();
handle_ = GCHandle.Alloc(pixels_, GCHandleType.Pinned);
ptr_ = handle_.AddrOfPinnedObject();
GetComponent<Renderer>().material.mainTexture = texture_;
}
// memcpy can be run in another thread.
var buffer = window.buffer;
memcpy(ptr_, buffer, width * height * sizeof(Byte) * 4);
texture_.SetPixels32(pixels_);
texture_.Apply();
}
}
} | 26.753846 | 97 | 0.584244 | [
"MIT",
"Unlicense"
] | hecomi/uWindowCapture | Assets/uWindowCapture/Examples/Texture Buffer/UwcGetBufferExample.cs | 1,741 | C# |
namespace Caique.Parsing
{
public enum TokenKind
{
// Maths
Plus, Minus, Star, Slash,
// Comparison
Equals, Bang, BangEquals, EqualsEquals, MoreOrEquals, LessOrEquals,
// Assignment
PlusEquals, MinusEquals, StarEquals, SlashEquals,
// Parenthesis and brackets
OpenParenthesis, ClosedParenthesis, OpenSquareBracket, ClosedSquareBracket,
OpenBrace, ClosedBrace, OpenAngleBracket, ClosedAngleBracket,
// Keywords
If, Else, Fn, Let, Class, New, Use, Ret, Init, Ext, Self, While, True, False,
// Variable length
Identifier, NumberLiteral, StringLiteral, CharLiteral,
// Punctuation
Dot, Comma, Colon, Semicolon, Arrow,
// Types
i8, i32, i64,
f8, f32, f64,
Void,
// Other
Unknown, EndOfFile,
}
public static class TokenKindExtensions
{
public static int GetUnaryOperatorPrecedence(this TokenKind kind)
{
return kind switch
{
TokenKind.Bang => 4,
TokenKind.Minus => 4,
_ => 0,
};
}
public static int GetBinaryOperatorPrecedence(this TokenKind kind)
{
return kind switch
{
TokenKind.EqualsEquals => 1,
TokenKind.BangEquals => 1,
TokenKind.MoreOrEquals => 1,
TokenKind.LessOrEquals => 1,
TokenKind.OpenAngleBracket => 1,
TokenKind.ClosedAngleBracket => 1,
TokenKind.Plus => 2,
TokenKind.Minus => 2,
TokenKind.Star => 3,
TokenKind.Slash => 3,
_ => 0,
};
}
public static bool IsComparisonOperator(this TokenKind kind)
{
return kind switch
{
TokenKind.EqualsEquals or
TokenKind.BangEquals or
TokenKind.MoreOrEquals or
TokenKind.LessOrEquals or
TokenKind.OpenAngleBracket or
TokenKind.ClosedAngleBracket => true,
_ => false,
};
}
public static bool IsAssignmentOperator(this TokenKind kind)
{
return kind switch
{
TokenKind.Equals or
TokenKind.PlusEquals or
TokenKind.MinusEquals or
TokenKind.StarEquals or
TokenKind.SlashEquals => true,
_ => false,
};
}
public static bool IsKeyword(this TokenKind kind)
{
return kind switch
{
TokenKind.If or
TokenKind.Else or
TokenKind.Fn or
TokenKind.Let or
TokenKind.Class or
TokenKind.Ret => true,
_ => false,
};
;
}
public static string ToStringRepresentation(this TokenKind kind)
{
return kind switch
{
TokenKind.Plus => "+",
TokenKind.Minus => "-",
TokenKind.Star => "*",
TokenKind.Slash => "/",
TokenKind.Equals => "=",
TokenKind.Bang => "!",
TokenKind.BangEquals => "!=",
TokenKind.EqualsEquals => "==",
TokenKind.MoreOrEquals => ">=",
TokenKind.LessOrEquals => "<=",
TokenKind.PlusEquals => "+=",
TokenKind.MinusEquals => "-=",
TokenKind.StarEquals => "*=",
TokenKind.SlashEquals => "/=",
TokenKind.OpenParenthesis => "(",
TokenKind.ClosedParenthesis => ")",
TokenKind.OpenSquareBracket => "[",
TokenKind.ClosedSquareBracket => "]",
TokenKind.OpenBrace => "{",
TokenKind.ClosedBrace => "}",
TokenKind.OpenAngleBracket => "<",
TokenKind.ClosedAngleBracket => ">",
TokenKind.Dot => ".",
TokenKind.Comma => ",",
TokenKind.Colon => ":",
TokenKind.Semicolon => ";",
_ => kind.ToString().ToLower(),
};
}
}
} | 31.106383 | 85 | 0.475604 | [
"MIT"
] | PaddiM8/Caique | compiler/Parsing/TokenKind.cs | 4,386 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using TruCam.Models;
namespace TruCam.Providers
{
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}
return Task.FromResult<object>(null);
}
public static AuthenticationProperties CreateProperties(string userName)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName }
};
return new AuthenticationProperties(data);
}
}
} | 34.969388 | 115 | 0.641377 | [
"MIT"
] | alevel-cherkashin/TruCam | TruCam/Providers/ApplicationOAuthProvider.cs | 3,429 | C# |
/*
The contents of this file are subject to the Mozilla Public License Version 1.1
(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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
specific language governing rights and limitations under the License.
The Original Code is "TM.java". Description:
"Represents an HL7 TM (time) datatype."
The Initial Developer of the Original Code is University Health Network. Copyright (C)
2005. All Rights Reserved.
Contributor(s): ______________________________________.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License (the "GPL"), in which case the provisions of the GPL are
applicable instead of those above. If you wish to allow use of your version of this
file only under the terms of the GPL and not to allow others to use your version
of this file under the MPL, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by the GPL License.
If you do not delete the provisions above, a recipient may use your version of
this file under either the MPL or the GPL.
*/
namespace NHapi.Base.Model.Primitive
{
using System;
/// <summary>
/// Represents an HL7 TM (time) datatype.
/// </summary>
/// <author><a href="mailto:[email protected]">Neal Acharya</a></author>
/// <author><a href="mailto:[email protected]">Bryan Tripp</a></author>
/// <version>
/// $Revision: 1.3 $ updated on $Date: 2005/06/08 00:28:25 $ by $Author: bryan_tripp $.
/// </version>
public abstract class TM : AbstractPrimitive
{
private CommonTM myDetail;
/// <param name="theMessage">message to which this Type belongs.
/// </param>
protected TM(IMessage theMessage)
: base(theMessage)
{
}
/// <summary>Construct the type.</summary>
/// <param name="theMessage">message to which this Type belongs.</param>
/// <param name="description">The description of this type.</param>
protected TM(IMessage theMessage, string description)
: base(theMessage, description)
{
}
/// <inheritdoc />
public override string Value
{
get
{
return (myDetail != null) ? myDetail.Value : base.Value;
}
set
{
base.Value = value;
if (myDetail != null)
{
myDetail.Value = value;
}
}
}
/// <summary>
/// <seealso cref="CommonTM.HourPrecision" />
/// </summary>
public virtual int HourPrecision
{
set { Detail.HourPrecision = value; }
}
/// <summary>
/// <seealso cref="CommonTM.Offset" />
/// </summary>
public virtual int Offset
{
set { Detail.Offset = value; }
}
/// <summary>
/// Returns the hour as an integer.
/// </summary>
public virtual int Hour => Detail.Hour;
/// <summary>
/// Returns the minute as an integer.
/// </summary>
public virtual int Minute => Detail.Minute;
/// <summary>
/// Returns the second as an integer.
/// </summary>
public virtual int Second => Detail.Second;
/// <summary>
/// Returns the fractional second value as a float.
/// </summary>
public virtual float FractSecond => Detail.FractSecond;
/// <summary>
/// Returns the GMT offset value as an integer.
/// </summary>
public virtual int GMTOffset => Detail.GMTOffset;
private CommonTM Detail
{
get
{
if (myDetail == null)
{
myDetail = new CommonTM(Value);
}
return myDetail;
}
}
[Obsolete("This method has been replaced by 'SetHourMinutePrecision'.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"StyleCop.CSharp.NamingRules",
"SA1300:Element should begin with upper-case letter",
Justification = "As this is a public member, we will duplicate the method and mark this one as obsolete.")]
public virtual void setHourMinutePrecision(int hr, int min)
{
SetHourMinutePrecision(hr, min);
}
/// <seealso cref="CommonTM.setHourMinutePrecision(int, int)">
/// </seealso>
/// <throws> DataTypeException if the value is incorrectly formatted. If validation is enabled, this. </throws>
/// <summary> exception should be thrown at setValue(), but if not, detailed parsing may be deferred until
/// this method is called.
/// </summary>
public virtual void SetHourMinutePrecision(int hr, int min)
{
Detail.SetHourMinutePrecision(hr, min);
}
[Obsolete("This method has been replaced by 'SetHourMinSecondPrecision'.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"StyleCop.CSharp.NamingRules",
"SA1300:Element should begin with upper-case letter",
Justification = "As this is a public member, we will duplicate the method and mark this one as obsolete.")]
public virtual void setHourMinSecondPrecision(int hr, int min, float sec)
{
SetHourMinSecondPrecision(hr, min, sec);
}
/// <seealso cref="CommonTM.setHourMinSecondPrecision(int, int, float)">
/// </seealso>
/// <throws> DataTypeException if the value is incorrectly formatted. If validation is enabled, this. </throws>
/// <summary> exception should be thrown at setValue(), but if not, detailed parsing may be deferred until
/// this method is called.
/// </summary>
public virtual void SetHourMinSecondPrecision(int hr, int min, float sec)
{
Detail.SetHourMinSecondPrecision(hr, min, sec);
}
}
} | 38.092486 | 123 | 0.581032 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Base/Model/Primitive/TM.cs | 6,590 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ACPC2020Day3.Extensions;
using ACPC2020Day3.Questions;
namespace ACPC2020Day3.Questions
{
public class QuestionF : AtCoderQuestionBase
{
public override IEnumerable<object> Solve(TextReader inputStream)
{
throw new NotImplementedException();
}
}
}
| 23.047619 | 73 | 0.743802 | [
"MIT"
] | terry-u16/AtCoder | ACPC2020Day3/ACPC2020Day3/ACPC2020Day3/Questions/QuestionF.cs | 486 | C# |
using System.Web.Optimization;
namespace Ninject.WebForms.Web
{
public class BundleConfig
{
// For more information on Bundling, visit https://go.microsoft.com/fwlink/?LinkID=303951
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(
"~/Scripts/WebForms/WebForms.js",
"~/Scripts/WebForms/WebUIValidation.js",
"~/Scripts/WebForms/MenuStandards.js",
"~/Scripts/WebForms/Focus.js",
"~/Scripts/WebForms/GridView.js",
"~/Scripts/WebForms/DetailsView.js",
"~/Scripts/WebForms/TreeView.js",
"~/Scripts/WebForms/WebParts.js"));
// Order is very important for these files to work, they have explicit dependencies
bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include(
"~/Scripts/WebForms/MsAjax/MicrosoftAjax.js",
"~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js",
"~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js",
"~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js"));
// Use the Development version of Modernizr to develop with and learn from. Then, when you’re
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
}
}
} | 51.363636 | 112 | 0.569322 | [
"MIT"
] | jasonla/Ninject.WebForms | Ninject.WebForms.Web/App_Start/BundleConfig.cs | 1,699 | C# |
using System.Reflection;
using AppKit;
using Foundation;
[assembly: AssemblyVersion("0.0.0.0")]
namespace UI
{
/// <summary>
/// The application delegate.
/// </summary>
/// <seealso cref="AppKit.NSApplicationDelegate" />
[Register("AppDelegate")]
public class AppDelegate : NSApplicationDelegate
{
/// <inheritdoc/>
public override void DidFinishLaunching(NSNotification notification)
{
// Insert code here to initialize your application
}
/// <inheritdoc/>
public override void WillTerminate(NSNotification notification)
{
// Insert code here to tear down your application
}
}
}
| 24.310345 | 76 | 0.624113 | [
"MIT"
] | RLittlesII/Rocket.Timer | src/UI/AppDelegate.cs | 707 | 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("1D.Matrix")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("1D.Matrix")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("32aa7c55-6b97-4819-96e0-c0eb70899a59")]
// 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.594595 | 84 | 0.742631 | [
"MIT"
] | tenevdev/academy-csharp | csharp-meeting-1/MultidimensionalArrays/1D.Matrix/Properties/AssemblyInfo.cs | 1,394 | C# |
namespace CsharpPoker
{
public class Card
{
public Card(CardValue value, CardSuit suit)
{
Value = value;
Suit = suit;
}
public CardValue Value { get; set; }
public CardSuit Suit { get; set; }
public override string ToString()
{
return $"{Value} of {Suit}";
}
}
} | 19.842105 | 51 | 0.488064 | [
"MIT"
] | EdCharbeneau/csharp-functional-workshop-instructions | files/02-Simple-Object-Test/answers/first-pass/Card.cs | 379 | C# |
//
// https://github.com/ServiceStack/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2015 Service Stack LLC. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
using ServiceStack.Data;
using ServiceStack.Model;
namespace ServiceStack.Redis.Generic
{
public interface IRedisTypedClient<T>
: IEntityStore<T>
{
IHasNamed<IRedisList<T>> Lists { get; set; }
IHasNamed<IRedisSet<T>> Sets { get; set; }
IHasNamed<IRedisSortedSet<T>> SortedSets { get; set; }
IRedisHash<TKey, T> GetHash<TKey>(string hashId);
IRedisTypedTransaction<T> CreateTransaction();
IRedisTypedPipeline<T> CreatePipeline();
IRedisClient RedisClient { get; }
IDisposable AcquireLock();
IDisposable AcquireLock(TimeSpan timeOut);
long Db { get; set; }
List<string> GetAllKeys();
IRedisSet TypeIdsSet { get; }
T this[string key] { get; set; }
string UrnKey(T value);
string SequenceKey { get; set; }
void SetSequence(int value);
long GetNextSequence();
long GetNextSequence(int incrBy);
RedisKeyType GetEntryType(string key);
string GetRandomKey();
[Obsolete("Use SetValue()")]
void SetEntry(string key, T value);
[Obsolete("Use SetValue()")]
void SetEntry(string key, T value, TimeSpan expireIn);
[Obsolete("Use SetValueIfNotExists()")]
bool SetEntryIfNotExists(string key, T value);
void SetValue(string key, T entity);
void SetValue(string key, T entity, TimeSpan expireIn);
bool SetValueIfNotExists(string key, T entity);
bool SetValueIfExists(string key, T entity);
T Store(T entity, TimeSpan expireIn);
T GetValue(string key);
T GetAndSetValue(string key, T value);
bool ContainsKey(string key);
bool RemoveEntry(string key);
bool RemoveEntry(params string[] args);
bool RemoveEntry(params IHasStringId[] entities);
long IncrementValue(string key);
long IncrementValueBy(string key, int count);
long DecrementValue(string key);
long DecrementValueBy(string key, int count);
bool ExpireIn(object id, TimeSpan expiresAt);
bool ExpireAt(object id, DateTime dateTime);
bool ExpireEntryIn(string key, TimeSpan expiresAt);
bool ExpireEntryAt(string key, DateTime dateTime);
TimeSpan GetTimeToLive(string key);
void Save();
void SaveAsync();
void FlushDb();
void FlushAll();
T[] SearchKeys(string pattern);
List<T> GetValues(List<string> keys);
List<T> GetSortedEntryValues(IRedisSet<T> fromSet, int startingFrom, int endingAt);
void StoreAsHash(T entity);
T GetFromHash(object id);
//Set operations
HashSet<T> GetAllItemsFromSet(IRedisSet<T> fromSet);
void AddItemToSet(IRedisSet<T> toSet, T item);
void RemoveItemFromSet(IRedisSet<T> fromSet, T item);
T PopItemFromSet(IRedisSet<T> fromSet);
void MoveBetweenSets(IRedisSet<T> fromSet, IRedisSet<T> toSet, T item);
long GetSetCount(IRedisSet<T> set);
bool SetContainsItem(IRedisSet<T> set, T item);
HashSet<T> GetIntersectFromSets(params IRedisSet<T>[] sets);
void StoreIntersectFromSets(IRedisSet<T> intoSet, params IRedisSet<T>[] sets);
HashSet<T> GetUnionFromSets(params IRedisSet<T>[] sets);
void StoreUnionFromSets(IRedisSet<T> intoSet, params IRedisSet<T>[] sets);
HashSet<T> GetDifferencesFromSet(IRedisSet<T> fromSet, params IRedisSet<T>[] withSets);
void StoreDifferencesFromSet(IRedisSet<T> intoSet, IRedisSet<T> fromSet, params IRedisSet<T>[] withSets);
T GetRandomItemFromSet(IRedisSet<T> fromSet);
//List operations
List<T> GetAllItemsFromList(IRedisList<T> fromList);
List<T> GetRangeFromList(IRedisList<T> fromList, int startingFrom, int endingAt);
List<T> SortList(IRedisList<T> fromList, int startingFrom, int endingAt);
void AddItemToList(IRedisList<T> fromList, T value);
void PrependItemToList(IRedisList<T> fromList, T value);
T RemoveStartFromList(IRedisList<T> fromList);
T BlockingRemoveStartFromList(IRedisList<T> fromList, TimeSpan? timeOut);
T RemoveEndFromList(IRedisList<T> fromList);
void RemoveAllFromList(IRedisList<T> fromList);
void TrimList(IRedisList<T> fromList, int keepStartingFrom, int keepEndingAt);
long RemoveItemFromList(IRedisList<T> fromList, T value);
long RemoveItemFromList(IRedisList<T> fromList, T value, int noOfMatches);
long GetListCount(IRedisList<T> fromList);
T GetItemFromList(IRedisList<T> fromList, int listIndex);
void SetItemInList(IRedisList<T> toList, int listIndex, T value);
void InsertBeforeItemInList(IRedisList<T> toList, T pivot, T value);
void InsertAfterItemInList(IRedisList<T> toList, T pivot, T value);
//Queue operations
void EnqueueItemOnList(IRedisList<T> fromList, T item);
T DequeueItemFromList(IRedisList<T> fromList);
T BlockingDequeueItemFromList(IRedisList<T> fromList, TimeSpan? timeOut);
//Stack operations
void PushItemToList(IRedisList<T> fromList, T item);
T PopItemFromList(IRedisList<T> fromList);
T BlockingPopItemFromList(IRedisList<T> fromList, TimeSpan? timeOut);
T PopAndPushItemBetweenLists(IRedisList<T> fromList, IRedisList<T> toList);
T BlockingPopAndPushItemBetweenLists(IRedisList<T> fromList, IRedisList<T> toList, TimeSpan? timeOut);
//Sorted Set operations
void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value);
void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value, double score);
bool RemoveItemFromSortedSet(IRedisSortedSet<T> fromSet, T value);
T PopItemWithLowestScoreFromSortedSet(IRedisSortedSet<T> fromSet);
T PopItemWithHighestScoreFromSortedSet(IRedisSortedSet<T> fromSet);
bool SortedSetContainsItem(IRedisSortedSet<T> set, T value);
double IncrementItemInSortedSet(IRedisSortedSet<T> set, T value, double incrementBy);
long GetItemIndexInSortedSet(IRedisSortedSet<T> set, T value);
long GetItemIndexInSortedSetDesc(IRedisSortedSet<T> set, T value);
List<T> GetAllItemsFromSortedSet(IRedisSortedSet<T> set);
List<T> GetAllItemsFromSortedSetDesc(IRedisSortedSet<T> set);
List<T> GetRangeFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank);
List<T> GetRangeFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank);
IDictionary<T, double> GetAllWithScoresFromSortedSet(IRedisSortedSet<T> set);
IDictionary<T, double> GetRangeWithScoresFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank);
IDictionary<T, double> GetRangeWithScoresFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank);
List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore);
List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take);
List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore);
List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take);
List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore);
List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take);
List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore);
List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore);
IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take);
long RemoveRangeFromSortedSet(IRedisSortedSet<T> set, int minRank, int maxRank);
long RemoveRangeFromSortedSetByScore(IRedisSortedSet<T> set, double fromScore, double toScore);
long GetSortedSetCount(IRedisSortedSet<T> set);
double GetItemScoreInSortedSet(IRedisSortedSet<T> set, T value);
long StoreIntersectFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds);
long StoreIntersectFromSortedSets(IRedisSortedSet<T> intoSetId, IRedisSortedSet<T>[] setIds, string[] args);
long StoreUnionFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds);
long StoreUnionFromSortedSets(IRedisSortedSet<T> intoSetId, IRedisSortedSet<T>[] setIds, string[] args);
//Hash operations
bool HashContainsEntry<TKey>(IRedisHash<TKey, T> hash, TKey key);
bool SetEntryInHash<TKey>(IRedisHash<TKey, T> hash, TKey key, T value);
bool SetEntryInHashIfNotExists<TKey>(IRedisHash<TKey, T> hash, TKey key, T value);
void SetRangeInHash<TKey>(IRedisHash<TKey, T> hash, IEnumerable<KeyValuePair<TKey, T>> keyValuePairs);
T GetValueFromHash<TKey>(IRedisHash<TKey, T> hash, TKey key);
bool RemoveEntryFromHash<TKey>(IRedisHash<TKey, T> hash, TKey key);
long GetHashCount<TKey>(IRedisHash<TKey, T> hash);
List<TKey> GetHashKeys<TKey>(IRedisHash<TKey, T> hash);
List<T> GetHashValues<TKey>(IRedisHash<TKey, T> hash);
Dictionary<TKey, T> GetAllEntriesFromHash<TKey>(IRedisHash<TKey, T> hash);
//Useful common app-logic
void StoreRelatedEntities<TChild>(object parentId, List<TChild> children);
void StoreRelatedEntities<TChild>(object parentId, params TChild[] children);
void DeleteRelatedEntities<TChild>(object parentId);
void DeleteRelatedEntity<TChild>(object parentId, object childId);
List<TChild> GetRelatedEntities<TChild>(object parentId);
long GetRelatedEntitiesCount<TChild>(object parentId);
void AddToRecentsList(T value);
List<T> GetLatestFromRecentsList(int skip, int take);
List<T> GetEarliestFromRecentsList(int skip, int take);
}
} | 57.645631 | 170 | 0.703747 | [
"Apache-2.0"
] | bodell/ServiceStack | src/ServiceStack.Interfaces/Redis/Generic/IRedisTypedClient.cs | 11,670 | 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("ControlledSpheres")]
[assembly: AssemblyProduct("ControlledSpheres")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d52d41dc-ef92-452b-8437-e5d93a71432c")]
// 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("3.3.0.1951")]
[assembly: AssemblyFileVersion("3.3.0.1951")]
| 38.189189 | 84 | 0.748054 | [
"MIT"
] | MadRubicant/GameDesign | ControlledSpheres/Properties/AssemblyInfo.cs | 1,416 | C# |
namespace OnlineShop.Models.Products
{
using System;
using Common.Constants;
public abstract class Product : IProduct
{
private int _id;
private string _manufacturer;
private string _model;
private decimal _price;
private double _overallPerformance;
protected Product(int id, string manufacturer, string model, decimal price, double overallPerformance)
{
Id = id;
Manufacturer = manufacturer;
Model = model;
Price = price;
OverallPerformance = overallPerformance;
}
public int Id
{
get => _id;
private set
{
if (value <= 0)
{
throw new ArgumentException(ExceptionMessages.InvalidProductId);
}
_id = value;
}
}
public string Manufacturer
{
get => _manufacturer;
private set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(ExceptionMessages.InvalidManufacturer);
}
_manufacturer = value;
}
}
public string Model
{
get => _model;
private set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(ExceptionMessages.InvalidModel);
}
_model = value;
}
}
public virtual decimal Price
{
get => _price;
private set
{
if (value <= 0)
{
throw new ArgumentException(ExceptionMessages.InvalidPrice);
}
_price = value;
}
}
public virtual double OverallPerformance
{
get => _overallPerformance;
private set
{
if (value <= 0)
{
throw new ArgumentException(ExceptionMessages.InvalidOverallPerformance);
}
_overallPerformance = value;
}
}
public override string ToString()
{
return $"Overall Performance: {OverallPerformance:F2}. " +
$"Price: {Price:F2} - {this.GetType().Name}: " +
$"{Manufacturer} {Model} (Id: {Id})";
}
}
}
| 26.278351 | 110 | 0.461357 | [
"MIT"
] | HostVanyaD/SoftUni | C# OOP/Exams/OOPExam16Aug2020/OnlineShop/Models/Products/Product.cs | 2,551 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Domain.Repositories;
using Xer.Cqrs.EventStack;
using Xer.Cqrs.EventStack.Hosted;
using Xer.Cqrs.EventStack.Hosted.EventSources;
namespace Domain.DomainEvents
{
public class UsersLockoutTimeElapsedEvent : IEvent
{
public IReadOnlyCollection<string> LockedOutUsernames { get; }
public UsersLockoutTimeElapsedEvent(IEnumerable<string> usernames)
{
LockedOutUsernames = usernames.ToList().AsReadOnly();
}
}
#region Event Source
public class UsersLockoutTimeElapsedEventSource : PollingEventSource
{
private readonly IUserRepository _userRepository;
protected override TimeSpan Interval { get; }
public UsersLockoutTimeElapsedEventSource(IUserRepository userRepository, TimeSpan releaseInterval)
{
_userRepository = userRepository;
Interval = releaseInterval;
}
protected override async Task<IEvent> GetNextEventAsync(CancellationToken cancellationToken)
{
List<User> lockedOutUsers = await _userRepository.GetLockedOutUsersAsync();
if(lockedOutUsers.Count > 0)
{
// Put all usernames of locked-out users to the event.
return new UsersLockoutTimeElapsedEvent(lockedOutUsers.Select(u => u.GetCurrentState().Username));
}
return null;
}
}
#endregion Event Source
#region Hosted Event Handler
public class UsersLockoutTimeElapsedHostedEventHandler : HostedEventHandler<UsersLockoutTimeElapsedEvent>
{
private readonly IUserRepository _userRepository;
protected override IEventSource EventSource { get; }
public UsersLockoutTimeElapsedHostedEventHandler(IUserRepository userRepository, TimeSpan releaseInterval)
{
_userRepository = userRepository;
EventSource = new UsersLockoutTimeElapsedEventSource(userRepository, releaseInterval);
}
protected override async Task ProcessEventAsync(UsersLockoutTimeElapsedEvent receivedEvent, CancellationToken cancellationToken)
{
foreach(string username in receivedEvent.LockedOutUsernames)
{
User lockedOutUser = await _userRepository.GetUserByUsernameAsync(username, cancellationToken).ConfigureAwait(false);
if (lockedOutUser != null)
{
UserState state = lockedOutUser.GetCurrentState();
if(state.LockoutExpiry.HasValue && state.LockoutExpiry.Value > DateTime.Now)
{
// Expiry has elapsed.
lockedOutUser.ReleaseLock();
}
}
}
}
}
#endregion Hosted Event Handler
} | 33.636364 | 136 | 0.663514 | [
"MIT"
] | keeed/Venturi | Src/Auth/Domain/BackgroundEvents/UsersLockoutTimeElapsedEvent.cs | 2,960 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TextMagic_Test.Responses
{
/// <summary>
/// Common fields of all TextMagic API responses
/// </summary>
interface IResponse
{
/// <summary>
/// The status of the response
/// </summary>
ResponseStatus ResponseStatus { get; set; }
}
}
| 21.9 | 53 | 0.609589 | [
"MIT"
] | Work-Stuff/TextMagic-Test | TextMagic-Test/Responses/IResponse.cs | 440 | C# |
// It's generated file. DO NOT MODIFY IT!
using Diablerie.Engine.Datasheets;
using Diablerie.Engine.IO.D2Formats;
class TranslationLoader : Datasheet.Loader<Translation>
{
public void LoadRecord(ref Translation record, DatasheetStream stream)
{
stream.Read(ref record.key);
stream.Read(ref record.value);
}
}
| 22.3125 | 74 | 0.686275 | [
"MIT"
] | Bia10/Diablerie | Assets/Scripts/Generated/DatasheetLoaders/TranslationLoader.cs | 357 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
public enum vx_channel_type {
channel_type_normal = 0,
channel_type_positional = 2
}
| 31.3125 | 81 | 0.46507 | [
"MIT"
] | Jibin-John/Virtual-World | VivoxTest/Assets/Vivox/Runtime/VivoxUnity/generated_files/vx_channel_type.cs | 501 | C# |
namespace CloudinaryDotNet.Actions
{
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// Response of transformation update.
/// </summary>
[DataContract]
public class UpdateTransformResult : BaseResult
{
/// <summary>
/// The name of transformation.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; protected set; }
/// <summary>
/// Whether this transformation is allowed when Strict Transformations are enabled.
/// </summary>
[DataMember(Name = "allowed_for_strict")]
public bool Strict { get; protected set; }
/// <summary>
/// Whether the transformation was ever used.
/// </summary>
[DataMember(Name = "used")]
public bool Used { get; protected set; }
/// <summary>
/// Detailed info about the transformation.
/// </summary>
[DataMember(Name = "info")]
public Dictionary<string, string>[] Info { get; protected set; }
/// <summary>
/// An array with derived assets settings.
/// </summary>
[DataMember(Name = "derived")]
public TransformDerived[] Derived { get; protected set; }
}
}
| 29.930233 | 91 | 0.576535 | [
"MIT"
] | jordansjones/CloudinaryDotNet | Shared/Actions/UpdateTransformResult.cs | 1,289 | C# |
using UnityEngine;
using System.Collections;
using Meta;
using SocketIO;
using UnityEngine.UI;
public class StartDrone : MonoBehaviour {
/// <summary>
/// Zeigt an ob der Quadrocopter gestart ist oder nicht
/// </summary>
public bool isStarted = false;
/// <summary>
/// Mesh-Objekt für den linken Mittelpunkt
/// </summary>
public MeshRenderer arrowCenterLeft = null;
/// <summary>
/// Mesh-Objekt für den rechten Mittelpunkt
/// </summary>
public MeshRenderer arrowCenterRight = null;
/// <summary>
/// Text-Objekt zur benachrichtigung des Benutzers
/// </summary>
public Text hudText;
/// <summary>
/// Temporäre Variable zur Speicherung eines Zeitpunktes um die Geste zum Starten Zeitgesteuert ausführen zu können
/// @brief Die Geste zum Starten muss 5 sec gehalten werden, damit der Quadrocopter startet
/// </summary>
private float takeoffEndTime = -1;
/// <summary>
/// Temporäre Variable zur Speicherung eines Zeitpunktes um die Geste zum Landen Zeitgesteuert ausführen zu können
/// @brief Die Geste zum Landen muss 2 sec gehalten werden, damit der Quadrocopter startet
/// </summary>
private float killEndTime = -1;
/// <summary>
/// Temporäre Variable zur Speicherung eines Zeitpunktes um die Geste zum Landen Zeitgesteuert ausführen zu können
/// @brief Wenn keine Hänge erkannt werden, wird dem benutzer 10 sec Zeit gegeben, die Steuerung wieder aufzunehmen.
/// Ansonsten wird der Quadrocopter Notgelandet.
/// </summary>
private float noHandsEndTime = -1;
/// <summary>
/// Inizialisierung des Objekts
/// @brief Der HUD-Text wird gelert, damit der benutzer keine Benachrichtigung beim inizialisieren sieht
/// </summary>
void Start () {
hudText.text = "";
}
/// <summary>
/// Update() wird bei jedem Frame aufgerufen.
/// @brief Hier findet die eigentlich Steuerung statt
/// </summary>
void Update () {
startDrone ();
killDrone ();
safetyKill ();
}
/// <summary>
/// Gestenerkennung zum Starten des Quadrocopters
/// @brief Die linke Hand muss geöffnet und die Rechte geschlossen sein um den Quadrocopter zu starten
/// Die Geste muss dann 5 sec gehalten werden um die Drohne abheben zu lassen
/// </summary>
private void startDrone(){
if (Meta.Hands.right.gesture.type.Equals (MetaGesture.GRAB) && Meta.Hands.left.gesture.type.Equals (MetaGesture.OPEN) && isStarted == false) {
hudText.color = Color.green;
setColorToAll (Color.red);
if(takeoffEndTime == -1){
takeoffEndTime = Time.time + 5;
hudText.text = "Start in 5";
}
int timeLeft = (int)(takeoffEndTime - Time.time);
if (timeLeft <= 0) {
timeLeft = 0;
isStarted = true;
gameObject.GetComponent<SocketIOComponent> ().Emit ("takeoff");
setColorToAll (Color.green);
} else {
hudText.text = "Start in " + timeLeft.ToString ();
}
} else {
takeoffEndTime = -1;
hudText.text = "";
}
}
/// <summary>
/// Gestenerkennung zum Landen des Quadrocopters
/// @brief Beide Hände müssen geschlossen sein um den Quadrocopter zu landen
/// Die Geste muss dann 2 sec gehalten werden um die Drohne landen zu lassen
/// </summary>
private void killDrone(){
if (Meta.Hands.right.gesture.type.Equals (MetaGesture.GRAB) && Meta.Hands.left.gesture.type.Equals (MetaGesture.GRAB)) {
hudText.color = Color.red;
setColorToAll (Color.red);
if(killEndTime == -1){
killEndTime = Time.time + 2;
hudText.text = "Landen in 2";
}
int timeLeft = (int)(killEndTime - Time.time);
if (timeLeft <= 0) {
timeLeft = 0;
isStarted = false;
gameObject.GetComponent<SocketIOComponent> ().Emit ("kill");
setColorToAll (Color.red);
} else {
hudText.text = "Landen in " + timeLeft.ToString ();
}
} else {
killEndTime = -1;
}
}
/// <summary>
/// Sicherheitsfunktion zum Notlanden der Drohne wenn keine Hände erkannt werden
/// @brief Wenn keine Hände erkannt werden, wird die Drohne nach 10 sec Notgelandet.
/// </summary>
private void safetyKill(){
if ((!Meta.Hands.right.isValid && !Meta.Hands.left.isValid) && isStarted) {
hudText.fontSize = 60;
hudText.color = Color.red;
setColorToAll (Color.red);
if(noHandsEndTime == -1){
noHandsEndTime = Time.time + 10;
hudText.text = "Hände nicht erkannt \r\n Landen in 10";
}
int timeLeft = (int)(noHandsEndTime - Time.time);
if (timeLeft <= 0) {
timeLeft = 0;
isStarted = false;
gameObject.GetComponent<SocketIOComponent> ().Emit ("kill");
setColorToAll (Color.red);
} else {
hudText.text = "Hände nicht erkannt \r\n Landen in " + timeLeft.ToString ();
}
} else {
noHandsEndTime = -1;
hudText.fontSize = 80;
}
}
/// <summary>
/// Setzte beide Mittelpunkte auf die gleiche Farbe
/// </summary>
private void setColorToAll(Color _color){
arrowCenterLeft.material.color = _color;
arrowCenterRight.material.color = _color;
}
}
| 29.830303 | 144 | 0.680211 | [
"Apache-2.0"
] | TheAgentK/MetaDrone | game/Assets/MetaDrone/StartDrone.cs | 4,943 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
using Alipay.AopSdk.Core.Domain;
namespace Alipay.AopSdk.Core.Response
{
/// <summary>
/// AlipayCommerceCityfacilitatorVoucherBatchqueryResponse.
/// </summary>
public class AlipayCommerceCityfacilitatorVoucherBatchqueryResponse : AopResponse
{
/// <summary>
/// 查询到的订单信息列表
/// </summary>
[JsonProperty("tickets")]
public List<TicketDetailInfo> Tickets { get; set; }
}
} | 24 | 82 | 0.732456 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk.Core/Response/AlipayCommerceCityfacilitatorVoucherBatchqueryResponse.cs | 476 | C# |
using System.Collections;
namespace UniRx.Examples
{
public class Sample02_TypedBehaviour : ObservableMonoBehaviour
{
// all message is overridable, it's typesafe
public override void Update()
{
base.Update();
}
// use Coroutine, use "new" keyword
new public IEnumerator Start()
{
while (true)
{
yield return null;
}
}
}
} | 22.090909 | 67 | 0.5 | [
"MIT"
] | mikanbako/example-unity-pinch-gesture-with-rx | Assets/UniRx/Examples/Sample02_TypedBehaviour.cs | 488 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Sep.Git.Tfs.Commands;
using Sep.Git.Tfs.Core.TfsInterop;
namespace Sep.Git.Tfs.Core
{
public class TfsWorkspace : ITfsWorkspace
{
private readonly IWorkspace _workspace;
private readonly string _localDirectory;
private readonly TextWriter _stdout;
private readonly TfsChangesetInfo _contextVersion;
private readonly CheckinOptions _checkinOptions;
private readonly ITfsHelper _tfsHelper;
private readonly CheckinPolicyEvaluator _policyEvaluator;
public IGitTfsRemote Remote { get; private set; }
public TfsWorkspace(IWorkspace workspace, string localDirectory, TextWriter stdout, TfsChangesetInfo contextVersion, IGitTfsRemote remote, CheckinOptions checkinOptions, ITfsHelper tfsHelper, CheckinPolicyEvaluator policyEvaluator)
{
_workspace = workspace;
_policyEvaluator = policyEvaluator;
_contextVersion = contextVersion;
_checkinOptions = checkinOptions;
_tfsHelper = tfsHelper;
_localDirectory = remote.Repository.IsBare ? Path.GetFullPath(localDirectory) : localDirectory;
_stdout = stdout;
this.Remote = remote;
}
public void Shelve(string shelvesetName, bool evaluateCheckinPolicies, CheckinOptions checkinOptions)
{
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to shelve!");
var shelveset = _tfsHelper.CreateShelveset(_workspace, shelvesetName);
shelveset.Comment = checkinOptions.CheckinComment;
shelveset.WorkItemInfo = GetWorkItemInfos(checkinOptions).ToArray();
if (evaluateCheckinPolicies)
{
foreach (var message in _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, shelveset.Comment, null, shelveset.WorkItemInfo).Messages)
{
_stdout.WriteLine("[Checkin Policy] " + message);
}
}
_workspace.Shelve(shelveset, pendingChanges, _checkinOptions.Force ? TfsShelvingOptions.Replace : TfsShelvingOptions.None);
}
public int CheckinTool(Func<string> generateCheckinComment)
{
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to checkin!");
var checkinComment = _checkinOptions.CheckinComment;
if (string.IsNullOrWhiteSpace(checkinComment) && !_checkinOptions.NoGenerateCheckinComment)
checkinComment = generateCheckinComment();
var newChangesetId = _tfsHelper.ShowCheckinDialog(_workspace, pendingChanges, GetWorkItemCheckedInfos(), checkinComment);
if (newChangesetId <= 0)
throw new GitTfsException("Checkin canceled!");
return newChangesetId;
}
public void Merge(string sourceTfsPath, string tfsRepositoryPath)
{
_workspace.Merge(sourceTfsPath, tfsRepositoryPath);
}
public int Checkin(CheckinOptions options, Func<string> generateCheckinComment = null)
{
if (options == null) options = _checkinOptions;
var checkinComment = options.CheckinComment;
if (string.IsNullOrWhiteSpace(checkinComment) && !options.NoGenerateCheckinComment && generateCheckinComment != null)
checkinComment = generateCheckinComment();
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to checkin!");
var workItemInfos = GetWorkItemInfos(options);
var checkinNote = _tfsHelper.CreateCheckinNote(options.CheckinNotes);
var checkinProblems = _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, checkinComment, checkinNote, workItemInfos);
if (checkinProblems.HasErrors)
{
foreach (var message in checkinProblems.Messages)
{
if (options.Force && string.IsNullOrWhiteSpace(options.OverrideReason) == false)
{
_stdout.WriteLine("[OVERRIDDEN] " + message);
}
else
{
_stdout.WriteLine("[ERROR] " + message);
}
}
if (!options.Force)
{
throw new GitTfsException("No changes checked in.");
}
if (String.IsNullOrWhiteSpace(options.OverrideReason))
{
throw new GitTfsException("A reason must be supplied (-f REASON) to override the policy violations.");
}
}
var policyOverride = GetPolicyOverrides(options, checkinProblems.Result);
try
{
var newChangeset = _workspace.Checkin(pendingChanges, checkinComment, options.AuthorTfsUserId, checkinNote, workItemInfos, policyOverride, options.OverrideGatedCheckIn);
if (newChangeset == 0)
{
throw new GitTfsException("Checkin failed!");
}
else
{
return newChangeset;
}
}
catch(GitTfsGatedCheckinException e)
{
return LaunchGatedCheckinBuild(e.AffectedBuildDefinitions, e.ShelvesetName, e.CheckInTicket);
}
}
private int LaunchGatedCheckinBuild(ReadOnlyCollection<KeyValuePair<string, Uri>> affectedBuildDefinitions, string shelvesetName, string checkInTicket)
{
_stdout.WriteLine("Due to a gated check-in, a shelveset '" + shelvesetName + "' containing your changes has been created and need to be built before it can be committed.");
KeyValuePair<string, Uri> buildDefinition;
if (affectedBuildDefinitions.Count == 1)
{
buildDefinition = affectedBuildDefinitions.First();
}
else
{
int choice;
do
{
_stdout.WriteLine("Build definitions that can be used:");
for (int i = 0; i < affectedBuildDefinitions.Count; i++)
{
_stdout.WriteLine((i + 1) + ": " + affectedBuildDefinitions[i].Key);
}
_stdout.WriteLine("Please choose the build definition to trigger?");
} while (!int.TryParse(Console.ReadLine(), out choice) || choice <= 0 || choice > affectedBuildDefinitions.Count);
buildDefinition = affectedBuildDefinitions.ElementAt(choice - 1);
}
return Remote.Tfs.QueueGatedCheckinBuild(buildDefinition.Value, buildDefinition.Key, shelvesetName, checkInTicket);
}
private TfsPolicyOverrideInfo GetPolicyOverrides(CheckinOptions options, ICheckinEvaluationResult checkinProblems)
{
if (!options.Force || String.IsNullOrWhiteSpace(options.OverrideReason))
return null;
return new TfsPolicyOverrideInfo { Comment = options.OverrideReason, Failures = checkinProblems.PolicyFailures };
}
public string GetLocalPath(string path)
{
return Path.Combine(_localDirectory, path);
}
public void Add(string path)
{
_stdout.WriteLine(" add " + path);
var added = _workspace.PendAdd(GetLocalPath(path));
if (added != 1) throw new Exception("One item should have been added, but actually added " + added + " items.");
}
public void Edit(string path)
{
var localPath = GetLocalPath(path);
_stdout.WriteLine(" edit " + localPath);
GetFromTfs(localPath);
var edited = _workspace.PendEdit(localPath);
if (edited != 1)
{
if (_checkinOptions.IgnoreMissingItems)
{
_stdout.WriteLine("Warning: One item should have been edited, but actually edited " + edited + ". Ignoring item.");
}
else if (edited == 0 && _checkinOptions.AddMissingItems)
{
_stdout.WriteLine("Warning: One item should have been edited, but was not found. Adding the file instead.");
Add(path);
}
else
{
throw new Exception("One item should have been edited, but actually edited " + edited + " items.");
}
}
}
public void Delete(string path)
{
path = GetLocalPath(path);
_stdout.WriteLine(" delete " + path);
GetFromTfs(path);
var deleted = _workspace.PendDelete(path);
if (deleted != 1) throw new Exception("One item should have been deleted, but actually deleted " + deleted + " items.");
}
public void Rename(string pathFrom, string pathTo, string score)
{
_stdout.WriteLine(" rename " + pathFrom + " to " + pathTo + " (score: " + score + ")");
GetFromTfs(GetLocalPath(pathFrom));
var result = _workspace.PendRename(GetLocalPath(pathFrom), GetLocalPath(pathTo));
if (result != 1) throw new ApplicationException("Unable to rename item from " + pathFrom + " to " + pathTo);
}
private void GetFromTfs(string path)
{
_workspace.ForceGetFile(_workspace.GetServerItemForLocalItem(path), _contextVersion.ChangesetId);
}
public void Get(int changesetId)
{
_workspace.GetSpecificVersion(changesetId);
}
public void Get(IChangeset changeset)
{
_workspace.GetSpecificVersion(changeset);
}
public void Get(int changesetId, IEnumerable<IChange> changes)
{
if (changes.Any())
{
_workspace.GetSpecificVersion(changesetId, changes);
}
}
public string GetLocalItemForServerItem(string serverItem)
{
return _workspace.GetLocalItemForServerItem(serverItem);
}
private IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(CheckinOptions options = null)
{
return GetWorkItemInfosHelper<IWorkItemCheckinInfo>(_tfsHelper.GetWorkItemInfos, options);
}
private IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos()
{
return GetWorkItemInfosHelper<IWorkItemCheckedInfo>(_tfsHelper.GetWorkItemCheckedInfos);
}
private IEnumerable<T> GetWorkItemInfosHelper<T>(Func<IEnumerable<string>, TfsWorkItemCheckinAction, IEnumerable<T>> func, CheckinOptions options = null)
{
var checkinOptions = options ?? _checkinOptions;
var workItemInfos = func(checkinOptions.WorkItemsToAssociate, TfsWorkItemCheckinAction.Associate);
workItemInfos = workItemInfos.Append(
func(checkinOptions.WorkItemsToResolve, TfsWorkItemCheckinAction.Resolve));
return workItemInfos;
}
}
}
| 42.638376 | 239 | 0.606231 | [
"Apache-2.0"
] | ivan-danilov/git-tfs | GitTfs/Core/TfsWorkspace.cs | 11,555 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Storage.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The replication policy rule between two containers.
/// </summary>
public partial class ObjectReplicationPolicyRule
{
/// <summary>
/// Initializes a new instance of the ObjectReplicationPolicyRule
/// class.
/// </summary>
public ObjectReplicationPolicyRule()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ObjectReplicationPolicyRule
/// class.
/// </summary>
/// <param name="sourceContainer">Required. Source container
/// name.</param>
/// <param name="destinationContainer">Required. Destination container
/// name.</param>
/// <param name="ruleId">Rule Id is auto-generated for each new rule on
/// destination account. It is required for put policy on source
/// account.</param>
/// <param name="filters">Optional. An object that defines the filter
/// set.</param>
public ObjectReplicationPolicyRule(string sourceContainer, string destinationContainer, string ruleId = default(string), ObjectReplicationPolicyFilter filters = default(ObjectReplicationPolicyFilter))
{
RuleId = ruleId;
SourceContainer = sourceContainer;
DestinationContainer = destinationContainer;
Filters = filters;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets rule Id is auto-generated for each new rule on
/// destination account. It is required for put policy on source
/// account.
/// </summary>
[JsonProperty(PropertyName = "ruleId")]
public string RuleId { get; set; }
/// <summary>
/// Gets or sets required. Source container name.
/// </summary>
[JsonProperty(PropertyName = "sourceContainer")]
public string SourceContainer { get; set; }
/// <summary>
/// Gets or sets required. Destination container name.
/// </summary>
[JsonProperty(PropertyName = "destinationContainer")]
public string DestinationContainer { get; set; }
/// <summary>
/// Gets or sets optional. An object that defines the filter set.
/// </summary>
[JsonProperty(PropertyName = "filters")]
public ObjectReplicationPolicyFilter Filters { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (SourceContainer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "SourceContainer");
}
if (DestinationContainer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "DestinationContainer");
}
}
}
}
| 35.582524 | 208 | 0.606276 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/storage/Microsoft.Azure.Management.Storage/src/Generated/Models/ObjectReplicationPolicyRule.cs | 3,665 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Soltys.Library.Bson
{
public class BsonArray : BsonValue
{
internal override ElementType Type => ElementType.Array;
private readonly List<BsonValue> values;
public IReadOnlyCollection<BsonValue> Values => this.values;
public BsonArray()
{
this.values = new List<BsonValue>();
}
public BsonArray(params BsonValue[] values)
{
this.values = new List<BsonValue>(values);
}
public void Add(BsonValue value)
{
this.values.Add(value);
}
public void AddRange(IEnumerable<BsonValue> v)
{
this.values.AddRange(v);
}
public BsonValue this[int index] => this.values[index];
public override ReadOnlySpan<byte> GetBytes() => BsonEncoder.EncodeAsDocument(ToElements());
/// <summary>
/// Array - The document for an array is a normal BSON document with integer values for the keys,
/// starting with 0 and continuing sequentially. For example, the array ['red', 'blue'] would be encoded as the document {'0': 'red', '1': 'blue'}.
/// The keys must be in ascending numerical order.
///</summary>
private IEnumerable<Element> ToElements() => this.values.Select((value, i) => new Element(i.ToString(), value));
public override string ToString() => $"[{ToString(this.values)}]";
private static string ToString(IEnumerable<BsonValue> values) => string.Join(", ", values.Select(x => x.ToString()));
}
}
| 33.244898 | 155 | 0.618171 | [
"MIT"
] | soltys/Melange | src/Library/Soltys.Library/Structures/Bson/Values/BsonArray.cs | 1,629 | 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("RemoveWhiteSpace2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RemoveWhiteSpace2")]
[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("1d32e31f-af5b-4cfb-b4eb-c7ed2ca57395")]
// 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.891892 | 84 | 0.749643 | [
"MIT"
] | robyscar/C-_10_AllInOne4Dummies_sourcecode | source/BK01/CH03/RemoveWhiteSpace2/Properties/AssemblyInfo.cs | 1,405 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.AppService.Models;
namespace Azure.ResourceManager.AppService
{
/// <summary>
/// A class representing a collection of <see cref="HostingEnvironmentPrivateEndpointConnectionResource" /> and their operations.
/// Each <see cref="HostingEnvironmentPrivateEndpointConnectionResource" /> in the collection will belong to the same instance of <see cref="AppServiceEnvironmentResource" />.
/// To get a <see cref="HostingEnvironmentPrivateEndpointConnectionCollection" /> instance call the GetHostingEnvironmentPrivateEndpointConnections method from an instance of <see cref="AppServiceEnvironmentResource" />.
/// </summary>
public partial class HostingEnvironmentPrivateEndpointConnectionCollection : ArmCollection, IEnumerable<HostingEnvironmentPrivateEndpointConnectionResource>, IAsyncEnumerable<HostingEnvironmentPrivateEndpointConnectionResource>
{
private readonly ClientDiagnostics _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics;
private readonly AppServiceEnvironmentsRestOperations _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient;
/// <summary> Initializes a new instance of the <see cref="HostingEnvironmentPrivateEndpointConnectionCollection"/> class for mocking. </summary>
protected HostingEnvironmentPrivateEndpointConnectionCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="HostingEnvironmentPrivateEndpointConnectionCollection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
internal HostingEnvironmentPrivateEndpointConnectionCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.AppService", HostingEnvironmentPrivateEndpointConnectionResource.ResourceType.Namespace, Diagnostics);
TryGetApiVersion(HostingEnvironmentPrivateEndpointConnectionResource.ResourceType, out string hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsApiVersion);
_hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient = new AppServiceEnvironmentsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != AppServiceEnvironmentResource.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, AppServiceEnvironmentResource.ResourceType), nameof(id));
}
/// <summary>
/// Description for Approves or rejects a private endpoint connection
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: AppServiceEnvironments_ApproveOrRejectPrivateEndpointConnection
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="privateEndpointConnectionName"> The String to use. </param>
/// <param name="privateEndpointWrapper"> The PrivateLinkConnectionApprovalRequestResource to use. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> or <paramref name="privateEndpointWrapper"/> is null. </exception>
public virtual async Task<ArmOperation<HostingEnvironmentPrivateEndpointConnectionResource>> CreateOrUpdateAsync(WaitUntil waitUntil, string privateEndpointConnectionName, PrivateLinkConnectionApprovalRequestResource privateEndpointWrapper, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateEndpointConnectionName, nameof(privateEndpointConnectionName));
Argument.AssertNotNull(privateEndpointWrapper, nameof(privateEndpointWrapper));
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.ApproveOrRejectPrivateEndpointConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, privateEndpointWrapper, cancellationToken).ConfigureAwait(false);
var operation = new AppServiceArmOperation<HostingEnvironmentPrivateEndpointConnectionResource>(new HostingEnvironmentPrivateEndpointConnectionOperationSource(Client), _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics, Pipeline, _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.CreateApproveOrRejectPrivateEndpointConnectionRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, privateEndpointWrapper).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Approves or rejects a private endpoint connection
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: AppServiceEnvironments_ApproveOrRejectPrivateEndpointConnection
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="privateEndpointConnectionName"> The String to use. </param>
/// <param name="privateEndpointWrapper"> The PrivateLinkConnectionApprovalRequestResource to use. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> or <paramref name="privateEndpointWrapper"/> is null. </exception>
public virtual ArmOperation<HostingEnvironmentPrivateEndpointConnectionResource> CreateOrUpdate(WaitUntil waitUntil, string privateEndpointConnectionName, PrivateLinkConnectionApprovalRequestResource privateEndpointWrapper, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateEndpointConnectionName, nameof(privateEndpointConnectionName));
Argument.AssertNotNull(privateEndpointWrapper, nameof(privateEndpointWrapper));
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.ApproveOrRejectPrivateEndpointConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, privateEndpointWrapper, cancellationToken);
var operation = new AppServiceArmOperation<HostingEnvironmentPrivateEndpointConnectionResource>(new HostingEnvironmentPrivateEndpointConnectionOperationSource(Client), _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics, Pipeline, _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.CreateApproveOrRejectPrivateEndpointConnectionRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, privateEndpointWrapper).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Gets a private endpoint connection
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: AppServiceEnvironments_GetPrivateEndpointConnection
/// </summary>
/// <param name="privateEndpointConnectionName"> Name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
public virtual async Task<Response<HostingEnvironmentPrivateEndpointConnectionResource>> GetAsync(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateEndpointConnectionName, nameof(privateEndpointConnectionName));
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.Get");
scope.Start();
try
{
var response = await _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new HostingEnvironmentPrivateEndpointConnectionResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Gets a private endpoint connection
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: AppServiceEnvironments_GetPrivateEndpointConnection
/// </summary>
/// <param name="privateEndpointConnectionName"> Name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
public virtual Response<HostingEnvironmentPrivateEndpointConnectionResource> Get(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateEndpointConnectionName, nameof(privateEndpointConnectionName));
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.Get");
scope.Start();
try
{
var response = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new HostingEnvironmentPrivateEndpointConnectionResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Gets the list of private endpoints associated with a hosting environment
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections
/// Operation Id: AppServiceEnvironments_GetPrivateEndpointConnectionList
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="HostingEnvironmentPrivateEndpointConnectionResource" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<HostingEnvironmentPrivateEndpointConnectionResource> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<HostingEnvironmentPrivateEndpointConnectionResource>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.GetAll");
scope.Start();
try
{
var response = await _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnectionListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new HostingEnvironmentPrivateEndpointConnectionResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<HostingEnvironmentPrivateEndpointConnectionResource>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.GetAll");
scope.Start();
try
{
var response = await _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnectionListNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new HostingEnvironmentPrivateEndpointConnectionResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Description for Gets the list of private endpoints associated with a hosting environment
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections
/// Operation Id: AppServiceEnvironments_GetPrivateEndpointConnectionList
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="HostingEnvironmentPrivateEndpointConnectionResource" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<HostingEnvironmentPrivateEndpointConnectionResource> GetAll(CancellationToken cancellationToken = default)
{
Page<HostingEnvironmentPrivateEndpointConnectionResource> FirstPageFunc(int? pageSizeHint)
{
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.GetAll");
scope.Start();
try
{
var response = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnectionList(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new HostingEnvironmentPrivateEndpointConnectionResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<HostingEnvironmentPrivateEndpointConnectionResource> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.GetAll");
scope.Start();
try
{
var response = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnectionListNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new HostingEnvironmentPrivateEndpointConnectionResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: AppServiceEnvironments_GetPrivateEndpointConnection
/// </summary>
/// <param name="privateEndpointConnectionName"> Name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
public virtual async Task<Response<bool>> ExistsAsync(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateEndpointConnectionName, nameof(privateEndpointConnectionName));
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.Exists");
scope.Start();
try
{
var response = await _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnectionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: AppServiceEnvironments_GetPrivateEndpointConnection
/// </summary>
/// <param name="privateEndpointConnectionName"> Name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
public virtual Response<bool> Exists(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateEndpointConnectionName, nameof(privateEndpointConnectionName));
using var scope = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsClientDiagnostics.CreateScope("HostingEnvironmentPrivateEndpointConnectionCollection.Exists");
scope.Start();
try
{
var response = _hostingEnvironmentPrivateEndpointConnectionAppServiceEnvironmentsRestClient.GetPrivateEndpointConnection(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateEndpointConnectionName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<HostingEnvironmentPrivateEndpointConnectionResource> IEnumerable<HostingEnvironmentPrivateEndpointConnectionResource>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<HostingEnvironmentPrivateEndpointConnectionResource> IAsyncEnumerable<HostingEnvironmentPrivateEndpointConnectionResource>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 74.295522 | 567 | 0.732814 | [
"MIT"
] | alexbuckgit/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/HostingEnvironmentPrivateEndpointConnectionCollection.cs | 24,889 | C# |
using System;
namespace TypingGame.Logic
{
public class ColorRGBAFactory : IColorRGBAFactory
{
private readonly Random random;
public ColorRGBAFactory()
{
random = new Random();
}
public ColorRGBA GetColor()
{
var index = random.Next(3);
switch (index)
{
case 0: return new ColorRGBA { R = 256, G = 0, B = 0, Alpha = 0 };
case 1: return new ColorRGBA { R = 0, G = 0, B = 256, Alpha = 0 };
case 2: return new ColorRGBA { R = 0, G = 256, B = 0, Alpha = 0 };
default: return new ColorRGBA { R = 256, G = 256, B = 256, Alpha = 0 };
}
}
}
}
| 26.178571 | 87 | 0.47749 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | JBurant/TypingGame | TypingGame/Logic/ColorRGBAFactory.cs | 735 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.EntityFrameworkCore;
public class DesignApiConsistencyTest : ApiConsistencyTestBase<DesignApiConsistencyTest.DesignApiConsistencyFixture>
{
public DesignApiConsistencyTest(DesignApiConsistencyFixture fixture)
: base(fixture)
{
}
protected override void AddServices(ServiceCollection serviceCollection)
{
}
protected override Assembly TargetAssembly
=> typeof(OperationExecutor).Assembly;
public class DesignApiConsistencyFixture : ApiConsistencyFixtureBase
{
public override HashSet<Type> FluentApiTypes { get; } = new() { typeof(DesignTimeServiceCollectionExtensions) };
}
}
| 32.08 | 120 | 0.763092 | [
"MIT"
] | AraHaan/efcore | test/EFCore.Design.Tests/DesignApiConsistencyTest.cs | 802 | C# |
using System;
using JetBrains.Annotations;
using OrchestratR.Server;
namespace OrchestratR.Extension.RabbitMq
{
internal class OrchestratrObserverFaultRule : IOrchestratrObserverFaultRule
{
public OrchestratrObserverFaultRule([NotNull] string absolutePath, Type errorType)
{
AbsolutePath = absolutePath ?? throw new ArgumentNullException(nameof(absolutePath));
ErrorType = errorType;
}
public string AbsolutePath { get; }
public Type ErrorType { get; }
}
} | 29.666667 | 97 | 0.702247 | [
"MIT"
] | dkzkv/OrchestratR | src/OrchestratR.Extension.RabbitMq/OrchestratrObserverFaultRule.cs | 534 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ram-2018-01-04.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.RAM
{
/// <summary>
/// Constants used for properties of type ResourceOwner.
/// </summary>
public class ResourceOwner : ConstantClass
{
/// <summary>
/// Constant OTHERACCOUNTS for ResourceOwner
/// </summary>
public static readonly ResourceOwner OTHERACCOUNTS = new ResourceOwner("OTHER-ACCOUNTS");
/// <summary>
/// Constant SELF for ResourceOwner
/// </summary>
public static readonly ResourceOwner SELF = new ResourceOwner("SELF");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceOwner(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceOwner FindValue(string value)
{
return FindValue<ResourceOwner>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceOwner(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceShareAssociationStatus.
/// </summary>
public class ResourceShareAssociationStatus : ConstantClass
{
/// <summary>
/// Constant ASSOCIATED for ResourceShareAssociationStatus
/// </summary>
public static readonly ResourceShareAssociationStatus ASSOCIATED = new ResourceShareAssociationStatus("ASSOCIATED");
/// <summary>
/// Constant ASSOCIATING for ResourceShareAssociationStatus
/// </summary>
public static readonly ResourceShareAssociationStatus ASSOCIATING = new ResourceShareAssociationStatus("ASSOCIATING");
/// <summary>
/// Constant DISASSOCIATED for ResourceShareAssociationStatus
/// </summary>
public static readonly ResourceShareAssociationStatus DISASSOCIATED = new ResourceShareAssociationStatus("DISASSOCIATED");
/// <summary>
/// Constant DISASSOCIATING for ResourceShareAssociationStatus
/// </summary>
public static readonly ResourceShareAssociationStatus DISASSOCIATING = new ResourceShareAssociationStatus("DISASSOCIATING");
/// <summary>
/// Constant FAILED for ResourceShareAssociationStatus
/// </summary>
public static readonly ResourceShareAssociationStatus FAILED = new ResourceShareAssociationStatus("FAILED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceShareAssociationStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceShareAssociationStatus FindValue(string value)
{
return FindValue<ResourceShareAssociationStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceShareAssociationStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceShareAssociationType.
/// </summary>
public class ResourceShareAssociationType : ConstantClass
{
/// <summary>
/// Constant PRINCIPAL for ResourceShareAssociationType
/// </summary>
public static readonly ResourceShareAssociationType PRINCIPAL = new ResourceShareAssociationType("PRINCIPAL");
/// <summary>
/// Constant RESOURCE for ResourceShareAssociationType
/// </summary>
public static readonly ResourceShareAssociationType RESOURCE = new ResourceShareAssociationType("RESOURCE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceShareAssociationType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceShareAssociationType FindValue(string value)
{
return FindValue<ResourceShareAssociationType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceShareAssociationType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceShareInvitationStatus.
/// </summary>
public class ResourceShareInvitationStatus : ConstantClass
{
/// <summary>
/// Constant ACCEPTED for ResourceShareInvitationStatus
/// </summary>
public static readonly ResourceShareInvitationStatus ACCEPTED = new ResourceShareInvitationStatus("ACCEPTED");
/// <summary>
/// Constant EXPIRED for ResourceShareInvitationStatus
/// </summary>
public static readonly ResourceShareInvitationStatus EXPIRED = new ResourceShareInvitationStatus("EXPIRED");
/// <summary>
/// Constant PENDING for ResourceShareInvitationStatus
/// </summary>
public static readonly ResourceShareInvitationStatus PENDING = new ResourceShareInvitationStatus("PENDING");
/// <summary>
/// Constant REJECTED for ResourceShareInvitationStatus
/// </summary>
public static readonly ResourceShareInvitationStatus REJECTED = new ResourceShareInvitationStatus("REJECTED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceShareInvitationStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceShareInvitationStatus FindValue(string value)
{
return FindValue<ResourceShareInvitationStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceShareInvitationStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceShareStatus.
/// </summary>
public class ResourceShareStatus : ConstantClass
{
/// <summary>
/// Constant ACTIVE for ResourceShareStatus
/// </summary>
public static readonly ResourceShareStatus ACTIVE = new ResourceShareStatus("ACTIVE");
/// <summary>
/// Constant DELETED for ResourceShareStatus
/// </summary>
public static readonly ResourceShareStatus DELETED = new ResourceShareStatus("DELETED");
/// <summary>
/// Constant DELETING for ResourceShareStatus
/// </summary>
public static readonly ResourceShareStatus DELETING = new ResourceShareStatus("DELETING");
/// <summary>
/// Constant FAILED for ResourceShareStatus
/// </summary>
public static readonly ResourceShareStatus FAILED = new ResourceShareStatus("FAILED");
/// <summary>
/// Constant PENDING for ResourceShareStatus
/// </summary>
public static readonly ResourceShareStatus PENDING = new ResourceShareStatus("PENDING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceShareStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceShareStatus FindValue(string value)
{
return FindValue<ResourceShareStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceShareStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceStatus.
/// </summary>
public class ResourceStatus : ConstantClass
{
/// <summary>
/// Constant AVAILABLE for ResourceStatus
/// </summary>
public static readonly ResourceStatus AVAILABLE = new ResourceStatus("AVAILABLE");
/// <summary>
/// Constant LIMIT_EXCEEDED for ResourceStatus
/// </summary>
public static readonly ResourceStatus LIMIT_EXCEEDED = new ResourceStatus("LIMIT_EXCEEDED");
/// <summary>
/// Constant UNAVAILABLE for ResourceStatus
/// </summary>
public static readonly ResourceStatus UNAVAILABLE = new ResourceStatus("UNAVAILABLE");
/// <summary>
/// Constant ZONAL_RESOURCE_INACCESSIBLE for ResourceStatus
/// </summary>
public static readonly ResourceStatus ZONAL_RESOURCE_INACCESSIBLE = new ResourceStatus("ZONAL_RESOURCE_INACCESSIBLE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceStatus FindValue(string value)
{
return FindValue<ResourceStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceStatus(string value)
{
return FindValue(value);
}
}
} | 39.360656 | 132 | 0.633208 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/RAM/Generated/ServiceEnumerations.cs | 14,406 | C# |
//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using System.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("Queuing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rare Crowds Inc")]
[assembly: AssemblyProduct("Queuing")]
[assembly: AssemblyCopyright("Copyright © Rare Crowds Inc 2012")]
[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("1cb156bc-d2f2-4222-b5f1-473ee3cf747c")]
// 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")]
[assembly: InternalsVisibleTo("RuntimeIoc.WebRole")]
[assembly: InternalsVisibleTo("RuntimeIoc.WorkerRole")]
[assembly: InternalsVisibleTo("RuntimeIoc.WebRole.IntegrationTests")]
[assembly: InternalsVisibleTo("RuntimeIoc.WorkerRole.IntegrationTests")]
[assembly: InternalsVisibleTo("AzureQueueUnitTests")]
[assembly: InternalsVisibleTo("QueuingUnitTests")]
[assembly: InternalsVisibleTo("ScheduledActivityUnitTests")] | 44.225806 | 85 | 0.695842 | [
"Apache-2.0"
] | bewood/OpenAdStack | Queuing/Queuing/Properties/AssemblyInfo.cs | 2,745 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
namespace EfsTools.Items.Nv
{
[Ignore]
[Serializable]
[NvItemId(2826)]
[Attributes(9)]
public class Wcdma1800RxAgcMin3
{
[ElementsCount(1)]
[ElementType("uint8")]
[Description("")]
public byte Field1 { get; set; }
[ElementsCount(1)]
[ElementType("uint8")]
[Description("")]
public byte Field2 { get; set; }
}
} | 20.75 | 41 | 0.560241 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Nv/WCDMA1800RxAgcMin3.cs | 498 | 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.AzureNative.Cdn.V20191231.Outputs
{
[OutputType]
public sealed class PostArgsMatchConditionParametersResponse
{
/// <summary>
/// The match value for the condition of the delivery rule
/// </summary>
public readonly ImmutableArray<string> MatchValues;
/// <summary>
/// Describes if this is negate condition or not
/// </summary>
public readonly bool? NegateCondition;
public readonly string OdataType;
/// <summary>
/// Describes operator to be matched
/// </summary>
public readonly string Operator;
/// <summary>
/// Name of PostArg to be matched
/// </summary>
public readonly string? Selector;
/// <summary>
/// List of transforms
/// </summary>
public readonly ImmutableArray<string> Transforms;
[OutputConstructor]
private PostArgsMatchConditionParametersResponse(
ImmutableArray<string> matchValues,
bool? negateCondition,
string odataType,
string @operator,
string? selector,
ImmutableArray<string> transforms)
{
MatchValues = matchValues;
NegateCondition = negateCondition;
OdataType = odataType;
Operator = @operator;
Selector = selector;
Transforms = transforms;
}
}
}
| 28.918033 | 81 | 0.608277 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Cdn/V20191231/Outputs/PostArgsMatchConditionParametersResponse.cs | 1,764 | C# |
namespace Cosmos.Collections;
/// <summary>
/// Array copy options <br />
/// 数组复制选项
/// </summary>
public enum ArrayCopyOptions
{
/// <summary>
/// Length <br />
/// 根据长度
/// </summary>
Length = 0,
/// <summary>
/// Since Index <br />
/// 根据起始的索引值
/// </summary>
SinceIndex = 1
}
/// <summary>
/// Array utilities <br />
/// 数组工具
/// </summary>
public static partial class Arrays
{
/// <summary>
/// Cloning of a one-dimensional array <br />
/// 克隆一个一维数组
/// </summary>
public static T[] Copy<T>(T[] bytes)
{
var newBytes = new T[bytes.Length];
Array.Copy(bytes, newBytes, bytes.Length);
return newBytes;
}
/// <summary>
/// Cloning of a two-dimensional array <br />
/// 克隆一个二维数组
/// </summary>
public static T[,] Copy<T>(T[,] bytes)
{
int width = bytes.GetLength(0),
height = bytes.GetLength(1);
var newBytes = new T[width, height];
Array.Copy(bytes, newBytes, bytes.Length);
return newBytes;
}
/// <summary>
/// Cloning of three-dimensional array <br />
/// 克隆一个三维数组
/// </summary>
public static T[,,] Copy<T>(T[,,] bytes)
{
int x = bytes.GetLength(0),
y = bytes.GetLength(1),
z = bytes.GetLength(2);
var newBytes = new T[x, y, z];
Array.Copy(bytes, newBytes, bytes.Length);
return newBytes;
}
/// <summary>
/// Cloning of four-dimensional array <br />
/// 克隆一个四维数组
/// </summary>
public static T[,,,] Copy<T>(T[,,,] bytes)
{
int x = bytes.GetLength(0),
y = bytes.GetLength(1),
z = bytes.GetLength(2),
m = bytes.GetLength(3);
var newBytes = new T[x, y, z, m];
Array.Copy(bytes, newBytes, bytes.Length);
return newBytes;
}
/// <summary>
/// Cloning of five-dimensional array <br />
/// 克隆一个五维数组
/// </summary>
public static T[,,,,] Copy<T>(T[,,,,] bytes)
{
int x = bytes.GetLength(0),
y = bytes.GetLength(1),
z = bytes.GetLength(2),
m = bytes.GetLength(3),
n = bytes.GetLength(4);
var newBytes = new T[x, y, z, m, n];
Array.Copy(bytes, newBytes, bytes.Length);
return newBytes;
}
/// <summary>
/// Cloning of six-dimensional array <br />
/// 克隆一个六维数组
/// </summary>
public static T[,,,,,] Copy<T>(T[,,,,,] bytes)
{
int x = bytes.GetLength(0),
y = bytes.GetLength(1),
z = bytes.GetLength(2),
m = bytes.GetLength(3),
n = bytes.GetLength(4),
o = bytes.GetLength(5);
var newBytes = new T[x, y, z, m, n, o];
Array.Copy(bytes, newBytes, bytes.Length);
return newBytes;
}
/// <summary>
/// Cloning of seven-dimensional array <br />
/// 克隆一个七维数组
/// </summary>
public static T[,,,,,,] Copy<T>(T[,,,,,,] bytes)
{
int x = bytes.GetLength(0),
y = bytes.GetLength(1),
z = bytes.GetLength(2),
m = bytes.GetLength(3),
n = bytes.GetLength(4),
o = bytes.GetLength(5),
p = bytes.GetLength(6);
var newBytes = new T[x, y, z, m, n, o, p];
Array.Copy(bytes, newBytes, bytes.Length);
return newBytes;
}
}
/// <summary>
/// Array extensions <br />
/// 数组扩展
/// </summary>
public static class ArraysExtensions
{
/// <summary>
/// Cloning of a one-dimensional array from an <see cref="T:System.Array" /> starting at the specified source index
/// and pastes them to another <see cref="T:System.Array" /> starting at the specified destination index.
/// The length and the indexes are specified as 64-bit integers. <br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组并将它们粘贴到另一个 <see cref="T:System.Array" /> 从指定的源索引开始 目的地索引。 长度和索引指定为 64 位整数。
/// </summary>
/// <param name="bytes"></param>
/// <param name="numericVal"></param>
/// <param name="options"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T[] Copy<T>(this T[] bytes, int numericVal, ArrayCopyOptions options = ArrayCopyOptions.Length)
{
var arrayLength = options switch
{
ArrayCopyOptions.Length => numericVal,
ArrayCopyOptions.SinceIndex => bytes.Length - numericVal,
_ => numericVal
};
if (arrayLength <= 0)
{
#if NET452
return new T[0];
#else
return Array.Empty<T>();
#endif
}
var array = new T[arrayLength];
switch (options)
{
case ArrayCopyOptions.Length:
Array.Copy(bytes, array, numericVal);
break;
case ArrayCopyOptions.SinceIndex:
Array.Copy(bytes, numericVal, array, 0, arrayLength);
break;
default:
Array.Copy(bytes, array, numericVal);
break;
}
return array;
}
/// <summary>
/// Cloning of a one-dimensional array from an <see cref="T:System.Array" /> starting at the specified source index
/// and pastes them to another <see cref="T:System.Array" /> starting at the specified destination index.
/// The length and the indexes are specified as 64-bit integers. <br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组并将它们粘贴到另一个 <see cref="T:System.Array" /> 从指定的源索引开始 目的地索引。 长度和索引指定为 64 位整数。
/// </summary>
/// <param name="bytes"></param>
/// <param name="numericVal"></param>
/// <param name="options"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T[] Copy<T>(this T[] bytes, long numericVal, ArrayCopyOptions options = ArrayCopyOptions.Length)
{
var arrayLength = options switch
{
ArrayCopyOptions.Length => numericVal,
ArrayCopyOptions.SinceIndex => bytes.Length - numericVal,
_ => numericVal
};
if (arrayLength <= 0)
{
#if NET452
return new T[0];
#else
return Array.Empty<T>();
#endif
}
var array = new T[arrayLength];
switch (options)
{
case ArrayCopyOptions.Length:
Array.Copy(bytes, array, numericVal);
break;
case ArrayCopyOptions.SinceIndex:
Array.Copy(bytes, numericVal, array, 0, arrayLength);
break;
default:
Array.Copy(bytes, array, numericVal);
break;
}
return array;
}
/// <summary>
/// Cloning of a one-dimensional array from an <see cref="T:System.Array" /> starting at the specified source index.
/// Guarantees that all changes are undone if the copy does not succeed completely. <br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组。 如果复制没有完全成功,则保证所有更改都将被撤消。
/// </summary>
/// <param name="bytes"></param>
/// <param name="sourceIndex"></param>
/// <param name="length"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T[] Copy<T>(this T[] bytes, int sourceIndex, int length)
{
var array = (bytes.Length - sourceIndex - length) switch
{
<= 0 => new T[bytes.Length - sourceIndex],
> 0 => new T[length]
};
Array.Copy(bytes, sourceIndex, array, 0, length);
return array;
}
/// <summary>
/// Cloning of a one-dimensional array from an <see cref="T:System.Array" /> starting at the specified source index.
/// Guarantees that all changes are undone if the copy does not succeed completely. <br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组。 如果复制没有完全成功,则保证所有更改都将被撤消。
/// </summary>
/// <param name="bytes"></param>
/// <param name="sourceIndex"></param>
/// <param name="length"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T[] Copy<T>(this T[] bytes, long sourceIndex, long length)
{
var array = (bytes.Length - sourceIndex - length) switch
{
<= 0 => new T[bytes.Length - sourceIndex],
> 0 => new T[length]
};
Array.Copy(bytes, sourceIndex, array, 0, length);
return array;
}
/// <summary>
/// Cloning of a one-dimensional array <br />
/// 克隆一个一维数组
/// </summary>
public static T[] Copy<T>(this T[] bytes)
{
return Arrays.Copy(bytes);
}
/// <summary>
/// Cloning of a two-dimensional array <br />
/// 克隆一个二维数组
/// </summary>
public static T[,] Copy<T>(this T[,] bytes)
{
return Arrays.Copy(bytes);
}
/// <summary>
/// Cloning of three-dimensional array <br />
/// 克隆一个三维数组
/// </summary>
public static T[,,] Copy<T>(this T[,,] bytes)
{
return Arrays.Copy(bytes);
}
/// <summary>
/// Cloning of four-dimensional array <br />
/// 克隆一个四维数组
/// </summary>
public static T[,,,] Copy<T>(this T[,,,] bytes)
{
return Arrays.Copy(bytes);
}
/// <summary>
/// Cloning of five-dimensional array <br />
/// 克隆一个五维数组
/// </summary>
public static T[,,,,] Copy<T>(this T[,,,,] bytes)
{
return Arrays.Copy(bytes);
}
/// <summary>
/// Cloning of six-dimensional array <br />
/// 克隆一个六维数组
/// </summary>
public static T[,,,,,] Copy<T>(this T[,,,,,] bytes)
{
return Arrays.Copy(bytes);
}
/// <summary>
/// Cloning of seven-dimensional array <br />
/// 克隆一个七维数组
/// </summary>
public static T[,,,,,,] Copy<T>(this T[,,,,,,] bytes)
{
return Arrays.Copy(bytes);
}
}
/// <summary>
/// Array shortcut extensions <br />
/// 数组捷径扩展
/// </summary>
public static partial class ArraysShortcutExtensions
{
/// <summary>
/// Copies a range of elements from an <see cref="T:System.Array" /> starting at the specified source index
/// and pastes them to another <see cref="T:System.Array" /> starting at the specified destination index.
/// The length and the indexes are specified as 64-bit integers.<br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组并将它们粘贴到另一个 <see cref="T:System.Array" /> 从指定的源索引开始 目的地索引。 长度和索引指定为 64 位整数。
/// </summary>
/// <param name="sourceArray"></param>
/// <param name="destinationArray"></param>
/// <param name="length"></param>
public static void Copy(this Array sourceArray, Array destinationArray, int length)
{
Array.Copy(sourceArray, destinationArray, length);
}
/// <summary>
/// Copies a range of elements from an <see cref="T:System.Array" /> starting at the specified source index
/// and pastes them to another <see cref="T:System.Array" /> starting at the specified destination index.
/// The length and the indexes are specified as 64-bit integers.<br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组并将它们粘贴到另一个 <see cref="T:System.Array" /> 从指定的源索引开始 目的地索引。 长度和索引指定为 64 位整数。
/// </summary>
/// <param name="sourceArray"></param>
/// <param name="sourceIndex"></param>
/// <param name="destinationArray"></param>
/// <param name="destinationIndex"></param>
/// <param name="length"></param>
public static void Copy(this Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length);
}
/// <summary>
/// Copies a range of elements from an <see cref="T:System.Array" /> starting at the specified source index
/// and pastes them to another <see cref="T:System.Array" /> starting at the specified destination index.
/// The length and the indexes are specified as 64-bit integers.<br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组并将它们粘贴到另一个 <see cref="T:System.Array" /> 从指定的源索引开始 目的地索引。 长度和索引指定为 64 位整数。
/// </summary>
/// <param name="sourceArray"></param>
/// <param name="destinationArray"></param>
/// <param name="length"></param>
public static void Copy(this Array sourceArray, Array destinationArray, long length)
{
Array.Copy(sourceArray, destinationArray, length);
}
/// <summary>
/// Copies a range of elements from an <see cref="T:System.Array" /> starting at the specified source index
/// and pastes them to another <see cref="T:System.Array" /> starting at the specified destination index.
/// The length and the indexes are specified as 64-bit integers.<br />
/// 从指定的源索引开始从 <see cref="T:System.Array" /> 克隆一维数组并将它们粘贴到另一个 <see cref="T:System.Array" /> 从指定的源索引开始 目的地索引。 长度和索引指定为 64 位整数。
/// </summary>
/// <param name="sourceArray"></param>
/// <param name="sourceIndex"></param>
/// <param name="destinationArray"></param>
/// <param name="destinationIndex"></param>
/// <param name="length"></param>
public static void Copy(this Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length)
{
Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length);
}
/// <summary>
/// Copies a range of elements from an <see cref="T:System.Array" /> starting at the specified source index
/// and pastes them to another <see cref="T:System.Array" /> starting at the specified destination index.
/// Guarantees that all changes are undone if the copy does not succeed completely. <br />
/// 从指定源索引开始的 <see cref="T:System.Array" /> 复制一系列元素,并将它们粘贴到另一个 <see cref="T:System.Array" /> 从指定目标索引开始 . 如果复制没有完全成功,则保证所有更改都将被撤消。
/// </summary>
/// <param name="sourceArray"></param>
/// <param name="sourceIndex"></param>
/// <param name="destinationArray"></param>
/// <param name="destinationIndex"></param>
/// <param name="length"></param>
public static void ConstrainedCopy(this Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
Array.ConstrainedCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length);
}
/// <summary>
/// Copies a specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset. <br />
/// 将指定数量的字节从以特定偏移量开始的源数组复制到以特定偏移量开始的目标数组。
/// </summary>
/// <param name="sourceArray"></param>
/// <param name="sourceOffset"></param>
/// <param name="destinationArray"></param>
/// <param name="dstOffset"></param>
/// <param name="count"></param>
public static void BlockCopy(this Array sourceArray, int sourceOffset, Array destinationArray, int dstOffset, int count)
{
Buffer.BlockCopy(sourceArray, sourceOffset, destinationArray, dstOffset, count);
}
} | 33.936652 | 157 | 0.585733 | [
"Apache-2.0"
] | cosmos-loops/Cosmos.Standard | src/Cosmos.Extensions.Collections/Cosmos/Collections/Arrays.Copy.cs | 16,286 | C# |
using System;
public class EventCode
{
public const byte AppStats = 0xe2;
[Obsolete("TCP routing was removed after becoming obsolete.")]
public const byte AzureNodeInfo = 210;
public const byte GameList = 230;
public const byte GameListUpdate = 0xe5;
public const byte Join = 0xff;
public const byte Leave = 0xfe;
public const byte Match = 0xe3;
public const byte PropertiesChanged = 0xfd;
public const byte QueueState = 0xe4;
[Obsolete("Use PropertiesChanged now.")]
public const byte SetProperties = 0xfd;
public const byte TypedLobbyStats = 0xe0;
}
| 31.3 | 67 | 0.686901 | [
"MIT"
] | Jagerente/RCFixed | Source/EventCode.cs | 628 | C# |
using Microsoft.AspNetCore.Routing;
namespace Microsoft.AspNetCore.Modules
{
public interface IModularTenantRouteBuilder
{
IRouteBuilder Build();
void Configure(IRouteBuilder builder);
}
}
| 18.333333 | 47 | 0.718182 | [
"BSD-3-Clause"
] | ChipSoftTech/CST-CMS | src/OrchardCore/Microsoft.AspNetCore.Modules.Abstractions/IModularTenantRouteBuilder.cs | 222 | C# |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.Globalization;
namespace DiscUtils.HfsPlus
{
internal struct CatalogNodeId
{
public static readonly CatalogNodeId RootParentId = new CatalogNodeId(1);
public static readonly CatalogNodeId RootFolderId = new CatalogNodeId(2);
public static readonly CatalogNodeId ExtentsFileId = new CatalogNodeId(3);
public static readonly CatalogNodeId CatalogFileId = new CatalogNodeId(4);
public static readonly CatalogNodeId BadBlockFileId = new CatalogNodeId(5);
public static readonly CatalogNodeId AllocationFileId = new CatalogNodeId(6);
public static readonly CatalogNodeId StartupFileId = new CatalogNodeId(7);
public static readonly CatalogNodeId AttributesFileId = new CatalogNodeId(8);
public static readonly CatalogNodeId RepairCatalogFileId = new CatalogNodeId(14);
public static readonly CatalogNodeId BogusExtentFileId = new CatalogNodeId(15);
public static readonly CatalogNodeId FirstUserCatalogNodeId = new CatalogNodeId(16);
private readonly uint _id;
public CatalogNodeId(uint id)
{
_id = id;
}
public static implicit operator uint(CatalogNodeId nodeId)
{
return nodeId._id;
}
public static implicit operator CatalogNodeId(uint id)
{
return new CatalogNodeId(id);
}
public override string ToString()
{
return _id.ToString(CultureInfo.InvariantCulture);
}
}
} | 42.190476 | 92 | 0.719338 | [
"MIT"
] | AssafTzurEl/DiscUtils | Library/DiscUtils.HfsPlus/CatalogNodeId.cs | 2,660 | C# |
using BeYourMarket.Core.Helpers;
using BeYourMarket.Core.Plugins;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Compilation;
using System.Web.Hosting;
//Credit to NopCommerce
//http://shazwazza.com/post/Developing-a-plugin-framework-in-ASPNET-with-medium-trust.aspx
[assembly: PreApplicationStartMethod(typeof(PluginManager), "Initialize")]
namespace BeYourMarket.Core.Plugins
{
/// <summary>
/// Sets the application up for the plugin referencing
/// </summary>
public class PluginManager
{
#region Const
private const string InstalledPluginsFilePath = "~/Plugins/installed.json";
private const string PluginsPath = "~/Plugins";
private const string ShadowCopyPath = "~/Plugins/bin";
public const string ManifestJson = "manifest.json";
#endregion
#region Fields
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
private static DirectoryInfo _shadowCopyFolder;
private static bool _clearShadowDirectoryOnStartup;
#endregion
#region Methods
/// <summary>
/// Returns a collection of all referenced plugin assemblies that have been shadow copied
/// </summary>
public static IEnumerable<PluginDescriptor> ReferencedPlugins { get; set; }
/// <summary>
/// Returns a collection of all plugin which are not compatible with the current version
/// </summary>
public static IEnumerable<string> IncompatiblePlugins { get; set; }
/// <summary>
/// Initialize
/// </summary>
public static void Initialize()
{
using (new WriteLockDisposable(Locker))
{
var pluginFolder = new DirectoryInfo(HostingEnvironment.MapPath(PluginsPath));
_shadowCopyFolder = new DirectoryInfo(HostingEnvironment.MapPath(ShadowCopyPath));
var referencedPlugins = new List<PluginDescriptor>();
var incompatiblePlugins = new List<string>();
_clearShadowDirectoryOnStartup = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["ClearPluginsShadowDirectoryOnStartup"]) &&
Convert.ToBoolean(ConfigurationManager.AppSettings["ClearPluginsShadowDirectoryOnStartup"]);
try
{
var installedPluginSystemNames = PluginFileParser.ParseInstalledPluginsFile(GetInstalledPluginsFilePath());
Debug.WriteLine("Creating shadow copy folder and querying for dlls");
//ensure folders are created
Directory.CreateDirectory(pluginFolder.FullName);
Directory.CreateDirectory(_shadowCopyFolder.FullName);
//get list of all files in bin
var binFiles = _shadowCopyFolder.GetFiles("*", SearchOption.AllDirectories);
if (_clearShadowDirectoryOnStartup)
{
//clear out shadow copied plugins
foreach (var f in binFiles)
{
Debug.WriteLine("Deleting " + f.Name);
try
{
File.Delete(f.FullName);
}
catch (Exception exc)
{
Debug.WriteLine("Error deleting file " + f.Name + ". Exception: " + exc);
}
}
}
//load description files
foreach (var dfd in GetDescriptionFilesAndDescriptors(pluginFolder))
{
var descriptionFile = dfd.Key;
var pluginDescriptor = dfd.Value;
//ensure that version of plugin is valid
if (!pluginDescriptor.SupportedVersions.Contains(PlatformVersion.CurrentVersion, StringComparer.InvariantCultureIgnoreCase))
{
incompatiblePlugins.Add(pluginDescriptor.SystemName);
continue;
}
//some validation
if (String.IsNullOrWhiteSpace(pluginDescriptor.SystemName))
throw new Exception(string.Format("A plugin '{0}' has no system name. Try assigning the plugin a unique name and recompiling.", descriptionFile.FullName));
if (referencedPlugins.Contains(pluginDescriptor))
throw new Exception(string.Format("A plugin with '{0}' system name is already defined", pluginDescriptor.SystemName));
//set 'Installed' property
var pluginFound = installedPluginSystemNames.Plugins
.FirstOrDefault(x => x.SystemName.Equals(pluginDescriptor.SystemName, StringComparison.InvariantCultureIgnoreCase));
pluginDescriptor.Installed = pluginFound != null;
pluginDescriptor.Enabled = pluginFound != null ? pluginFound.Enabled : false;
try
{
if (descriptionFile.Directory == null)
throw new Exception(string.Format("Directory cannot be resolved for '{0}' description file", descriptionFile.Name));
//get list of all DLLs in plugins (not in bin!)
var pluginFiles = descriptionFile.Directory.GetFiles("*.dll", SearchOption.AllDirectories)
//just make sure we're not registering shadow copied plugins
.Where(x => !binFiles.Select(q => q.FullName).Contains(x.FullName))
.Where(x => IsPackagePluginFolder(x.Directory))
.ToList();
//other plugin description info
var mainPluginFile = pluginFiles
.FirstOrDefault(x => x.Name.Equals(pluginDescriptor.PluginFileName, StringComparison.InvariantCultureIgnoreCase));
pluginDescriptor.OriginalAssemblyFile = mainPluginFile;
//shadow copy main plugin file
pluginDescriptor.ReferencedAssembly = PerformFileDeploy(mainPluginFile);
//load all other referenced assemblies now
foreach (var plugin in pluginFiles
.Where(x => !x.Name.Equals(mainPluginFile.Name, StringComparison.InvariantCultureIgnoreCase))
.Where(x => !IsAlreadyLoaded(x)))
PerformFileDeploy(plugin);
//init plugin type (only one plugin per assembly is allowed)
foreach (var t in pluginDescriptor.ReferencedAssembly.GetTypes())
if (typeof(IPlugin).IsAssignableFrom(t))
if (!t.IsInterface)
if (t.IsClass && !t.IsAbstract)
{
pluginDescriptor.PluginType = t;
break;
}
referencedPlugins.Add(pluginDescriptor);
}
catch (ReflectionTypeLoadException ex)
{
var msg = string.Empty;
foreach (var e in ex.LoaderExceptions)
msg += e.Message + Environment.NewLine;
var fail = new Exception(msg, ex);
Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
}
catch (Exception ex)
{
var msg = string.Empty;
for (var e = ex; e != null; e = e.InnerException)
msg += e.Message + Environment.NewLine;
var fail = new Exception(msg, ex);
Debug.WriteLine(fail.Message, fail);
throw fail;
}
ReferencedPlugins = referencedPlugins;
IncompatiblePlugins = incompatiblePlugins;
}
}
/// <summary>
/// Mark plugin as installed
/// </summary>
/// <param name="systemName">Plugin system name</param>
public static void MarkPluginAsInstalled(string systemName)
{
if (String.IsNullOrEmpty(systemName))
throw new ArgumentNullException("systemName");
var filePath = HostingEnvironment.MapPath(InstalledPluginsFilePath);
if (!File.Exists(filePath))
using (File.Create(filePath))
{
//we use 'using' to close the file after it's created
}
var pluginInstalled = PluginFileParser.ParseInstalledPluginsFile(GetInstalledPluginsFilePath());
var pluginFound = pluginInstalled.Plugins
.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.InvariantCultureIgnoreCase));
bool alreadyMarkedAsInstalled = pluginFound != null;
if (!alreadyMarkedAsInstalled)
{
pluginInstalled.Plugins.Add(new PluginState()
{
SystemName = systemName,
Enabled = false
});
}
// add
var plugin = ReferencedPlugins.Where(x => x.SystemName.Equals(systemName, StringComparison.InvariantCulture)).FirstOrDefault();
plugin.Installed = true;
plugin.Enabled = false;
PluginFileParser.SaveInstalledPluginsFile(pluginInstalled, filePath);
}
/// <summary>
/// Mark plugin as uninstalled
/// </summary>
/// <param name="systemName">Plugin system name</param>
public static void MarkPluginAsUninstalled(string systemName)
{
if (String.IsNullOrEmpty(systemName))
throw new ArgumentNullException("systemName");
var filePath = HostingEnvironment.MapPath(InstalledPluginsFilePath);
if (!File.Exists(filePath))
using (File.Create(filePath))
{
//we use 'using' to close the file after it's created
}
var pluginInstalled = PluginFileParser.ParseInstalledPluginsFile(GetInstalledPluginsFilePath());
var pluginFound = pluginInstalled.Plugins
.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.InvariantCultureIgnoreCase));
bool alreadyMarkedAsInstalled = pluginFound != null;
if (alreadyMarkedAsInstalled)
pluginInstalled.Plugins.Remove(pluginFound);
// remove
var plugin = ReferencedPlugins.Where(x => x.SystemName.Equals(systemName, StringComparison.InvariantCulture)).FirstOrDefault();
plugin.Installed = false;
plugin.Enabled = false;
PluginFileParser.SaveInstalledPluginsFile(pluginInstalled, filePath);
}
public static void MarkPluginAsEnabled(string systemName, bool enable)
{
if (String.IsNullOrEmpty(systemName))
throw new ArgumentNullException("systemName");
var filePath = HostingEnvironment.MapPath(InstalledPluginsFilePath);
if (!File.Exists(filePath))
using (File.Create(filePath))
{
//we use 'using' to close the file after it's created
}
var pluginInstalled = PluginFileParser.ParseInstalledPluginsFile(GetInstalledPluginsFilePath());
var pluginFound = pluginInstalled.Plugins
.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.InvariantCultureIgnoreCase));
if (pluginFound != null)
pluginFound.Enabled = enable;
// remove
var plugin = ReferencedPlugins.Where(x => x.SystemName.Equals(systemName, StringComparison.InvariantCulture)).FirstOrDefault();
plugin.Enabled = enable;
PluginFileParser.SaveInstalledPluginsFile(pluginInstalled, filePath);
}
/// <summary>
/// Mark plugin as uninstalled
/// </summary>
public static void MarkAllPluginsAsUninstalled()
{
var filePath = HostingEnvironment.MapPath(InstalledPluginsFilePath);
if (File.Exists(filePath))
File.Delete(filePath);
ReferencedPlugins = new List<PluginDescriptor>();
}
#endregion
#region Utilities
/// <summary>
/// Get description files
/// </summary>
/// <param name="pluginFolder">Plugin direcotry info</param>
/// <returns>Original and parsed description files</returns>
private static IEnumerable<KeyValuePair<FileInfo, PluginDescriptor>> GetDescriptionFilesAndDescriptors(DirectoryInfo pluginFolder)
{
if (pluginFolder == null)
throw new ArgumentNullException("pluginFolder");
//create list (<file info, parsed plugin descritor>)
var result = new List<KeyValuePair<FileInfo, PluginDescriptor>>();
//add display order and path to list
foreach (var descriptionFile in pluginFolder.GetFiles(ManifestJson, SearchOption.AllDirectories))
{
if (!IsPackagePluginFolder(descriptionFile.Directory))
continue;
//parse file
var pluginDescriptor = PluginFileParser.ParsePluginDescriptionFile(descriptionFile.FullName);
//populate list
result.Add(new KeyValuePair<FileInfo, PluginDescriptor>(descriptionFile, pluginDescriptor));
}
result.Sort((firstPair, nextPair) => firstPair.Value.DisplayOrder.CompareTo(nextPair.Value.DisplayOrder));
return result;
}
/// <summary>
/// Indicates whether assembly file is already loaded
/// </summary>
/// <param name="fileInfo">File info</param>
/// <returns>Result</returns>
private static bool IsAlreadyLoaded(FileInfo fileInfo)
{
//compare full assembly name
//var fileAssemblyName = AssemblyName.GetAssemblyName(fileInfo.FullName);
//foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
//{
// if (a.FullName.Equals(fileAssemblyName.FullName, StringComparison.InvariantCultureIgnoreCase))
// return true;
//}
//return false;
//do not compare the full assembly name, just filename
try
{
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileInfo.FullName);
if (fileNameWithoutExt == null)
throw new Exception(string.Format("Cannot get file extnension for {0}", fileInfo.Name));
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
string assemblyName = a.FullName.Split(new[] { ',' }).FirstOrDefault();
if (fileNameWithoutExt.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
}
catch (Exception exc)
{
Debug.WriteLine("Cannot validate whether an assembly is already loaded. " + exc);
}
return false;
}
/// <summary>
/// Perform file deply
/// </summary>
/// <param name="plug">Plugin file info</param>
/// <returns>Assembly</returns>
private static Assembly PerformFileDeploy(FileInfo plug)
{
if (plug.Directory.Parent == null)
throw new InvalidOperationException("The plugin directory for the " + plug.Name +
" file exists in a folder outside of the allowed nopCommerce folder heirarchy");
FileInfo shadowCopiedPlug;
if (CommonHelper.GetTrustLevel() != AspNetHostingPermissionLevel.Unrestricted)
{
//all plugins will need to be copied to ~/Plugins/bin/
//this is aboslutely required because all of this relies on probingPaths being set statically in the web.config
//were running in med trust, so copy to custom bin folder
var shadowCopyPlugFolder = Directory.CreateDirectory(_shadowCopyFolder.FullName);
shadowCopiedPlug = InitializeMediumTrust(plug, shadowCopyPlugFolder);
}
else
{
var directory = AppDomain.CurrentDomain.DynamicDirectory;
Debug.WriteLine(plug.FullName + " to " + directory);
//were running in full trust so copy to standard dynamic folder
shadowCopiedPlug = InitializeFullTrust(plug, new DirectoryInfo(directory));
}
//we can now register the plugin definition
var shadowCopiedAssembly = Assembly.Load(AssemblyName.GetAssemblyName(shadowCopiedPlug.FullName));
//add the reference to the build manager
Debug.WriteLine("Adding to BuildManager: '{0}'", shadowCopiedAssembly.FullName);
BuildManager.AddReferencedAssembly(shadowCopiedAssembly);
return shadowCopiedAssembly;
}
/// <summary>
/// Used to initialize plugins when running in Full Trust
/// </summary>
/// <param name="plug"></param>
/// <param name="shadowCopyPlugFolder"></param>
/// <returns></returns>
private static FileInfo InitializeFullTrust(FileInfo plug, DirectoryInfo shadowCopyPlugFolder)
{
var shadowCopiedPlug = new FileInfo(Path.Combine(shadowCopyPlugFolder.FullName, plug.Name));
try
{
File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
}
catch (IOException)
{
Debug.WriteLine(shadowCopiedPlug.FullName + " is locked, attempting to rename");
//this occurs when the files are locked,
//for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them
//which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy
try
{
var oldFile = shadowCopiedPlug.FullName + Guid.NewGuid().ToString("N") + ".old";
File.Move(shadowCopiedPlug.FullName, oldFile);
}
catch (IOException exc)
{
throw new IOException(shadowCopiedPlug.FullName + " rename failed, cannot initialize plugin", exc);
}
//ok, we've made it this far, now retry the shadow copy
File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
}
return shadowCopiedPlug;
}
/// <summary>
/// Used to initialize plugins when running in Medium Trust
/// </summary>
/// <param name="plug"></param>
/// <param name="shadowCopyPlugFolder"></param>
/// <returns></returns>
private static FileInfo InitializeMediumTrust(FileInfo plug, DirectoryInfo shadowCopyPlugFolder)
{
var shouldCopy = true;
var shadowCopiedPlug = new FileInfo(Path.Combine(shadowCopyPlugFolder.FullName, plug.Name));
//check if a shadow copied file already exists and if it does, check if it's updated, if not don't copy
if (shadowCopiedPlug.Exists)
{
//it's better to use LastWriteTimeUTC, but not all file systems have this property
//maybe it is better to compare file hash?
var areFilesIdentical = shadowCopiedPlug.CreationTimeUtc.Ticks >= plug.CreationTimeUtc.Ticks;
if (areFilesIdentical)
{
Debug.WriteLine("Not copying; files appear identical: '{0}'", shadowCopiedPlug.Name);
shouldCopy = false;
}
else
{
//delete an existing file
//More info: http://www.nopcommerce.com/boards/t/11511/access-error-nopplugindiscountrulesbillingcountrydll.aspx?p=4#60838
Debug.WriteLine("New plugin found; Deleting the old file: '{0}'", shadowCopiedPlug.Name);
File.Delete(shadowCopiedPlug.FullName);
}
}
if (shouldCopy)
{
try
{
File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
}
catch (IOException)
{
Debug.WriteLine(shadowCopiedPlug.FullName + " is locked, attempting to rename");
//this occurs when the files are locked,
//for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them
//which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy
try
{
var oldFile = shadowCopiedPlug.FullName + Guid.NewGuid().ToString("N") + ".old";
File.Move(shadowCopiedPlug.FullName, oldFile);
}
catch (IOException exc)
{
throw new IOException(shadowCopiedPlug.FullName + " rename failed, cannot initialize plugin", exc);
}
//ok, we've made it this far, now retry the shadow copy
File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
}
}
return shadowCopiedPlug;
}
/// <summary>
/// Determines if the folder is a bin plugin folder for a package
/// </summary>
/// <param name="folder"></param>
/// <returns></returns>
private static bool IsPackagePluginFolder(DirectoryInfo folder)
{
if (folder == null) return false;
if (folder.Parent == null) return false;
if (!folder.Parent.Name.Equals("Plugins", StringComparison.InvariantCultureIgnoreCase)) return false;
return true;
}
/// <summary>
/// Gets the full path of InstalledPlugins.txt file
/// </summary>
/// <returns></returns>
private static string GetInstalledPluginsFilePath()
{
var filePath = HostingEnvironment.MapPath(InstalledPluginsFilePath);
return filePath;
}
#endregion
}
}
| 44.451493 | 183 | 0.559851 | [
"MIT"
] | DuDuu-Group/photos | src/BeYourMarket.Core/Plugins/PluginManager.cs | 23,828 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
// [START compute_v1_generated_BackendBuckets_Patch_sync_flattened]
using Google.Cloud.Compute.V1;
using lro = Google.LongRunning;
public sealed partial class GeneratedBackendBucketsClientSnippets
{
/// <summary>Snippet for Patch</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void Patch()
{
// Create client
BackendBucketsClient backendBucketsClient = BackendBucketsClient.Create();
// Initialize request argument(s)
string project = "";
string backendBucket = "";
BackendBucket backendBucketResource = new BackendBucket();
// Make the request
lro::Operation<Operation, Operation> response = backendBucketsClient.Patch(project, backendBucket, backendBucketResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = backendBucketsClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
}
}
// [END compute_v1_generated_BackendBuckets_Patch_sync_flattened]
}
| 43.566667 | 134 | 0.677888 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/BackendBucketsClient.PatchSnippet.g.cs | 2,614 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using SSRD.IdentityUI.Core.Interfaces.Services;
using SSRD.IdentityUI.Core.Models.Result;
namespace SSRD.IdentityUI.Admin.Areas.IdentityAdmin.Views.Shared.Components.imHeader
{
public class imHeaderViewComponent : ViewComponent
{
public imHeaderViewComponent()
{
}
public IViewComponentResult Invoke()
{
return View();
}
}
}
| 22.4 | 84 | 0.708929 | [
"MIT"
] | faizu-619/IdentityUI | src/IdentityUI.Admin/Areas/IdentityAdmin/Views/Shared/Components/imHeader/imHeaderViewComponent.cs | 562 | C# |
// ReSharper disable All
namespace OpenTl.Schema
{
using System;
using System.Collections;
using System.Text;
using OpenTl.Schema;
using OpenTl.Schema.Serialization.Attributes;
[Serialize(0x57e2f66c)]
public sealed class TInputMessagesFilterEmpty : IMessagesFilter, IEmpty
{
}
}
| 16.333333 | 72 | 0.772109 | [
"MIT"
] | zzz8415/OpenTl.Schema | src/OpenTl.Schema/_generated/_Entities/MessagesFilter/TInputMessagesFilterEmpty.cs | 296 | 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.Devices.V20200801
{
/// <summary>
/// The X509 Certificate.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:devices/v20200801:Certificate")]
public partial class Certificate : Pulumi.CustomResource
{
/// <summary>
/// The entity tag.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// The name of the certificate.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The description of an X509 CA Certificate.
/// </summary>
[Output("properties")]
public Output<Outputs.CertificatePropertiesResponse> Properties { get; private set; } = null!;
/// <summary>
/// The resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Certificate resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Certificate(string name, CertificateArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:devices/v20200801:Certificate", name, args ?? new CertificateArgs(), MakeResourceOptions(options, ""))
{
}
private Certificate(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:devices/v20200801:Certificate", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:devices:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/latest:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20170701:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20180122:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20180401:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20181201preview:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20190322:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20190322preview:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20190701preview:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20191104:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200301:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200401:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200615:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200710preview:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200831:Certificate"},
new Pulumi.Alias { Type = "azure-nextgen:devices/v20200831preview:Certificate"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Certificate resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Certificate Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Certificate(name, id, options);
}
}
public sealed class CertificateArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the certificate
/// </summary>
[Input("certificateName")]
public Input<string>? CertificateName { get; set; }
/// <summary>
/// The description of an X509 CA Certificate.
/// </summary>
[Input("properties")]
public Input<Inputs.CertificatePropertiesArgs>? Properties { get; set; }
/// <summary>
/// The name of the resource group that contains the IoT hub.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the IoT hub.
/// </summary>
[Input("resourceName", required: true)]
public Input<string> ResourceName { get; set; } = null!;
public CertificateArgs()
{
}
}
}
| 43.962963 | 136 | 0.599495 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Devices/V20200801/Certificate.cs | 5,935 | 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("RetryOperationHelper")]
[assembly: AssemblyDescription("RetryOperationHelper")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RetryOperationHelper")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e2f24eb2-b926-41e2-9c1d-3565020222f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.72973 | 84 | 0.75157 | [
"MIT"
] | ConnectionMaster/RetryOperationHelper | RetryOperationHelper/Properties/AssemblyInfo.cs | 1,436 | C# |
// Copyright 2020 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!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V5.Resources
{
/// <summary>Resource name for the <c>ManagedPlacementView</c> resource.</summary>
public sealed partial class ManagedPlacementViewName : gax::IResourceName, sys::IEquatable<ManagedPlacementViewName>
{
/// <summary>The possible contents of <see cref="ManagedPlacementViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c>.
/// </summary>
CustomerManagedPlacementView = 1,
}
private static gax::PathTemplate s_customerManagedPlacementView = new gax::PathTemplate("customers/{customer}/managedPlacementViews/{managed_placement_view}");
/// <summary>Creates a <see cref="ManagedPlacementViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ManagedPlacementViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ManagedPlacementViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ManagedPlacementViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ManagedPlacementViewName"/> with the pattern
/// <c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managedPlacementViewId">
/// The <c>ManagedPlacementView</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ManagedPlacementViewName"/> constructed from the provided ids.
/// </returns>
public static ManagedPlacementViewName FromCustomerManagedPlacementView(string customerId, string managedPlacementViewId) =>
new ManagedPlacementViewName(ResourceNameType.CustomerManagedPlacementView, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), managedPlacementViewId: gax::GaxPreconditions.CheckNotNullOrEmpty(managedPlacementViewId, nameof(managedPlacementViewId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managedPlacementViewId">
/// The <c>ManagedPlacementView</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c>.
/// </returns>
public static string Format(string customerId, string managedPlacementViewId) =>
FormatCustomerManagedPlacementView(customerId, managedPlacementViewId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managedPlacementViewId">
/// The <c>ManagedPlacementView</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c>.
/// </returns>
public static string FormatCustomerManagedPlacementView(string customerId, string managedPlacementViewId) =>
s_customerManagedPlacementView.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(managedPlacementViewId, nameof(managedPlacementViewId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ManagedPlacementViewName"/> if successful.</returns>
public static ManagedPlacementViewName Parse(string managedPlacementViewName) =>
Parse(managedPlacementViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ManagedPlacementViewName"/> if successful.</returns>
public static ManagedPlacementViewName Parse(string managedPlacementViewName, bool allowUnparsed) =>
TryParse(managedPlacementViewName, allowUnparsed, out ManagedPlacementViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ManagedPlacementViewName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string managedPlacementViewName, out ManagedPlacementViewName result) =>
TryParse(managedPlacementViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ManagedPlacementViewName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string managedPlacementViewName, bool allowUnparsed, out ManagedPlacementViewName result)
{
gax::GaxPreconditions.CheckNotNull(managedPlacementViewName, nameof(managedPlacementViewName));
gax::TemplatedResourceName resourceName;
if (s_customerManagedPlacementView.TryParseName(managedPlacementViewName, out resourceName))
{
result = FromCustomerManagedPlacementView(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(managedPlacementViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ManagedPlacementViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string managedPlacementViewId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
ManagedPlacementViewId = managedPlacementViewId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ManagedPlacementViewName"/> class from the component parts of
/// pattern <c>customers/{customer}/managedPlacementViews/{managed_placement_view}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managedPlacementViewId">
/// The <c>ManagedPlacementView</c> ID. Must not be <c>null</c> or empty.
/// </param>
public ManagedPlacementViewName(string customerId, string managedPlacementViewId) : this(ResourceNameType.CustomerManagedPlacementView, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), managedPlacementViewId: gax::GaxPreconditions.CheckNotNullOrEmpty(managedPlacementViewId, nameof(managedPlacementViewId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>ManagedPlacementView</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string ManagedPlacementViewId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerManagedPlacementView: return s_customerManagedPlacementView.Expand(CustomerId, ManagedPlacementViewId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ManagedPlacementViewName);
/// <inheritdoc/>
public bool Equals(ManagedPlacementViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ManagedPlacementViewName a, ManagedPlacementViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ManagedPlacementViewName a, ManagedPlacementViewName b) => !(a == b);
}
public partial class ManagedPlacementView
{
/// <summary>
/// <see cref="ManagedPlacementViewName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal ManagedPlacementViewName ResourceNameAsManagedPlacementViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ManagedPlacementViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| 54.353571 | 353 | 0.65208 | [
"Apache-2.0"
] | PierrickVoulet/google-ads-dotnet | src/V5/Resources/ManagedPlacementViewResourceNames.g.cs | 15,219 | C# |
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using static Unity.Mathematics.math;
[UpdateBefore(typeof(SpawnSystem))]
public class StresstestSystem : JobComponentSystem
{
private Settings settings;
[BurstCompile]
struct StresstestSystemJob : IJobForEach<SpawnScheduler>
{
public void Execute(ref SpawnScheduler sc)
{
sc.SpawnsOrdered = 5;
sc.TimeLeftToSpawn = 0;
}
}
protected override void OnCreate()
{
base.OnCreate();
if (!GameManager.Instance.IsSettingsLoaded)
{
GameManager.Instance.OnSettingsLoaded += OnSettingsLoaded;
Enabled = false;
}
else
{
InitializeSystem();
}
}
private void InitializeSystem()
{
settings = GameManager.Instance.LoadedSettings;
Enabled = true;
}
private void OnSettingsLoaded(Settings obj)
{
InitializeSystem();
}
protected override JobHandle OnUpdate(JobHandle inputDependencies)
{
if (UnityEngine.Input.GetKey(UnityEngine.KeyCode.F9))
{
settings.UnitSpawnTime = 0.01f;
settings.UnitCost = 0;
var job = new StresstestSystemJob();
var handle = job.Schedule(this, inputDependencies);
handle.Complete();
return inputDependencies;
}
return inputDependencies;
}
} | 22.130435 | 70 | 0.614276 | [
"MIT"
] | maqqr/fgj2020 | SuperMouseRTS/Assets/SuperMouseRTS/Scripts/StresstestSystem.cs | 1,529 | C# |
using De.Osthus.Ambeth.Threading;
namespace De.Osthus.Ambeth.Security
{
public interface ISecurityContextHolder
{
ISecurityContext Context { get; }
ISecurityContext GetCreateContext();
void ClearContext();
R SetScopedAuthentication<R>(IAuthentication authentication, IResultingBackgroundWorkerDelegate<R> runnableScope);
}
} | 24.066667 | 119 | 0.753463 | [
"Apache-2.0"
] | Dennis-Koch/ambeth | ambeth/Ambeth.Security/ambeth/security/ISecurityContextHolder.cs | 361 | C# |
public enum Tension
{
PEACEFUL,
LOW,
MEDIUM,
DANGER,
THREAT,
NONE
}; | 10.222222 | 19 | 0.543478 | [
"MIT"
] | RoperoIvan/NarrativeMechanicsTFG | SubmarinePrototype/Assets/Scripts/Classes/Tension.cs | 92 | C# |
namespace JadeFramework.Core.Consul
{
public class ServiceDiscoveryOptions
{
public ServiceOptions Service { get; set; }
public string UserServiceName { get; set; }
public ConsulOptions Consul { get; set; }
}
}
| 22.636364 | 51 | 0.654618 | [
"Apache-2.0"
] | wangmaosheng/JadeFramework | JadeFramework.Core/Consul/ServiceDiscoveryOptions.cs | 251 | C# |
using System;
using System.Collections.Generic;
namespace Search8.Models
{
/// <summary>
/// Directory entries for use in LINQ queries.
/// </summary>
public class DirEntries : List<DirectoryEntry>
{
public DirEntries()
{
}
}
/// <summary>
/// Directory entry for use in LINQ queries.
/// </summary>
public class DirectoryEntry
{
public string StdHlq { get; set; }
public string StdDir { get; set; }
public string StdFile { get; set; }
public long StdSize { get; set; }
public DateTime StdDate { get; set; }
public string StdType { get; set; }
public string CtlComparison { get; set; }
public DirectoryEntry()
{
}
}
} | 23.393939 | 50 | 0.566062 | [
"Apache-2.0"
] | mcskik/Utilities | Search8/Search8/Models/DirectoryEntry.cs | 772 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
*
*
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace JDCloudSDK.Vpc.Model
{
/// <summary>
/// modifyRouteTableSpec
/// </summary>
public class ModifyRouteTableSpec
{
///<summary>
/// 路由表的名字。名称取值范围:1-32个中文、英文大小写的字母、数字和下划线分隔符
///</summary>
public string RouteTableName{ get; set; }
///<summary>
/// 路由表的描述,取值范围:0-256个UTF-8编码下的全部字符
///</summary>
public string Description{ get; set; }
}
}
| 24.18 | 76 | 0.665012 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Vpc/Model/ModifyRouteTableSpec.cs | 1,323 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Green.Transform;
using Aliyun.Acs.Green.Transform.V20180509;
namespace Aliyun.Acs.Green.Model.V20180509
{
public class AddVideoDnaGroupRequest : RoaAcsRequest<AddVideoDnaGroupResponse>
{
public AddVideoDnaGroupRequest()
: base("Green", "2018-05-09", "AddVideoDnaGroup", "green", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
UriPattern = "/green/video/dna/group/add";
Method = MethodType.POST;
}
private string clientInfo;
public string ClientInfo
{
get
{
return clientInfo;
}
set
{
clientInfo = value;
DictionaryUtil.Add(QueryParameters, "ClientInfo", value);
}
}
public override AddVideoDnaGroupResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return AddVideoDnaGroupResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 34.261538 | 134 | 0.701392 | [
"Apache-2.0"
] | bitType/aliyun-openapi-net-sdk | aliyun-net-sdk-green/Green/Model/V20180509/AddVideoDnaGroupRequest.cs | 2,227 | C# |
using System;
using System.Linq;
namespace Take_Two
{
class TakeTwo
{
static void Main(string[] args)
{
var numbers = Console.ReadLine().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse)
.ToList();
numbers = numbers.Where(n => n >= 10 && n <= 20)
.Distinct().Take(2).ToList();
Console.WriteLine(string.Join(" ",numbers));
}
}
}
| 23.1 | 120 | 0.532468 | [
"MIT"
] | mkpetrov/CSharpAdvanced | LINQ/Take Two/TakeTwo.cs | 464 | C# |
using ExtraMetadataLoader.Common;
using ExtraMetadataLoader.Models;
using Playnite.SDK;
using Playnite.SDK.Controls;
using Playnite.SDK.Data;
using Playnite.SDK.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Threading;
namespace ExtraMetadataLoader
{
/// <summary>
/// Interaction logic for VideoPlayerControl.xaml
/// </summary>
public partial class VideoPlayerControl : PluginUserControl, INotifyPropertyChanged
{
private static readonly ILogger logger = LogManager.GetLogger();
private static readonly Regex steamLinkRegex = new Regex(@"^https?:\/\/store\.steampowered\.com\/app\/(\d+)", RegexOptions.Compiled);
public enum ActiveVideoType { Microtrailer, Trailer, None };
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
IPlayniteAPI PlayniteApi; public ExtraMetadataLoaderSettingsViewModel SettingsModel { get; set; }
private bool useMicrovideosSource;
private readonly string pluginDataPath;
private readonly DispatcherTimer updatePlayerTimer;
private ActiveVideoType activeVideoType;
private bool isDragging;
private Uri microVideoPath;
private Uri trailerVideoPath;
private bool multipleSourcesAvailable = false;
private Game currentGame;
private DesktopView activeViewAtCreation;
public DesktopView ActiveViewAtCreation
{
get => activeViewAtCreation;
set
{
activeViewAtCreation = value;
OnPropertyChanged();
}
}
private Uri videoSource;
public Uri VideoSource
{
get => videoSource;
set
{
videoSource = value;
OnPropertyChanged();
}
}
private bool isPlayerMuted = false;
public bool IsPlayerMuted
{
get => isPlayerMuted;
set
{
isPlayerMuted = value;
OnPropertyChanged();
}
}
private double videoPlayerVolume;
public double VideoPlayerVolume
{
get => videoPlayerVolume;
set
{
videoPlayerVolume = value * value;
OnPropertyChanged();
}
}
DispatcherTimer timer;
private string playbackTimeProgress = "00:00";
public string PlaybackTimeProgress
{
get => playbackTimeProgress;
set
{
playbackTimeProgress = value;
OnPropertyChanged();
}
}
private string playbackTimeTotal = "00:00";
public string PlaybackTimeTotal
{
get => playbackTimeTotal;
set
{
playbackTimeTotal = value;
OnPropertyChanged();
}
}
private Visibility controlVisibility = Visibility.Collapsed;
public Visibility ControlVisibility
{
get => controlVisibility;
set
{
controlVisibility = value;
OnPropertyChanged();
}
}
public VideoPlayerControl(IPlayniteAPI PlayniteApi, ExtraMetadataLoaderSettingsViewModel settings, string pluginDataPath)
{
InitializeComponent();
this.pluginDataPath = pluginDataPath;
this.PlayniteApi = PlayniteApi;
SettingsModel = settings;
DataContext = this;
useMicrovideosSource = settings.Settings.UseMicrotrailersDefault;
if (settings.Settings.StartNoSound)
{
IsPlayerMuted = true;
}
var initialVolumeValue = settings.Settings.DefaultVolume / 100;
volumeSlider.Value = initialVolumeValue;
VideoPlayerVolume = initialVolumeValue;
if (PlayniteApi.ApplicationInfo.Mode == ApplicationMode.Desktop)
{
ActiveViewAtCreation = PlayniteApi.MainView.ActiveDesktopView;
}
volumeSlider.ValueChanged += VolumeSlider_ValueChanged;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(250);
timer.Tick += new EventHandler(timer_Tick);
updatePlayerTimer = new DispatcherTimer();
updatePlayerTimer.Interval = TimeSpan.FromMilliseconds(220);
updatePlayerTimer.Tick += new EventHandler(UpdaterPlayerTimer_Tick);
}
private void UpdaterPlayerTimer_Tick(object sender, EventArgs e)
{
updatePlayerTimer.Stop();
if (SettingsModel.Settings.EnableVideoPlayer && currentGame != null)
{
UpdateGameVideoSources();
playingContextChanged();
}
}
private void timer_Tick(object sender, EventArgs e)
{
if (!isDragging)
{
timelineSlider.Value = player.Position.TotalSeconds;
}
PlaybackTimeProgress = player.Position.ToString(@"mm\:ss") ?? "00:00";
playbackProgressBar.Value = player.Position.TotalSeconds;
}
private void VolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
VideoPlayerVolume = e.NewValue;
}
private void timelineSlider_DragStarted(object sender, DragStartedEventArgs e)
{
isDragging = true;
}
private void timelineSlider_DragCompleted(object sender, DragCompletedEventArgs e)
{
isDragging = false;
player.Position = TimeSpan.FromSeconds(timelineSlider.Value);
}
public RelayCommand<object> VideoPlayCommand
{
get => new RelayCommand<object>((a) =>
{
MediaPlay();
}, (a) => !SettingsModel.Settings.IsVideoPlaying && VideoSource != null);
}
void MediaPlay()
{
player.Play();
timer.Start();
SettingsModel.Settings.IsVideoPlaying = true;
}
public RelayCommand<object> VideoPauseCommand
{
get => new RelayCommand<object>((a) =>
{
MediaPause();
}, (a) => SettingsModel.Settings.IsVideoPlaying && VideoSource != null);
}
public void MediaPause()
{
player.Pause();
timer.Stop();
SettingsModel.Settings.IsVideoPlaying = false;
}
public RelayCommand<object> VideoMuteCommand
{
get => new RelayCommand<object>((a) =>
{
MediaMute();
});
}
void MediaMute()
{
IsPlayerMuted = !IsPlayerMuted;
}
public RelayCommand<object> SwitchVideoSourceCommand
{
get => new RelayCommand<object>((a) =>
{
SwitchVideoSource();
}, (a) => multipleSourcesAvailable == true);
}
void SwitchVideoSource()
{
var activeVideoTypeSender = activeVideoType;
var sourceSwitched = false;
ResetPlayerValues();
// Paths need to be revaluated in case videos were deleted since video playing started
UpdateGameVideoSources();
if (activeVideoTypeSender == ActiveVideoType.Trailer && microVideoPath != null)
{
VideoSource = microVideoPath;
activeVideoType = ActiveVideoType.Microtrailer;
sourceSwitched = true;
}
else if (activeVideoTypeSender == ActiveVideoType.Microtrailer && trailerVideoPath != null)
{
VideoSource = trailerVideoPath;
activeVideoType = ActiveVideoType.Trailer;
sourceSwitched = true;
}
if (sourceSwitched)
{
useMicrovideosSource = !useMicrovideosSource;
playingContextChanged();
}
}
private void player_MediaOpened(object sender, EventArgs e)
{
if (player.NaturalDuration.HasTimeSpan)
{
TimeSpan ts = player.NaturalDuration.TimeSpan;
timelineSlider.SmallChange = 0.25;
timelineSlider.LargeChange = Math.Min(10, ts.Seconds / 10);
timelineSlider.Maximum = ts.TotalSeconds;
playbackProgressBar.Maximum = ts.TotalSeconds;
PlaybackTimeTotal = ts.ToString(@"mm\:ss");
}
}
private void player_MediaEnded(object sender, EventArgs e)
{
if (activeVideoType == ActiveVideoType.Trailer && SettingsModel.Settings.RepeatTrailerVideos
|| activeVideoType == ActiveVideoType.Microtrailer)
{
player.Position = new TimeSpan(0, 0, 0);
MediaPlay();
}
else
{
player.Stop();
timer.Stop();
SettingsModel.Settings.IsVideoPlaying = false;
}
}
public void ResetPlayerValues()
{
VideoSource = null;
player.Stop();
SettingsModel.Settings.IsVideoPlaying = false;
timelineSlider.Value = 0;
playbackProgressBar.Value = 0;
PlaybackTimeProgress = "00:00";
PlaybackTimeTotal = "00:00";
activeVideoType = ActiveVideoType.None;
SettingsModel.Settings.IsAnyVideoAvailable = false;
SettingsModel.Settings.IsTrailerAvailable = false;
SettingsModel.Settings.IsMicrotrailerAvailable = false;
microVideoPath = null;
trailerVideoPath = null;
multipleSourcesAvailable = false;
}
public override void GameContextChanged(Game oldContext, Game newContext)
{
//The GameContextChanged method is rised even when the control
//is not in the active view. To prevent unecessary processing we
//can stop processing if the active view is not the same one was
//the one during creation
if (PlayniteApi.ApplicationInfo.Mode == ApplicationMode.Desktop &&
ActiveViewAtCreation != PlayniteApi.MainView.ActiveDesktopView)
{
VideoSource = null;
return;
}
currentGame = null;
if (newContext != null)
{
currentGame = newContext;
}
RefreshPlayer();
}
public void RefreshPlayer()
{
ResetPlayerValues();
ControlVisibility = Visibility.Collapsed;
SettingsModel.Settings.NewContextVideoAvailable = false;
// Used to prevent using processing while quickly changing games
updatePlayerTimer.Stop();
updatePlayerTimer.Start();
}
private void playingContextChanged()
{
if (videoSource == null)
{
SettingsModel.Settings.NewContextVideoAvailable = false;
ControlVisibility = Visibility.Collapsed;
return;
}
SettingsModel.Settings.NewContextVideoAvailable = true;
if (SettingsModel.Settings.AutoPlayVideos)
{
MediaPlay();
}
else
{
SettingsModel.Settings.IsVideoPlaying = false;
}
ControlVisibility = Visibility.Visible;
}
public void UpdateGameVideoSources()
{
if (currentGame == null)
{
return;
}
var game = currentGame;
var videoPath = Path.Combine(PlayniteApi.Paths.ConfigurationPath, "ExtraMetadata", "games", game.Id.ToString(), "VideoTrailer.mp4");
if (File.Exists(videoPath))
{
SettingsModel.Settings.IsAnyVideoAvailable = true;
SettingsModel.Settings.IsTrailerAvailable = true;
trailerVideoPath = new Uri(videoPath);
}
var videoMicroPath = Path.Combine(PlayniteApi.Paths.ConfigurationPath, "ExtraMetadata", "games", game.Id.ToString(), "VideoMicrotrailer.mp4");
if (File.Exists(videoMicroPath))
{
SettingsModel.Settings.IsAnyVideoAvailable = true;
SettingsModel.Settings.IsMicrotrailerAvailable = true;
microVideoPath = new Uri(videoMicroPath);
}
if (SettingsModel.Settings.StreamSteamVideosOnDemand && trailerVideoPath == null)
{
var gameDataPath = Path.Combine(pluginDataPath, $"{game.Id}_SteamAppDetails.json");
var jsonDownloadValid = true;
if (!File.Exists(gameDataPath))
{
string steamId = GetSteamId(game);
if (steamId != null)
{
var url = string.Format(@"https://store.steampowered.com/api/appdetails?appids={0}", steamId);
jsonDownloadValid = HttpDownloader.DownloadFileAsync(url, gameDataPath).GetAwaiter().GetResult();
}
}
if (File.Exists(gameDataPath) && jsonDownloadValid)
{
var jsonString = File.ReadAllText(gameDataPath);
try
{
var parsedData = Serialization.FromJson<Dictionary<string, SteamAppDetails>>(jsonString);
if (parsedData.Keys?.Any() == true)
{
var response = parsedData[parsedData.Keys.First()];
if (response.success == true && response.data != null)
{
if (trailerVideoPath == null)
{
if (SettingsModel.Settings.StreamSteamHighQuality)
{
trailerVideoPath = response.data.Movies?[0].Mp4.Max;
}
else
{
trailerVideoPath = response.data.Movies?[0].Mp4.Q480;
}
SettingsModel.Settings.IsAnyVideoAvailable = true;
SettingsModel.Settings.IsTrailerAvailable = true;
}
}
}
}
catch
{
// According to #169, it seems that for some reason the uri redirects to
// another page and a html source gets downloaded so it needs to be deleted
logger.Error($"Error deserializing steam appdetails json file in {gameDataPath}");
IoHelper.DeleteFile(gameDataPath);
}
}
}
if (trailerVideoPath != null && microVideoPath != null)
{
multipleSourcesAvailable = true;
}
if (useMicrovideosSource)
{
if (microVideoPath != null)
{
VideoSource = microVideoPath;
activeVideoType = ActiveVideoType.Microtrailer;
}
else if (trailerVideoPath != null && SettingsModel.Settings.FallbackVideoSource)
{
VideoSource = trailerVideoPath;
activeVideoType = ActiveVideoType.Trailer;
}
}
else
{
if (trailerVideoPath != null)
{
VideoSource = trailerVideoPath;
activeVideoType = ActiveVideoType.Trailer;
}
else if (microVideoPath != null && SettingsModel.Settings.FallbackVideoSource)
{
VideoSource = microVideoPath;
activeVideoType = ActiveVideoType.Microtrailer;
}
}
}
private string GetSteamId(Game game)
{
if (game.PluginId == Guid.Parse("cb91dfc9-b977-43bf-8e70-55f46e410fab"))
{
return game.GameId;
}
else
{
if (game.Links == null)
{
return null;
}
foreach (Link gameLink in game.Links)
{
var linkMatch = steamLinkRegex.Match(gameLink.Url);
if (linkMatch.Success)
{
return linkMatch.Groups[1].Value;
}
}
return null;
}
}
}
}
| 34.724609 | 154 | 0.531188 | [
"MIT"
] | bburky/PlayniteExtensionsCollection | source/Generic/ExtraMetadataLoader/Controls/VideoPlayerControl.xaml.cs | 17,781 | C# |
using System.Collections.Generic;
namespace Hyperpack.Models.Internal
{
public class Pack
{
public PackProperties Properties;
public Source[] Sources;
public IList<IResolvedMod> LockedContent = new List<IResolvedMod>();
}
} | 23.636364 | 76 | 0.692308 | [
"MIT"
] | CitadelCore/Hyperpack | Models/Internal/Pack.cs | 260 | C# |
using Webpay.Integration.CSharp.Config;
using Webpay.Integration.CSharp.Hosted.Admin.Actions;
using Webpay.Integration.CSharp.Util.Constant;
namespace Webpay.Integration.CSharp.Hosted.Admin
{
public class HostedAdmin
{
public readonly IConfigurationProvider ConfigurationProvider;
public readonly CountryCode CountryCode;
public readonly string MerchantId;
public HostedAdmin(IConfigurationProvider configurationProvider, CountryCode countryCode)
{
ConfigurationProvider = configurationProvider;
MerchantId = configurationProvider.GetMerchantId(PaymentType.HOSTED, countryCode);
CountryCode = countryCode;
}
public HostedActionRequest Annul(Annul annul)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<annul>
<transactionid>{0}</transactionid>
</annul>", annul.TransactionId);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider, "/annul");
}
public HostedActionRequest CancelRecurSubscription(CancelRecurSubscription cancelRecurSubscription)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<cancelrecursubscription>
<subscriptionid>{0}</subscriptionid>
</cancelrecursubscription>", cancelRecurSubscription.SubscriptionId);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider,
"/cancelrecursubscription");
}
public HostedActionRequest Confirm(Confirm confirm)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<confirm>
<transactionid>{0}</transactionid>
<capturedate>{1}</capturedate>
</confirm>", confirm.TransactionId, confirm.CaptureDate.ToString("yyyy-MM-dd"));
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider, "/confirm");
}
public HostedActionRequest Credit(Credit credit)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<credit>
<transactionid>{0}</transactionid>
<amounttocredit>{1}</amounttocredit>
</credit>", credit.TransactionId, credit.AmountToCredit);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider, "/credit");
}
public HostedActionRequest GetPaymentMethods(GetPaymentMethods getPaymentMethods)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<getpaymentmethods>
<merchantid>{0}</merchantid>
</getpaymentmethods>", getPaymentMethods.MerchantId);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider,
"/getpaymentmethods");
}
public HostedActionRequest GetReconciliationReport(GetReconciliationReport getReconciliationReport)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<getreconciliationreport>
<date>{0}</date>
</getreconciliationreport>", getReconciliationReport.Date.ToString("yyyy-MM-dd"));
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider,
"/getreconciliationreport");
}
public HostedActionRequest LowerAmount(LowerAmount lowerAmount)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<loweramount>
<transactionid>{0}</transactionid>
<amounttolower>{1}</amounttolower>
</loweramount>", lowerAmount.TransactionId, lowerAmount.AmountToLower);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider, "/loweramount");
}
public HostedActionRequest LowerAmountConfirm(LowerAmountConfirm lowerAmount)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<loweramountconfirm>
<transactionid>{0}</transactionid>
<amounttolower>{1}</amounttolower>
<capturedate>{2}</capturedate>
</loweramountconfirm>", lowerAmount.TransactionId,
lowerAmount.AmountToLower,
lowerAmount.CaptureDate.ToString("yyyy-MM-dd"));
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider, "/loweramountconfirm");
}
public HostedActionRequest Query(QueryByTransactionId query)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<query>
<transactionid>{0}</transactionid>
</query>", query.TransactionId);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider,
"/querytransactionid");
}
public HostedActionRequest Query(QueryByCustomerRefNo query)
{
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<query>
<customerrefno>{0}</customerrefno>
</query>", query.CustomerRefNo);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider,
"/querycustomerrefno");
}
public HostedActionRequest Recur(Recur recur)
{
var vat = recur.Vat != 0 ? "<vat>" + recur.Vat + "</vat>" : "";
var xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<recur>
<customerrefno>{0}</customerrefno>
<subscriptionid>{1}</subscriptionid>
<currency>{2}</currency>
<amount>{3}</amount>
{4}
</recur >", recur.CustomerRefNo, recur.SubscriptionId, recur.Currency, recur.Amount, vat);
return new HostedActionRequest(xml, CountryCode, MerchantId, ConfigurationProvider, "/recur");
}
}
} | 44.166667 | 119 | 0.599057 | [
"Apache-2.0"
] | sveawebpay/dotnet-integration | Webpay.Integration.CSharp/Webpay.Integration.CSharp/Hosted/Admin/HostedAdmin.cs | 6,360 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Xml.Linq;
namespace NuGet
{
public static class XElementExtensions
{
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We don't care about base types")]
public static string GetOptionalAttributeValue(this XElement element, string localName, string namespaceName = null)
{
XAttribute attr = null;
if (String.IsNullOrEmpty(namespaceName))
{
attr = element.Attribute(localName);
}
else
{
attr = element.Attribute(XName.Get(localName, namespaceName));
}
return attr != null ? attr.Value : null;
}
public static string GetOptionalElementValue(this XContainer element, string localName, string namespaceName = null)
{
XElement child;
if (String.IsNullOrEmpty(namespaceName))
{
child = element.ElementsNoNamespace(localName).FirstOrDefault();
}
else
{
child = element.Element(XName.Get(localName, namespaceName));
}
return child != null ? child.Value : null;
}
public static IEnumerable<XElement> ElementsNoNamespace(this XContainer container, string localName)
{
return container.Elements().Where(e => e.Name.LocalName == localName);
}
public static IEnumerable<XElement> ElementsNoNamespace(this IEnumerable<XContainer> source, string localName)
{
return source.Elements().Where(e => e.Name.LocalName == localName);
}
// REVIEW: We can use a stack if the perf is bad for Except and MergeWith
public static XElement Except(this XElement source, XElement target)
{
if (target == null)
{
return source;
}
var attributesToRemove = from e in source.Attributes()
where AttributeEquals(e, target.Attribute(e.Name))
select e;
// Remove the attributes
foreach (var a in attributesToRemove.ToList())
{
a.Remove();
}
foreach (var sourceChild in source.Elements().ToList())
{
var targetChild = FindElement(target, sourceChild);
if (targetChild != null && !HasConflict(sourceChild, targetChild))
{
Except(sourceChild, targetChild);
bool hasContent = sourceChild.HasAttributes || sourceChild.HasElements;
if (!hasContent)
{
// Remove the element if there is no content
sourceChild.Remove();
targetChild.Remove();
}
}
}
return source;
}
public static XElement MergeWith(this XElement source, XElement target)
{
return MergeWith(source, target, null);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "No reason to create a new type")]
public static XElement MergeWith(this XElement source, XElement target, IDictionary<XName, Action<XElement, XElement>> nodeActions)
{
if (target == null)
{
return source;
}
// Merge the attributes
foreach (var targetAttribute in target.Attributes())
{
var sourceAttribute = source.Attribute(targetAttribute.Name);
if (sourceAttribute == null)
{
source.Add(targetAttribute);
}
}
// Go through the elements to be merged
foreach (var targetChild in target.Elements())
{
var sourceChild = FindElement(source, targetChild);
if (sourceChild != null && !HasConflict(sourceChild, targetChild))
{
// Other wise merge recursively
sourceChild.MergeWith(targetChild, nodeActions);
}
else
{
Action<XElement, XElement> nodeAction;
if (nodeActions != null && nodeActions.TryGetValue(targetChild.Name, out nodeAction))
{
nodeAction(source, targetChild);
}
else
{
// If that element is null then add that node
source.Add(targetChild);
}
}
}
return source;
}
private static XElement FindElement(XElement source, XElement targetChild)
{
// Get all of the elements in the source that match this name
var sourceElements = source.Elements(targetChild.Name).ToList();
// Try to find the best matching element based on attribute names and values
sourceElements.Sort((a, b) => Compare(targetChild, a, b));
return sourceElements.FirstOrDefault();
}
private static int Compare(XElement target, XElement left, XElement right)
{
Debug.Assert(left.Name == right.Name);
// First check how much attribute names and values match
int leftExactMathes = CountMatches(left, target, AttributeEquals);
int rightExactMathes = CountMatches(right, target, AttributeEquals);
if (leftExactMathes == rightExactMathes)
{
// Then check which names match
int leftNameMatches = CountMatches(left, target, (a, b) => a.Name == b.Name);
int rightNameMatches = CountMatches(right, target, (a, b) => a.Name == b.Name);
return rightNameMatches.CompareTo(leftNameMatches);
}
return rightExactMathes.CompareTo(leftExactMathes);
}
private static int CountMatches(XElement left, XElement right, Func<XAttribute, XAttribute, bool> matcher)
{
return (from la in left.Attributes()
from ta in right.Attributes()
where matcher(la, ta)
select la).Count();
}
private static bool HasConflict(XElement source, XElement target)
{
// Get all attributes as name value pairs
var sourceAttr = source.Attributes().ToDictionary(a => a.Name, a => a.Value);
// Loop over all the other attributes and see if there are
foreach (var targetAttr in target.Attributes())
{
string sourceValue;
// if any of the attributes are in the source (names match) but the value doesn't match then we've found a conflict
if (sourceAttr.TryGetValue(targetAttr.Name, out sourceValue) && sourceValue != targetAttr.Value)
{
return true;
}
}
return false;
}
public static void RemoveAttributes(this XElement element, Func<XAttribute, bool> condition)
{
element.Attributes()
.Where(condition)
.ToList()
.Remove();
element.Descendants()
.ToList()
.ForEach(e => RemoveAttributes(e, condition));
}
private static bool AttributeEquals(XAttribute source, XAttribute target)
{
if (source == null && target == null)
{
return true;
}
if (source == null || target == null)
{
return false;
}
return source.Name == target.Name && source.Value == target.Value;
}
}
}
| 37.573394 | 145 | 0.537053 | [
"Apache-2.0"
] | monoman/NugetCracker | Nuget/src/Core/Extensions/XElementExtensions.cs | 8,191 | C# |
/// OSVR-Unity Connection
///
/// http://sensics.com/osvr
///
/// <copyright>
/// Copyright 2015 Sensics, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </copyright>
/// <summary>
/// Author: Greg Aring
/// Email: [email protected]
/// </summary>
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections;
using System;
namespace OSVR
{
namespace Unity
{
//*This class is responsible for creating stereo rendering in a scene, and updating viewing parameters
// throughout a scene's lifecycle.
// The number of viewers, eyes, and surfaces, as well as viewports, projection matrices,and distortion
// paramerters are obtained from OSVR via ClientKit.
//
// DisplayController creates VRViewers and VREyes as children. Although VRViewers and VREyes are siblings
// in the scene hierarchy, conceptually VREyes are indeed children of VRViewers. The reason they are siblings
// in the Unity scene is because GetViewerEyePose(...) returns a pose relative to world space, not head space.
//
// In this implementation, we are assuming that there is exactly one viewer and one surface per eye.
//*/
public class DisplayController : MonoBehaviour
{
public const uint NUM_VIEWERS = 1;
private const int TARGET_FRAME_RATE = 60; //@todo get from OSVR
private ClientKit _clientKit;
private OSVR.ClientKit.DisplayConfig _displayConfig;
private VRViewer[] _viewers;
private uint _viewerCount;
private bool _displayConfigInitialized = false;
private uint _totalDisplayWidth;
private uint _totalSurfaceHeight;
private bool _osvrClientKitError = false;
//variables for controlling use of osvrUnityRenderingPlugin.dll which enables DirectMode
private OsvrRenderManager _renderManager;
private bool _useRenderManager = false; //requires Unity 5.2+ and RenderManager configured osvr server
public bool UseRenderManager { get { return _useRenderManager; } set { _useRenderManager = value; } }
public OSVR.ClientKit.DisplayConfig DisplayConfig
{
get { return _displayConfig; }
set { _displayConfig = value; }
}
public VRViewer[] Viewers { get { return _viewers; } }
public uint ViewerCount { get { return _viewerCount; } }
public OsvrRenderManager RenderManager { get { return _renderManager; } }
[Tooltip("Renders an extra camera to show what the HMD user sees while in Direct Mode. Comes at a framerate cost until this feature becomes part of RenderManager.")]
public bool showDirectModePreview = false; //should the monitor show what the user sees in the HMD?
public uint TotalDisplayWidth
{
get { return _totalDisplayWidth; }
set { _totalDisplayWidth = value; }
}
public uint TotalDisplayHeight
{
get { return _totalSurfaceHeight; }
set { _totalSurfaceHeight = value; }
}
void Start()
{
_clientKit = ClientKit.instance;
if (_clientKit == null)
{
Debug.LogError("[OSVR-Unity] DisplayController requires a ClientKit object in the scene.");
}
SetupApplicationSettings();
}
void SetupApplicationSettings()
{
//Set the framerate and performance settings
Application.targetFrameRate = -1;
Application.runInBackground = true;
QualitySettings.vSyncCount = 0;
QualitySettings.maxQueuedFrames = -1; //limit the number of frames queued up to be rendered, reducing latency
Screen.sleepTimeout = SleepTimeout.NeverSleep; //VR should never timeout the screen:
}
// Setup RenderManager for DirectMode or non-DirectMode rendering.
// Checks to make sure Unity version and Graphics API are supported,
// and that a RenderManager config file is being used.
void SetupRenderManager()
{
//check if we are configured to use RenderManager or not
string renderManagerPath = _clientKit.context.getStringParameter("/renderManagerConfig");
_useRenderManager = !(renderManagerPath == null || renderManagerPath.Equals(""));
if (_useRenderManager)
{
//found a RenderManager config
_renderManager = GameObject.FindObjectOfType<OsvrRenderManager>();
if (_renderManager == null)
{
GameObject renderManagerGameObject = new GameObject("RenderManager");
//add a RenderManager component
_renderManager = renderManagerGameObject.AddComponent<OsvrRenderManager>();
}
//check to make sure Unity version and Graphics API are supported
bool supportsRenderManager = _renderManager.IsRenderManagerSupported();
_useRenderManager = supportsRenderManager;
if (!_useRenderManager)
{
Debug.LogError("[OSVR-Unity] RenderManager config found but RenderManager is not supported.");
Destroy(_renderManager);
}
else
{
// attempt to create a RenderManager in the plugin
int result = _renderManager.InitRenderManager();
if (result != 0)
{
Debug.LogError("[OSVR-Unity] Failed to create RenderManager.");
_useRenderManager = false;
}
}
}
else
{
Debug.Log("[OSVR-Unity] RenderManager config not detected. Using normal Unity rendering path.");
}
}
// Get a DisplayConfig object from the server via ClientKit.
// Setup stereo rendering with DisplayConfig data.
void SetupDisplay()
{
//get the DisplayConfig object from ClientKit
if (_clientKit == null || _clientKit.context == null)
{
if (!_osvrClientKitError)
{
Debug.LogError("[OSVR-Unity] ClientContext is null. Can't setup display.");
_osvrClientKitError = true;
}
return;
}
_displayConfig = _clientKit.context.GetDisplayConfig();
if (_displayConfig == null)
{
return;
}
_displayConfigInitialized = true;
SetupRenderManager();
//get the number of viewers, bail if there isn't exactly one viewer for now
_viewerCount = _displayConfig.GetNumViewers();
if (_viewerCount != 1)
{
Debug.LogError("[OSVR-Unity] " + _viewerCount + " viewers found, but this implementation requires exactly one viewer.");
return;
}
//Set Unity player resolution
SetResolution();
//create scene objects
CreateHeadAndEyes();
//create RenderBuffers in RenderManager
if(UseRenderManager && RenderManager != null)
{
RenderManager.ConstructBuffers();
}
SetRenderParams();
}
//Set RenderManager rendering parameters: near and far clip plane distance and IPD
private void SetRenderParams()
{
if (UseRenderManager && RenderManager != null)
{
RenderManager.SetNearClippingPlaneDistance(Camera.main.nearClipPlane);
RenderManager.SetFarClippingPlaneDistance(Camera.main.farClipPlane);
//could set IPD as well
}
}
//Set Resolution of the Unity game window based on total surface width
private void SetResolution()
{
TotalDisplayWidth = 0; //add up the width of each eye
TotalDisplayHeight = 0; //don't add up heights
int numDisplayInputs = DisplayConfig.GetNumDisplayInputs();
//for each display
for (int i = 0; i < numDisplayInputs; i++)
{
OSVR.ClientKit.DisplayDimensions surfaceDisplayDimensions = DisplayConfig.GetDisplayDimensions((byte)i);
TotalDisplayWidth += (uint)surfaceDisplayDimensions.Width; //add up the width of each eye
TotalDisplayHeight = (uint)surfaceDisplayDimensions.Height; //store the height -- this shouldn't change
}
//Set the resolution. Don't force fullscreen if we have multiple display inputs
//We only need to do this if we aren't using RenderManager, because it adjusts the window size for us
//@todo figure out why this causes problems with direct mode, perhaps overfill factor?
if (numDisplayInputs > 1 && !UseRenderManager)
{
Screen.SetResolution((int)TotalDisplayWidth, (int)TotalDisplayHeight, false);
}
}
// Creates a head and eyes as configured in clientKit
// Viewers and Eyes are siblings, children of DisplayController
// Each eye has one child Surface which has a camera
private void CreateHeadAndEyes()
{
/* ASSUME ONE VIEWER */
// Create VRViewers, only one in this implementation
_viewerCount = (uint)_displayConfig.GetNumViewers();
if (_viewerCount != NUM_VIEWERS)
{
Debug.LogError("[OSVR-Unity] " + _viewerCount + " viewers detected. This implementation supports exactly one viewer.");
return;
}
_viewers = new VRViewer[_viewerCount];
uint viewerIndex = 0;
//Check if there are already VRViewers in the scene.
//If so, create eyes for them.
VRViewer[] viewersInScene = FindObjectsOfType<VRViewer>();
if (viewersInScene != null && viewersInScene.Length > 0)
{
for (viewerIndex = 0; viewerIndex < viewersInScene.Length; viewerIndex++)
{
VRViewer viewer = viewersInScene[viewerIndex];
// get the VRViewer gameobject
GameObject vrViewer = viewer.gameObject;
vrViewer.name = "VRViewer" + viewerIndex; //change its name to VRViewer0
//@todo optionally add components
if (vrViewer.GetComponent<AudioListener>() == null)
{
vrViewer.AddComponent<AudioListener>(); //add an audio listener
}
viewer.DisplayController = this; //pass DisplayController to Viewers
viewer.ViewerIndex = viewerIndex; //set the viewer's index
vrViewer.transform.parent = this.transform; //child of DisplayController
vrViewer.transform.localPosition = Vector3.zero;
_viewers[viewerIndex] = viewer;
if (viewerIndex == 0)
{
vrViewer.tag = "MainCamera"; //set the MainCamera tag for the first Viewer
}
// create Viewer's VREyes
uint eyeCount = (uint)_displayConfig.GetNumEyesForViewer(viewerIndex); //get the number of eyes for this viewer
viewer.CreateEyes(eyeCount);
}
}
// loop through viewers because at some point we could support multiple viewers
// but this implementation currently supports exactly one
for (; viewerIndex < _viewerCount; viewerIndex++)
{
// create a VRViewer
GameObject vrViewer = new GameObject("VRViewer" + viewerIndex);
if (vrViewer.GetComponent<AudioListener>() == null)
{
vrViewer.AddComponent<AudioListener>(); //add an audio listener
}
VRViewer vrViewerComponent = vrViewer.AddComponent<VRViewer>();
vrViewerComponent.DisplayController = this; //pass DisplayController to Viewers
vrViewerComponent.ViewerIndex = viewerIndex; //set the viewer's index
vrViewer.transform.parent = this.transform; //child of DisplayController
vrViewer.transform.localPosition = Vector3.zero;
_viewers[viewerIndex] = vrViewerComponent;
vrViewer.tag = "MainCamera";
// create Viewer's VREyes
uint eyeCount = (uint)_displayConfig.GetNumEyesForViewer(viewerIndex); //get the number of eyes for this viewer
vrViewerComponent.CreateEyes(eyeCount);
}
}
void Update()
{
// sometimes it takes a few frames to get a DisplayConfig from ClientKit
// keep trying until we have initialized
if (!_displayConfigInitialized)
{
SetupDisplay();
}
//Sends queued-up commands in the driver's command buffer to the GPU.
//only accessible in Unity 5.4+ API
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 || UNITY_4_7 || UNITY_4_6)
GL.Flush();
#endif
}
//helper method for updating the client context
public void UpdateClient()
{
_clientKit.context.update();
}
public bool CheckDisplayStartup()
{
return DisplayConfig != null && _displayConfigInitialized && DisplayConfig.CheckDisplayStartup();
}
public void ExitRenderManager()
{
if (UseRenderManager && RenderManager != null)
{
RenderManager.ExitRenderManager();
}
}
}
}
}
| 45.175287 | 177 | 0.549647 | [
"Apache-2.0"
] | OSVR/HDK-Tray-Application | OSVR_SampleScene/Assets/OSVRUnity/src/DisplayController.cs | 15,723 | C# |
using System;
namespace Ultraviolet.Graphics.PackedVector
{
public partial struct NormalizedShort4 : IEquatable<NormalizedShort4>
{
/// <inheritdoc/>
public override Int32 GetHashCode() => HashCode.Combine(X, Y, Z, W);
/// <summary>
/// Compares two objects to determine whether they are equal.
/// </summary>
/// <param name="v1">The first value to compare.</param>
/// <param name="v2">The second value to compare.</param>
/// <returns><see langword="true"/> if the two values are equal; otherwise, <see langword="false"/>.</returns>
public static Boolean operator ==(NormalizedShort4 v1, NormalizedShort4 v2) => v1.Equals(v2);
/// <summary>
/// Compares two objects to determine whether they are unequal.
/// </summary>
/// <param name="v1">The first value to compare.</param>
/// <param name="v2">The second value to compare.</param>
/// <returns><see langword="true"/> if the two values are unequal; otherwise, <see langword="false"/>.</returns>
public static Boolean operator !=(NormalizedShort4 v1, NormalizedShort4 v2) => !v1.Equals(v2);
/// <inheritdoc/>
public override Boolean Equals(Object obj) => (obj is NormalizedShort4 pv) && Equals(pv);
/// <inheritdoc/>
public Boolean Equals(NormalizedShort4 obj) =>
obj.X == this.X &&
obj.Y == this.Y &&
obj.Z == this.Z &&
obj.W == this.W;
}
}
| 41.216216 | 120 | 0.598033 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet/Shared/Graphics/PackedVector/NormalizedShort4.Equality.cs | 1,527 | C# |
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace Frederikskaj2.EmailAgent.Functions.Extensions
{
internal static class StringExtensions
{
private static readonly Regex markdownRegex = new Regex(@"[\\`\*_\{\}\[\]\(\)#\+\-\.!]");
public static string EscapeMarkdown(this string @string) => markdownRegex.Replace(@string, match => $"&#{(int) match.Captures[0].Value[0]};");
public static string EscapeJsonString(this string @string) => JsonConvert.ToString(@string)[1..^1];
}
}
| 35.8 | 150 | 0.679702 | [
"MIT"
] | Frederikskaj2/EmailAgent | Functions/Extensions/StringExtensions.cs | 539 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HurriyetDotNet.Models
{
public class Column : BaseModel
{
public string FullName { get; set; }
public string Description { get; set; }
public List<File> Files { get; set; }
public string WriterId { get; set; }
public string Text { get; set; }
}
}
| 19.590909 | 47 | 0.645012 | [
"MIT"
] | agtokty/HurriyetDotNet | HurriyetDotNet/Models/Column.cs | 433 | C# |
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
namespace WalkingTec.Mvvm.TagHelpers.LayUI.Form
{
[HtmlTargetElement("wt:selector", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.NormalOrSelfClosing)]
public class SelectorTagHelper : BaseFieldTag
{
private new const string REQUIRED_ATTR_NAME = "field,list-vm,text-bind";
/// <summary>
/// EmptyText
/// </summary>
public string EmptyText { get; set; }
/// <summary>
/// 按钮文本
/// </summary>
public string SelectButtonText { get; set; }
/// <summary>
/// 选择按钮宽度,默认50
/// </summary>
public int? SelectButtonWidth { get; set; }
/// <summary>
/// 标题
/// </summary>
public string WindowTitle { get; set; }
/// <summary>
/// 显示
/// </summary>
public bool Display { get; set; }
/// <summary>
/// 宽
/// </summary>
public int? WindowWidth { get; set; }
/// <summary>
/// 高
/// </summary>
public int? WindowHeight { get; set; }
/// <summary>
/// 是否多选
/// 默认根据Field 绑定的值类型进行判断。Array or List 即多选,否则单选
/// </summary>
public bool? MultiSelect { get; set; }
/// <summary>
/// ListVM
/// </summary>
public ModelExpression ListVM { get; set; }
/// <summary>
/// 文本显示字段
/// </summary>
public ModelExpression TextBind { get; set; }
/// <summary>
/// 暂时无用 默认 Id
/// </summary>
public ModelExpression ValBind { get; set; }
/// <summary>
/// 用于指定弹出窗口的搜索条件,多条件逗号分隔,例如Searcher.Con1=a,Searcher.Con2=b
/// </summary>
public string Paras { get; set; }
public string SubmitFunc { get; set; }
/// <summary>
/// 弹出窗口之前运行的js函数
/// </summary>
public string BeforeOnpenDialogFunc { get; set; }
/// <summary>
/// 排除的搜索条件
/// </summary>
private static readonly string[] _excludeParams = new string[]
{
"Page",
"Limit",
"Count",
"PageCount",
"FC",
"DC",
"VMFullName",
"SortInfo",
"TreeMode",
"IsPostBack",
"DC",
"LoginUserInfo"
};
/// <summary>
/// 排除的搜索条件类型,搜索条件数据源可能会存储在Searcher对象中
/// </summary>
private static readonly Type[] _excludeTypes = new Type[]
{
typeof(List<ComboSelectListItem>),
typeof(ComboSelectListItem[]),
typeof(IEnumerable<ComboSelectListItem>)
};
public override void Process(TagHelperContext context, TagHelperOutput output)
{
#region Display Value
var modelType = Field.Metadata.ModelType;
var list = new List<string>();
if (Field.Model != null)
{
// 数组 or 泛型集合
if (modelType.IsArray || (modelType.IsGenericType && typeof(List<>).IsAssignableFrom(modelType.GetGenericTypeDefinition())))
{
foreach (var item in Field.Model as dynamic)
{
list.Add(item.ToString());
}
}
else
{
list.Add(Field.Model.ToString());
}
}
if (ListVM == null || ListVM.Model == null)
throw new Exception("The ListVM of the Selector is null");
var listVM = ListVM.Model as IBasePagedListVM<TopBasePoco, ISearcher>;
var value = new List<string>();
if (context.Items.ContainsKey("model") == true)
{
listVM.CopyContext(context.Items["model"] as BaseVM);
}
if (list.Count > 0)
{
listVM.Ids = list;
listVM.NeedPage = false;
listVM.IsSearched = false;
listVM.ClearEntityList();
listVM.SearcherMode = ListVMSearchModeEnum.Batch;
if (!string.IsNullOrEmpty(Paras))
{
var p = Paras.Split(',');
Regex r = new Regex("(\\s*)\\S*?=\\S*?(\\s*)");
foreach (var item in p)
{
var s = Regex.Split(item, "=");
if (s != null && s.Length == 2)
{
listVM.SetPropertyValue(s[0], s[1]);
}
}
}
var entityList = listVM.GetEntityList().ToList();
foreach (var item in entityList)
{
value.Add(item.GetType().GetProperty(TextBind?.Metadata.PropertyName)?.GetValue(item).ToString());
}
}
#endregion
if (Display)
{
output.TagName = "label";
output.TagMode = TagMode.StartTagAndEndTag;
output.Attributes.Add("class", "layui-form-label");
output.Attributes.Add("style", "text-align:left;padding:9px 0;");
var val = string.Empty;
if (Field.Model != null)
{
if (Field.Model.GetType().IsEnumOrNullableEnum())
{
val = PropertyHelper.GetEnumDisplayName(Field.Model.GetType(), Field.Model.ToString());
}
else
{
val = Field.Model.ToString();
}
}
output.Content.AppendHtml(string.Join(",", value));
base.Process(context, output);
}
else
{
var windowid = Guid.NewGuid().ToString();
if (MultiSelect == null)
{
MultiSelect = false;
var type = Field.Metadata.ModelType;
if (type.IsArray || (type.IsGenericType && typeof(List<>).IsAssignableFrom(type.GetGenericTypeDefinition())))// Array or List
{
MultiSelect = true;
}
}
if (WindowWidth == null)
{
WindowWidth = 800;
}
output.TagName = "input";
output.TagMode = TagMode.StartTagOnly;
output.Attributes.Add("type", "text");
output.Attributes.Add("id", Id + "_Display");
output.Attributes.Add("name", Field.Name + "_Display");
if (listVM.Searcher != null)
{
var searcher = listVM.Searcher;
searcher.CopyContext(listVM);
searcher.DoInit();
}
var content = output.GetChildContentAsync().Result.GetContent().Trim();
#region 移除因 RowTagHelper 生成的外层 div 即 <div class="layui-col-xs6"></div>
var regStart = new Regex(@"^<div\s+class=""layui-col-md[0-9]+"">");
var regEnd = new Regex("</div>$");
content = regStart.Replace(content, string.Empty);
content = regEnd.Replace(content, string.Empty);
#endregion
var reg = new Regex("(name=\")([0-9a-zA-z]{0,}[.]?)(Searcher[.]?[0-9a-zA-z]{0,}\")", RegexOptions.Multiline | RegexOptions.IgnoreCase);
content = reg.Replace(content, "$1$3");
content = content.Replace("<script>", "$$script$$").Replace("</script>", "$$#script$$");
var searchPanelTemplate = $@"<script type=""text/template"" id=""Temp{Id}"">{content}</script>";
output.Attributes.Add("value", string.Join(",", value));
output.Attributes.Add("placeholder", EmptyText ?? Program._localizer["PleaseSelect"]);
output.Attributes.Add("class", "layui-input");
this.Disabled = true;
var vmQualifiedName = ListVM.Metadata.ModelType.AssemblyQualifiedName;
vmQualifiedName = vmQualifiedName.Substring(0, vmQualifiedName.LastIndexOf(", Version="));
var Filter = new Dictionary<string, object>
{
{ "_DONOT_USE_VMNAME", vmQualifiedName },
{ "_DONOT_USE_KFIELD", TextBind?.Metadata.PropertyName },
{ "_DONOT_USE_VFIELD", ValBind == null ? "ID" : ValBind?.Metadata.PropertyName },
{ "_DONOT_USE_FIELD", Field.Name },
{ "_DONOT_USE_MULTI_SEL", MultiSelect },
{ "_DONOT_USE_SEL_ID", Id },
{ "Ids", list }
};
if (!string.IsNullOrEmpty(SubmitFunc))
{
Filter.Add("_DONOT_USE_SUBMIT", SubmitFunc);
}
if (listVM.Searcher != null)
{
var props = listVM.Searcher.GetType().GetProperties();
props = props.Where(x => !_excludeTypes.Contains(x.PropertyType)).ToArray();
foreach (var prop in props)
{
if (!_excludeParams.Contains(prop.Name))
{
Filter.Add($"Searcher.{prop.Name}", prop.GetValue(listVM.Searcher));
}
}
}
if (!string.IsNullOrEmpty(Paras))
{
var p = Paras.Split(',');
Regex r = new Regex("(\\s*)\\S*?=\\S*?(\\s*)");
foreach (var item in p)
{
var s = Regex.Split(item, "=");
if (s != null && s.Length == 2)
{
if (Filter.ContainsKey(s[0]))
{
Filter[s[0]] = s[1];
}
else
{
Filter.Add(s[0], s[1]);
}
}
}
}
var hiddenStr = string.Empty;
var sb = new StringBuilder();
foreach (var item in list)
{
sb.Append($"<input type='hidden' name='{Field.Name}' value='{item.ToString()}' />");
}
hiddenStr = sb.ToString();
output.PreElement.AppendHtml($@"<div id=""{Id}_Container"" style=""position:absolute;right:{SelectButtonWidth?.ToString() ?? "50"}px;left:0px;width:auto"">");
output.PostElement.AppendHtml($@"
{hiddenStr}
</div>
<button class='layui-btn layui-btn-sm layui-btn-warm' type='button' id='{Id}_Select' style='color:white;position:absolute;right:0px'>{SelectButtonText ?? " . . . "}</button>
<hidden id='{Id}' name='{Field.Name}' />
<script>
var {Id}filter = {{}};
$('#{Id}_Select').on('click',function(){{
{(string.IsNullOrEmpty(BeforeOnpenDialogFunc) == true ? "" : "var data={};" + FormatFuncName(BeforeOnpenDialogFunc) + ";")}
var filter = {JsonConvert.SerializeObject(Filter)};
var vals = $('#{Id}_Container input[type=hidden]');
filter.Ids = [];
for(var i=0;i<vals.length;i++){{
filter.Ids.push(vals[i].value);
}};
var ffilter = $.extend(filter, {Id}filter)
ff.OpenDialog2('/_Framework/Selector', '{windowid}', '{WindowTitle ?? Program._localizer["PleaseSelect"]}',{WindowWidth?.ToString() ?? "null"}, {WindowHeight?.ToString() ?? "500"},'#Temp{Id}', ffilter);
}});
</script>
{searchPanelTemplate}
");
base.Process(context, output);
}
}
}
}
| 36.798193 | 204 | 0.473602 | [
"MIT"
] | 17713017177/WTM | src/WalkingTec.Mvvm.TagHelpers.LayUI/Form/SelectorTagHelper.cs | 12,499 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace OnnxObjectDetectionE2EAPP.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}
| 17.833333 | 42 | 0.71028 | [
"MIT"
] | AbhiAgarwal192/machinelearning-samples | samples/csharp/end-to-end-apps/DeepLearning_ObjectDetection_Onnx/OnnxObjectDetectionE2EAPP/Pages/Index.cshtml.cs | 323 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
using MonoGame.GameManager.Controls.InputEvent;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MonoGame.GameManager.Controls.ControlsUI
{
public class ScrollViewerPinchZoom
{
public bool IsPinchActive { get; private set; }
private readonly ScrollViewer scrollViewer;
private float lastScale;
private float nthZoom;
private Vector2 lastZoomCenter;
private Vector2[] startTouchPositions;
private float zoomFactor = 1;
private Vector2 offset = Vector2.Zero;
public ScrollViewerPinchZoom(ScrollViewer scrollViewer)
{
this.scrollViewer = scrollViewer;
scrollViewer.AddOnMultipleTouchpoints(OnMultipleTouchpointsUpdate);
}
private void OnMultipleTouchpointsUpdate(ControlMultipleTouchpointsEventArgs multipleTouchpointsArgs)
{
var touchpoints = multipleTouchpointsArgs.Touchpoints.ToArray().Take(2).ToList();
var isReleased = touchpoints.Any(x => x.State == TouchLocationState.Released);
if (touchpoints.Count < 2 || !IsPinchActive && isReleased)
return;
var touchPositions = GetTouchpointsPositions(touchpoints);
if (!IsPinchActive)
OnPinchStart(touchPositions);
else if (!isReleased)
OnPinchMoved(touchPositions);
else
OnPinchReleased();
}
private void OnPinchStart(Vector2[] touchPositions)
{
IsPinchActive = true;
lastScale = 1;
nthZoom = 0;
startTouchPositions = touchPositions;
offset = -scrollViewer.GetScrollPosition();
zoomFactor = scrollViewer.Zoom.X / GetInitialZoomFactor();
}
private void OnPinchMoved(Vector2[] touchpositions)
{
var newScale = CalculateScale(startTouchPositions, touchpositions);
// a relative scale factor is used
var touchCenter = GetTouchCenter(touchpositions);
var scale = newScale / lastScale;
lastScale = newScale;
// the first touch events are thrown away since they are not precise
nthZoom += 1;
if (nthZoom > 3)
{
Scale(scale, touchCenter);
Drag(touchCenter, lastZoomCenter);
}
lastZoomCenter = touchCenter;
var zoomFactor = GetInitialZoomFactor() * this.zoomFactor;
scrollViewer.SetZoom(new Vector2(zoomFactor));
scrollViewer.MoveContainer(-offset - scrollViewer.ScrollPosition);
}
private void OnPinchReleased()
{
SetPinchAsInactive();
scrollViewer.HideBars();
}
public void SetPinchAsInactive()
{
IsPinchActive = false;
}
private void AddOffset(Vector2 offset)
{
this.offset += offset;
}
private void Scale(float scale, Vector2 center)
{
scale = ScaleZoomFactor(scale);
AddOffset((scale - 1) * (center + offset));
}
private float ScaleZoomFactor(float scale)
{
var originalZoomFactor = zoomFactor;
zoomFactor *= scale;
var initialZoomFactor = GetInitialZoomFactor();
zoomFactor = MathHelper.Clamp(zoomFactor, scrollViewer.MinZoom.X / initialZoomFactor, scrollViewer.MaxZoom.X / initialZoomFactor);
return zoomFactor / originalZoomFactor;
}
private void Drag(Vector2 center, Vector2 lastCenter)
{
AddOffset(-(center - lastCenter));
}
private float CalculateScale(Vector2[] startTouchpoints, Vector2[] endTouchpoints)
{
var startDistance = GetDistance(startTouchpoints[0], startTouchpoints[1]);
var endDistance = GetDistance(endTouchpoints[0], endTouchpoints[1]);
return endDistance / startDistance;
}
private Vector2[] GetTouchpointsPositions(List<TouchLocation> touchpoints)
{
// Disconsidere the container position
var containerPosition = scrollViewer.DestinationRectangle.Location.ToVector2();
return touchpoints.Select(touchpoint => touchpoint.Position - containerPosition).ToArray();
}
private float GetInitialZoomFactor()
=> scrollViewer.Size.X / (scrollViewer.ContainerSize.X / scrollViewer.Zoom.X);
private Vector2 GetTouchCenter(Vector2[] touchpoints)
=> new Vector2(touchpoints.Sum(x => x.X) / touchpoints.Count(), touchpoints.Sum(x => x.Y) / touchpoints.Count());
private float GetDistance(Vector2 a, Vector2 b)
=> (float)Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));
}
}
| 35.57554 | 142 | 0.619009 | [
"MIT"
] | DaniloPeres/MonoGame.GameManager | MonoGame.GameManager/Controls/ControlsUI/ScrollViewerPinchZoom.cs | 4,947 | C# |
using System;
namespace RarExt
{
class Program
{
static void Main(string[] args)
{
//DoScan(@"d:\tmp\aaa");
if (args == null || args.Length <= 0)
{
Console.WriteLine("请输入要压缩的目录");
return;
}
new RarLastDirNoSubDir().DoScan(args[0]);
}
}
}
| 17.619048 | 53 | 0.42973 | [
"Apache-2.0"
] | youbl/products | RarExt/RarExt/Program.cs | 390 | 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("UnitTester")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnitTester")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a2015997-5e37-4458-8945-232277fd7c5c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.621622 | 85 | 0.725682 | [
"BSD-2-Clause"
] | borzel/win-xenguestagent | src/UnitTester/Properties/AssemblyInfo.cs | 1,432 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
namespace Cauldron.VaultFive
{
public class DirectorWellsCardController : VaultFiveUtilityCardController
{
public DirectorWellsCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController)
{
SpecialStringMaker.ShowHeroCharacterCardWithLowestHP().Condition = () => !Card.IsInPlayAndHasGameText;
SpecialStringMaker.ShowSpecialString(() => BuildPlayersWithArtifactInHandSpecialString());
}
public override void AddTriggers()
{
//That hero is immune to psychic damage.
AddImmuneToDamageTrigger((DealDamageAction dd) => dd.DamageType == DamageType.Psychic && GetCardThisCardIsNextTo() != null && dd.Target == GetCardThisCardIsNextTo());
//Players with Artifact cards in their hand cannot draw cards.
CannotDrawCards((TurnTakerController ttc) => GetPlayersWithArtifactsInHand().Contains(ttc.TurnTaker));
}
public override IEnumerator DeterminePlayLocation(List<MoveCardDestination> storedResults, bool isPutIntoPlay, List<IDecision> decisionSources, Location overridePlayArea = null, LinqTurnTakerCriteria additionalTurnTakerCriteria = null)
{
//Play this card next to the hero with the lowest HP
List<Card> foundTarget = new List<Card>();
IEnumerator coroutine = base.GameController.FindTargetWithLowestHitPoints(1, (Card c) => c.IsHeroCharacterCard && (overridePlayArea == null || c.IsAtLocationRecursive(overridePlayArea)), foundTarget, cardSource: base.GetCardSource());
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
Card lowestHero = foundTarget.FirstOrDefault();
if (lowestHero != null && storedResults != null)
{
//Play this card next to the hero with the lowest HP
storedResults.Add(new MoveCardDestination(lowestHero.NextToLocation, false, false, false));
}
else
{
string message = $"There are no heroes in play to put {Card.Title} next to. Moving it to {TurnTaker.Trash.GetFriendlyName()} instead.";
storedResults.Add(new MoveCardDestination(TurnTaker.Trash));
coroutine = GameController.SendMessageAction(message, Priority.Medium, GetCardSource(), showCardSource: true);
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
}
yield break;
}
}
}
| 46.772727 | 246 | 0.648202 | [
"MIT"
] | SotMSteamMods/CauldronMods | CauldronMods/Controller/Environments/VaultFive/Cards/DirectorWellsCardController.cs | 3,089 | C# |
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using Musoq.Schema.DataSources;
namespace Musoq.Schema.Os.Zip
{
public class ZipSource : RowSource
{
private readonly string _zipPath;
private readonly RuntimeContext _communicator;
public ZipSource(string zipPath, RuntimeContext communicator)
{
_zipPath = zipPath;
_communicator = communicator;
}
public override IEnumerable<IObjectResolver> Rows
{
get
{
var endWorkToken = _communicator.EndWorkToken;
using (var file = File.OpenRead(_zipPath))
{
using (var zip = new ZipArchive(file))
{
foreach (var entry in zip.Entries)
{
endWorkToken.ThrowIfCancellationRequested();
if (entry.Name != string.Empty)
{
yield return new EntityResolver<ZipArchiveEntry>(
entry,
SchemaZipHelper.NameToIndexMap,
SchemaZipHelper.IndexToMethodAccessMap);
}
}
}
}
}
}
}
} | 32.227273 | 81 | 0.466855 | [
"MIT"
] | JTOne123/Musoq | Musoq.Schema.Os/Zip/ZipSource.cs | 1,420 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Monitoring.V1
{
/// <summary>
/// Optional: points to a secret object containing parameters used to connect to OpenStack.
/// </summary>
public class PrometheusSpecVolumesCinderSecretRefArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names TODO: Add other useful fields. apiVersion, kind, uid?
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
public PrometheusSpecVolumesCinderSecretRefArgs()
{
}
}
}
| 32.586207 | 177 | 0.68254 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/prometheus/dotnet/Kubernetes/Crds/Operators/Prometheus/Monitoring/V1/Inputs/PrometheusSpecVolumesCinderSecretRefArgs.cs | 945 | C# |
// ClassicalSharp copyright 2014-2016 UnknownShadow200 | Licensed under MIT
using System;
using System.Drawing;
using ClassicalSharp.Model;
using OpenTK;
using OpenTK.Input;
namespace ClassicalSharp {
public static class MathUtils {
/// <summary> Creates a vector with all components at 1E25. </summary>
public static Vector3 MaxPos() { return new Vector3( 1E25f, 1E25f, 1E25f ); }
/// <summary> Clamps that specified value such that min ≤ value ≤ max </summary>
public static void Clamp( ref float value, float min, float max ) {
if( value < min ) value = min;
if( value > max ) value = max;
}
/// <summary> Clamps that specified value such that min ≤ value ≤ max </summary>
public static void Clamp( ref int value, int min, int max ) {
if( value < min ) value = min;
if( value > max ) value = max;
}
public static Vector3 Mul( Vector3 a, Vector3 scale ) {
a.X *= scale.X; a.Y *= scale.Y; a.Z *= scale.Z;
return a;
}
/// <summary> Returns the next highest power of 2 that is ≥ to the given value. </summary>
public static int NextPowerOf2( int value ) {
int next = 1;
while( value > next )
next <<= 1;
return next;
}
/// <summary> Returns whether the given value is a power of 2. </summary>
public static bool IsPowerOf2( int value ) {
return value != 0 && (value & (value - 1)) == 0;
}
/// <summary> Multiply a value in degrees by this to get its value in radians. </summary>
public const float Deg2Rad = (float)(Math.PI / 180);
/// <summary> Multiply a value in radians by this to get its value in degrees. </summary>
public const float Rad2Deg = (float)(180 / Math.PI);
public static int DegreesToPacked( double degrees, int period ) {
return (int)(degrees * period / 360.0) % period;
}
public static int DegreesToPacked( double degrees ) {
return (int)(degrees * 256 / 360.0) & 0xFF;
}
public static double PackedToDegrees( byte packed ) {
return packed * 360.0 / 256.0;
}
/// <summary> Rotates the given 3D coordinates around the y axis. </summary>
public static Vector3 RotateY( Vector3 v, float angle ) {
float cosA = (float)Math.Cos( angle );
float sinA = (float)Math.Sin( angle );
return new Vector3( cosA * v.X - sinA * v.Z, v.Y, sinA * v.X + cosA * v.Z );
}
/// <summary> Rotates the given 3D coordinates around the y axis. </summary>
public static Vector3 RotateY( float x, float y, float z, float angle ) {
float cosA = (float)Math.Cos( angle );
float sinA = (float)Math.Sin( angle );
return new Vector3( cosA * x - sinA * z, y, sinA * x + cosA * z );
}
/// <summary> Rotates the given 3D coordinates around the x axis. </summary>
public static void RotateX( ref float y, ref float z, float cosA, float sinA ) {
float y2 = cosA * y + sinA * z; z = -sinA * y + cosA * z; y = y2;
}
/// <summary> Rotates the given 3D coordinates around the y axis. </summary>
public static void RotateY( ref float x, ref float z, float cosA, float sinA ) {
float x2 = cosA * x - sinA * z; z = sinA * x + cosA * z; x = x2;
}
/// <summary> Rotates the given 3D coordinates around the z axis. </summary>
public static void RotateZ( ref float x, ref float y, float cosA, float sinA ) {
float x2 = cosA * x + sinA * y; y = -sinA * x + cosA * y; x = x2;
}
/// <summary> Returns the square of the euclidean distance between two points. </summary>
public static float DistanceSquared( Vector3 p1, Vector3 p2 ) {
float dx = p2.X - p1.X;
float dy = p2.Y - p1.Y;
float dz = p2.Z - p1.Z;
return dx * dx + dy * dy + dz * dz;
}
/// <summary> Returns the square of the euclidean distance between two points. </summary>
public static float DistanceSquared( float x1, float y1, float z1, float x2, float y2, float z2 ) {
float dx = x2 - x1;
float dy = y2 - y1;
float dz = z2 - z1;
return dx * dx + dy * dy + dz * dz;
}
/// <summary> Returns the square of the euclidean distance between two points. </summary>
public static int DistanceSquared( int x1, int y1, int z1, int x2, int y2, int z2 ) {
int dx = x2 - x1;
int dy = y2 - y1;
int dz = z2 - z1;
return dx * dx + dy * dy + dz * dz;
}
/// <summary> Returns a normalised vector that faces in the direction
/// described by the given yaw and pitch. </summary>
public static Vector3 GetDirVector( double yawRad, double pitchRad ) {
double x = -Math.Cos( pitchRad ) * -Math.Sin( yawRad );
double y = -Math.Sin( pitchRad );
double z = -Math.Cos( pitchRad ) * Math.Cos( yawRad );
return new Vector3( (float)x, (float)y, (float)z );
}
public static void GetHeading( Vector3 dir, out double yawRad, out double pitchRad ) {
pitchRad = Math.Asin( -dir.Y );
yawRad = Math.Atan2( dir.Z, dir.X );
}
// http://www.opengl-tutorial.org/intermediate-tutorials/billboards-particles/billboards/
public static void CalcBillboardPoints( Vector2 size, Vector3 position, ref Matrix4 view, out Vector3 p111,
out Vector3 p121, out Vector3 p212, out Vector3 p222 ) {
Vector3 centre = position; centre.Y += size.Y / 2;
Vector3 a = new Vector3( view.Row0.X * size.X, view.Row1.X * size.X, view.Row2.X * size.X ); // right * size.X
Vector3 b = new Vector3( view.Row0.Y * size.Y, view.Row1.Y * size.Y, view.Row2.Y * size.Y ); // up * size.Y
p111 = centre + a * -0.5f + b * -0.5f;
p121 = centre + a * -0.5f + b * 0.5f;
p212 = centre + a * 0.5f + b * -0.5f;
p222 = centre + a * 0.5f + b * 0.5f;
}
/// <summary> Linearly interpolates between a given angle range, adjusting if necessary. </summary>
public static float LerpAngle( float leftAngle, float rightAngle, float t ) {
// we have to cheat a bit for angles here.
// Consider 350* --> 0*, we only want to travel 10*,
// but without adjusting for this case, we would interpolate back the whole 350* degrees.
bool invertLeft = leftAngle > 270 && rightAngle < 90;
bool invertRight = rightAngle > 270 && leftAngle < 90;
if( invertLeft ) leftAngle = leftAngle - 360;
if( invertRight ) rightAngle = rightAngle - 360;
return Utils.Lerp( leftAngle, rightAngle, t );
}
}
} | 41.206452 | 114 | 0.622358 | [
"BSD-3-Clause"
] | Andresian/ClassicalSharp | ClassicalSharp/Utils/MathUtils.cs | 6,245 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using MVCAppWithADAuth.Models;
namespace MVCAppWithADAuth.Controllers
{
[Authorize]
public class UserProfileController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private string graphResourceID = "https://graph.windows.net/";
// GET: UserProfile
public async Task<ActionResult> Index()
{
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
try
{
Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => await GetTokenForApplication());
// Use the token for querying the graph to get the user details
var result = await activeDirectoryClient.Users
.Where(u => u.ObjectId.Equals(userObjectID))
.ExecuteAsync();
IUser user = result.CurrentPage.ToList().First();
return View(user);
}
catch (AdalException)
{
// Return to error page.
return View("Error");
}
// If the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
catch (Exception)
{
return View("Relogin");
}
}
public void RefreshSession()
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/UserProfile" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
public async Task<string> GetTokenForApplication()
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// Get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
ClientCredential clientcred = new ClientCredential(clientId, appKey);
// Initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
return authenticationResult.AccessToken;
}
}
}
| 47.243902 | 200 | 0.679659 | [
"MIT"
] | fmustaf/Samples | MVCAppWithADAuth/MVCAppWithADAuth/Controllers/UserProfileController.cs | 3,876 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.