commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
2c58d3e5547de869d5bdf2119c88a12ed4115b2d | Allow use viewmodel context in custom controls, obsolete Control property | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/components/ViewModelContext.cs | R7.University/components/ViewModelContext.cs | //
// ViewModelContext.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Web.UI;
using DotNetNuke.UI.Modules;
namespace R7.University
{
public class ViewModelContext
{
[Obsolete]
public IModuleControl Control { get; protected set; }
public string LocalResourceFile { get; protected set; }
public ModuleInstanceContext Module { get; protected set; }
public ViewModelContext (IModuleControl module)
{
Control = module;
Module = module.ModuleContext;
LocalResourceFile = module.LocalResourceFile;
}
public ViewModelContext (Control control, IModuleControl module)
{
Module = module.ModuleContext;
LocalResourceFile = DotNetNuke.Web.UI.Utilities.GetLocalResourceFile (control);
}
}
}
| //
// ViewModelContext.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using DotNetNuke.UI.Modules;
namespace R7.University
{
public class ViewModelContext
{
public IModuleControl Control { get; protected set; }
public ModuleInstanceContext Module
{
get { return Control.ModuleContext; }
}
public ViewModelContext (IModuleControl control)
{
Control = control;
}
}
}
| agpl-3.0 | C# |
b13e81d864164d750d4a6a3980f2c02f60893539 | Clean up 'AssemblyInfo.cs'. | McSherry/libSemVer.NET,McSherry/McSherry.SemanticVersioning | McSherry.SemanticVersioning/Properties/AssemblyInfo.cs | McSherry.SemanticVersioning/Properties/AssemblyInfo.cs | // Copyright (c) 2015-20 Liam McSherry
//
// 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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using CLSCompliantAttribute = System.CLSCompliantAttribute;
// Since the introduction of the new 'csproj' format, there's no need to specify
// author, version, etc. metadata in an 'AssemblyInfo.cs' file, so we're only
// using it here since it's the most appropriate place to put assembly attributes.
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("McSherry.SemanticVersioning.Testing")]
[assembly: CLSCompliant(true)]
| // Copyright (c) 2015-16 Liam McSherry
//
// 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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using CLSCompliantAttribute = System.CLSCompliantAttribute;
// 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("Semantic Versioning for .NET")]
//[assembly: AssemblyProduct("Semantic Versioning for .NET")]
//[assembly: AssemblyCopyright("Copyright 2015-16 © Liam McSherry")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("McSherry.SemanticVersioning.Testing")]
[assembly: CLSCompliant(true)]
// We're using Semantic Versioning for the library, but this doesn't translate
// exactly to .NET versioning. To get around this, we're going to specify two
// version attributes:
//
// [AssemblyInformationalVersion]: We're using this for the "actual" (semantic)
// version number.
//
// [AssemblyVersion]: This will track the "actual" version number's
// major and minor versions. This should allow any
// patched versions to be swapped out without
// needing a recompile (e.g. you built against
// v1.0.0, but you should be able to use v1.0.1 or
// v1.0.2 without needing to recompile).
//
//[assembly: AssemblyVersion("1.2.0.0")]
//[assembly: AssemblyInformationalVersion("1.2.0")]
| mit | C# |
cd0ee7ec62fad15d73763c0a12b288e9934846a3 | Add CellUtil.CreateBoundCellRenderer | lytico/xwt,cra0zy/xwt,TheBrainTech/xwt,mminns/xwt,directhex/xwt,hwthomas/xwt,iainx/xwt,sevoku/xwt,steffenWi/xwt,mminns/xwt,hamekoz/xwt,akrisiun/xwt,mono/xwt,antmicro/xwt,residuum/xwt | Xwt.WPF/Xwt.WPFBackend.Utilities/CellUtil.cs | Xwt.WPF/Xwt.WPFBackend.Utilities/CellUtil.cs | //
// CellUtil.cs
//
// Author:
// Luís Reis <luiscubal@gmail.com>
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Luís Reis
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using SWC = System.Windows.Controls;
using SWM = System.Windows.Media;
using Xwt.Engine;
using Xwt.Drawing;
namespace Xwt.WPFBackend.Utilities
{
public static class CellUtil
{
internal static FrameworkElement CreateCellRenderer (TreeNode node, CellView view)
{
if (view is TextCellView)
{
DataField field = ((TextCellView) view).TextField;
int index = field.Index;
SWC.TextBlock label = new SWC.TextBlock ();
label.Text = (node.Values[index] ?? "null").ToString();
label.Padding = new Thickness(2);
return label;
}
else if (view is ImageCellView)
{
DataField field = ((ImageCellView)view).ImageField;
int index = field.Index;
SWM.ImageSource image = (SWM.ImageSource) WidgetRegistry.GetBackend(node.Values[index]);
SWC.Image imageCtrl = new SWC.Image
{
Source = image,
Width = image.Width,
Height = image.Height
};
return imageCtrl;
}
throw new NotImplementedException ();
}
internal static FrameworkElementFactory CreateBoundCellRenderer (CellView view)
{
TextCellView textView = view as TextCellView;
if (textView != null) {
FrameworkElementFactory factory = new FrameworkElementFactory (typeof (SWC.TextBlock));
if (textView.TextField != null)
factory.SetBinding (SWC.TextBlock.TextProperty, new Binding (".[" + textView.TextField.Index + "]"));
factory.SetValue (SWC.Control.PaddingProperty, new Thickness (2));
return factory;
}
ImageCellView imageView = view as ImageCellView;
if (imageView != null) {
FrameworkElementFactory factory = new FrameworkElementFactory (typeof (SWC.Image));
if (imageView.ImageField != null) {
var binding = new Binding (".[" + imageView.ImageField.Index + "]")
{ Converter = new ImageToImageSourceConverter () };
factory.SetBinding (SWC.Image.SourceProperty, binding);
}
return factory;
}
throw new NotImplementedException ();
}
}
}
| //
// CellUtil.cs
//
// Author:
// Luís Reis <luiscubal@gmail.com>
//
// Copyright (c) 2012 Luís Reis
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using SWC = System.Windows.Controls;
using SWM = System.Windows.Media;
using Xwt.Engine;
using Xwt.Drawing;
namespace Xwt.WPFBackend.Utilities
{
public static class CellUtil
{
internal static FrameworkElement CreateCellRenderer (TreeNode node, CellView view)
{
if (view is TextCellView)
{
DataField field = ((TextCellView) view).TextField;
int index = field.Index;
SWC.TextBlock label = new SWC.TextBlock ();
label.Text = (node.Values[index] ?? "null").ToString();
label.Padding = new Thickness(2);
return label;
}
else if (view is ImageCellView)
{
DataField field = ((ImageCellView)view).ImageField;
int index = field.Index;
SWM.ImageSource image = (SWM.ImageSource) WidgetRegistry.GetBackend(node.Values[index]);
SWC.Image imageCtrl = new SWC.Image
{
Source = image,
Width = image.Width,
Height = image.Height
};
return imageCtrl;
}
throw new NotImplementedException ();
}
}
}
| mit | C# |
01ba2f7794ae7677458565f6ea3f809aadfc90fd | Format assembly properties | PetSerAl/PetSerAl.PowerShell.Data | Assembly.cs | Assembly.cs | using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("1.0.0"), AssemblyFileVersion("1.0.0")]
[assembly: ComVisible(false)]
| using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(false),
NeutralResourcesLanguage("en"),
AssemblyVersion("1.0.0"),
AssemblyFileVersion("1.0.0"),
ComVisible(false)]
| mit | C# |
25adb254fee4d7499fe6e4955f8b876c06ff3234 | Put Description back in for FieldLookupString. It is only available for taxonomies. | axomic/openasset-rest-cs | OpenAsset.RestClient.Library/Noun/FieldLookupString.cs | OpenAsset.RestClient.Library/Noun/FieldLookupString.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// serialization stuff
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
namespace OpenAsset.RestClient.Library.Noun
{
[JsonObject(MemberSerialization.OptIn)]
public class FieldLookupString : Base.BaseNoun
{
#region private serializable properties
[JsonProperty("value",NullValueHandling = NullValueHandling.Ignore), NestedNounProperty]
public string _value;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore), NestedNounProperty]
public string description;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore), NestedNounProperty]
protected int? display_order;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore), NestedNounProperty]
protected int? field_id;
#endregion
#region Accessors
public virtual string Value
{
get { return _value; }
set { _value = value; }
}
public virtual string Description
{
get { return description; }
set { description = value; }
}
public virtual int DisplayOrder
{
get { return display_order ?? default(int); }
set { display_order = value; }
}
public virtual int FieldId
{
get { return field_id ?? default(int); }
set { field_id = value; }
}
#endregion
public override int CompareTo(object obj)
{
if (obj == null) return 1;
FieldLookupString otherFieldLookupString = obj as FieldLookupString;
if (otherFieldLookupString != null)
return this.ToString().CompareTo(otherFieldLookupString.ToString());
else
throw new ArgumentException("Object is not a FieldLookupString");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// serialization stuff
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
namespace OpenAsset.RestClient.Library.Noun
{
[JsonObject(MemberSerialization.OptIn)]
public class FieldLookupString : Base.BaseNoun
{
#region private serializable properties
[JsonProperty("value",NullValueHandling = NullValueHandling.Ignore), NestedNounProperty]
public string _value;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore), NestedNounProperty]
protected int? display_order;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore), NestedNounProperty]
protected int? field_id;
#endregion
#region Accessors
public virtual string Value
{
get { return _value; }
set { _value = value; }
}
public virtual int DisplayOrder
{
get { return display_order ?? default(int); }
set { display_order = value; }
}
public virtual int FieldId
{
get { return field_id ?? default(int); }
set { field_id = value; }
}
#endregion
public override int CompareTo(object obj)
{
if (obj == null) return 1;
FieldLookupString otherFieldLookupString = obj as FieldLookupString;
if (otherFieldLookupString != null)
return this.ToString().CompareTo(otherFieldLookupString.ToString());
else
throw new ArgumentException("Object is not a FieldLookupString");
}
}
}
| mit | C# |
9409037b8215d008f3db8efbcebd6b3b320be469 | add test code | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Samples/AdventureWorksModel/Production/WorkOrderRepository.cs | Samples/AdventureWorksModel/Production/WorkOrderRepository.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using NakedObjects;
using NakedObjects.Services;
namespace AdventureWorksModel {
[DisplayName("Work Orders")]
public class WorkOrderRepository : AbstractFactoryAndRepository {
[FinderAction]
[QueryOnly]
public WorkOrder RandomWorkOrder() {
return Random<WorkOrder>();
}
[FinderAction]
public WorkOrder CreateNewWorkOrder([ContributedAction("Work Orders"), FindMenu, Description("product partial name")] Product product) {
var wo = NewTransientInstance<WorkOrder>();
wo.Product = product;
return wo;
}
[PageSize(20)]
public IQueryable<Product> AutoComplete0CreateNewWorkOrder([MinLength(2)] string name) {
return Container.Instances<Product>().Where(p => p.Name.Contains(name));
}
[DescribedAs("Has no auto-complete or FindMenu - to test use of 'auto-auto-complete' from recently viewed")]
public WorkOrder CreateNewWorkOrder2(Product product) {
return CreateNewWorkOrder(product);
}
[DescribedAs("Create workorder based on random product - to test transient creation")]
[QueryOnly]
public WorkOrder CreateNewWorkOrder3() {
var product = Random<Product>();
return CreateNewWorkOrder(product);
}
#region Injected Services
// This region should contain properties to hold references to any services required by the
// object. Use the 'injs' shortcut to add a new service.
#endregion
#region CurrentWorkOrders
[TableView(true, "Product", "OrderQty", "StartDate")]
public IQueryable<WorkOrder> WorkOrders([ContributedAction("Work Orders")] Product product, bool currentOrdersOnly) {
return from obj in Instances<WorkOrder>()
where obj.Product.ProductID == product.ProductID &&
(currentOrdersOnly == false || obj.EndDate == null)
select obj;
}
[PageSize(20)]
public IQueryable<Product> AutoComplete0WorkOrders([MinLength(2)] string name) {
return Container.Instances<Product>().Where(p => p.Name.Contains(name));
}
#endregion
}
} | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using NakedObjects;
using NakedObjects.Services;
namespace AdventureWorksModel {
[DisplayName("Work Orders")]
public class WorkOrderRepository : AbstractFactoryAndRepository {
[FinderAction]
[QueryOnly]
public WorkOrder RandomWorkOrder() {
return Random<WorkOrder>();
}
[FinderAction]
public WorkOrder CreateNewWorkOrder([ContributedAction("Work Orders"), FindMenu, Description("product partial name")] Product product) {
var wo = NewTransientInstance<WorkOrder>();
wo.Product = product;
return wo;
}
[PageSize(20)]
public IQueryable<Product> AutoComplete0CreateNewWorkOrder([MinLength(2)] string name) {
return Container.Instances<Product>().Where(p => p.Name.Contains(name));
}
[DescribedAs("Has no auto-complete or FindMenu - to test use of 'auto-auto-complete' from recently viewed")]
public WorkOrder CreateNewWorkOrder2(Product product) {
return CreateNewWorkOrder(product);
}
#region Injected Services
// This region should contain properties to hold references to any services required by the
// object. Use the 'injs' shortcut to add a new service.
#endregion
#region CurrentWorkOrders
[TableView(true, "Product", "OrderQty", "StartDate")]
public IQueryable<WorkOrder> WorkOrders([ContributedAction("Work Orders")] Product product, bool currentOrdersOnly) {
return from obj in Instances<WorkOrder>()
where obj.Product.ProductID == product.ProductID &&
(currentOrdersOnly == false || obj.EndDate == null)
select obj;
}
[PageSize(20)]
public IQueryable<Product> AutoComplete0WorkOrders([MinLength(2)] string name) {
return Container.Instances<Product>().Where(p => p.Name.Contains(name));
}
#endregion
}
} | apache-2.0 | C# |
abff48cc07384784565dcac5ee7893e13b55b18a | Make queary async | OrganizeSanayi/HospitalAutomation | HospitalAutomation.Core/Services/UserService.cs | HospitalAutomation.Core/Services/UserService.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalAutomation.Services
{
public class UserService
{
public static bool IsValidLogin(string username, string password)
{
using (var context = new HospitalAutomationEntities())
{
var task = context.OTURUMs.FirstOrDefaultAsync(p => p.KullaniciAdi == username && p.Sifre == password);
task.Wait();
return task.Result != null;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalAutomation.Services
{
public class UserService
{
public static bool IsValidLogin(string username, string password)
{
using (var context = new HospitalAutomationEntities())
{
return context.OTURUMs.FirstOrDefaultAsync(p => p.KullaniciAdi == username && p.Sifre == password) != null;
}
}
}
}
| apache-2.0 | C# |
2dc524f9a4596314b03a5e76bedaf1787df6a31b | Update Products. Switch Controller to use FromServices. | JasonGT/NorthwindTraders,JasonGT/NorthwindTraders,JasonGT/NorthwindTraders,JasonGT/NorthwindTraders | Northwind.Web/Controllers/ProductsController.cs | Northwind.Web/Controllers/ProductsController.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Northwind.Application.Products.Commands;
using Northwind.Application.Products.Models;
using Northwind.Application.Products.Queries;
namespace Northwind.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// GET: api/Products
[HttpGet]
public async Task<IEnumerable<ProductDto>> GetProducts(
[FromServices] IGetAllProductsQuery query)
{
return await query.Execute();
}
// GET: api/Products/5
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(
[FromServices] IGetProductQuery query,
int id)
{
return Ok(await query.Execute(id));
}
// POST: api/Products
[HttpPost]
public async Task<IActionResult> PostProduct(
[FromServices] ICreateProductCommand command,
[FromBody] ProductDto product)
{
var newProduct = await command.Execute(product);
return CreatedAtAction("GetProduct", new { id = newProduct.ProductId }, newProduct);
}
// PUT: api/Products/5
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct(
[FromServices] IUpdateProductCommand command,
[FromBody] ProductDto product)
{
return Ok(await command.Execute(product));
}
// DELETE: api/Products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(
[FromServices] IDeleteProductCommand command,
int id)
{
await command.Execute(id);
return NoContent();
}
}
} | using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Northwind.Application.Products.Commands;
using Northwind.Application.Products.Models;
using Northwind.Application.Products.Queries;
using Northwind.Persistence;
namespace Northwind.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly IGetAllProductsQuery _getAllProductsQuery;
private readonly IGetProductQuery _getProductQuery;
private readonly ICreateProductCommand _createProductCommand;
private readonly IUpdateProductCommand _updateProductCommand;
private readonly IDeleteProductCommand _deleteProductCommand;
public ProductsController(NorthwindDbContext context,
IGetAllProductsQuery getAllProductsQuery,
IGetProductQuery getProductQuery,
ICreateProductCommand createProductCommand,
IUpdateProductCommand updateProductCommand,
IDeleteProductCommand deleteProductCommand)
{
_getAllProductsQuery = getAllProductsQuery;
_getProductQuery = getProductQuery;
_createProductCommand = createProductCommand;
_updateProductCommand = updateProductCommand;
_deleteProductCommand = deleteProductCommand;
}
// GET: api/Products
[HttpGet]
public async Task<IEnumerable<ProductDto>> GetProducts()
{
return await _getAllProductsQuery.Execute();
}
// GET: api/Products/5
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct([FromRoute] int id)
{
return Ok(await _getProductQuery.Execute(id));
}
// POST: api/Products
[HttpPost]
public async Task<IActionResult> PostProduct([FromBody] ProductDto product)
{
var newProduct = await _createProductCommand.Execute(product);
return CreatedAtAction("GetProduct", new { id = newProduct.ProductId }, newProduct);
}
// PUT: api/Products/5
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct([FromBody] ProductDto product)
{
return Ok(await _updateProductCommand.Execute(product));
}
// DELETE: api/Products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct([FromRoute] int id)
{
await _deleteProductCommand.Execute(id);
return NoContent();
}
}
} | mit | C# |
23b7cde941495bdc43944cdc66b634600370060a | Add milliseconds value alongside | smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu | osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs | osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaRulesetSetting.ScrollTime, 1500.0, DrawableManiaRuleset.MIN_TIME_RANGE, DrawableManiaRuleset.MAX_TIME_RANGE, 1);
Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime,
v => new SettingDescription(v, "Scroll Speed", $"{(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / v)} ({v}ms)"))
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaRulesetSetting.ScrollTime, 1500.0, DrawableManiaRuleset.MIN_TIME_RANGE, DrawableManiaRuleset.MAX_TIME_RANGE, 1);
Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Speed", $"{(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / v)}"))
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection
}
}
| mit | C# |
d87f86bd533dd630e6e8159327faafa6dc6ee63a | Fix UnitTest assembly name. | undeadlabs/msgpack-cli,msgpack/msgpack-cli,modulexcite/msgpack-cli,scopely/msgpack-cli,scopely/msgpack-cli,msgpack/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli | cli/src/MsgPack.WindowsPhone.7.1/Properties/AssemblyInfo.cs | cli/src/MsgPack.WindowsPhone.7.1/Properties/AssemblyInfo.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle( "MessagePack for Windows Phone 7.1" )]
[assembly: AssemblyDescription( "MessagePack for Windows Phone 7.1 packing/unpacking core library." )]
[assembly: AssemblyConfiguration( "Experimental" )]
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2011" )]
// TODO: use script. Major = Informational-Major, Minor = Informational-Minor, Build = Epoc days from 2010/1/1, Revision = Epoc minutes from 00:00:00
[assembly: AssemblyFileVersion( "0.2.0.0" )]
#if DEBUG || PERFORMANCE_TEST
[assembly: InternalsVisibleTo( "MsgPack.WindowsPhone.UnitTest" )]
#endif
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle( "MessagePack for Windows Phone 7.1" )]
[assembly: AssemblyDescription( "MessagePack for Windows Phone 7.1 packing/unpacking core library." )]
[assembly: AssemblyConfiguration( "Experimental" )]
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2011" )]
// TODO: use script. Major = Informational-Major, Minor = Informational-Minor, Build = Epoc days from 2010/1/1, Revision = Epoc minutes from 00:00:00
[assembly: AssemblyFileVersion( "0.2.0.0" )]
#if DEBUG || PERFORMANCE_TEST
[assembly: InternalsVisibleTo( "MsgPack.Silverlight.UnitTest" )]
#endif
| apache-2.0 | C# |
0e7bb8b42f0d903a67f1121d09aeb14352c8a159 | Fix bug when splitting conjunctions | terrajobst/nquery-vnext | src/NQuery/Optimization/Condition.cs | src/NQuery/Optimization/Condition.cs | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal static class Condition
{
public static BoundExpression And(BoundExpression left, BoundExpression right)
{
if (left == null)
return right;
if (right == null)
return left;
var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
return new BoundBinaryExpression(left, result, right);
}
public static BoundExpression And(IEnumerable<BoundExpression> conditions)
{
return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n));
}
public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
{
var stack = new Stack<BoundExpression>();
stack.Push(expression);
while (stack.Count > 0)
{
var current = stack.Pop();
var binary = current as BoundBinaryExpression;
if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd)
{
stack.Push(binary.Left);
stack.Push(binary.Right);
}
else
{
yield return current;
}
}
}
public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
{
var finder = new ValueSlotDependencyFinder();
finder.VisitExpression(expression);
return finder.ValueSlots.Overlaps(valueSlots);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal static class Condition
{
public static BoundExpression And(BoundExpression left, BoundExpression right)
{
if (left == null)
return right;
if (right == null)
return left;
var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
return new BoundBinaryExpression(left, result, right);
}
public static BoundExpression And(IEnumerable<BoundExpression> conditions)
{
return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n));
}
public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
{
var stack = new Stack<BoundExpression>();
stack.Push(expression);
while (stack.Count > 0)
{
var current = stack.Pop();
var binary = current as BoundBinaryExpression;
if (binary != null && binary.OperatorKind == BinaryOperatorKind.LogicalAnd)
{
stack.Push(binary.Left);
stack.Push(binary.Right);
}
else
{
yield return binary;
}
}
}
public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
{
var finder = new ValueSlotDependencyFinder();
finder.VisitExpression(expression);
return finder.ValueSlots.Overlaps(valueSlots);
}
}
} | mit | C# |
171afa7b416338503f935822758260d4fcc24ed1 | テスト中用のコメントの削除とTreeのキー指定が間違っていたので修正。 | SunriseDigital/cs-sdx | Sdx/Data/TreeMapper/Record.cs | Sdx/Data/TreeMapper/Record.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
namespace Sdx.Data.TreeMapper
{
public class Record<T, R>
where T : Sdx.Data.TreeMapper.Record.Item, new()
where R : Sdx.Db.Record
{
private Tree Tree;
private Sdx.Db.RecordSet RecordSet;
private Func<T, R, bool> Condition;
public Record(Tree tree, Sdx.Db.RecordSet recordSet, Func<T, R, bool> condition)
{
Tree = tree;
RecordSet = recordSet;
Condition = condition;
}
public IEnumerable<Sdx.Data.TreeMapper.Record.Item> GetItems(string key)
{
foreach (var childTree in Tree.Get(key).List)
{
var treeItem = new T();
treeItem.Tree = childTree;
treeItem.Record = RecordSet.Select(rec => (R)rec).FirstOrDefault(rec => this.Condition(treeItem, rec));
yield return treeItem;
}
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
namespace Sdx.Data.TreeMapper
{
public class Record<T, R>
where T : Sdx.Data.TreeMapper.Record.Item, new()
where R : Sdx.Db.Record
{
private Tree Tree;
private Sdx.Db.RecordSet RecordSet;
private Func<T, R, bool> Condition;
public Record(Tree tree, Sdx.Db.RecordSet recordSet, Func<T, R, bool> condition)
{
Tree = tree;
RecordSet = recordSet;
Condition = condition;
}
public IEnumerable<Sdx.Data.TreeMapper.Record.Item> GetItems(string key)
{
//foreach (var childTree in new List<Sdx.Data.TreeJson>())
foreach (var childTree in Tree.Get("list").List)
{
var treeItem = new T();
//treeItem.Tree = new Sdx.Data.TreeJson();
treeItem.Tree = childTree;
treeItem.Record = RecordSet.Select(rec => (R)rec).FirstOrDefault(rec => this.Condition(treeItem, rec));
yield return treeItem;
}
}
}
}
| mit | C# |
a2315bb792eb95233cf924d4e4d84c2040de5cd4 | Set LastKnownChange as it was forgotten | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/WabiSabi/Backend/Banning/Warden.cs | WalletWasabi/WabiSabi/Backend/Banning/Warden.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Bases;
using WalletWasabi.Logging;
namespace WalletWasabi.WabiSabi.Backend.Banning
{
/// <summary>
/// Serializes and releases the prison population periodically.
/// </summary>
public class Warden : PeriodicRunner
{
/// <param name="period">How often to serialize and release inmates.</param>
public Warden(TimeSpan period, string prisonFilePath, WabiSabiConfig config) : base(period)
{
PrisonFilePath = prisonFilePath;
Config = config;
Prison = DeserializePrison(PrisonFilePath);
LastKnownChange = Prison.ChangeId;
}
public Prison Prison { get; }
public Guid LastKnownChange { get; private set; }
private string PrisonFilePath { get; }
public WabiSabiConfig Config { get; }
private static Prison DeserializePrison(string prisonFilePath)
{
IoHelpers.EnsureContainingDirectoryExists(prisonFilePath);
var inmates = new List<Inmate>();
if (File.Exists(prisonFilePath))
{
try
{
foreach (var inmate in File.ReadAllLines(prisonFilePath).Select(Inmate.FromString))
{
inmates.Add(inmate);
}
}
catch (Exception ex)
{
Logger.LogError(ex);
Logger.LogWarning($"Deleting {prisonFilePath}");
File.Delete(prisonFilePath);
}
}
var prison = new Prison(inmates);
var (noted, banned) = prison.CountInmates();
if (noted > 0)
{
Logger.LogInfo($"{noted} noted UTXOs are found in prison.");
}
if (banned > 0)
{
Logger.LogInfo($"{banned} banned UTXOs are found in prison.");
}
return prison;
}
public async Task SerializePrisonAsync()
{
IoHelpers.EnsureContainingDirectoryExists(PrisonFilePath);
await File.WriteAllLinesAsync(PrisonFilePath, Prison.GetInmates().Select(x => x.ToString())).ConfigureAwait(false);
}
protected override async Task ActionAsync(CancellationToken cancel)
{
var count = Prison.ReleaseEligibleInmates(Config.ReleaseUtxoFromPrisonAfter).Count();
if (count > 0)
{
Logger.LogInfo($"{count} UTXOs are released from prison.");
}
// If something changed, send prison to file.
if (LastKnownChange != Prison.ChangeId)
{
await SerializePrisonAsync().ConfigureAwait(false);
LastKnownChange = Prison.ChangeId;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Bases;
using WalletWasabi.Logging;
namespace WalletWasabi.WabiSabi.Backend.Banning
{
/// <summary>
/// Serializes and releases the prison population periodically.
/// </summary>
public class Warden : PeriodicRunner
{
/// <param name="period">How often to serialize and release inmates.</param>
public Warden(TimeSpan period, string prisonFilePath, WabiSabiConfig config) : base(period)
{
PrisonFilePath = prisonFilePath;
Config = config;
Prison = DeserializePrison(PrisonFilePath);
LastKnownChange = Prison.ChangeId;
}
public Prison Prison { get; }
public Guid LastKnownChange { get; private set; }
private string PrisonFilePath { get; }
public WabiSabiConfig Config { get; }
private static Prison DeserializePrison(string prisonFilePath)
{
IoHelpers.EnsureContainingDirectoryExists(prisonFilePath);
var inmates = new List<Inmate>();
if (File.Exists(prisonFilePath))
{
try
{
foreach (var inmate in File.ReadAllLines(prisonFilePath).Select(Inmate.FromString))
{
inmates.Add(inmate);
}
}
catch (Exception ex)
{
Logger.LogError(ex);
Logger.LogWarning($"Deleting {prisonFilePath}");
File.Delete(prisonFilePath);
}
}
var prison = new Prison(inmates);
var (noted, banned) = prison.CountInmates();
if (noted > 0)
{
Logger.LogInfo($"{noted} noted UTXOs are found in prison.");
}
if (banned > 0)
{
Logger.LogInfo($"{banned} banned UTXOs are found in prison.");
}
return prison;
}
public async Task SerializePrisonAsync()
{
IoHelpers.EnsureContainingDirectoryExists(PrisonFilePath);
await File.WriteAllLinesAsync(PrisonFilePath, Prison.GetInmates().Select(x => x.ToString())).ConfigureAwait(false);
}
protected override async Task ActionAsync(CancellationToken cancel)
{
var count = Prison.ReleaseEligibleInmates(Config.ReleaseUtxoFromPrisonAfter).Count();
if (count > 0)
{
Logger.LogInfo($"{count} UTXOs are released from prison.");
}
// If something changed, send prison to file.
if (LastKnownChange != Prison.ChangeId)
{
await SerializePrisonAsync().ConfigureAwait(false);
}
}
}
}
| mit | C# |
bf0154d16507a9ea3b6a0a0a427b9cdb316ae8d3 | fix test | qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox | Wox.Test/PluginProgramTest.cs | Wox.Test/PluginProgramTest.cs | using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Wox.Core.Configuration;
using Wox.Core.Plugin;
using Wox.Image;
using Wox.Infrastructure;
using Wox.Infrastructure.UserSettings;
using Wox.Plugin;
using Wox.ViewModel;
namespace Wox.Test
{
[TestFixture]
class PluginProgramTest
{
private Plugin.Program.Main plugin;
[OneTimeSetUp]
public void Setup()
{
Settings.Initialize();
Portable portable = new Portable();
SettingWindowViewModel settingsVm = new SettingWindowViewModel(portable);
StringMatcher stringMatcher = new StringMatcher();
StringMatcher.Instance = stringMatcher;
stringMatcher.UserSettingSearchPrecision = Settings.Instance.QuerySearchPrecision;
PluginManager.LoadPlugins(Settings.Instance.PluginSettings);
MainViewModel mainVm = new MainViewModel(false);
PublicAPIInstance api = new PublicAPIInstance(settingsVm, mainVm);
plugin = new Plugin.Program.Main();
plugin.InitSync(new PluginInitContext()
{
API = api,
});
}
//[TestCase("powershell", "Windows PowerShell")] skip for appveyror
[TestCase("note", "Notepad")]
[TestCase("computer", "computer")]
public void Win32Test(string QueryText, string ResultTitle)
{
Query query = QueryBuilder.Build(QueryText.Trim(), new Dictionary<string, PluginPair>());
Result result = plugin.Query(query).OrderByDescending(r => r.Score).First();
Assert.IsTrue(result.Title.StartsWith(ResultTitle));
}
}
}
| using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Wox.Core.Configuration;
using Wox.Core.Plugin;
using Wox.Image;
using Wox.Infrastructure;
using Wox.Infrastructure.UserSettings;
using Wox.Plugin;
using Wox.ViewModel;
namespace Wox.Test
{
[TestFixture]
class PluginProgramTest
{
private Plugin.Program.Main plugin;
[OneTimeSetUp]
public void Setup()
{
Settings.Initialize();
Portable portable = new Portable();
SettingWindowViewModel settingsVm = new SettingWindowViewModel(portable);
StringMatcher stringMatcher = new StringMatcher();
StringMatcher.Instance = stringMatcher;
stringMatcher.UserSettingSearchPrecision = Settings.Instance.QuerySearchPrecision;
PluginManager.LoadPlugins(Settings.Instance.PluginSettings);
MainViewModel mainVm = new MainViewModel(false);
PublicAPIInstance api = new PublicAPIInstance(settingsVm, mainVm);
plugin = new Plugin.Program.Main();
plugin.InitSync(new PluginInitContext()
{
API = api,
});
}
[TestCase("powershell", "Windows PowerShell")]
[TestCase("note", "Notepad")]
[TestCase("computer", "computer")]
public void Win32Test(string QueryText, string ResultTitle)
{
Query query = QueryBuilder.Build(QueryText.Trim(), new Dictionary<string, PluginPair>());
Result result = plugin.Query(query).OrderByDescending(r => r.Score).First();
Assert.IsTrue(result.Title.StartsWith(ResultTitle));
}
}
}
| mit | C# |
844caad420cc53eaa02a76829aed3617882f4835 | fix #648 little addendum to @gmarz's work on #649 allowing a an enumerable of documents to passed in, no longer pass ids over querystring but instead always translate them to documents inside the POST body internally | UdiBen/elasticsearch-net,starckgates/elasticsearch-net,elastic/elasticsearch-net,faisal00813/elasticsearch-net,elastic/elasticsearch-net,joehmchan/elasticsearch-net,Grastveit/NEST,azubanov/elasticsearch-net,RossLieberman/NEST,Grastveit/NEST,faisal00813/elasticsearch-net,abibell/elasticsearch-net,UdiBen/elasticsearch-net,robrich/elasticsearch-net,gayancc/elasticsearch-net,faisal00813/elasticsearch-net,TheFireCookie/elasticsearch-net,geofeedia/elasticsearch-net,joehmchan/elasticsearch-net,cstlaurent/elasticsearch-net,DavidSSL/elasticsearch-net,LeoYao/elasticsearch-net,CSGOpenSource/elasticsearch-net,wawrzyn/elasticsearch-net,wawrzyn/elasticsearch-net,robertlyson/elasticsearch-net,KodrAus/elasticsearch-net,tkirill/elasticsearch-net,alanprot/elasticsearch-net,SeanKilleen/elasticsearch-net,joehmchan/elasticsearch-net,SeanKilleen/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,junlapong/elasticsearch-net,robrich/elasticsearch-net,DavidSSL/elasticsearch-net,geofeedia/elasticsearch-net,alanprot/elasticsearch-net,ststeiger/elasticsearch-net,jonyadamit/elasticsearch-net,KodrAus/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,cstlaurent/elasticsearch-net,azubanov/elasticsearch-net,gayancc/elasticsearch-net,jonyadamit/elasticsearch-net,mac2000/elasticsearch-net,amyzheng424/elasticsearch-net,junlapong/elasticsearch-net,junlapong/elasticsearch-net,jonyadamit/elasticsearch-net,ststeiger/elasticsearch-net,abibell/elasticsearch-net,ststeiger/elasticsearch-net,mac2000/elasticsearch-net,robertlyson/elasticsearch-net,cstlaurent/elasticsearch-net,alanprot/elasticsearch-net,amyzheng424/elasticsearch-net,geofeedia/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,gayancc/elasticsearch-net,robrich/elasticsearch-net,adam-mccoy/elasticsearch-net,robertlyson/elasticsearch-net,azubanov/elasticsearch-net,starckgates/elasticsearch-net,tkirill/elasticsearch-net,amyzheng424/elasticsearch-net,Grastveit/NEST,LeoYao/elasticsearch-net,RossLieberman/NEST,tkirill/elasticsearch-net,LeoYao/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,wawrzyn/elasticsearch-net,SeanKilleen/elasticsearch-net,alanprot/elasticsearch-net,adam-mccoy/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,starckgates/elasticsearch-net,DavidSSL/elasticsearch-net | src/Nest/DSL/MultiTermVectorsDescriptor.cs | src/Nest/DSL/MultiTermVectorsDescriptor.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Elasticsearch.Net;
using Newtonsoft.Json;
namespace Nest
{
[DescriptorFor("Mtermvectors")]
public partial class MultiTermVectorsDescriptor<T> :
IndexTypePathTypedDescriptor<MultiTermVectorsDescriptor<T>, MultiTermVectorsRequestParameters, T>
, IPathInfo<MultiTermVectorsRequestParameters> where T : class
{
[JsonProperty("docs")]
internal IEnumerable<MultiTermVectorDocument> _Documents { get; set;}
public MultiTermVectorsDescriptor<T> Documents(params Func<MultiTermVectorDocumentDescriptor<T>, IMultiTermVectorDocumentDescriptor>[] documentSelectors)
{
this._Documents = documentSelectors.Select(s => s(new MultiTermVectorDocumentDescriptor<T>()).GetDocument()).Where(d=>d!= null).ToList();
return this;
}
public MultiTermVectorsDescriptor<T> Documents(IEnumerable<MultiTermVectorDocument> documents)
{
this._Documents = documents;
return this;
}
public MultiTermVectorsDescriptor<T> Ids(params string[] ids)
{
return this.Documents(ids.Select(id => new MultiTermVectorDocument { Id = id }));
}
public MultiTermVectorsDescriptor<T> Ids(params long[] ids)
{
return this.Documents(ids.Select(id => new MultiTermVectorDocument { Id = id.ToString(CultureInfo.InvariantCulture) }));
}
public MultiTermVectorsDescriptor<T> Ids(IEnumerable<string> ids)
{
return this.Documents(ids.Select(id => new MultiTermVectorDocument { Id = id }));
}
public MultiTermVectorsDescriptor<T> Ids(IEnumerable<long> ids)
{
return this.Documents(ids.Select(id => new MultiTermVectorDocument { Id = id.ToString(CultureInfo.InvariantCulture) }));
}
ElasticsearchPathInfo<MultiTermVectorsRequestParameters> IPathInfo<MultiTermVectorsRequestParameters>.ToPathInfo(IConnectionSettingsValues settings)
{
var pathInfo = base.ToPathInfo(settings, this._QueryString);
pathInfo.HttpMethod = PathInfoHttpMethod.POST;
return pathInfo;
}
}
public interface IMultiTermVectorDocumentDescriptor
{
MultiTermVectorDocument Document { get; set; }
MultiTermVectorDocument GetDocument();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Elasticsearch.Net;
using Newtonsoft.Json;
namespace Nest
{
[DescriptorFor("Mtermvectors")]
public partial class MultiTermVectorsDescriptor<T> :
IndexTypePathTypedDescriptor<MultiTermVectorsDescriptor<T>, MultiTermVectorsRequestParameters, T>
, IPathInfo<MultiTermVectorsRequestParameters> where T : class
{
[JsonProperty("docs")]
internal IEnumerable<MultiTermVectorDocument> _Documents { get; set;}
public MultiTermVectorsDescriptor<T> Documents(params Func<MultiTermVectorDocumentDescriptor<T>, IMultiTermVectorDocumentDescriptor>[] documentSelectors)
{
this._Documents = documentSelectors.Select(s => s(new MultiTermVectorDocumentDescriptor<T>()).GetDocument()).Where(d=>d!= null).ToList();
return this;
}
public MultiTermVectorsDescriptor<T> Documents(IEnumerable<MultiTermVectorDocument> documents)
{
this._Documents = documents;
return this;
}
ElasticsearchPathInfo<MultiTermVectorsRequestParameters> IPathInfo<MultiTermVectorsRequestParameters>.ToPathInfo(IConnectionSettingsValues settings)
{
var pathInfo = base.ToPathInfo(settings, this._QueryString);
pathInfo.HttpMethod = PathInfoHttpMethod.POST;
return pathInfo;
}
}
public interface IMultiTermVectorDocumentDescriptor
{
MultiTermVectorDocument Document { get; set; }
MultiTermVectorDocument GetDocument();
}
}
| apache-2.0 | C# |
b3f1c92f68f18add95d8ea034b82f7981e90d6aa | Modify progress helper so that activity indicator stops after last call ends | codestuffers/MvvmCrossPlugins | src/UserInteraction/Core/ProgressHelper.cs | src/UserInteraction/Core/ProgressHelper.cs | using Cirrious.CrossCore.Core;
using System;
using System.Threading.Tasks;
namespace codestuffers.MvvmCrossPlugins.UserInteraction
{
/// <summary>
/// Helper class that executes a task with a progress bar
/// </summary>
public class ProgressHelper
{
private readonly IMvxMainThreadDispatcher _dispatcher;
private int _progressIndicatorCount;
public ProgressHelper(IMvxMainThreadDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
/// <summary>
/// Setup the execution of the task with a progress indicator
/// </summary>
/// <typeparam name="T">Type of task return value</typeparam>
/// <param name="task">Task that is executing</param>
/// <param name="onCompletion">Action that will be executed when the task is complete</param>
/// <param name="startProgressAction">Action that will show the progress indicator</param>
/// <param name="stopProgressAction">Action that will hide the progress indicator</param>
public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction)
{
_progressIndicatorCount++;
_dispatcher.RequestMainThreadAction(startProgressAction);
task.ContinueWith(x =>
{
onCompletion(task);
if (--_progressIndicatorCount == 0)
{
_dispatcher.RequestMainThreadAction(stopProgressAction);
}
});
}
}
}
| using Cirrious.CrossCore.Core;
using System;
using System.Threading.Tasks;
namespace codestuffers.MvvmCrossPlugins.UserInteraction
{
/// <summary>
/// Helper class that executes a task with a progress bar
/// </summary>
public class ProgressHelper
{
private readonly IMvxMainThreadDispatcher _dispatcher;
public ProgressHelper(IMvxMainThreadDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
/// <summary>
/// Setup the execution of the task with a progress indicator
/// </summary>
/// <typeparam name="T">Type of task return value</typeparam>
/// <param name="task">Task that is executing</param>
/// <param name="onCompletion">Action that will be executed when the task is complete</param>
/// <param name="startProgressAction">Action that will show the progress indicator</param>
/// <param name="stopProgressAction">Action that will hide the progress indicator</param>
public void SetupTask<T>(Task<T> task, Action<Task<T>> onCompletion, Action startProgressAction, Action stopProgressAction)
{
_dispatcher.RequestMainThreadAction(startProgressAction);
task.ContinueWith(x =>
{
onCompletion(task);
_dispatcher.RequestMainThreadAction(stopProgressAction);
});
}
}
}
| mit | C# |
52503b6f26a0221f986e71c2f5abb91865645a8e | remove todo comments | virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016 | Assets/Scripts/RoomNavigationManager.cs | Assets/Scripts/RoomNavigationManager.cs | using UnityEngine;
using System.Collections;
public class RoomNavigationManager : MonoBehaviour {
public GameObject PlayerGameObject;
public GameObject[] RoomPrefabs;
private GameObject activeRoomPrefab;
void Awake() {
activeRoomPrefab = Instantiate(RoomPrefabs[0]);
activeRoomPrefab.GetComponent<RoomDetails>().Doors[0].GetComponent<DoorDetails>().SetConnectedDoor(1, 1);
}
// Change room prefab
public void ChangeRoom(int connectedRoomId, int connectedDoorId) {
// remove current room prefab from scene
Destroy(activeRoomPrefab);
// spawn connectedRoom and save reference
activeRoomPrefab = Instantiate(GetRoomPrefabById(connectedRoomId));
// find position of connected door
Vector3 connectedDoorPosition = GetDoorPosition(connectedDoorId);
// determin if player should be on the left or right side of the door's location
bool spawnCharacterOnLeftOfDoor = isDoorOnRight(connectedDoorPosition);
// position player slightly off of door's location
float characterOffsetX = 2f;
if (spawnCharacterOnLeftOfDoor) {
characterOffsetX *= -1;
}
PlayerGameObject.transform.localPosition = new Vector3(connectedDoorPosition.x + characterOffsetX, connectedDoorPosition.y, 0);
}
// assumes that a valid ID is provided, if not bad things will happen
GameObject GetRoomPrefabById(int id) {
// loop through all the room prefabs
foreach(GameObject room in RoomPrefabs) {
if(room.GetComponent<RoomDetails>().Id == id) {
return room;
}
}
return new GameObject();
}
// assumes that a valid ID is provided, if not bad things will happen
Vector3 GetDoorPosition(int doorId) {
Vector3 doorPosition = Vector3.zero;
foreach(GameObject door in activeRoomPrefab.GetComponent<RoomDetails>().Doors) {
if(door.GetComponent<DoorDetails>().Id == doorId) {
doorPosition = door.transform.position;
}
}
return doorPosition;
}
bool isDoorOnRight(Vector3 doorPosition) {
if(doorPosition.x > 0) {
return true;
}
return false;
}
}
| using UnityEngine;
using System.Collections;
public class RoomNavigationManager : MonoBehaviour {
public GameObject PlayerGameObject;
public GameObject[] RoomPrefabs;
private GameObject activeRoomPrefab;
void Awake() {
activeRoomPrefab = Instantiate(RoomPrefabs[0]);
activeRoomPrefab.GetComponent<RoomDetails>().Doors[0].GetComponent<DoorDetails>().SetConnectedDoor(1, 1);
}
// Change room prefab
public void ChangeRoom(int connectedRoomId, int connectedDoorId) {
// remove current room prefab from scene
Destroy(activeRoomPrefab);
// spawn connectedRoom and save reference
activeRoomPrefab = Instantiate(GetRoomPrefabById(connectedRoomId));
// place player near connected door
// find position of connected door
Vector3 connectedDoorPosition = GetDoorPosition(connectedDoorId);
// determin if player should be on the left or right side of the door's location
bool spawnCharacterOnLeftOfDoor = isDoorOnRight(connectedDoorPosition);
// position player slightly off of door's location
float characterOffsetX = 2f;
if (spawnCharacterOnLeftOfDoor) {
characterOffsetX *= -1;
}
PlayerGameObject.transform.localPosition = new Vector3(connectedDoorPosition.x + characterOffsetX, connectedDoorPosition.y, 0);
}
// assumes that a valid ID is provided, if not bad things will happen
// TODO how can this be done safer, or throw an error if no room is found with the given ID?
GameObject GetRoomPrefabById(int id) {
// loop through all the room prefabs
foreach(GameObject room in RoomPrefabs) {
if(room.GetComponent<RoomDetails>().Id == id) {
return room;
}
}
return new GameObject();
}
// assumes that a valid ID is provided, if not bad things will happen
// TODO how can this be done safer, or throw an error if no room is found with the given ID?
// TODO perhaps change roomDetail's Door array into an array of DoorDetails rather than GameObjects
Vector3 GetDoorPosition(int doorId) {
Vector3 doorPosition = Vector3.zero;
foreach(GameObject door in activeRoomPrefab.GetComponent<RoomDetails>().Doors) {
if(door.GetComponent<DoorDetails>().Id == doorId) {
doorPosition = door.transform.position;
}
}
return doorPosition;
}
bool isDoorOnRight(Vector3 doorPosition) {
if(doorPosition.x > 0) {
return true;
}
return false;
}
}
| mit | C# |
9c46592e0e45279e4a92d4f9b415b61b17510787 | Move collection change event binding to LoadComplete | ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game/Graphics/Containers/OsuRearrangeableListContainer.cs | osu.Game/Graphics/Containers/OsuRearrangeableListContainer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Specialized;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
namespace osu.Game.Graphics.Containers
{
public abstract class OsuRearrangeableListContainer<TModel> : RearrangeableListContainer<TModel>
{
/// <summary>
/// Whether any item is currently being dragged. Used to hide other items' drag handles.
/// </summary>
protected readonly BindableBool DragActive = new BindableBool();
protected override ScrollContainer<Drawable> CreateScrollContainer() => new OsuScrollContainer();
private Sample sampleSwap;
private double sampleLastPlaybackTime;
protected sealed override RearrangeableListItem<TModel> CreateDrawable(TModel item) => CreateOsuDrawable(item).With(d =>
{
d.DragActive.BindTo(DragActive);
});
protected abstract OsuRearrangeableListItem<TModel> CreateOsuDrawable(TModel item);
protected override void LoadComplete()
{
base.LoadComplete();
Items.CollectionChanged += (_, args) =>
{
if (args.Action == NotifyCollectionChangedAction.Move)
playSwapSample();
};
}
private void playSwapSample()
{
if (Time.Current - sampleLastPlaybackTime <= 35)
return;
var channel = sampleSwap?.GetChannel();
if (channel == null)
return;
channel.Frequency.Value = 0.96 + RNG.NextDouble(0.08);
channel.Play();
sampleLastPlaybackTime = Time.Current;
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleSwap = audio.Samples.Get(@"UI/item-swap");
sampleLastPlaybackTime = Time.Current;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Specialized;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
namespace osu.Game.Graphics.Containers
{
public abstract class OsuRearrangeableListContainer<TModel> : RearrangeableListContainer<TModel>
{
/// <summary>
/// Whether any item is currently being dragged. Used to hide other items' drag handles.
/// </summary>
protected readonly BindableBool DragActive = new BindableBool();
protected override ScrollContainer<Drawable> CreateScrollContainer() => new OsuScrollContainer();
private Sample sampleSwap;
private double sampleLastPlaybackTime;
protected sealed override RearrangeableListItem<TModel> CreateDrawable(TModel item) => CreateOsuDrawable(item).With(d =>
{
d.DragActive.BindTo(DragActive);
});
protected abstract OsuRearrangeableListItem<TModel> CreateOsuDrawable(TModel item);
protected OsuRearrangeableListContainer()
{
Items.CollectionChanged += (_, args) =>
{
if (args.Action == NotifyCollectionChangedAction.Move)
playSwapSample();
};
}
private void playSwapSample()
{
if (Time.Current - sampleLastPlaybackTime <= 35)
return;
var channel = sampleSwap?.GetChannel();
if (channel == null)
return;
channel.Frequency.Value = 0.96 + RNG.NextDouble(0.08);
channel.Play();
sampleLastPlaybackTime = Time.Current;
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleSwap = audio.Samples.Get(@"UI/item-swap");
sampleLastPlaybackTime = Time.Current;
}
}
}
| mit | C# |
0a23d1634de7196e9b92de3f9295a50f61c5de4b | Change the actual versions allowed to connect, which is different from the interface major version | TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,TomDataworks/opensim,RavenB/opensim,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC | OpenSim/Server/Base/ProtocolVersions.cs | OpenSim/Server/Base/ProtocolVersions.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace OpenSim.Server.Base
{
public class ProtocolVersions
{
/// <value>
/// This is the external protocol versions. It is separate from the OpenSimulator project version.
///
/// These version numbers should be increased by 1 every time a code
/// change in the Service.Connectors and Server.Handlers, espectively,
/// makes the previous OpenSimulator revision incompatible
/// with the new revision.
///
/// Changes which are compatible with an older revision (e.g. older revisions experience degraded functionality
/// but not outright failure) do not need a version number increment.
///
/// Having this version number allows the grid service to reject connections from regions running a version
/// of the code that is too old.
///
/// </value>
// The range of acceptable servers for client-side connectors
public readonly static int ClientProtocolVersionMin = 1;
public readonly static int ClientProtocolVersionMax = 1;
// The range of acceptable clients in server-side handlers
public readonly static int ServerProtocolVersionMin = 1;
public readonly static int ServerProtocolVersionMax = 1;
}
}
| /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace OpenSim.Server.Base
{
public class ProtocolVersions
{
/// <value>
/// This is the external protocol versions. It is separate from the OpenSimulator project version.
///
/// These version numbers should be increased by 1 every time a code
/// change in the Service.Connectors and Server.Handlers, espectively,
/// makes the previous OpenSimulator revision incompatible
/// with the new revision.
///
/// Changes which are compatible with an older revision (e.g. older revisions experience degraded functionality
/// but not outright failure) do not need a version number increment.
///
/// Having this version number allows the grid service to reject connections from regions running a version
/// of the code that is too old.
///
/// </value>
// The range of acceptable servers for client-side connectors
public readonly static int ClientProtocolVersionMin = 0;
public readonly static int ClientProtocolVersionMax = 0;
// The range of acceptable clients in server-side handlers
public readonly static int ServerProtocolVersionMin = 0;
public readonly static int ServerProtocolVersionMax = 0;
}
}
| bsd-3-clause | C# |
3f534e72f2fd0a604fb8034ebb74fa9317e54c87 | Set decimal separator by culture | sqlkata/querybuilder | QueryBuilder.Tests/ParameterTypeTest.cs | QueryBuilder.Tests/ParameterTypeTest.cs | using System;
using System.Collections.Generic;
using SqlKata.Execution;
using SqlKata;
using SqlKata.Compilers;
using Xunit;
using System.Collections;
public enum EnumExample
{
First,
Second,
Third,
}
public class ParameterTypeTest
{
private readonly Compiler pgsql;
private readonly MySqlCompiler mysql;
private readonly FirebirdCompiler fbsql;
public SqlServerCompiler mssql { get; private set; }
public ParameterTypeTest()
{
mssql = new SqlServerCompiler();
mysql = new MySqlCompiler();
pgsql = new PostgresCompiler();
fbsql = new FirebirdCompiler();
}
private string[] Compile(Query q)
{
return new[] {
mssql.Compile(q.Clone()).ToString(),
mysql.Compile(q.Clone()).ToString(),
pgsql.Compile(q.Clone()).ToString(),
fbsql.Compile(q.Clone()).ToString(),
};
}
public class ParameterTypeGenerator : IEnumerable<object[]>
{
private readonly List<object[]> _data = new List<object[]>
{
new object[] {"1", 1},
new object[] {Convert.ToSingle("10.5", CultureInfo.InvariantCulture).ToString(), 10.5},
new object[] {"-2", -2},
new object[] {Convert.ToSingle("-2.8", CultureInfo.InvariantCulture).ToString(), -2.8},
new object[] {"true", true},
new object[] {"false", false},
new object[] {"'2018-10-28 19:22:00'", new DateTime(2018, 10, 28, 19, 22, 0)},
new object[] {"0 /* First */", EnumExample.First},
new object[] {"1 /* Second */", EnumExample.Second},
new object[] {"'a string'", "a string"},
};
public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
[Theory]
[ClassData(typeof(ParameterTypeGenerator))]
public void CorrectParameterTypeOutput(string rendered, object input)
{
var query = new Query("Table").Where("Col", input);
var c = Compile(query);
Assert.Equal($"SELECT * FROM [Table] WHERE [Col] = {rendered}", c[0]);
}
}
| using System;
using System.Collections.Generic;
using SqlKata.Execution;
using SqlKata;
using SqlKata.Compilers;
using Xunit;
using System.Collections;
public enum EnumExample
{
First,
Second,
Third,
}
public class ParameterTypeTest
{
private readonly Compiler pgsql;
private readonly MySqlCompiler mysql;
private readonly FirebirdCompiler fbsql;
public SqlServerCompiler mssql { get; private set; }
public ParameterTypeTest()
{
mssql = new SqlServerCompiler();
mysql = new MySqlCompiler();
pgsql = new PostgresCompiler();
fbsql = new FirebirdCompiler();
}
private string[] Compile(Query q)
{
return new[] {
mssql.Compile(q.Clone()).ToString(),
mysql.Compile(q.Clone()).ToString(),
pgsql.Compile(q.Clone()).ToString(),
fbsql.Compile(q.Clone()).ToString(),
};
}
public class ParameterTypeGenerator : IEnumerable<object[]>
{
private readonly List<object[]> _data = new List<object[]>
{
new object[] {"1", 1},
new object[] {"10.5", 10.5},
new object[] {"-2", -2},
new object[] {"-2.8", -2.8},
new object[] {"true", true},
new object[] {"false", false},
new object[] {"'2018-10-28 19:22:00'", new DateTime(2018, 10, 28, 19, 22, 0)},
new object[] {"0 /* First */", EnumExample.First},
new object[] {"1 /* Second */", EnumExample.Second},
new object[] {"'a string'", "a string"},
};
public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
[Theory]
[ClassData(typeof(ParameterTypeGenerator))]
public void CorrectParameterTypeOutput(string rendered, object input)
{
var query = new Query("Table").Where("Col", input);
var c = Compile(query);
Assert.Equal($"SELECT * FROM [Table] WHERE [Col] = {rendered}", c[0]);
}
}
| mit | C# |
1f1cdc73ee989c891756ce6b4e8bb7b5215c55de | Update AssemblyInfo.cs | ipjohnson/Grace | Source/Grace/Properties/AssemblyInfo.cs | Source/Grace/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// 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("Grace")]
[assembly: AssemblyDescription("Grace is a portable class library that contains a feature rich Dependency Injection Container and other services")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ian Johnson")]
[assembly: AssemblyProduct("Grace")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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: AssemblyInformationalVersion("1.0.0.0")]
| using System.Reflection;
using System.Resources;
// 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("Grace")]
[assembly: AssemblyDescription("Grace is a portable class library that contains a feature rich Dependency Injection Container and other services")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ian Johnson")]
[assembly: AssemblyProduct("Grace")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")] | mit | C# |
2872adabe6295d78b10ec569191028f5a9a8b646 | bump version of windows desktop app | PapaMufflon/StandUpTimer,PapaMufflon/StandUpTimer,PapaMufflon/StandUpTimer | StandUpTimer/Properties/AssemblyInfo.cs | StandUpTimer/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("0.7.1")]
[assembly: AssemblyFileVersion("0.7.1")]
[assembly: InternalsVisibleTo("StandUpTimer.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("0.7.0")]
[assembly: AssemblyFileVersion("0.7.0")]
[assembly: InternalsVisibleTo("StandUpTimer.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | mit | C# |
8eccfa476cbbff5a3e6ceb1e0cef9b2c0e74a683 | Add loading states | ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu | osu.Game/Online/RealtimeMultiplayer/MultiplayerUserState.cs | osu.Game/Online/RealtimeMultiplayer/MultiplayerUserState.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.RealtimeMultiplayer
{
public enum MultiplayerUserState
{
Idle,
Ready,
WaitingForLoad,
Loaded,
Playing,
Results,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Online.RealtimeMultiplayer
{
public enum MultiplayerUserState
{
Idle,
Ready,
Playing,
Results,
}
}
| mit | C# |
ccd9726170370faa0a0dd531fdcb6949ef59f4ba | Fix settings not saving when opening "Options" | danielchalmers/SteamAccountSwitcher | SteamAccountSwitcher/Options.xaml.cs | SteamAccountSwitcher/Options.xaml.cs | #region
using System.Windows;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for Options.xaml
/// </summary>
public partial class Options : Window
{
public Options()
{
InitializeComponent();
Settings.Default.Save();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Save();
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Reload();
DialogResult = true;
}
}
} | #region
using System.Windows;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
/// <summary>
/// Interaction logic for Options.xaml
/// </summary>
public partial class Options : Window
{
public Options()
{
InitializeComponent();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Save();
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Reload();
DialogResult = true;
}
}
} | mit | C# |
25a5cbc9e03fdd64bc1103c773d6ca83ff2981ae | Update Userlist.cs | stanriders/den0bot,stanriders/den0bot | den0bot/Userlist.cs | den0bot/Userlist.cs |
namespace den0bot
{
public enum Users
{
// User(Nickname, osuID)
[User("Фаердиггер", 5292815)]
Digger = 0,
[User("Веточка", 5100305)]
Vetochka = 1,
[User("Шоквейв", 2295157)]
Shockwave = 2,
[User("Амати", 5291370)]
Amaty = 3,
[User("Динозавр", 5385151)]
Denosaur = 4,
[User("Жаба", 6068934)]
Frog = 5,
[User("Оринель", 7589924)]
Orinel = 6,
[User("Сони", 5483135)]
Sony = 7,
[User("Тудути", 5651245)]
Tduty = 8,
[User("Стен", 7217455)]
Stan = 9,
[User("Шладик", 6393126)]
Wlad = 10,
[User("Егорыч", 6468387)]
Egor = 11,
[User("Панда", 5410993)]
Panda = 12,
[User("Ромачка", 5675579)]
Roma = 13,
[User("Куги", 6997572)]
Kugi = 14,
[User("Рефлекс", 5260387)]
Reflex = 15,
[User("Ельцин", 5217336)]
Qwerty = 16,
[User("Жека", 4880222)]
Emabb = 17,
[User("ккк", 4735736)]
Kkk = 18,
[User("Кирюша", 2746956)]
Railgun = 19,
UserCount = 20
}
}
|
namespace den0bot
{
public enum Users
{
// User(Nickname, osuID)
[User("Фаердиггер", 5292815)]
Digger = 0,
[User("Веточка", 5100305)]
Vetochka = 1,
[User("Шоквейв", 2295157)]
Shockwave = 2,
[User("Амати", 5291370)]
Amaty = 3,
[User("Динозавр", 5385151)]
Denosaur = 4,
[User("Жаба", 6068934)]
Frog = 5,
[User("Оринель", 7589924)]
Orinel = 6,
[User("Сони", 5483135)]
Sony = 7,
[User("Тудути", 5651245)]
Tduty = 8,
[User("Стен", 7217455)]
Stan = 9,
[User("Шладик", 6393126)]
Wlad = 10,
[User("Егорыч", 6468387)]
Egor = 11,
[User("Панда", 5410993)]
Panda = 12,
[User("Ромачка", 5675579)]
Roma = 13,
[User("Куги", 6997572)]
Kugi = 14,
[User("Рефлекс", 5260387)]
Reflex = 15,
[User("Ельцин", 5217336)]
Qwerty = 16,
[User("Жека", 4880222)]
Emabb = 17,
[User("ккк", 4735736)]
Kkk = 18,
UserCount = 19
}
}
| mit | C# |
7b2b29d7a86b8cd5ee96375b99b8d81a86280bca | Change recommended TFMs from netcore to win. | StephenCleary/PortableLibraryProfiles | src/FrameworkProfiles/NugetTargets.cs | src/FrameworkProfiles/NugetTargets.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
namespace FrameworkProfiles
{
public static class NugetTargets
{
// https://github.com/NuGet/NuGet3/blob/dev/src/NuGet.Frameworks/FrameworkConstants.cs
// https://github.com/NuGet/NuGet3/blob/dev/src/NuGet.Frameworks/DefaultFrameworkMappings.cs
private static readonly Dictionary<FrameworkName, string> KnownNugetTargets = new Dictionary<FrameworkName, string>
{
{ new FrameworkName("Silverlight,Version=v4.0"), "sl40" },
{ new FrameworkName("Silverlight,Version=v5.0"), "sl50" },
{ new FrameworkName("Silverlight,Version=v4.0,Profile=WindowsPhone*"), "wp70" },
{ new FrameworkName("Silverlight,Version=v4.0,Profile=WindowsPhone7*"), "wp71" },
// Prefer "win" TFMs to reduce confusion with the new .NET Core (which has nothing to do with the netcore TFM).
{ new FrameworkName(".NETCore,Version=v4.5,Profile=*"), "win8" },
{ new FrameworkName(".NETCore,Version=v4.5.1,Profile=*"), "win81" },
};
private static readonly Dictionary<string, string> KnownNugetPlatforms = new Dictionary<string, string>
{
{ ".NETFramework", "net" },
{ "WindowsPhone", "wp" },
{ "WindowsPhoneApp", "wpa" },
{ "MonoAndroid", "monoandroid" },
{ "MonoTouch", "monotouch" },
{ "Xamarin.iOS", "xamarinios" },
};
public static string GetNugetTarget(FrameworkProfile profile)
{
string result;
if (KnownNugetTargets.TryGetValue(profile.Name, out result))
return result;
string platform;
if (!KnownNugetPlatforms.TryGetValue(profile.Name.Identifier, out platform))
return string.Empty;
var version = profile.Name.Version.ToString();
while (version.EndsWith(".0"))
version = version.Substring(0, version.Length - 2);
// This is dangerous if any version number goes >= 10, but hey, that's NuGet's problem...
return platform + version.Replace(".", string.Empty);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
namespace FrameworkProfiles
{
public static class NugetTargets
{
// https://github.com/NuGet/NuGet3/blob/dev/src/NuGet.Frameworks/FrameworkConstants.cs
// https://github.com/NuGet/NuGet3/blob/dev/src/NuGet.Frameworks/DefaultFrameworkMappings.cs
private static readonly Dictionary<FrameworkName, string> KnownNugetTargets = new Dictionary<FrameworkName, string>
{
{ new FrameworkName("Silverlight,Version=v4.0"), "sl40" },
{ new FrameworkName("Silverlight,Version=v5.0"), "sl50" },
{ new FrameworkName("Silverlight,Version=v4.0,Profile=WindowsPhone*"), "wp70" },
{ new FrameworkName("Silverlight,Version=v4.0,Profile=WindowsPhone7*"), "wp71" },
};
private static readonly Dictionary<string, string> KnownNugetPlatforms = new Dictionary<string, string>
{
{ ".NETFramework", "net" },
{ "WindowsPhone", "wp" },
{ "WindowsPhoneApp", "wpa" },
{ ".NETCore", "netcore" },
{ "MonoAndroid", "monoandroid" },
{ "MonoTouch", "monotouch" },
{ "Xamarin.iOS", "xamarinios" },
{ "DNXcore", "dnxcore" }
};
public static string GetNugetTarget(FrameworkProfile profile)
{
string result;
if (KnownNugetTargets.TryGetValue(profile.Name, out result))
return result;
string platform;
if (!KnownNugetPlatforms.TryGetValue(profile.Name.Identifier, out platform))
return string.Empty;
var version = profile.Name.Version.ToString();
while (version.EndsWith(".0"))
version = version.Substring(0, version.Length - 2);
// This is dangerous if any version number goes >= 10, but hey, that's NuGet's problem...
return platform + version.Replace(".", string.Empty);
}
}
}
| mit | C# |
6d33a867a82ca8811a562ee4c59804bdb8ddee03 | Add tests for null checking | inputfalken/Sharpy | Tests/GeneratorAPI/GeneratorTests.cs | Tests/GeneratorAPI/GeneratorTests.cs | using System;
using GeneratorAPI;
using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Tests.GeneratorAPI {
[TestFixture]
internal class GeneratorTests {
[SetUp]
public void Initiate() {
_generator = new Generator<Randomizer>(new Randomizer(Seed));
}
[TearDown]
public void Dispose() {
_generator = null;
}
private Generator<Randomizer> _generator;
private const int Seed = 100;
[Test(
Author = "Robert",
Description = "Check that constructor throws exception if argument is null"
)]
public void Constructor_Null_Argument() {
Assert.Throws<ArgumentNullException>(() => new Generator<Randomizer>(null));
}
[Test(
Author = "Robert",
Description = "Checks that the result from Generate is not null"
)]
public void Generate_Does_Not_Return_With_Valid_Arg() {
var result = _generator.Generate(randomizer => randomizer.GetString());
Assert.IsNotNull(result);
}
[Test(
Author = "Robert",
Description = "Checks that an exception is thrown when generate argument is null"
)]
public void Generate_With_Null() {
Assert.Throws<ArgumentNullException>(() => _generator.Generate<string>(randomizer => null));
}
[Test(
Author = "Robert",
Description = "Checks that provider is assigned in the constructor."
)]
public void Provider_Is_not_Null() {
var result = _generator.Provider;
Assert.IsNotNull(result);
}
}
} | using GeneratorAPI;
using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Tests.GeneratorAPI {
[TestFixture]
internal class GeneratorTests {
[SetUp]
public void Initiate() {
_generator = new Generator<Randomizer>(new Randomizer(Seed));
}
[TearDown]
public void Dispose() {
_generator = null;
}
private Generator<Randomizer> _generator;
private const int Seed = 100;
[Test(
Author = "Robert",
Description = "Checks that the result from Generate is not null"
)]
public void Test() {
var result = _generator.Generate(randomizer => randomizer.GetString());
Assert.IsNotNull(result);
}
[Test(
Author = "Robert",
Description = "Checks that provider is assigned in the constructor."
)]
public void Test_Provider_Is_not_Null() {
Assert.IsNotNull(_generator);
}
}
} | mit | C# |
17813488ab82396c1dbf7c2b456a80e0a0a524b1 | Change view for android | wcoder/MvvmCrossStarterKit | src/Mobile.Android/Views/FirstView.cs | src/Mobile.Android/Views/FirstView.cs | using Android.App;
using Cirrious.MvvmCross.Droid.Views;
using Mobile.Core.ViewModels;
namespace Mobile.Android.Views
{
[Activity]
public class FirstView : MvxActivity<FirstViewModel>
{
protected override void OnViewModelSet()
{
base.OnViewModelSet();
SetContentView(Resource.Layout.FirstView);
}
}
} | using Android.App;
using Android.OS;
using Cirrious.MvvmCross.Droid.Views;
using Mobile.Core.ViewModels;
namespace Mobile.Android.Views
{
[Activity(Label = "View for FirstViewModel")]
public class FirstView : MvxActivity<FirstViewModel>
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.FirstView);
}
}
} | mit | C# |
120ff5cc3cc8804979f702c75c0deefb0e4708b7 | 删除用户状态枚举中的“Suspended”条目。 :sushi: | Zongsoft/Zongsoft.CoreLibrary | src/Security/Membership/UserStatus.cs | src/Security/Membership/UserStatus.cs | /*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2003-2016 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.ComponentModel;
namespace Zongsoft.Security.Membership
{
/// <summary>
/// 表示用户状态的枚举。
/// </summary>
public enum UserStatus : byte
{
/// <summary>正常可用</summary>
Active = 0,
/// <summary>待审核</summary>
Unapproved,
/// <summary>已停用</summary>
Disabled,
}
}
| /*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2003-2016 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.ComponentModel;
namespace Zongsoft.Security.Membership
{
/// <summary>
/// 表示用户状态的枚举。
/// </summary>
public enum UserStatus : byte
{
/// <summary>正常可用</summary>
Active = 0,
/// <summary>待审核</summary>
Unapproved,
/// <summary>已停用</summary>
Disabled,
/// <summary>被挂起,特指密码验证失败超过特定次数。</summary>
Suspended,
}
}
| lgpl-2.1 | C# |
ca681d8c795ac9ccac2767df81887e94b3027296 | Test Team Foundation Service | bbenetskyy/WinParse | WinParse/WinParse.WinForms/Person.cs | WinParse/WinParse.WinForms/Person.cs | using System;
namespace WinParse.WinForms
{
internal class Person
{
private string firstName;
private string secondName;
private string comments;
public Person(string firstName, string secondName)
{
this.firstName = firstName;
this.secondName = secondName;
comments = String.Empty;
}
public Person(string firstName, string secondName, string comments)
: this(firstName, secondName)
{
this.comments = comments;
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string SecondName
{
get { return secondName; }
set { secondName = value; }
}
public string Comments
{
get { return comments; }
set { comments = value; }
}
}
} | using System;
namespace WinParse.WinForms
{
internal class Person
{
private string firstName;
private string secondName;
private string comments;
public Person(string firstName, string secondName)
{
this.firstName = firstName;
this.secondName = secondName;
comments = String.Empty;
}
public Person(string firstName, string secondName, string comments)
: this(firstName, secondName)
{
this.comments = comments;
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string SecondName
{
get { return secondName; }
set { secondName = value; }
}
public string Comments
{
get { return comments; }
set { comments = value; }
}
}
} | unlicense | C# |
eb6bd900f979502470bdc643bc80fdf41e5fff9b | Update Label.cs | vvoid-inc/VoidEngine,thakyZ/VoidEngine | VoidEngine/Label.cs | VoidEngine/Label.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace VoidEngine
{
/// <summary>
/// The Label class for the VoidEngine
/// </summary>
public class Label
{
protected string text;
protected SpriteFont texture;
protected Vector2 position;
/// <summary>
/// Creates the Label.
/// </summary>
/// <param name="text">The text that will be in the label.</param>
public Label(Vector2 position, SpriteFont texture, string text)
{
this.text = text;
this.texture = texture;
this.position = position;
}
public virtual void Update(GameTime gameTime, string text2)
{
text = text2;
}
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
Vector2 FontOrigin = texture.MeasureString(text) / 2;
// Draw the string
spriteBatch.DrawString(texture, text, position, Color.White, 0, new Vector2(0,0), 0.5f, SpriteEffects.None, 0.5f);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace VoidEngine
{
/// <summary>
/// The Label class for the VoidEngine
/// </summary>
public class Label
{
protected string text;
protected SpriteFont texture;
protected Vector2 position;
/// <summary>
/// Creates the Label.
/// </summary>
/// <param name="text">The text that will be in the label.</param>
public Label(Vector2 position, SpriteFont texture, string text)
{
this.text = text;
this.texture = texture;
this.position = position;
}
public virtual void Update(GameTime gameTime, string text)
{
this.text = text;
}
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
Vector2 FontOrigin = texture.MeasureString(text) / 2;
// Draw the string
spriteBatch.DrawString(texture, text, position, Color.White, 0, FontOrigin, 0.5f, SpriteEffects.None, 0.5f);
}
}
}
| mit | C# |
149ae66409a5b25342eb69c4594f7b796e9d86fd | Increment version number | R-Smith/vmPing | vmPing/Properties/AssemblyInfo.cs | vmPing/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("vmPing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("vmPing")]
[assembly: AssemblyCopyright("Copyright © 2019 Ryan Smith")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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.3.1.0")]
[assembly: AssemblyFileVersion("1.3.1.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("vmPing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("vmPing")]
[assembly: AssemblyCopyright("Copyright © 2019 Ryan Smith")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| mit | C# |
e6578d4c0f6b55ecb0ba949b42d3c4af2d260ca5 | Change API :'/api/v1/analysis/result' to 'api/v3/analysis/result' | Minjung-Baek/Dexter,KarolAntczak/Dexter,Minjung-Baek/Dexter,Samsung/Dexter,Minjung-Baek/Dexter,KarolAntczak/Dexter,Minjung-Baek/Dexter,KarolAntczak/Dexter,Samsung/Dexter,Minjung-Baek/Dexter,Samsung/Dexter,Minjung-Baek/Dexter,Samsung/Dexter,KarolAntczak/Dexter,KarolAntczak/Dexter,Minjung-Baek/Dexter,Minjung-Baek/Dexter,Samsung/Dexter,Samsung/Dexter,Minjung-Baek/Dexter,KarolAntczak/Dexter,Samsung/Dexter,KarolAntczak/Dexter,KarolAntczak/Dexter,Samsung/Dexter,Minjung-Baek/Dexter,KarolAntczak/Dexter,KarolAntczak/Dexter,Samsung/Dexter,Samsung/Dexter | project/dexter-vs/Dexter/Common/Core/Client/DexterClient.cs | project/dexter-vs/Dexter/Common/Core/Client/DexterClient.cs | using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using System.Diagnostics;
using Dexter.Common.Defect;
using System.Web;
using System.ComponentModel.Composition;
using System;
namespace Dexter.Common.Client
{
/// <summary>
/// Communicates with the dexter server
/// </summary>
public class DexterClient : IDexterClient
{
public static readonly string POST_ANALYSIS_RESULT_V3 = "/api/v3/analysis/result";
public static readonly string POST_SNAPSHOT_SOURCECODE = "/api/v1/analysis/snapshot/source";
public static readonly string POST_ACCOUNT_ADD_V1 = "/api/v1/accounts/add";
private readonly IHttpClient httpClient;
public DexterClient(IHttpClient httpClient)
{
this.httpClient = httpClient;
}
/// <summary>
/// Sends the source code with comments to the dexter server
/// </summary>
/// <param name="source">Source code with comments</param>
public async Task SendSourceCode(SourceCodeJsonFormat source)
{
HttpResponseMessage response = await httpClient.PostAsync(POST_SNAPSHOT_SOURCECODE,
JsonConvert.SerializeObject(source));
if (!response.IsSuccessStatusCode.Equals(true))
{
Debug.WriteLine(response, "Failed to SendSourceCode");
}
}
public async Task<HttpResponseMessage> SendAnalysisResult(DexterResult result)
{
var dexterResultString = JsonConvert.SerializeObject(result);
var dexterResultStringWrapped = JsonConvert.SerializeObject(new { result = dexterResultString });
return await httpClient.PostAsync(POST_ANALYSIS_RESULT_V3, dexterResultStringWrapped);
}
public async Task<HttpResponseMessage> AddAccount(string userName, string userPassword, bool isAdmin)
{
var queryParams = HttpUtility.ParseQueryString("");
queryParams.Add("userId", userName);
queryParams.Add("userId2", userPassword);
queryParams.Add("isAdmin", isAdmin.ToString());
return await httpClient.PostAsync($"{POST_ACCOUNT_ADD_V1}?{queryParams}","");
}
}
}
| using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using System.Diagnostics;
using Dexter.Common.Defect;
using System.Web;
using System.ComponentModel.Composition;
using System;
namespace Dexter.Common.Client
{
/// <summary>
/// Communicates with the dexter server
/// </summary>
public class DexterClient : IDexterClient
{
public static readonly string POST_ANALYSIS_RESULT_V3 = "/api/v1/analysis/result";
public static readonly string POST_SNAPSHOT_SOURCECODE = "/api/v1/analysis/snapshot/source";
public static readonly string POST_ACCOUNT_ADD_V1 = "/api/v1/accounts/add";
private readonly IHttpClient httpClient;
public DexterClient(IHttpClient httpClient)
{
this.httpClient = httpClient;
}
/// <summary>
/// Sends the source code with comments to the dexter server
/// </summary>
/// <param name="source">Source code with comments</param>
public async Task SendSourceCode(SourceCodeJsonFormat source)
{
HttpResponseMessage response = await httpClient.PostAsync(POST_SNAPSHOT_SOURCECODE,
JsonConvert.SerializeObject(source));
if (!response.IsSuccessStatusCode.Equals(true))
{
Debug.WriteLine(response, "Failed to SendSourceCode");
}
}
public async Task<HttpResponseMessage> SendAnalysisResult(DexterResult result)
{
var dexterResultString = JsonConvert.SerializeObject(result);
var dexterResultStringWrapped = JsonConvert.SerializeObject(new { result = dexterResultString });
return await httpClient.PostAsync(POST_ANALYSIS_RESULT_V3, dexterResultStringWrapped);
}
public async Task<HttpResponseMessage> AddAccount(string userName, string userPassword, bool isAdmin)
{
var queryParams = HttpUtility.ParseQueryString("");
queryParams.Add("userId", userName);
queryParams.Add("userId2", userPassword);
queryParams.Add("isAdmin", isAdmin.ToString());
return await httpClient.PostAsync($"{POST_ACCOUNT_ADD_V1}?{queryParams}","");
}
}
}
| bsd-2-clause | C# |
ef5704ab2f63d373ba53ab1895cae1b073027a51 | Fix empty alerts issue. | ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton | src/CK.Glouton.Server/Handlers/AlertHandlerConfiguration.cs | src/CK.Glouton.Server/Handlers/AlertHandlerConfiguration.cs | using CK.Glouton.Model.Server.Handlers;
using System.Collections.Generic;
namespace CK.Glouton.Server.Handlers
{
public class AlertHandlerConfiguration : IGloutonHandlerConfiguration
{
public List<IAlertExpressionModel> Alerts { get; set; }
public IGloutonHandlerConfiguration Clone()
{
return new AlertHandlerConfiguration
{
Alerts = Alerts
};
}
public AlertHandlerConfiguration()
{
Alerts = new List<IAlertExpressionModel>();
}
}
} | using CK.Glouton.Model.Server.Handlers;
using System.Collections.Generic;
namespace CK.Glouton.Server.Handlers
{
public class AlertHandlerConfiguration : IGloutonHandlerConfiguration
{
public List<IAlertExpressionModel> Alerts { get; set; }
public IGloutonHandlerConfiguration Clone()
{
return new AlertHandlerConfiguration
{
Alerts = Alerts
};
}
}
} | mit | C# |
1d55bf77bd2c11bec78bef2d2c7d8b895a3e7d66 | Update Path2DPathEffect.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.ViewModels/Style/PathEffects/Path2DPathEffect.cs | src/Draw2D.ViewModels/Style/PathEffects/Path2DPathEffect.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Draw2D.ViewModels.Style.PathEffects
{
[DataContract(IsReference = true)]
public class Path2DPathEffect : ViewModelBase, IPathEffect
{
private Matrix _matrix;
private string _path;
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public Matrix Matrix
{
get => _matrix;
set => Update(ref _matrix, value);
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public string Path
{
get => _path;
set => Update(ref _path, value);
}
public Path2DPathEffect()
{
}
public Path2DPathEffect(Matrix matrix, string path)
{
this.Matrix = matrix;
this.Path = path;
}
public static IPathEffect MakeTile()
{
// TODO:
var matrix = Matrix.MakeIdentity();
matrix.ScaleX = 30;
matrix.ScaleY = 30;
var path = "M-15 -15L15 -15L15 15L-15 15L-15 -15Z";
return new Path2DPathEffect(matrix, path) { Title = "2DPathTile" };
}
public object Copy(Dictionary<object, object> shared)
{
return new Path2DPathEffect()
{
Title = this.Title,
Matrix = (Matrix)this.Matrix.Copy(shared),
Path = this.Path
};
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Draw2D.ViewModels.Style.PathEffects
{
[DataContract(IsReference = true)]
public class Path2DPathEffect : ViewModelBase, IPathEffect
{
private Matrix _matrix;
private string _path;
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public Matrix Matrix
{
get => _matrix;
set => Update(ref _matrix, value);
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public string Path
{
get => _path;
set => Update(ref _path, value);
}
public Path2DPathEffect()
{
}
public Path2DPathEffect(Matrix matrix, string path)
{
this.Matrix = matrix;
this.Path = path;
}
public static IPathEffect MakeTile()
{
// TODO:
var matrix = Matrix.MakeIdentity();
var path = "";
return new Path2DPathEffect(matrix, path) { Title = "2DPathTile" };
}
public object Copy(Dictionary<object, object> shared)
{
return new Path2DPathEffect()
{
Title = this.Title,
Matrix = (Matrix)this.Matrix.Copy(shared),
Path = this.Path
};
}
}
}
| mit | C# |
619977a0e745a8d237bcccbe87b67db1d4875859 | Make sure metadata is set before being returned | Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype | src/Glimpse.Server/Configuration/DefaultMetadataProvider.cs | src/Glimpse.Server/Configuration/DefaultMetadataProvider.cs | using System.Collections.Generic;
using System.Linq;
using Glimpse.Server.Internal;
using Glimpse.Internal.Extensions;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse.Server.Configuration
{
public class DefaultMetadataProvider : IMetadataProvider
{
private readonly IResourceManager _resourceManager;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly GlimpseServerOptions _serverOptions;
private Metadata _metadata;
public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions)
{
_resourceManager = resourceManager;
_httpContextAccessor = httpContextAccessor;
_serverOptions = serverOptions.Value;
}
public Metadata BuildInstance()
{
if (_metadata != null)
return _metadata;
var request = _httpContextAccessor.HttpContext.Request;
var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/";
var resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}");
if (_serverOptions.OverrideResources != null)
_serverOptions.OverrideResources(resources);
_metadata = new Metadata(resources);
return _metadata;
}
}
} | using System.Collections.Generic;
using System.Linq;
using Glimpse.Server.Internal;
using Glimpse.Internal.Extensions;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.OptionsModel;
namespace Glimpse.Server.Configuration
{
public class DefaultMetadataProvider : IMetadataProvider
{
private readonly IResourceManager _resourceManager;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly GlimpseServerOptions _serverOptions;
private Metadata _metadata;
public DefaultMetadataProvider(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor, IOptions<GlimpseServerOptions> serverOptions)
{
_resourceManager = resourceManager;
_httpContextAccessor = httpContextAccessor;
_serverOptions = serverOptions.Value;
}
public Metadata BuildInstance()
{
if (_metadata != null)
return _metadata;
var request = _httpContextAccessor.HttpContext.Request;
var baseUrl = $"{request.Scheme}://{request.Host}/{_serverOptions.BasePath}/";
IDictionary<string, string> resources = _resourceManager.RegisteredUris.ToDictionary(kvp => kvp.Key.KebabCase(), kvp => $"{baseUrl}{kvp.Key}/{kvp.Value}");
if (_serverOptions.OverrideResources != null)
_serverOptions.OverrideResources(resources);
return new Metadata(resources);
}
}
} | mit | C# |
09a5cc9d7a17c1f6839467ab82b50eb70f2ac55a | Update IPathFigure.cs | wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D/Model/Path/IPathFigure.cs | src/Core2D/Model/Path/IPathFigure.cs | using System.Collections.Generic;
using System.Collections.Immutable;
using Core2D.Shapes;
namespace Core2D.Path
{
/// <summary>
/// Defines path figure contract.
/// </summary>
public interface IPathFigure : IObservableObject, IStringExporter
{
/// <summary>
/// Gets or sets start point.
/// </summary>
IPointShape StartPoint { get; set; }
/// <summary>
/// Gets or sets segments collection.
/// </summary>
ImmutableArray<IPathSegment> Segments { get; set; }
/// <summary>
/// Gets or sets flag indicating whether path is filled.
/// </summary>
bool IsFilled { get; set; }
/// <summary>
/// Gets or sets flag indicating whether path is closed.
/// </summary>
bool IsClosed { get; set; }
/// <summary>
/// Get all points in the figure.
/// </summary>
/// <returns>All points in the figure.</returns>
IEnumerable<IPointShape> GetPoints();
}
}
| using System.Collections.Generic;
using System.Collections.Immutable;
using Core2D.Shapes;
namespace Core2D.Path
{
/// <summary>
/// Defines path figure contract.
/// </summary>
public interface IPathFigure : IObservableObject
{
/// <summary>
/// Gets or sets start point.
/// </summary>
IPointShape StartPoint { get; set; }
/// <summary>
/// Gets or sets segments collection.
/// </summary>
ImmutableArray<IPathSegment> Segments { get; set; }
/// <summary>
/// Gets or sets flag indicating whether path is filled.
/// </summary>
bool IsFilled { get; set; }
/// <summary>
/// Gets or sets flag indicating whether path is closed.
/// </summary>
bool IsClosed { get; set; }
/// <summary>
/// Get all points in the figure.
/// </summary>
/// <returns>All points in the figure.</returns>
IEnumerable<IPointShape> GetPoints();
}
}
| mit | C# |
0c179e388af79f8f3c4b7573456f1418410dc11f | Stop using RedirectUrl in test (#2527) | stripe/stripe-dotnet | src/StripeTests/Services/LoginLinks/LoginLinkServiceTest.cs | src/StripeTests/Services/LoginLinks/LoginLinkServiceTest.cs | namespace StripeTests
{
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Stripe;
using Xunit;
public class LoginLinkServiceTest : BaseStripeTest
{
private const string AccountId = "acct_123";
private readonly LoginLinkService service;
private readonly LoginLinkCreateOptions createOptions;
public LoginLinkServiceTest(
StripeMockFixture stripeMockFixture,
MockHttpClientFixture mockHttpClientFixture)
: base(stripeMockFixture, mockHttpClientFixture)
{
this.service = new LoginLinkService(this.StripeClient);
this.createOptions = new LoginLinkCreateOptions();
}
[Fact]
public void Create()
{
var loginLink = this.service.Create(AccountId, this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123/login_links");
Assert.NotNull(loginLink);
Assert.Equal("login_link", loginLink.Object);
}
[Fact]
public async Task CreateAsync()
{
var loginLink = await this.service.CreateAsync(AccountId, this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123/login_links");
Assert.NotNull(loginLink);
Assert.Equal("login_link", loginLink.Object);
}
}
}
| namespace StripeTests
{
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Stripe;
using Xunit;
public class LoginLinkServiceTest : BaseStripeTest
{
private const string AccountId = "acct_123";
private readonly LoginLinkService service;
private readonly LoginLinkCreateOptions createOptions;
public LoginLinkServiceTest(
StripeMockFixture stripeMockFixture,
MockHttpClientFixture mockHttpClientFixture)
: base(stripeMockFixture, mockHttpClientFixture)
{
this.service = new LoginLinkService(this.StripeClient);
this.createOptions = new LoginLinkCreateOptions
{
RedirectUrl = "https://stripe.com/redirect?param=value",
};
}
[Fact]
public void Create()
{
var loginLink = this.service.Create(AccountId, this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123/login_links");
Assert.NotNull(loginLink);
Assert.Equal("login_link", loginLink.Object);
}
[Fact]
public async Task CreateAsync()
{
var loginLink = await this.service.CreateAsync(AccountId, this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/accounts/acct_123/login_links");
Assert.NotNull(loginLink);
Assert.Equal("login_link", loginLink.Object);
}
}
}
| apache-2.0 | C# |
07113b8f78bab3e72fe3d5d7ff755df824c9b286 | Update Program.cs | ThomasKV/GitTest1 | ConsoleApp1/ConsoleApp1/Program.cs | ConsoleApp1/ConsoleApp1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// This remark was inserted using GitHub
// Another remark inserted using GitHub
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// This remark was inserted using GitHub
}
}
}
| mit | C# |
bd9fb6c689cfa71e59960f5892ed8ce261d3a557 | Fix CategoryDiscoverer first-chance exception while debugging (#5710) | sergeybykov/orleans,hoopsomuah/orleans,waynemunro/orleans,amccool/orleans,ElanHasson/orleans,hoopsomuah/orleans,jason-bragg/orleans,galvesribeiro/orleans,waynemunro/orleans,amccool/orleans,benjaminpetit/orleans,yevhen/orleans,ElanHasson/orleans,ibondy/orleans,dotnet/orleans,dotnet/orleans,ibondy/orleans,amccool/orleans,galvesribeiro/orleans,yevhen/orleans,jthelin/orleans,veikkoeeva/orleans,sergeybykov/orleans,ReubenBond/orleans | test/TestInfrastructure/TestExtensions/TestCategory.cs | test/TestInfrastructure/TestExtensions/TestCategory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Xunit.Abstractions;
using Xunit.Sdk;
/// <summary>
/// This is a replacement for the MSTest [TestCategoryAttribute] on xunit
/// xunit does not have the concept of Category for tests and instead, the have [TraitAttribute(string key, string value)]
/// If we replace the MSTest [TestCategoryAttribute] for the [Trait("Category", "BVT")], we will surely fall at some time in cases
/// where people will typo on the "Category" key part of the Trait.
/// On order to achieve the same behaviour as on MSTest, a custom [TestCategory] was created
/// to mimic the MSTest one and avoid replace it on every existing test.
/// The tests can be filtered by xunit runners by usage of "-trait" on the command line with the expression like
/// <code>-trait "Category=BVT"</code> for example that will only run the tests with [TestCategory("BVT")] on it.
/// More on Trait extensibility <see href="https://github.com/xunit/samples.xunit/tree/master/TraitExtensibility" />
/// </summary>
[TraitDiscoverer("CategoryDiscoverer", "TestExtensions")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class TestCategoryAttribute : Attribute, ITraitAttribute
{
public TestCategoryAttribute(string category) { }
}
public class CategoryDiscoverer : ITraitDiscoverer
{
public CategoryDiscoverer(IMessageSink diagnosticMessageSink)
{
}
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
var ctorArgs = traitAttribute.GetConstructorArguments().ToList();
yield return new KeyValuePair<string, string>("Category", ctorArgs[0].ToString());
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Xunit.Abstractions;
using Xunit.Sdk;
/// <summary>
/// This is a replacement for the MSTest [TestCategoryAttribute] on xunit
/// xunit does not have the concept of Category for tests and instead, the have [TraitAttribute(string key, string value)]
/// If we replace the MSTest [TestCategoryAttribute] for the [Trait("Category", "BVT")], we will surely fall at some time in cases
/// where people will typo on the "Category" key part of the Trait.
/// On order to achieve the same behaviour as on MSTest, a custom [TestCategory] was created
/// to mimic the MSTest one and avoid replace it on every existing test.
/// The tests can be filtered by xunit runners by usage of "-trait" on the command line with the expression like
/// <code>-trait "Category=BVT"</code> for example that will only run the tests with [TestCategory("BVT")] on it.
/// More on Trait extensibility <see href="https://github.com/xunit/samples.xunit/tree/master/TraitExtensibility" />
/// </summary>
[TraitDiscoverer("CategoryDiscoverer", "TestExtensions")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class TestCategoryAttribute : Attribute, ITraitAttribute
{
public TestCategoryAttribute(string category) { }
}
public class CategoryDiscoverer : ITraitDiscoverer
{
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
var ctorArgs = traitAttribute.GetConstructorArguments().ToList();
yield return new KeyValuePair<string, string>("Category", ctorArgs[0].ToString());
}
}
| mit | C# |
9a73f3480df6a78d201ddb01d660179a135db0f3 | Remove unused using statements. | wangkanai/Detection | test/Wangkanai.Detection.Test/DetectionServiceTests.cs | test/Wangkanai.Detection.Test/DetectionServiceTests.cs |
using Microsoft.AspNetCore.Http;
using System;
using Xunit;
namespace Wangkanai.Detection.Test
{
public class DetectionServiceTests
{
[Fact]
public void Ctor_IServiceProvider_Success()
{
string userAgent = "Agent";
var context = new DefaultHttpContext();
context.Request.Headers["User-Agent"] = userAgent;
var serviceProvider = new ServiceProvider()
{
HttpContextAccessor = new HttpContextAccessor()
{
HttpContext = context
}
};
var detectionService = new DetectionService(serviceProvider);
Assert.NotNull(detectionService.Context);
Assert.NotNull(detectionService.UserAgent);
Assert.Equal(userAgent.ToLowerInvariant(), detectionService.UserAgent.ToString());
}
[Fact]
public void Ctor_Null_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DetectionService(null));
}
[Fact]
public void Ctor_HttpContextAccessorNotResolved_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => new DetectionService(new ServiceProvider()));
}
[Fact]
public void Ctor_HttpContextNull_ThrowsArgumentNullException()
{
var serviceProvider = new ServiceProvider()
{
HttpContextAccessor = new HttpContextAccessor()
};
Assert.Null(serviceProvider.HttpContextAccessor.HttpContext);
Assert.Throws<ArgumentNullException>(() => new DetectionService(serviceProvider));
}
private class ServiceProvider : IServiceProvider
{
public IHttpContextAccessor HttpContextAccessor { get; set; }
public object GetService(Type serviceType)
{
return this.HttpContextAccessor;
}
}
}
}
|
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using Xunit;
namespace Wangkanai.Detection.Test
{
public class DetectionServiceTests
{
[Fact]
public void Ctor_IServiceProvider_Success()
{
string userAgent = "Agent";
var context = new DefaultHttpContext();
context.Request.Headers["User-Agent"] = userAgent;
var serviceProvider = new ServiceProvider()
{
HttpContextAccessor = new HttpContextAccessor()
{
HttpContext = context
}
};
var detectionService = new DetectionService(serviceProvider);
Assert.NotNull(detectionService.Context);
Assert.NotNull(detectionService.UserAgent);
Assert.Equal(userAgent.ToLowerInvariant(), detectionService.UserAgent.ToString());
}
[Fact]
public void Ctor_Null_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DetectionService(null));
}
[Fact]
public void Ctor_HttpContextAccessorNotResolved_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => new DetectionService(new ServiceProvider()));
}
[Fact]
public void Ctor_HttpContextNull_ThrowsArgumentNullException()
{
var serviceProvider = new ServiceProvider()
{
HttpContextAccessor = new HttpContextAccessor()
};
Assert.Null(serviceProvider.HttpContextAccessor.HttpContext);
Assert.Throws<ArgumentNullException>(() => new DetectionService(serviceProvider));
}
private class ServiceProvider : IServiceProvider
{
public IHttpContextAccessor HttpContextAccessor { get; set; }
public object GetService(Type serviceType)
{
return this.HttpContextAccessor;
}
}
}
}
| apache-2.0 | C# |
494cacf300858a5894fbf18117677aba5557c030 | fix SetSelfModified | signumsoftware/framework,AlejandroCano/framework,avifatal/framework,AlejandroCano/framework,avifatal/framework,signumsoftware/framework | Signum.Entities/Modifiable.cs | Signum.Entities/Modifiable.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Utilities;
using System.Collections.ObjectModel;
using Signum.Utilities.DataStructures;
using Signum.Entities.Reflection;
namespace Signum.Entities
{
[Serializable]
public abstract class Modifiable
{
[Ignore]
ModifiedState modified;
[HiddenProperty]
public ModifiedState Modified
{
get { return modified; }
protected internal set
{
if (modified == ModifiedState.Sealed)
throw new InvalidOperationException("The instance {0} is sealed and can not be modified".Formato(this));
modified = value;
}
}
public void SetCleanModified(bool isSealed)
{
Modified = isSealed ? ModifiedState.Sealed : ModifiedState.Clean;
}
/// <summary>
/// True if SelfModified or (saving) and Modified
/// </summary>
[HiddenProperty]
public bool IsGraphModified
{
get { return Modified == ModifiedState.Modified || Modified == ModifiedState.SelfModified; }
}
protected internal virtual void SetSelfModified()
{
Modified = ModifiedState.SelfModified;
}
protected internal virtual void PreSaving(ref bool graphModified)
{
}
protected internal virtual void PostRetrieving()
{
}
}
public enum ModifiedState
{
SelfModified,
/// <summary>
/// Recursively Clean (only valid during saving)
/// </summary>
Clean,
/// <summary>
/// Recursively Modified (only valid during saving)
/// </summary>
Modified,
Sealed,
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Utilities;
using System.Collections.ObjectModel;
using Signum.Utilities.DataStructures;
using Signum.Entities.Reflection;
namespace Signum.Entities
{
[Serializable]
public abstract class Modifiable
{
[Ignore]
ModifiedState modified;
[HiddenProperty]
public ModifiedState Modified
{
get { return modified; }
protected internal set
{
if (modified == ModifiedState.Sealed)
throw new InvalidOperationException("The instance {0} is sealed and can not be modified".Formato(this));
modified = value;
}
}
public void SetCleanModified(bool isSealed)
{
Modified = isSealed ? ModifiedState.Sealed : ModifiedState.Clean;
}
/// <summary>
/// True if SelfModified or (saving) and Modified
/// </summary>
[HiddenProperty]
public bool IsGraphModified
{
get { return Modified == ModifiedState.Modified || Modified == ModifiedState.SelfModified; }
}
protected internal virtual void SetSelfModified()
{
modified = ModifiedState.SelfModified;
}
protected internal virtual void PreSaving(ref bool graphModified)
{
}
protected internal virtual void PostRetrieving()
{
}
}
public enum ModifiedState
{
SelfModified,
/// <summary>
/// Recursively Clean (only valid during saving)
/// </summary>
Clean,
/// <summary>
/// Recursively Modified (only valid during saving)
/// </summary>
Modified,
Sealed,
}
}
| mit | C# |
c740386f99bed0fb683ff810bd3b200ce50273cf | Add missing test for CSharp | emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata,emilybache/Parrot-Refactoring-Kata | CSharp/Parrot.Tests/ParrotTest.cs | CSharp/Parrot.Tests/ParrotTest.cs | using Xunit;
namespace Parrot.Tests
{
public class ParrotTest
{
[Fact]
public void GetSpeedNorwegianBlueParrot_nailed()
{
var parrot = new Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 0, true);
Assert.Equal(0.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedNorwegianBlueParrot_not_nailed()
{
var parrot = new Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 1.5, false);
Assert.Equal(18.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedNorwegianBlueParrot_not_nailed_high_voltage()
{
var parrot = new Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 4, false);
Assert.Equal(24.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedOfAfricanParrot_With_No_Coconuts()
{
var parrot = new Parrot(ParrotTypeEnum.AFRICAN, 0, 0, false);
Assert.Equal(12.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedOfAfricanParrot_With_One_Coconut()
{
var parrot = new Parrot(ParrotTypeEnum.AFRICAN, 1, 0, false);
Assert.Equal(3.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedOfAfricanParrot_With_Two_Coconuts()
{
var parrot = new Parrot(ParrotTypeEnum.AFRICAN, 2, 0, false);
Assert.Equal(0.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedOfEuropeanParrot()
{
var parrot = new Parrot(ParrotTypeEnum.EUROPEAN, 0, 0, false);
Assert.Equal(12.0, parrot.GetSpeed());
}
}
} | using Xunit;
namespace Parrot.Tests
{
public class ParrotTest
{
[Fact]
public void GetSpeedNorwegianBlueParrot_nailed()
{
var parrot = new Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 0, true);
Assert.Equal(0.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedNorwegianBlueParrot_not_nailed()
{
var parrot = new Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 1.5, false);
Assert.Equal(18.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedNorwegianBlueParrot_not_nailed_high_voltage()
{
var parrot = new Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 4, false);
}
[Fact]
public void GetSpeedOfAfricanParrot_With_No_Coconuts()
{
var parrot = new Parrot(ParrotTypeEnum.AFRICAN, 0, 0, false);
Assert.Equal(12.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedOfAfricanParrot_With_One_Coconut()
{
var parrot = new Parrot(ParrotTypeEnum.AFRICAN, 1, 0, false);
Assert.Equal(3.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedOfAfricanParrot_With_Two_Coconuts()
{
var parrot = new Parrot(ParrotTypeEnum.AFRICAN, 2, 0, false);
Assert.Equal(0.0, parrot.GetSpeed());
}
[Fact]
public void GetSpeedOfEuropeanParrot()
{
var parrot = new Parrot(ParrotTypeEnum.EUROPEAN, 0, 0, false);
Assert.Equal(12.0, parrot.GetSpeed());
}
}
} | mit | C# |
97674402f01eacf212621058d01c149a90f109f0 | Update wallet balance endpoint. | wranders/ESISharp | ESISharp/Path/Character/Wallet.cs | ESISharp/Path/Character/Wallet.cs | using ESISharp.Web;
namespace ESISharp.ESIPath.Character
{
/// <summary>Authenticated Character Wallet paths</summary>
public class CharacterWallet
{
protected ESIEve EasyObject;
internal CharacterWallet(ESIEve EasyEve)
{
EasyObject = EasyEve;
}
/// <summary>Get Character's wallet balance</summary>
/// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
/// <param name="CharacterID">(Int32) Character ID</param>
/// <returns>EsiRequest</returns>
public EsiRequest GetWalletBalance(int CharacterID)
{
var Path = $"/characters/{CharacterID.ToString()}/wallet/";
return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
}
}
}
| using ESISharp.Web;
namespace ESISharp.ESIPath.Character
{
/// <summary>Authenticated Character Wallet paths</summary>
public class CharacterWallet
{
protected ESIEve EasyObject;
internal CharacterWallet(ESIEve EasyEve)
{
EasyObject = EasyEve;
}
/// <summary>Get Character's wallets and balances</summary>
/// <remarks>Requires SSO Authentication, using "read_character_wallet" scope</remarks>
/// <param name="CharacterID">(Int32) Character ID</param>
/// <returns>EsiRequest</returns>
public EsiRequest GetWallets(int CharacterID)
{
var Path = $"/characters/{CharacterID.ToString()}/wallets/";
return new EsiRequest(EasyObject, Path, EsiWebMethod.AuthGet);
}
}
}
| mit | C# |
592b215474bd106c02ca78dff677f5cdc1404e58 | Mark the dictionary used to store _PlatformFolders readonly | ubisoftinc/Sharpmake,ubisoftinc/Sharpmake,ubisoftinc/Sharpmake | Sharpmake/MSBuildGlobalSettings.cs | Sharpmake/MSBuildGlobalSettings.cs | // Copyright (c) 2017 Ubisoft Entertainment
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
namespace Sharpmake
{
/// <summary>
/// This class contains some global msbuild settings
/// </summary>
public class MSBuildGlobalSettings
{
private static readonly ConcurrentDictionary<Tuple<DevEnv, Platform>, string> s_cppPlatformFolders = new ConcurrentDictionary<Tuple<DevEnv, Platform>, string>();
/// <summary>
/// Allows overwriting the MSBuild platform folder used for a given platform and Visual Studio version.
/// This is typically used if you want to put VS files in source control such as Perforce or nuget.
/// </summary>
/// <param name="devEnv">Visual studio version affected</param>
/// <param name="platform">Platform affected</param>
/// <returns></returns>
public static void SetCppPlatformFolder(DevEnv devEnv, Platform platform, string value)
{
Tuple<DevEnv, Platform> key = Tuple.Create(devEnv, platform);
if (!s_cppPlatformFolders.TryAdd(key, value))
throw new Error("You can't register more than once a platform folder for a specific combinaison. Key already registered: " + key.ToString());
}
/// <summary>
/// Get the overwritten MSBuild platform folder used for a given platform and Visual studio version.
/// This is typically used if you want to put your VS files in source control such as Perforce or nuget.
/// </summary>
/// <param name="devEnv">Visual studio version affected</param>
/// <param name="platform">Platform affected</param>
/// <returns>the registered msbuild foldervalue for the requested pair. null if not found</returns>
public static string GetCppPlatformFolder(DevEnv devEnv, Platform platform)
{
Tuple<DevEnv, Platform> key = Tuple.Create(devEnv, platform);
string value;
if (s_cppPlatformFolders.TryGetValue(key, out value))
return value;
return null; // No override found
}
}
} | // Copyright (c) 2017 Ubisoft Entertainment
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
namespace Sharpmake
{
/// <summary>
/// This class contains some global msbuild settings
/// </summary>
public class MSBuildGlobalSettings
{
private static ConcurrentDictionary<Tuple<DevEnv, Platform>, string> s_cppPlatformFolders = new ConcurrentDictionary<Tuple<DevEnv, Platform>, string>();
/// <summary>
/// Allows overwriting the MSBuild platform folder used for a given platform and Visual Studio version.
/// This is typically used if you want to put VS files in source control such as Perforce or nuget.
/// </summary>
/// <param name="devEnv">Visual studio version affected</param>
/// <param name="platform">Platform affected</param>
/// <returns></returns>
public static void SetCppPlatformFolder(DevEnv devEnv, Platform platform, string value)
{
Tuple<DevEnv, Platform> key = Tuple.Create(devEnv, platform);
if (!s_cppPlatformFolders.TryAdd(key, value))
throw new Error("You can't register more than once a platform folder for a specific combinaison. Key already registered: " + key.ToString());
}
/// <summary>
/// Get the overwritten MSBuild platform folder used for a given platform and Visual studio version.
/// This is typically used if you want to put your VS files in source control such as Perforce or nuget.
/// </summary>
/// <param name="devEnv">Visual studio version affected</param>
/// <param name="platform">Platform affected</param>
/// <returns>the registered msbuild foldervalue for the requested pair. null if not found</returns>
public static string GetCppPlatformFolder(DevEnv devEnv, Platform platform)
{
Tuple<DevEnv, Platform> key = Tuple.Create(devEnv, platform);
string value;
if (s_cppPlatformFolders.TryGetValue(key, out value))
return value;
return null; // No override found
}
}
} | apache-2.0 | C# |
4dc5902592d89872f37e98c8940864e87ffcf2f6 | Edit namespace | Vtek/Pulsar | Pulsar/Content/ContentResolver.cs | Pulsar/Content/ContentResolver.cs | /* License
*
* The MIT License (MIT)
*
* Copyright (c) 2014, Sylvain PONTOREAU (pontoreau.sylvain@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace Pulsar.Content
{
/// <summary>
/// Resolve a content type
/// </summary>
public abstract class ContentResolver
{
/// <summary>
/// The content manager
/// </summary>
protected internal ContentManager Content { get; internal set; }
/// <summary>
/// Load a content from a asset file name
/// </summary>
/// <param name="assetFileName">Asset name, relative to the loader root directory, and including the file extension.</param>
/// <returns>Return a object type corresponding</returns>
public abstract object Load(string assetFileName);
}
}
| /* License
*
* The MIT License (MIT)
*
* Copyright (c) 2014, Sylvain PONTOREAU (pontoreau.sylvain@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace Pulsar
{
/// <summary>
/// Resolve a content type
/// </summary>
public abstract class ContentResolver
{
/// <summary>
/// The content manager
/// </summary>
protected internal ContentManager Content { get; internal set; }
/// <summary>
/// Load a content from a asset file name
/// </summary>
/// <param name="assetFileName">Asset name, relative to the loader root directory, and including the file extension.</param>
/// <returns>Return a object type corresponding</returns>
public abstract object Load(string assetFileName);
}
}
| mit | C# |
958f1eda3efecf74386cc43d9e31b6113f4e1271 | Update IAzureTableStorageRepository.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/AzureStorage/IAzureTableStorageRepository.cs | TIKSN.Core/Data/AzureStorage/IAzureTableStorageRepository.cs | using Microsoft.Azure.Cosmos.Table;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.AzureStorage
{
public interface IAzureTableStorageRepository<T> where T : ITableEntity
{
Task AddAsync(T entity, CancellationToken cancellationToken);
Task AddOrMergeAsync(T entity, CancellationToken cancellationToken);
Task AddOrReplaceAsync(T entity, CancellationToken cancellationToken);
Task DeleteAsync(T entity, CancellationToken cancellationToken);
Task MergeAsync(T entity, CancellationToken cancellationToken);
Task ReplaceAsync(T entity, CancellationToken cancellationToken);
}
} | using Microsoft.WindowsAzure.Storage.Table;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.AzureStorage
{
public interface IAzureTableStorageRepository<T> where T : ITableEntity
{
Task AddAsync(T entity, CancellationToken cancellationToken);
Task AddOrMergeAsync(T entity, CancellationToken cancellationToken);
Task AddOrReplaceAsync(T entity, CancellationToken cancellationToken);
Task DeleteAsync(T entity, CancellationToken cancellationToken);
Task MergeAsync(T entity, CancellationToken cancellationToken);
Task ReplaceAsync(T entity, CancellationToken cancellationToken);
}
} | mit | C# |
9681f91fbdcbdec5752b66bdb0f6135dd6fee8d0 | upgrade version to 2.8.4 the main change is to fix an important issue #69 | tangxuehua/enode | src/ENode/Properties/AssemblyInfo.cs | src/ENode/Properties/AssemblyInfo.cs | 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("ENode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ENode")]
[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("bdf470ac-90a3-47cf-9032-a3f7a298a688")]
// 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("2.8.4")]
[assembly: AssemblyFileVersion("2.8.4")]
| 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("ENode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ENode")]
[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("bdf470ac-90a3-47cf-9032-a3f7a298a688")]
// 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("2.8.3")]
[assembly: AssemblyFileVersion("2.8.3")]
| mit | C# |
790fa0eae790d6aa328b89854476ee4da7788a7a | Remove unused usings. | Faithlife/Parsing | src/Faithlife.Parsing/Parser-Trim.cs | src/Faithlife.Parsing/Parser-Trim.cs | namespace Faithlife.Parsing
{
public static partial class Parser
{
/// <summary>
/// Succeeds if the specified parser also succeeds beforehand (ignoring its result).
/// </summary>
public static IParser<T> PrecededBy<T, U>(this IParser<T> parser, IParser<U> precededBy)
{
return precededBy.Then(_ => parser);
}
/// <summary>
/// Succeeds if the specified parser also succeeds afterward (ignoring its result).
/// </summary>
public static IParser<T> FollowedBy<T, U>(this IParser<T> parser, IParser<U> followedBy)
{
return parser.Then(followedBy.Success);
}
/// <summary>
/// Succeeds if the specified parsers succeed beforehand and afterward (ignoring their results).
/// </summary>
public static IParser<T> Bracketed<T, U, V>(this IParser<T> parser, IParser<U> precededBy, IParser<V> followedBy)
{
return parser.PrecededBy(precededBy).FollowedBy(followedBy);
}
/// <summary>
/// Succeeds if the specified parser succeeds, ignoring any whitespace characters beforehand.
/// </summary>
public static IParser<T> TrimStart<T>(this IParser<T> parser)
{
return parser.PrecededBy(WhiteSpace.Many());
}
/// <summary>
/// Succeeds if the specified parser succeeds, ignoring any whitespace characters afterward.
/// </summary>
public static IParser<T> TrimEnd<T>(this IParser<T> parser)
{
return parser.FollowedBy(WhiteSpace.Many());
}
/// <summary>
/// Succeeds if the specified parser succeeds, ignoring any whitespace characters beforehand or afterward.
/// </summary>
public static IParser<T> Trim<T>(this IParser<T> parser)
{
return parser.TrimStart().TrimEnd();
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace Faithlife.Parsing
{
public static partial class Parser
{
/// <summary>
/// Succeeds if the specified parser also succeeds beforehand (ignoring its result).
/// </summary>
public static IParser<T> PrecededBy<T, U>(this IParser<T> parser, IParser<U> precededBy)
{
return precededBy.Then(_ => parser);
}
/// <summary>
/// Succeeds if the specified parser also succeeds afterward (ignoring its result).
/// </summary>
public static IParser<T> FollowedBy<T, U>(this IParser<T> parser, IParser<U> followedBy)
{
return parser.Then(followedBy.Success);
}
/// <summary>
/// Succeeds if the specified parsers succeed beforehand and afterward (ignoring their results).
/// </summary>
public static IParser<T> Bracketed<T, U, V>(this IParser<T> parser, IParser<U> precededBy, IParser<V> followedBy)
{
return parser.PrecededBy(precededBy).FollowedBy(followedBy);
}
/// <summary>
/// Succeeds if the specified parser succeeds, ignoring any whitespace characters beforehand.
/// </summary>
public static IParser<T> TrimStart<T>(this IParser<T> parser)
{
return parser.PrecededBy(WhiteSpace.Many());
}
/// <summary>
/// Succeeds if the specified parser succeeds, ignoring any whitespace characters afterward.
/// </summary>
public static IParser<T> TrimEnd<T>(this IParser<T> parser)
{
return parser.FollowedBy(WhiteSpace.Many());
}
/// <summary>
/// Succeeds if the specified parser succeeds, ignoring any whitespace characters beforehand or afterward.
/// </summary>
public static IParser<T> Trim<T>(this IParser<T> parser)
{
return parser.TrimStart().TrimEnd();
}
}
}
| mit | C# |
c4698c409efa29d31d35446515b17c4a874dbc97 | Make Properties static | BYVoid/distribox | Distribox/Distribox.CommonLib/Properties.cs | Distribox/Distribox.CommonLib/Properties.cs | using System;
namespace Distribox.CommonLib
{
public static class Properties
{
public const string PathSep = "/";
public const string MetaFolder = ".Distribox";
public const string MetaFolderTmp = Properties.MetaFolder + Properties.PathSep + "tmp";
public const string MetaFolderData = Properties.MetaFolder + Properties.PathSep + "data";
public const string BundleFileExt = ".zip";
public const string DeltaFile = "Delta.txt";
public const string VersionListFile = "VersionList.txt";
public const string VersionListFilePath = Properties.MetaFolder + Properties.PathSep + Properties.VersionListFile;
public const string PeerListFile = "PeerList.json";
public const string PeerListFilePath = Properties.MetaFolder + Properties.PathSep + Properties.PeerListFile;
}
}
| using System;
namespace Distribox.CommonLib
{
public class Properties
{
public const string PathSep = "/";
public const string MetaFolder = ".Distribox";
public const string MetaFolderTmp = Properties.MetaFolder + Properties.PathSep + "tmp";
public const string MetaFolderData = Properties.MetaFolder + Properties.PathSep + "data";
public const string BundleFileExt = ".zip";
public const string DeltaFile = "Delta.txt";
public const string VersionListFile = "VersionList.txt";
public const string VersionListFilePath = Properties.MetaFolder + Properties.PathSep + Properties.VersionListFile;
public const string PeerListFile = "PeerList.json";
public const string PeerListFilePath = Properties.MetaFolder + Properties.PathSep + Properties.PeerListFile;
}
}
| mit | C# |
763955ff519a1f9bbcf4dfa9ede3aee21dc15ce0 | Add PointUtility.WithOffset | SaberSnail/GoldenAnvil.Utility | GoldenAnvil.Utility.Windows/PointUtility.cs | GoldenAnvil.Utility.Windows/PointUtility.cs | using System;
using System.Windows;
namespace GoldenAnvil.Utility.Windows
{
public static class PointUtility
{
public static Point WithOffset(this Point point, Point that)
{
return new Point(point.X + that.X, point.Y + that.Y);
}
public static double DistanceTo(this Point point, Point target)
{
var dx = point.X - target.X;
var dy = point.Y - target.Y;
return Math.Sqrt((dx * dx) + (dy * dy));
}
public static Vector VectorTo(this Point point, Point target)
{
return new Vector(target.X - point.X, target.Y - point.Y);
}
}
}
| using System;
using System.Windows;
namespace GoldenAnvil.Utility.Windows
{
public static class PointUtility
{
public static double DistanceTo(this Point point, Point target)
{
var dx = point.X - target.X;
var dy = point.Y - target.Y;
return Math.Sqrt((dx * dx) + (dy * dy));
}
public static Vector VectorTo(this Point point, Point target)
{
return new Vector(target.X - point.X, target.Y - point.Y);
}
}
}
| mit | C# |
90fdb46611e69f97f0e72690ab5749d353da3828 | Add test trying to recreate the issue | SolrNet/SolrNet,mausch/SolrNet,SolrNet/SolrNet,mausch/SolrNet,mausch/SolrNet | SolrNet.Cloud.Tests/UnityTests.cs | SolrNet.Cloud.Tests/UnityTests.cs | using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;
namespace SolrNet.Cloud.Tests
{
public class UnityTests
{
private IUnityContainer Setup() {
return new SolrNetContainerConfiguration().ConfigureContainer(
new FakeProvider(),
new UnityContainer());
}
[Fact]
public void ShouldResolveBasicOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveOperationsFromStartupContainer() {
Assert.NotNull(
Setup().Resolve<ISolrOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveIOperations ()
{
using (var container = new UnityContainer())
{
var cont = new Unity.SolrNetCloudIntegration.SolrNetContainerConfiguration().ConfigureContainer(new FakeProvider(), container);
var obj = cont.Resolve<ISolrOperations<Camera>>();
}
}
public class Camera
{
[Attributes.SolrField("Name")]
public string Name { get; set; }
[Attributes.SolrField("UID")]
public int UID { get; set; }
[Attributes.SolrField("id")]
public string Id { get; set; }
}
}
}
| using Xunit;
using Unity.SolrNetCloudIntegration;
using Unity;
namespace SolrNet.Cloud.Tests
{
public class UnityTests
{
private IUnityContainer Setup() {
return new SolrNetContainerConfiguration().ConfigureContainer(
new FakeProvider(),
new UnityContainer());
}
[Fact]
public void ShouldResolveBasicOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveBasicReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrBasicReadOnlyOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveOperationsFromStartupContainer() {
Assert.NotNull(
Setup().Resolve<ISolrOperations<FakeEntity>>());
}
[Fact]
public void ShouldResolveReadOnlyOperationsFromStartupContainer()
{
Assert.NotNull(
Setup().Resolve<ISolrReadOnlyOperations<FakeEntity>>());
}
}
} | apache-2.0 | C# |
b2fc119729e2c9bce386a767f9fae81321926792 | fix JsonSerializerExtensions in string values | signumsoftware/framework,avifatal/framework,AlejandroCano/framework,signumsoftware/framework,AlejandroCano/framework,avifatal/framework | Signum.React/JsonConverters/JsonSerializerExtensions.cs | Signum.React/JsonConverters/JsonSerializerExtensions.cs | using Newtonsoft.Json;
using Signum.Entities;
using Signum.Utilities;
using System;
using System.Linq;
namespace Signum.React.Json
{
public static class JsonSerializerExtensions
{
public static object DeserializeValue(this JsonSerializer serializer, JsonReader reader, Type valueType, object oldValue)
{
if (oldValue != null)
{
var conv = serializer.Converters.FirstOrDefault(c => c.CanConvert(valueType));
if (conv != null)
return conv.ReadJson(reader, valueType, oldValue, serializer);
}
if (valueType == typeof(string)) // string with valid iso datetime get converted otherwise
return reader.Value;
return serializer.Deserialize(reader, valueType);
}
public static void Assert(this JsonReader reader, JsonToken expected)
{
if (reader.TokenType != expected)
throw new JsonSerializationException($"Expected '{expected}' but '{reader.TokenType}' found in '{reader.Path}'");
}
static readonly ThreadVariable<PropertyRoute> currentPropertyRoute = Statics.ThreadVariable<PropertyRoute>("jsonPropertyRoute");
public static PropertyRoute CurrentPropertyRoute
{
get { return currentPropertyRoute.Value; }
}
public static IDisposable SetCurrentPropertyRoute(PropertyRoute route)
{
var old = currentPropertyRoute.Value;
currentPropertyRoute.Value = route;
return new Disposable(() => { currentPropertyRoute.Value = old; });
}
}
}
| using Newtonsoft.Json;
using Signum.Entities;
using Signum.Utilities;
using System;
using System.Linq;
namespace Signum.React.Json
{
public static class JsonSerializerExtensions
{
public static object DeserializeValue(this JsonSerializer serializer, JsonReader reader, Type valueType, object oldValue)
{
if (oldValue != null)
{
var conv = serializer.Converters.FirstOrDefault(c => c.CanConvert(valueType));
if (conv != null)
return conv.ReadJson(reader, valueType, oldValue, serializer);
}
return serializer.Deserialize(reader, valueType);
}
public static void Assert(this JsonReader reader, JsonToken expected)
{
if (reader.TokenType != expected)
throw new JsonSerializationException($"Expected '{expected}' but '{reader.TokenType}' found in '{reader.Path}'");
}
static readonly ThreadVariable<PropertyRoute> currentPropertyRoute = Statics.ThreadVariable<PropertyRoute>("jsonPropertyRoute");
public static PropertyRoute CurrentPropertyRoute
{
get { return currentPropertyRoute.Value; }
}
public static IDisposable SetCurrentPropertyRoute(PropertyRoute route)
{
var old = currentPropertyRoute.Value;
currentPropertyRoute.Value = route;
return new Disposable(() => { currentPropertyRoute.Value = old; });
}
}
} | mit | C# |
ce73df2e8e1cff7b3b1a0529965f67892000a1fd | Downgrade ClientVersion | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Helpers/Constants.cs | WalletWasabi/Helpers/Constants.cs | using NBitcoin;
using NBitcoin.Protocol;
using System;
using WalletWasabi.Backend.Models.Responses;
namespace WalletWasabi.Helpers
{
public static class Constants
{
public static readonly Version ClientVersion = new Version(1, 1, 5);
public const string BackendMajorVersion = "3";
public static readonly VersionsResponse VersionsResponse = new VersionsResponse { ClientVersion = ClientVersion.ToString(), BackendMajorVersion = BackendMajorVersion };
public const uint ProtocolVersion_WITNESS_VERSION = 70012;
public const int MaxPasswordLength = 150;
public static readonly NodeRequirement NodeRequirements = new NodeRequirement {
RequiredServices = NodeServices.NODE_WITNESS,
MinVersion = ProtocolVersion_WITNESS_VERSION,
MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true, SupportMempoolQuery = true }
};
public static readonly NodeRequirement LocalNodeRequirements = new NodeRequirement {
RequiredServices = NodeServices.NODE_WITNESS,
MinVersion = ProtocolVersion_WITNESS_VERSION,
MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true }
};
public static readonly NodeRequirement LocalBackendNodeRequirements = new NodeRequirement {
RequiredServices = NodeServices.NODE_WITNESS,
MinVersion = ProtocolVersion_WITNESS_VERSION,
MinProtocolCapabilities = new ProtocolCapabilities {
SupportGetBlock = true,
SupportWitness = true,
SupportMempoolQuery = true,
SupportSendHeaders = true,
SupportPingPong = true,
PeerTooOld = true
}
};
public const int P2wpkhInputSizeInBytes = 41;
public const int P2pkhInputSizeInBytes = 145;
public const int OutputSizeInBytes = 33;
// https://en.bitcoin.it/wiki/Bitcoin
// There are a maximum of 2,099,999,997,690,000 Bitcoin elements (called satoshis), which are currently most commonly measured in units of 100,000,000 known as BTC. Stated another way, no more than 21 million BTC can ever be created.
public const long MaximumNumberOfSatoshis = 2099999997690000;
private static readonly BitcoinWitPubKeyAddress MainNetCoordinatorAddress = new BitcoinWitPubKeyAddress("bc1qs604c7jv6amk4cxqlnvuxv26hv3e48cds4m0ew", Network.Main);
private static readonly BitcoinWitPubKeyAddress TestNetCoordinatorAddress = new BitcoinWitPubKeyAddress("tb1qecaheev3hjzs9a3w9x33wr8n0ptu7txp359exs", Network.TestNet);
private static readonly BitcoinWitPubKeyAddress RegTestCoordinatorAddress = new BitcoinWitPubKeyAddress("bcrt1qangxrwyej05x9mnztkakk29s4yfdv4n586gs8l", Network.RegTest);
public static BitcoinWitPubKeyAddress GetCoordinatorAddress(Network network)
{
Guard.NotNull(nameof(network), network);
if (network == Network.Main)
{
return MainNetCoordinatorAddress;
}
if (network == Network.TestNet)
{
return TestNetCoordinatorAddress;
}
// else regtest
return RegTestCoordinatorAddress;
}
public const string ChangeOfSpecialLabelStart = "change of (";
public const string ChangeOfSpecialLabelEnd = ")";
public const int BigFileReadWriteBufferSize = 1 * 1024 * 1024;
public const int SevenDaysConfirmationTarget = 1008;
}
}
| using NBitcoin;
using NBitcoin.Protocol;
using System;
using WalletWasabi.Backend.Models.Responses;
namespace WalletWasabi.Helpers
{
public static class Constants
{
public static readonly Version ClientVersion = new Version(1, 1, 6);
public const string BackendMajorVersion = "3";
public static readonly VersionsResponse VersionsResponse = new VersionsResponse { ClientVersion = ClientVersion.ToString(), BackendMajorVersion = BackendMajorVersion };
public const uint ProtocolVersion_WITNESS_VERSION = 70012;
public const int MaxPasswordLength = 150;
public static readonly NodeRequirement NodeRequirements = new NodeRequirement {
RequiredServices = NodeServices.NODE_WITNESS,
MinVersion = ProtocolVersion_WITNESS_VERSION,
MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true, SupportMempoolQuery = true }
};
public static readonly NodeRequirement LocalNodeRequirements = new NodeRequirement {
RequiredServices = NodeServices.NODE_WITNESS,
MinVersion = ProtocolVersion_WITNESS_VERSION,
MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true }
};
public static readonly NodeRequirement LocalBackendNodeRequirements = new NodeRequirement {
RequiredServices = NodeServices.NODE_WITNESS,
MinVersion = ProtocolVersion_WITNESS_VERSION,
MinProtocolCapabilities = new ProtocolCapabilities {
SupportGetBlock = true,
SupportWitness = true,
SupportMempoolQuery = true,
SupportSendHeaders = true,
SupportPingPong = true,
PeerTooOld = true
}
};
public const int P2wpkhInputSizeInBytes = 41;
public const int P2pkhInputSizeInBytes = 145;
public const int OutputSizeInBytes = 33;
// https://en.bitcoin.it/wiki/Bitcoin
// There are a maximum of 2,099,999,997,690,000 Bitcoin elements (called satoshis), which are currently most commonly measured in units of 100,000,000 known as BTC. Stated another way, no more than 21 million BTC can ever be created.
public const long MaximumNumberOfSatoshis = 2099999997690000;
private static readonly BitcoinWitPubKeyAddress MainNetCoordinatorAddress = new BitcoinWitPubKeyAddress("bc1qs604c7jv6amk4cxqlnvuxv26hv3e48cds4m0ew", Network.Main);
private static readonly BitcoinWitPubKeyAddress TestNetCoordinatorAddress = new BitcoinWitPubKeyAddress("tb1qecaheev3hjzs9a3w9x33wr8n0ptu7txp359exs", Network.TestNet);
private static readonly BitcoinWitPubKeyAddress RegTestCoordinatorAddress = new BitcoinWitPubKeyAddress("bcrt1qangxrwyej05x9mnztkakk29s4yfdv4n586gs8l", Network.RegTest);
public static BitcoinWitPubKeyAddress GetCoordinatorAddress(Network network)
{
Guard.NotNull(nameof(network), network);
if (network == Network.Main)
{
return MainNetCoordinatorAddress;
}
if (network == Network.TestNet)
{
return TestNetCoordinatorAddress;
}
// else regtest
return RegTestCoordinatorAddress;
}
public const string ChangeOfSpecialLabelStart = "change of (";
public const string ChangeOfSpecialLabelEnd = ")";
public const int BigFileReadWriteBufferSize = 1 * 1024 * 1024;
public const int SevenDaysConfirmationTarget = 1008;
}
}
| mit | C# |
607a67ef027203aa11e708c79dbec8bf07cd4c33 | add fatal log level to Help | adamralph/bau,eatdrinksleepcode/bau,huoxudong125/bau,aarondandy/bau,bau-build/bau,huoxudong125/bau,aarondandy/bau,eatdrinksleepcode/bau,adamralph/bau,modulexcite/bau,bau-build/bau,adamralph/bau,adamralph/bau,eatdrinksleepcode/bau,aarondandy/bau,eatdrinksleepcode/bau,huoxudong125/bau,huoxudong125/bau,bau-build/bau,aarondandy/bau,bau-build/bau,modulexcite/bau,modulexcite/bau,modulexcite/bau | src/test/Bau.Test.Acceptance/Help.cs | src/test/Bau.Test.Acceptance/Help.cs | // <copyright file="Help.cs" company="Bau contributors">
// Copyright (c) Bau contributors. (baubuildch@gmail.com)
// </copyright>
namespace Bau.Test.Acceptance
{
using System.Reflection;
using Bau.Test.Acceptance.Support;
using FluentAssertions;
using Xbehave;
public static class Help
{
[Scenario]
[Example("-?")]
[Example("-h")]
[Example("-help")]
[Example("-Help")]
public static void SpecifiyingLogLevel(string arg, Baufile baufile, string output)
{
var scenario = MethodBase.GetCurrentMethod().GetFullName();
"Given a no-op baufile"
.f(() => baufile = Baufile.Create(scenario).WriteLine(@"Require<Bau>().Run();"));
"When I execute the baufile with argument '{0}'"
.f(() => output = baufile.Run(arg));
"Then help should be displayed"
.f(() =>
{
var help =
@"
Usage: scriptcs <baufile.csx> -- [tasks] [options]
Options:
-l|-loglevel a|all|t|trace|d|debug|i*|info|w|warn|e|error|f|fatal|o|off
Set the logging level.
-t Alias for -loglevel trace.
-d Alias for -loglevel debug.
-q Alias for -loglevel warn.
-qq Alias for -loglevel error.
-s Alias for -loglevel off.
-?|-h|-help Show help.
One and two character option aliases are case-sensitive.
Examples: scriptcs baufile.csx
scriptcs baufile.csx -- task1 task2
scriptcs baufile.csx -- -d
";
output.Should().Contain(help);
});
}
}
}
| // <copyright file="Help.cs" company="Bau contributors">
// Copyright (c) Bau contributors. (baubuildch@gmail.com)
// </copyright>
namespace Bau.Test.Acceptance
{
using System.Reflection;
using Bau.Test.Acceptance.Support;
using FluentAssertions;
using Xbehave;
public static class Help
{
[Scenario]
[Example("-?")]
[Example("-h")]
[Example("-help")]
[Example("-Help")]
public static void SpecifiyingLogLevel(string arg, Baufile baufile, string output)
{
var scenario = MethodBase.GetCurrentMethod().GetFullName();
"Given a no-op baufile"
.f(() => baufile = Baufile.Create(scenario).WriteLine(@"Require<Bau>().Run();"));
"When I execute the baufile with argument '{0}'"
.f(() => output = baufile.Run(arg));
"Then help should be displayed"
.f(() =>
{
var help =
@"
Usage: scriptcs <baufile.csx> -- [tasks] [options]
Options:
-l|-loglevel a|all|t|trace|d|debug|i*|info|w|warn|e|error|o|off
Set the logging level.
-t Alias for -loglevel trace.
-d Alias for -loglevel debug.
-q Alias for -loglevel warn.
-qq Alias for -loglevel error.
-s Alias for -loglevel off.
-?|-h|-help Show help.
One and two character option aliases are case-sensitive.
Examples: scriptcs baufile.csx
scriptcs baufile.csx -- task1 task2
scriptcs baufile.csx -- -d
";
output.Should().Contain(help);
});
}
}
}
| mit | C# |
e2c3b4118d096c9f76efc201970b5874cbba1902 | Add namespace for Singleton | petereichinger/unity-helpers | Assets/Scripts/Singleton/Singleton.cs | Assets/Scripts/Singleton/Singleton.cs | using UnityEngine;
namespace UnityHelpers.Singleton {
/// <summary>Singleton pattern.</summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
private static T _instance;
private static object _lock = new object();
public static T Instance {
get {
lock (_lock) {
if (_instance == null) {
_instance = (T)FindObjectOfType(typeof(T));
if (FindObjectsOfType(typeof(T)).Length > 1) {
Debug.LogError("[Singleton] Something went really wrong " +
" - there should never be more than 1 singleton!" +
" Reopening the scene might fix it.");
return _instance;
}
if (_instance == null) {
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) " + typeof(T).ToString();
DontDestroyOnLoad(singleton);
Debug.Log("[Singleton] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created with DontDestroyOnLoad.");
} else {
Debug.Log("[Singleton] Using instance already created: " +
_instance.gameObject.name);
}
}
return _instance;
}
}
}
}
}
| using UnityEngine;
/// <summary>Singleton pattern. Should only be used by <see cref="Toolbox"/>.</summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
private static T _instance;
private static object _lock = new object();
public static T Instance {
get {
lock (_lock) {
if (_instance == null) {
_instance = (T)FindObjectOfType(typeof(T));
if (FindObjectsOfType(typeof(T)).Length > 1) {
Debug.LogError("[Singleton] Something went really wrong " +
" - there should never be more than 1 singleton!" +
" Reopening the scene might fix it.");
return _instance;
}
if (_instance == null) {
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) " + typeof(T).ToString();
DontDestroyOnLoad(singleton);
Debug.Log("[Singleton] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created with DontDestroyOnLoad.");
} else {
Debug.Log("[Singleton] Using instance already created: " +
_instance.gameObject.name);
}
}
return _instance;
}
}
}
}
| mit | C# |
3b1d76b9f8fb3cceca1204ec56d39a951dcc114c | Update EllipseHitTest.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.Editor/Bounds/Shapes/EllipseHitTest.cs | src/Draw2D.Editor/Bounds/Shapes/EllipseHitTest.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Draw2D.Core;
using Draw2D.Core.Shapes;
using Draw2D.Spatial;
namespace Draw2D.Editor.Bounds.Shapes
{
public class EllipseHitTest : BoxHitTest
{
public override Type TargetType => typeof(EllipseShape);
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Draw2D.Core;
using Draw2D.Core.Shapes;
using Draw2D.Spatial;
namespace Draw2D.Editor.Bounds.Shapes
{
public class EllipseHitTest : HitTestBase
{
public override Type TargetType => typeof(EllipseShape);
public override PointShape TryToGetPoint(ShapeObject shape, Point2 target, double radius, IHitTest hitTest)
{
var ellipse = shape as EllipseShape;
if (ellipse == null)
throw new ArgumentNullException("shape");
var pointHitTest = hitTest.Registered[typeof(PointShape)];
if (pointHitTest.TryToGetPoint(ellipse.TopLeft, target, radius, hitTest) != null)
{
return ellipse.TopLeft;
}
if (pointHitTest.TryToGetPoint(ellipse.BottomRight, target, radius, hitTest) != null)
{
return ellipse.BottomRight;
}
foreach (var point in ellipse.Points)
{
if (pointHitTest.TryToGetPoint(point, target, radius, hitTest) != null)
{
return point;
}
}
return null;
}
public override ShapeObject Contains(ShapeObject shape, Point2 target, double radius, IHitTest hitTest)
{
var ellipse = shape as EllipseShape;
if (ellipse == null)
throw new ArgumentNullException("shape");
return Rect2.FromPoints(
ellipse.TopLeft.X,
ellipse.TopLeft.Y,
ellipse.BottomRight.X,
ellipse.BottomRight.Y).Contains(target) ? shape : null;
}
public override ShapeObject Overlaps(ShapeObject shape, Rect2 target, double radius, IHitTest hitTest)
{
var ellipse = shape as EllipseShape;
if (ellipse == null)
throw new ArgumentNullException("shape");
return Rect2.FromPoints(
ellipse.TopLeft.X,
ellipse.TopLeft.Y,
ellipse.BottomRight.X,
ellipse.BottomRight.Y).IntersectsWith(target) ? shape : null;
}
}
}
| mit | C# |
49b5576a0c6d664e6831ee9459f6dbbb20d0baf4 | Move location of .asm output for new test compiler. | fanoI/Cosmos,MetSystem/Cosmos,kant2002/Cosmos-1,trivalik/Cosmos,zarlo/Cosmos,fanoI/Cosmos,zdimension/Cosmos,MyvarHD/Cosmos,jp2masa/Cosmos,MyvarHD/Cosmos,zhangwenquan/Cosmos,Cyber4/Cosmos,MyvarHD/Cosmos,MetSystem/Cosmos,sgetaz/Cosmos,MyvarHD/Cosmos,kant2002/Cosmos-1,zdimension/Cosmos,zhangwenquan/Cosmos,sgetaz/Cosmos,zarlo/Cosmos,fanoI/Cosmos,trivalik/Cosmos,zarlo/Cosmos,MetSystem/Cosmos,zhangwenquan/Cosmos,sgetaz/Cosmos,zdimension/Cosmos,trivalik/Cosmos,sgetaz/Cosmos,Cyber4/Cosmos,MetSystem/Cosmos,sgetaz/Cosmos,kant2002/Cosmos-1,Cyber4/Cosmos,zdimension/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,MetSystem/Cosmos,CosmosOS/Cosmos,Cyber4/Cosmos,zhangwenquan/Cosmos,CosmosOS/Cosmos,zdimension/Cosmos,kant2002/Cosmos-1,MyvarHD/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zhangwenquan/Cosmos,Cyber4/Cosmos,tgiphil/Cosmos,jp2masa/Cosmos,jp2masa/Cosmos,tgiphil/Cosmos | source2/Users/Kudzu/HelloWorld/Program.cs | source2/Users/Kudzu/HelloWorld/Program.cs | using System;
using System.Reflection;
using Cosmos.IL2CPU;
using Cosmos.IL2CPU.X86;
using Indy.IL2CPU.Assembler.X86;
using S = Cosmos.Hardware.TextScreen;
using System.IO;
namespace HelloWorld {
class Program {
#region Cosmos Builder logic
// Most users wont touch this. This will call the Cosmos Build tool
[STAThread]
static void Main(string[] args) {
//Indy.IL2CPU.Engine.Execute()
// which is called from Builder.RunEngine()
//TODO: Move new build logic into new sort.
// Build stuff is all UI, launching QEMU, making ISO etc.
// IL2CPU should only contain scanning and assembling of binary files
var xAsmblr = new Cosmos.IL2CPU.X86.Assembler();
var xScanner = new ILScanner(xAsmblr);
var xEntryPoint = typeof(Program).GetMethod("Init", BindingFlags.Public | BindingFlags.Static);
using (var xOldAsmblr = new CosmosAssembler(0)) {
//InitializePlugs(aPlugs);
xScanner.Execute(xEntryPoint);
var xPath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
xPath = Path.Combine(xPath, @"..\..\Output.asm");
using (var xOut = File.CreateText(xPath)) {
xOldAsmblr.FlushText(xOut);
}
}
}
#endregion
// Main entry point of the kernel
public static void Init() {
var xBoot = new Cosmos.Sys.Boot();
xBoot.Execute();
Console.BackgroundColor = ConsoleColor.Green;
//TODO: What is this next line for?
S.ReallyClearScreen();
Console.WriteLine("Congratulations! You just booted C# code.");
Console.WriteLine("Edit Program.cs to create your own Operating System.");
Console.WriteLine("Press a key to shutdown...");
Console.Read();
Cosmos.Sys.Deboot.ShutDown();
}
}
} | using System;
using System.Reflection;
using Cosmos.IL2CPU;
using Cosmos.IL2CPU.X86;
using Indy.IL2CPU.Assembler.X86;
using S = Cosmos.Hardware.TextScreen;
using System.IO;
namespace HelloWorld {
class Program {
#region Cosmos Builder logic
// Most users wont touch this. This will call the Cosmos Build tool
[STAThread]
static void Main(string[] args) {
//Indy.IL2CPU.Engine.Execute()
// which is called from Builder.RunEngine()
//TODO: Move new build logic into new sort.
// Build stuff is all UI, launching QEMU, making ISO etc.
// IL2CPU should only contain scanning and assembling of binary files
var xAsmblr = new Cosmos.IL2CPU.X86.Assembler();
var xScanner = new ILScanner(xAsmblr);
var xEntryPoint = typeof(Program).GetMethod("Init", BindingFlags.Public | BindingFlags.Static);
using (var xOldAsmblr = new CosmosAssembler(0)) {
//InitializePlugs(aPlugs);
xScanner.Execute(xEntryPoint);
var xPath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
xPath = Path.Combine(xPath, "Output.asm");
using (var xOut = File.CreateText(xPath))
{
xOldAsmblr.FlushText(xOut);
}
}
}
#endregion
// Main entry point of the kernel
public static void Init() {
var xBoot = new Cosmos.Sys.Boot();
xBoot.Execute();
Console.BackgroundColor = ConsoleColor.Green;
//TODO: What is this next line for?
S.ReallyClearScreen();
Console.WriteLine("Congratulations! You just booted C# code.");
Console.WriteLine("Edit Program.cs to create your own Operating System.");
Console.WriteLine("Press a key to shutdown...");
Console.Read();
Cosmos.Sys.Deboot.ShutDown();
}
}
} | bsd-3-clause | C# |
ccf10d7d71795810218f2d8359fefdea1e9ad6ae | Update WeeklyXamarin.cs | stvansolano/planetxamarin,beraybentesen/planetxamarin,beraybentesen/planetxamarin,stvansolano/planetxamarin,stvansolano/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,beraybentesen/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/WeeklyXamarin.cs | src/Firehose.Web/Authors/WeeklyXamarin.cs | using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
namespace Firehose.Web.Authors
{
public class WeeklyXamarin : IAmACommunityMember
{
public string FirstName => "Weekly";
public string LastName => "Xamarin";
public string StateOrRegion => "Internet";
public string EmailAddress => "inbox@weeklyxamarin.com";
public string Title => "newsletter that contains a weekly hand-picked round up of the best development links. Curated by Geoffrey Huntley";
public Uri WebSite => new Uri("https://www.weeklyxamarin.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://weeklyxamarin.com/issues.rss"); }
}
public string TwitterHandle => "weeklyxamarin";
public string GravatarHash => "";
}
}
| using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
namespace Firehose.Web.Authors
{
public class WeeklyXamarin : IAmACommunityMember
{
public string FirstName => "Weekly";
public string LastName => "Xamarin";
public string StateOrRegion => "Internet";
public string EmailAddress => "inbox@weeklyxamarin.com";
public string Title => "Newsletter";
public Uri WebSite => new Uri("https://www.weeklyxamarin.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://weeklyxamarin.com/issues.rss"); }
}
public string TwitterHandle => "weeklyxamarin";
public string GravatarHash => "";
}
}
| mit | C# |
e4e9eee84dd45527a11184da9e77346c09828e71 | Update Dewey Index View's bootstrap for the table. | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Views/Deweys/Index.cshtml | src/Open-School-Library/Views/Deweys/Index.cshtml | @model IEnumerable<Open_School_Library.Models.DeweyViewModels.DeweyIndexViewModel>
@{
ViewData["Title"] = "Index";
}
<h2>Dewey Decimal System</h2>
<p>
<a asp-action="Create">Create New Dewey</a>
</p>
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Number)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.DeweyID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.DeweyID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.DeweyID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
| @model IEnumerable<Open_School_Library.Models.DeweyViewModels.DeweyIndexViewModel>
@{
ViewData["Title"] = "Index";
}
<h2>Dewey Decimal System</h2>
<p>
<a asp-action="Create">Create New Dewey</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Number)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.DeweyID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.DeweyID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.DeweyID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
| mit | C# |
38453734fa8ba220bc16f47ac788e3687a1e5913 | format that | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Web/MediaStorage/LocalImageStorage.cs | src/Tugberk.Web/MediaStorage/LocalImageStorage.cs | using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Tugberk.Web.MediaStorage
{
public class LocalImageStorage : IImageStorage
{
private const string UrlPrefix = "http://localhost:5000/local/images/";
private readonly ILogger<LocalImageStorage> _logger;
public LocalImageStorage(ILogger<LocalImageStorage> logger)
{
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
}
public async Task<ImageSaveResult> SaveImage(Stream content, string nameWithExtension)
{
var imagePath = LocalImagesPathProvider.GetRandomImagePath(nameWithExtension);
var fileName = Path.GetFileName(imagePath);
_logger.LogInformation("Saving {baseFileName} under {imagePath}",
nameWithExtension, imagePath);
using (var fileStream = File.Open(imagePath, FileMode.CreateNew))
{
await content.CopyToAsync(fileStream);
}
return new ImageSaveResult($"{UrlPrefix}{fileName}");
}
}
}
| using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Tugberk.Web.MediaStorage
{
public class LocalImageStorage : IImageStorage
{
private const string UrlPrefix = "http://localhost:5000/local/images/";
private readonly ILogger<LocalImageStorage> _logger;
public LocalImageStorage(ILogger<LocalImageStorage> logger)
{
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
}
public async Task<ImageSaveResult> SaveImage(Stream content, string nameWithExtension)
{
var imagePath = LocalImagesPathProvider.GetRandomImagePath(nameWithExtension);
var fileName = Path.GetFileName(imagePath);
_logger.LogInformation("Saving {baseFileName} under {imagePath}",
nameWithExtension, imagePath);
using(var fileStream = File.Open(imagePath, FileMode.CreateNew))
{
await content.CopyToAsync(fileStream);
}
return new ImageSaveResult($"{UrlPrefix}{fileName}");
}
}
}
| agpl-3.0 | C# |
64becf994959b877963d72aa1c84876803e60cbc | remove extra nulls | lbargaoanu/AutoMapper,AutoMapper/AutoMapper,BlaiseD/AutoMapper,gentledepp/AutoMapper,AutoMapper/AutoMapper | src/AutoMapper/ConstructorMap.cs | src/AutoMapper/ConstructorMap.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Execution;
using AutoMapper.QueryableExtensions;
using AutoMapper.QueryableExtensions.Impl;
namespace AutoMapper
{
using static Expression;
public class ConstructorMap
{
private readonly IList<ConstructorParameterMap> _ctorParams = new List<ConstructorParameterMap>();
public ConstructorInfo Ctor { get; }
public TypeMap TypeMap { get; }
internal IEnumerable<ConstructorParameterMap> CtorParams => _ctorParams;
public ConstructorMap(ConstructorInfo ctor, TypeMap typeMap)
{
Ctor = ctor;
TypeMap = typeMap;
}
private static readonly IExpressionResultConverter[] ExpressionResultConverters =
{
new MemberResolverExpressionResultConverter(),
new MemberGetterExpressionResultConverter()
};
public bool CanResolve => CtorParams.All(param => param.CanResolve);
public Expression NewExpression(Expression instanceParameter)
{
var parameters = CtorParams.Select(map =>
{
var result = new ExpressionResolutionResult(instanceParameter, Ctor.DeclaringType);
var matchingExpressionConverter =
ExpressionResultConverters.FirstOrDefault(c => c.CanGetExpressionResolutionResult(result, map));
result = matchingExpressionConverter?.GetExpressionResolutionResult(result, map)
?? throw new AutoMapperMappingException($"Unable to generate the instantiation expression for the constructor {Ctor}: no expression could be mapped for constructor parameter '{map.Parameter}'.", null, TypeMap.Types);
return result;
});
return New(Ctor, parameters.Select(p => p.ResolutionExpression));
}
public void AddParameter(ParameterInfo parameter, MemberInfo[] resolvers, bool canResolve)
{
_ctorParams.Add(new ConstructorParameterMap(parameter, resolvers, canResolve));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Execution;
using AutoMapper.QueryableExtensions;
using AutoMapper.QueryableExtensions.Impl;
namespace AutoMapper
{
using static Expression;
public class ConstructorMap
{
private readonly IList<ConstructorParameterMap> _ctorParams = new List<ConstructorParameterMap>();
public ConstructorInfo Ctor { get; }
public TypeMap TypeMap { get; }
internal IEnumerable<ConstructorParameterMap> CtorParams => _ctorParams;
public ConstructorMap(ConstructorInfo ctor, TypeMap typeMap)
{
Ctor = ctor;
TypeMap = typeMap;
}
private static readonly IExpressionResultConverter[] ExpressionResultConverters =
{
new MemberResolverExpressionResultConverter(),
new MemberGetterExpressionResultConverter()
};
public bool CanResolve => CtorParams.All(param => param.CanResolve);
public Expression NewExpression(Expression instanceParameter)
{
var parameters = CtorParams.Select(map =>
{
var result = new ExpressionResolutionResult(instanceParameter, Ctor.DeclaringType);
var matchingExpressionConverter =
ExpressionResultConverters.FirstOrDefault(c => c.CanGetExpressionResolutionResult(result, map));
result = matchingExpressionConverter?.GetExpressionResolutionResult(result, map)
?? throw new AutoMapperMappingException($"Unable to generate the instantiation expression for the constructor {Ctor}: no expression could be mapped for constructor parameter '{map.Parameter}'.", null, TypeMap.Types, null, null);
return result;
});
return New(Ctor, parameters.Select(p => p.ResolutionExpression));
}
public void AddParameter(ParameterInfo parameter, MemberInfo[] resolvers, bool canResolve)
{
_ctorParams.Add(new ConstructorParameterMap(parameter, resolvers, canResolve));
}
}
} | mit | C# |
1ceff6ebed4a72179da347b3769616fa4f04984e | Use the new 15.0 SDK to access meta via IServices | versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla | VersionOne.ServerConnector/EntityFactory.cs | VersionOne.ServerConnector/EntityFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using VersionOne.SDK.APIClient;
namespace VersionOne.ServerConnector {
// TODO extract interface and inject into VersionOneProcessor
internal class EntityFactory {
private readonly IServices services;
private readonly IEnumerable<AttributeInfo> attributesToQuery;
internal EntityFactory(IServices services, IEnumerable<AttributeInfo> attributesToQuery) {
this.services = services;
this.attributesToQuery = attributesToQuery;
}
internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) {
var assetType = services.Meta.GetAssetType(assetTypeName);
var asset = services.New(assetType, Oid.Null);
foreach (var attributeValue in attributeValues) {
if(attributeValue is SingleAttributeValue) {
asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value);
} else if(attributeValue is MultipleAttributeValue) {
var values = ((MultipleAttributeValue) attributeValue).Values;
var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name);
foreach (var value in values) {
asset.AddAttributeValue(attributeDefinition, value);
}
} else {
throw new NotSupportedException("Unknown Attribute Value type.");
}
}
foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) {
asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr));
}
services.Save(asset);
return asset;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using VersionOne.SDK.APIClient;
namespace VersionOne.ServerConnector {
// TODO extract interface and inject into VersionOneProcessor
internal class EntityFactory {
private readonly IMetaModel metaModel;
private readonly IServices services;
private readonly IEnumerable<AttributeInfo> attributesToQuery;
internal EntityFactory(IMetaModel metaModel, IServices services, IEnumerable<AttributeInfo> attributesToQuery) {
this.metaModel = metaModel;
this.services = services;
this.attributesToQuery = attributesToQuery;
}
internal Asset Create(string assetTypeName, IEnumerable<AttributeValue> attributeValues) {
var assetType = metaModel.GetAssetType(assetTypeName);
var asset = services.New(assetType, Oid.Null);
foreach (var attributeValue in attributeValues) {
if(attributeValue is SingleAttributeValue) {
asset.SetAttributeValue(assetType.GetAttributeDefinition(attributeValue.Name), ((SingleAttributeValue)attributeValue).Value);
} else if(attributeValue is MultipleAttributeValue) {
var values = ((MultipleAttributeValue) attributeValue).Values;
var attributeDefinition = assetType.GetAttributeDefinition(attributeValue.Name);
foreach (var value in values) {
asset.AddAttributeValue(attributeDefinition, value);
}
} else {
throw new NotSupportedException("Unknown Attribute Value type.");
}
}
foreach (var attributeInfo in attributesToQuery.Where(attributeInfo => attributeInfo.Prefix == assetTypeName)) {
asset.EnsureAttribute(assetType.GetAttributeDefinition(attributeInfo.Attr));
}
services.Save(asset);
return asset;
}
}
} | bsd-3-clause | C# |
686e1b1797f06b001082dd844c7ff94b894e65c2 | update command property of entity editor | dreign/ComBoost,dreign/ComBoost | Wodsoft.ComBoost.Wpf/Editor/EntityEditor.cs | Wodsoft.ComBoost.Wpf/Editor/EntityEditor.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Wodsoft.ComBoost.Wpf.Editor
{
[TemplatePart(Name = "PART_TextBox", Type = typeof(TextBox))]
public class EntityEditor : EditorBase
{
static EntityEditor()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(EntityEditor), new FrameworkPropertyMetadata(typeof(EntityEditor)));
}
public EntityEditor()
{
SelectCommand = new EntityCommand(SelectEntity);
ClearCommand = new EntityCommand(SelectEntity);
}
protected TextBox TextBox { get; private set; }
public override void OnApplyTemplate()
{
TextBox = (TextBox)GetTemplateChild("PART_TextBox");
TextBox.SetBinding(TextBox.TextProperty, new Binding { Source = this, Path = new PropertyPath(CurrentValueProperty), Mode = BindingMode.OneWay });
}
private void SelectEntity(IEntity entity)
{
//Editor.Controller
}
private void ClearEntity(IEntity entity)
{
CurrentValue = null;
IsChanged = OriginValue == null;
}
public ICommand SelectCommand { get { return (ICommand)GetValue(SelectCommandProperty); } protected set { SetValue(SelectCommandPropertyKey, value); } }
protected static readonly DependencyPropertyKey SelectCommandPropertyKey = DependencyProperty.RegisterReadOnly("SelectCommand", typeof(ICommand), typeof(EntityEditor), new PropertyMetadata());
public static readonly DependencyProperty SelectCommandProperty = SelectCommandPropertyKey.DependencyProperty;
public ICommand ClearCommand { get { return (ICommand)GetValue(ClearCommandProperty); } protected set { SetValue(ClearCommandPropertyKey, value); } }
protected static readonly DependencyPropertyKey ClearCommandPropertyKey = DependencyProperty.RegisterReadOnly("ClearCommand", typeof(ICommand), typeof(EntityEditor), new PropertyMetadata());
public static readonly DependencyProperty ClearCommandProperty = ClearCommandPropertyKey.DependencyProperty;
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Wodsoft.ComBoost.Wpf.Editor
{
[TemplatePart(Name = "PART_TextBox", Type = typeof(TextBox))]
public class EntityEditor : EditorBase
{
static EntityEditor()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(EntityEditor), new FrameworkPropertyMetadata(typeof(EntityEditor)));
}
public EntityEditor()
{
SelectCommand = new EntityCommand(SelectEntity);
ClearCommand = new EntityCommand(SelectEntity);
}
protected TextBox TextBox { get; private set; }
public override void OnApplyTemplate()
{
TextBox = (TextBox)GetTemplateChild("PART_TextBox");
TextBox.SetBinding(TextBox.TextProperty, new Binding { Source = this, Path = new PropertyPath(CurrentValueProperty), Mode = BindingMode.OneWay });
}
private void SelectEntity(IEntity entity)
{
//Editor.Controller
}
private void ClearEntity(IEntity entity)
{
CurrentValue = null;
IsChanged = OriginValue == null;
}
public ICommand SelectCommand { get; private set; }
public ICommand ClearCommand { get; private set; }
}
}
| mit | C# |
ae1577da1832baa78c05b29e4e8b0dd5382f27ab | Use platform spesific temp folders | filipw/dotnet-script,filipw/dotnet-script | src/Dotnet.Script.DependencyModel/ProjectSystem/FileUtils.cs | src/Dotnet.Script.DependencyModel/ProjectSystem/FileUtils.cs | using Dotnet.Script.DependencyModel.Environment;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Dotnet.Script.DependencyModel.ProjectSystem
{
public static class FileUtils
{
public static string CreateTempFolder(string targetDirectory, string targetFramework)
{
string pathToProjectDirectory = Path.Combine(GetPathToTempFolder(targetDirectory), targetFramework);
if (!Directory.Exists(pathToProjectDirectory))
{
Directory.CreateDirectory(pathToProjectDirectory);
}
return pathToProjectDirectory;
}
public static string GetPathToTempFolder(string targetDirectory)
{
if (!Path.IsPathRooted(targetDirectory))
{
throw new ArgumentOutOfRangeException(nameof(targetDirectory), "Must be a root path");
}
var tempDirectory = GetTempPath();
var pathRoot = Path.GetPathRoot(targetDirectory);
var targetDirectoryWithoutRoot = targetDirectory.Substring(pathRoot.Length);
if (pathRoot.Length > 0 && ScriptEnvironment.Default.IsWindows)
{
var driveLetter = pathRoot.Substring(0, 1);
if (driveLetter == "\\")
{
targetDirectoryWithoutRoot = targetDirectoryWithoutRoot.TrimStart(new char[] { '\\' });
driveLetter = "UNC";
}
targetDirectoryWithoutRoot = Path.Combine(driveLetter, targetDirectoryWithoutRoot);
}
var pathToProjectDirectory = Path.Combine(tempDirectory, "dotnet-script", targetDirectoryWithoutRoot);
return pathToProjectDirectory;
}
private static string GetTempPath()
{
var userFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return Path.Combine(userFolder, ".cache");
}
else
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return Path.Combine(userFolder, "Library/Caches/");
}
return Path.GetTempPath();
}
}
}
| using Dotnet.Script.DependencyModel.Environment;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Dotnet.Script.DependencyModel.ProjectSystem
{
public static class FileUtils
{
public static string CreateTempFolder(string targetDirectory, string targetFramework)
{
string pathToProjectDirectory = Path.Combine(GetPathToTempFolder(targetDirectory), targetFramework);
if (!Directory.Exists(pathToProjectDirectory))
{
Directory.CreateDirectory(pathToProjectDirectory);
}
return pathToProjectDirectory;
}
public static string GetPathToTempFolder(string targetDirectory)
{
if (!Path.IsPathRooted(targetDirectory))
{
throw new ArgumentOutOfRangeException(nameof(targetDirectory), "Must be a root path");
}
var tempDirectory = Path.GetTempPath();
var pathRoot = Path.GetPathRoot(targetDirectory);
var targetDirectoryWithoutRoot = targetDirectory.Substring(pathRoot.Length);
if (pathRoot.Length > 0 && ScriptEnvironment.Default.IsWindows)
{
var driveLetter = pathRoot.Substring(0, 1);
if (driveLetter == "\\")
{
targetDirectoryWithoutRoot = targetDirectoryWithoutRoot.TrimStart(new char[] { '\\' });
driveLetter = "UNC";
}
targetDirectoryWithoutRoot = Path.Combine(driveLetter, targetDirectoryWithoutRoot);
}
var pathToProjectDirectory = Path.Combine(tempDirectory, "scripts", targetDirectoryWithoutRoot);
return pathToProjectDirectory;
}
}
}
| mit | C# |
3f8ccb17d92e450ab20ff76818a5cd9ab2daf1c6 | Fix documentation mistake. | andrewdavey/cassette,damiensawyer/cassette,damiensawyer/cassette,BluewireTechnologies/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,honestegg/cassette,damiensawyer/cassette,honestegg/cassette,honestegg/cassette,andrewdavey/cassette | src/Website/Views/Documentation/Scripts_ExternalModules.cshtml | src/Website/Views/Documentation/Scripts_ExternalModules.cshtml | @{
ViewBag.Title = "External script modules";
}
<h1>External script modules</h1>
<p>
You may want to reference an external script URL in multiple pages. Repeating the URL in each page is not ideal. If you ever need to change
it you'll have to search through all the pages.
</p>
<p>
Cassette supports the definition of external script modules at the application level. You can then reference them by a short, fixed, name.
In addition you can specify a fallback URL if, for example, a CDN fails.
</p>
<pre><code><span class="keyword">public</span> <span class="keyword">class</span> <span class="code-type">CassetteConfiguration</span> : <span class="code-type">ICassetteConfiguration</span>
{
<span class="keyword">public</span> <span class="keyword">void</span> Configure(<span class="code-type">ModuleConfiguration</span> moduleConfiguration, <span class="code-type">ICassetteApplication</span> application)
{
moduleConfiguration.Add(
<span class="keyword">new</span> <span class="code-type">ExternalScriptModule</span>(<span class="string">"twitter"</span>, <span class="string">"http://platform.twitter.com/widgets.js"</span>)
{
Location = <span class="string">"body"</span> <span class="comment">// Module render location can be set here if required.</span>
},
<span class="keyword">new</span> <span class="code-type">ExternalScriptModule</span>(
<span class="string">"jquery"</span>,
<span class="comment">// Protocol relative URL are supported to work with HTTPS pages.</span>
<span class="string">"//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"</span>,
<span class="string">"!window.jQuery"</span>, <span class="comment">// JavaScript fallback condition expression</span>
<span class="comment">// When condition is true, this fallback is dynamically added to the page.</span>
<span class="string">"/fallback/jquery.js"</span>
)
);
}
}</code></pre>
<p>Now in view pages, these external scripts can be referenced by name.</p>
<pre><code><span class="code-tag">@@{</span>
<span class="code-type">Assets</span>.Scripts.Reference(<span class="string">"jquery"</span>);
<span class="code-type">Assets</span>.Scripts.Reference(<span class="string">"twitter"</span>);
<span class="code-tag">}</span>
<span class="open-tag"><!</span><span class="tag">DOCTYPE</span> <span class="attribute">html</span><span class="close-tag">></span>
<span class="open-tag"><</span><span class="tag">html</span><span class="close-tag">></span>
...
</code></pre> | @{
ViewBag.Title = "External script modules";
}
<h1>External script modules</h1>
<p>
You may want to reference an external script URL in multiple pages. Repeating the URL in each page is not ideal. If you ever need to change
it you'll have to search through all the pages.
</p>
<p>
Cassette supports the definition of external script modules at the application level. You can then reference them by a short, fixed, name.
In addition you can specify a fallback URL if, for example, a CDN fails.
</p>
<pre><code><span class="keyword">public</span> <span class="keyword">class</span> <span class="code-type">CassetteConfiguration</span> : <span class="code-type">ICassetteConfiguration</span>
{
<span class="keyword">public</span> <span class="keyword">void</span> Configure(<span class="code-type">ModuleConfiguration</span> moduleConfiguration, <span class="code-type">ICassetteApplication</span> application)
{
modules.Add(
<span class="keyword">new</span> <span class="code-type">ExternalScriptModule</span>(<span class="string">"twitter"</span>, <span class="string">"http://platform.twitter.com/widgets.js"</span>)
{
Location = <span class="string">"body"</span> <span class="comment">// Module render location can be set here if required.</span>
},
<span class="keyword">new</span> <span class="code-type">ExternalScriptModule</span>(
<span class="string">"jquery"</span>,
<span class="comment">// Protocol relative URL are supported to work with HTTPS pages.</span>
<span class="string">"//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"</span>,
<span class="string">"!window.jQuery"</span>, <span class="comment">// JavaScript fallback condition expression</span>
<span class="comment">// When condition is true, this fallback is dynamically added to the page.</span>
<span class="string">"/fallback/jquery.js"</span>
)
);
}
}</code></pre>
<p>Now in view pages, these external scripts can be referenced by name.</p>
<pre><code><span class="code-tag">@@{</span>
<span class="code-type">Assets</span>.Scripts.Reference(<span class="string">"jquery"</span>);
<span class="code-type">Assets</span>.Scripts.Reference(<span class="string">"twitter"</span>);
<span class="code-tag">}</span>
<span class="open-tag"><!</span><span class="tag">DOCTYPE</span> <span class="attribute">html</span><span class="close-tag">></span>
<span class="open-tag"><</span><span class="tag">html</span><span class="close-tag">></span>
...
</code></pre> | mit | C# |
7c05073cfcac1266ff797627673d69d3ce7055bb | Update AssemblyInfo.cs | stilldesign/AppTracking | AppTracking/Properties/AssemblyInfo.cs | AppTracking/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("AppTracking")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("StillDesign")]
[assembly: AssemblyProduct("AppTracking")]
[assembly: AssemblyCopyright("Copyright © StillDesign 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("AppTracking")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("AppTracking")]
[assembly: AssemblyCopyright("Copyright © StillDesign 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| mit | C# |
64b7b6f2f6845087b374f2bbb1807ed8016ebc94 | Add Coarse Dirt Handling (#352) | yungtechboy1/MiNET | src/MiNET/MiNET/Items/ItemHoe.cs | src/MiNET/MiNET/Items/ItemHoe.cs | using System.Collections.Generic;
using System.Numerics;
using log4net;
using MiNET.Blocks;
using MiNET.Utils;
using MiNET.Worlds;
namespace MiNET.Items
{
public class ItemHoe : Item
{
private static readonly ILog Log = LogManager.GetLogger(typeof (ItemHoe));
internal ItemHoe(short id) : base(id)
{
MaxStackSize = 1;
}
public override void PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
{
Block block = world.GetBlock(blockCoordinates);
if (block is Grass || (block is Dirt && block.Metadata != 1) || block is GrassPath)
{
Farmland farmland = new Farmland
{
Coordinates = blockCoordinates,
Metadata = 0
};
if (farmland.FindWater(world, blockCoordinates, new List<BlockCoordinates>(), 0))
{
Log.Warn("Found water source");
farmland.Metadata = 7;
}
world.SetBlock(farmland);
}
else if (block is Dirt && block.Metadata == 1)
{
Dirt dirt = new Dirt
{
Coordinates = blockCoordinates
};
world.SetBlock(dirt);
}
}
}
} | using System.Collections.Generic;
using System.Numerics;
using log4net;
using MiNET.Blocks;
using MiNET.Utils;
using MiNET.Worlds;
namespace MiNET.Items
{
public class ItemHoe : Item
{
private static readonly ILog Log = LogManager.GetLogger(typeof (ItemHoe));
internal ItemHoe(short id) : base(id)
{
MaxStackSize = 1;
}
public override void PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
{
Block block = world.GetBlock(blockCoordinates);
if (block is Grass || block is Dirt || block is GrassPath)
{
Farmland farmland = new Farmland
{
Coordinates = blockCoordinates,
Metadata = 0
};
if (farmland.FindWater(world, blockCoordinates, new List<BlockCoordinates>(), 0))
{
Log.Warn("Found water source");
farmland.Metadata = 7;
}
world.SetBlock(farmland);
}
}
}
} | mpl-2.0 | C# |
61859989e17aa8c3fd4e1a1452dbbc07ea2db150 | Update FibonacciNumbers.cs | DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges | Fibonacci_Numbers/FibonacciNumbers.cs | Fibonacci_Numbers/FibonacciNumbers.cs | using System;
namespace FibonacciNumbers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("This program requires 2 starting integers, and the max terms to count!\n");
Environment.Exit(0);
}
int start1 = Convert.ToInt32(args[0]);
int start2 = Convert.ToInt32(args[1]);
int maxCount = Convert.ToInt32(args[2]);
if (maxCount < 2)
maxCount = 2;
int[] fullList = new int[maxCount];
fullList[0] = start1;
fullList[1] = start2;
for (int i = 2; i < maxCount; i++)
fullList[i] = fullList[i - 1] + fullList[i-2];
Console.Write("Result - {");
foreach (int fib in fullList)
{
Console.Write($" {fib}");
}
Console.Write(" }\n");
Console.WriteLine();
Console.ReadKey();
}
}
}
| using System;
namespace FibonacciNumbers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("This program requires 2 starting integers, and the max terms to count!\n");
Environment.Exit(0);
}
int start1 = Convert.ToInt32(args[0]);
int start2 = Convert.ToInt32(args[1]);
int maxCount = Convert.ToInt32(args[2]);
if (maxCount < 2)
maxCount = 2;
int[] fullList = new int[maxCount];
fullList[0] = start1;
fullList[1] = start2;
for (int i = 2; i < maxCount; i++)
fullList[i] = fullList[i - 1] + fullList[i-2];
Console.Write("Result - {");
foreach (int fib in fullList)
{
Console.Write($" {fib}");
}
Console.Write(" }");
Console.WriteLine();
Console.ReadKey();
}
}
}
| unlicense | C# |
135dbe13cff0e8508df836dbd634a4df3b0e1a5d | Update FibonacciNumbers.cs | DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges | Fibonacci_Numbers/FibonacciNumbers.cs | Fibonacci_Numbers/FibonacciNumbers.cs | using System;
namespace FibonacciNumbers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("This program requires 2 starting integers, and the max terms to count!\n");
Environment.Exit(0);
}
int start1 = Convert.ToInt32(args[0]);
int start2 = Convert.ToInt32(args[1]);
int maxCount = Convert.ToInt32(args[2]);
if (maxCount < 2)
maxCount = 2;
int[] fullList = new int[maxCount];
fullList[0] = start1;
fullList[1] = start2;
for (int i = 2; i < maxCount; i++)
fullList[i] = fullList[i - 1] + fullList[i-2];
Console.Write("Result - {");
foreach (int fib in fullList)
Console.Write($" {fib}");
Console.Write(" }\n");
Console.WriteLine();
Console.ReadKey();
}
}
}
| using System;
namespace FibonacciNumbers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("This program requires 2 starting integers, and the max terms to count!\n");
Environment.Exit(0);
}
int start1 = Convert.ToInt32(args[0]);
int start2 = Convert.ToInt32(args[1]);
int maxCount = Convert.ToInt32(args[2]);
if (maxCount < 2)
maxCount = 2;
int[] fullList = new int[maxCount];
fullList[0] = start1;
fullList[1] = start2;
for (int i = 2; i < maxCount; i++)
fullList[i] = fullList[i - 1] + fullList[i-2];
Console.Write("Result - {");
foreach (int fib in fullList)
{
Console.Write($" {fib}");
}
Console.Write(" }\n");
Console.WriteLine();
Console.ReadKey();
}
}
}
| unlicense | C# |
3ee6cca15ced4ea357d2e709b2279a01e1536899 | Fix incorrect file path | laedit/vika | src/NVika/BuildServers/GitHub.cs | src/NVika/BuildServers/GitHub.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.ComponentModel.Composition;
using System.Text;
using NVika.Abstractions;
using NVika.Parsers;
namespace NVika.BuildServers
{
internal sealed class GitHub : BuildServerBase
{
private readonly IEnvironment _environment;
[ImportingConstructor]
internal GitHub(IEnvironment environment)
{
_environment = environment;
}
public override string Name => nameof(GitHub);
public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS"));
public override void WriteMessage(Issue issue)
{
var outputString = new StringBuilder();
switch (issue.Severity)
{
case IssueSeverity.Error:
outputString.Append("::error ");
break;
case IssueSeverity.Warning:
outputString.Append("::warning");
break;
}
if (issue.FilePath != null)
{
var file = issue.FilePath.Replace('\\', '/');
outputString.Append($"file={file},");
}
if (issue.Offset != null)
outputString.Append($"col={issue.Offset.Start},");
outputString.Append($"line={issue.Line}::{issue.Message}");
Console.WriteLine(outputString.ToString());
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.ComponentModel.Composition;
using System.Text;
using NVika.Abstractions;
using NVika.Parsers;
namespace NVika.BuildServers
{
internal sealed class GitHub : BuildServerBase
{
private readonly IEnvironment _environment;
[ImportingConstructor]
internal GitHub(IEnvironment environment)
{
_environment = environment;
}
public override string Name => nameof(GitHub);
public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS"));
public override void WriteMessage(Issue issue)
{
var outputString = new StringBuilder();
switch (issue.Severity)
{
case IssueSeverity.Error:
outputString.Append("::error ");
break;
case IssueSeverity.Warning:
outputString.Append("::warning");
break;
}
if (issue.FilePath != null)
{
var file = issue.Project != null
? issue.FilePath.Replace(issue.Project + @"\", string.Empty)
: issue.FilePath;
outputString.Append($"file={file},");
}
if (issue.Offset != null)
outputString.Append($"col={issue.Offset.Start},");
outputString.Append($"line={issue.Line}::{issue.Message}");
Console.WriteLine(outputString.ToString());
}
}
}
| apache-2.0 | C# |
923096cca347b4f0d173c144a28497b500a19665 | Implement RunOverrideTargetResponse | svermeulen/omnisharp-server,x335/omnisharp-server,syl20bnr/omnisharp-server,OmniSharp/omnisharp-server,syl20bnr/omnisharp-server,x335/omnisharp-server,mispencer/OmniSharpServer,corngood/omnisharp-server,corngood/omnisharp-server | OmniSharp/AutoComplete/Overrides/RunOverrideTargetResponse.cs | OmniSharp/AutoComplete/Overrides/RunOverrideTargetResponse.cs | using System;
using OmniSharp.Common;
using OmniSharp.Rename;
namespace OmniSharp.AutoComplete.Overrides {
public class RunOverrideTargetResponse : ModifiedFileResponse {
public RunOverrideTargetResponse() {}
public RunOverrideTargetResponse
( string fileName
, string buffer
, int line
, int column)
: base(fileName: fileName, buffer: buffer) {
this.Line = line;
this.Column = column;
}
public int Line {get; set;}
public int Column {get; set;}
}
}
| using System;
using OmniSharp.Common;
namespace OmniSharp.AutoComplete.Overrides {
public class RunOverrideTargetResponse {}
}
| mit | C# |
a5522416735185c0badd989f24e11d2e6094601c | Add values in enum 'LexerError' | lury-lang/lury-lexer | lury-lexer/LexerError.cs | lury-lexer/LexerError.cs | //
// LexerError.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Lury.Compiling.Lexer
{
// Lexer's Number Range: 0x10_0000 - 0x1f_ffff
public enum LexerError
{
// Number Range: 0x10_0000 - 0x10_ffff
Unknown = 0x100000,
InvalidIndentFirstLine = 0x100001,
InvalidCharacter = 0x100002,
InvalidIndent = 0x100003,
UnexpectedCharacterAfterBackslash = 0x100004,
UnclosedBlockComment = 0x100005,
UnclosedStringLiteral = 0x100006,
}
public enum LexerWarning
{
// Number Range: 0x11_0000 - 0x11_ffff
Unknown = 0x110000,
}
public enum LexerInfo
{
// Number Range: 0x12_0000 - 0x12_ffff
Unknown = 0x120000,
}
}
| //
// LexerError.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Lury.Compiling.Lexer
{
// Lexer's Number Range: 0x10_0000 - 0x1f_ffff
public enum LexerError
{
// Number Range: 0x10_0000 - 0x10_ffff
Unknown = 0x100000,
InvalidIndentFirstLine = 0x100001,
InvalidCharacter = 0x100002,
InvalidIndent = 0x100003,
}
public enum LexerWarning
{
// Number Range: 0x11_0000 - 0x11_ffff
Unknown = 0x110000,
}
public enum LexerInfo
{
// Number Range: 0x12_0000 - 0x12_ffff
Unknown = 0x120000,
}
}
| mit | C# |
5eb306ae0f09b440f20c68db1cb222e198aa3cb2 | Update existing documentation for person ids. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Get/People/TraktPersonIds.cs | Source/Lib/TraktApiSharp/Objects/Get/People/TraktPersonIds.cs | namespace TraktApiSharp.Objects.Get.People
{
using Newtonsoft.Json;
/// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt person.</summary>
public class TraktPersonIds
{
/// <summary>Gets or sets the Trakt numeric id.</summary>
[JsonProperty(PropertyName = "trakt")]
public int Trakt { get; set; }
/// <summary>Gets or sets the Trakt slug.</summary>
[JsonProperty(PropertyName = "slug")]
public string Slug { get; set; }
/// <summary>Gets or sets the id from imdb.com</summary>
[JsonProperty(PropertyName = "imdb")]
public string Imdb { get; set; }
/// <summary>Gets or sets the numeric id from themoviedb.org</summary>
[JsonProperty(PropertyName = "tmdb")]
public int? Tmdb { get; set; }
/// <summary>Gets or sets the numeric id from tvrage.com</summary>
[JsonProperty(PropertyName = "tvrage")]
public int? TvRage { get; set; }
/// <summary>Returns, whether any id has been set.</summary>
[JsonIgnore]
public bool HasAnyId => Trakt > 0 || !string.IsNullOrEmpty(Slug) || !string.IsNullOrEmpty(Imdb) || Tmdb > 0 || TvRage > 0;
/// <summary>Gets the most reliable id from those that have been set.</summary>
/// <returns>The id as a string or an empty string, if no id is set.</returns>
public string GetBestId()
{
if (Trakt > 0)
return Trakt.ToString();
if (!string.IsNullOrEmpty(Slug))
return Slug;
if (!string.IsNullOrEmpty(Imdb))
return Imdb;
if (Tmdb.HasValue && Tmdb.Value > 0)
return Tmdb.Value.ToString();
if (TvRage.HasValue && TvRage.Value > 0)
return TvRage.Value.ToString();
return string.Empty;
}
}
}
| namespace TraktApiSharp.Objects.Get.People
{
using Newtonsoft.Json;
using System.Globalization;
/// <summary>
/// A collection of ids for various web services for a Trakt person.
/// </summary>
public class TraktPersonIds
{
/// <summary>
/// The Trakt numeric id for the person.
/// </summary>
[JsonProperty(PropertyName = "trakt")]
public int Trakt { get; set; }
/// <summary>
/// The Trakt slug for the person.
/// </summary>
[JsonProperty(PropertyName = "slug")]
public string Slug { get; set; }
/// <summary>
/// The id for the person from imdb.com
/// </summary>
[JsonProperty(PropertyName = "imdb")]
public string Imdb { get; set; }
/// <summary>
/// The numeric id for the person from themoviedb.org
/// </summary>
[JsonProperty(PropertyName = "tmdb")]
public int? Tmdb { get; set; }
/// <summary>
/// The numeric id for the person from tvrage.com
/// </summary>
[JsonProperty(PropertyName = "tvrage")]
public int? TvRage { get; set; }
/// <summary>
/// Tests, if at least one id has been set.
/// </summary>
[JsonIgnore]
public bool HasAnyId => Trakt > 0 || !string.IsNullOrEmpty(Slug) || !string.IsNullOrEmpty(Imdb) || Tmdb > 0 || TvRage > 0;
/// <summary>
/// Get the most reliable id from those that have been set for the person.
/// </summary>
/// <returns>The id as a string.</returns>
public string GetBestId()
{
if (Trakt > 0)
return Trakt.ToString(CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(Slug))
return Slug;
if (!string.IsNullOrEmpty(Imdb))
return Imdb;
return string.Empty;
}
}
}
| mit | C# |
10b5117c69c6f56f95874ffbad60fb87f971526d | Convert to Unix linebreaks. | pmcvtm/FAKE,philipcpresley/FAKE,dlsteuer/FAKE,MichalDepta/FAKE,wooga/FAKE,mfalda/FAKE,hitesh97/FAKE,beeker/FAKE,xavierzwirtz/FAKE,modulexcite/FAKE,RMCKirby/FAKE,dlsteuer/FAKE,jayp33/FAKE,mfalda/FAKE,dmorgan3405/FAKE,rflechner/FAKE,dlsteuer/FAKE,dmorgan3405/FAKE,yonglehou/FAKE,neoeinstein/FAKE,brianary/FAKE,mat-mcloughlin/FAKE,pmcvtm/FAKE,satsuper/FAKE,jayp33/FAKE,mat-mcloughlin/FAKE,naveensrinivasan/FAKE,MiloszKrajewski/FAKE,modulexcite/FAKE,JonCanning/FAKE,jayp33/FAKE,xavierzwirtz/FAKE,molinch/FAKE,featuresnap/FAKE,dmorgan3405/FAKE,beeker/FAKE,MiloszKrajewski/FAKE,philipcpresley/FAKE,featuresnap/FAKE,NaseUkolyCZ/FAKE,beeker/FAKE,hitesh97/FAKE,gareth-evans/FAKE,xavierzwirtz/FAKE,naveensrinivasan/FAKE,Kazark/FAKE,ArturDorochowicz/FAKE,wooga/FAKE,ArturDorochowicz/FAKE,JonCanning/FAKE,hitesh97/FAKE,molinch/FAKE,ctaggart/FAKE,ctaggart/FAKE,MichalDepta/FAKE,dmorgan3405/FAKE,warnergodfrey/FAKE,pacificIT/FAKE,yonglehou/FAKE,leflings/FAKE,pacificIT/FAKE,NaseUkolyCZ/FAKE,mfalda/FAKE,ArturDorochowicz/FAKE,RMCKirby/FAKE,MichalDepta/FAKE,NaseUkolyCZ/FAKE,ovu/FAKE,brianary/FAKE,leflings/FAKE,satsuper/FAKE,rflechner/FAKE,ArturDorochowicz/FAKE,neoeinstein/FAKE,mglodack/FAKE,philipcpresley/FAKE,naveensrinivasan/FAKE,tpetricek/FAKE,ilkerde/FAKE,featuresnap/FAKE,dlsteuer/FAKE,haithemaraissia/FAKE,darrelmiller/FAKE,yonglehou/FAKE,gareth-evans/FAKE,tpetricek/FAKE,ctaggart/FAKE,JonCanning/FAKE,warnergodfrey/FAKE,pacificIT/FAKE,darrelmiller/FAKE,MiloszKrajewski/FAKE,MiloszKrajewski/FAKE,NaseUkolyCZ/FAKE,wooga/FAKE,mat-mcloughlin/FAKE,tpetricek/FAKE,warnergodfrey/FAKE,molinch/FAKE,leflings/FAKE,darrelmiller/FAKE,xavierzwirtz/FAKE,ovu/FAKE,JonCanning/FAKE,wooga/FAKE,neoeinstein/FAKE,daniel-chambers/FAKE,mglodack/FAKE,ilkerde/FAKE,Kazark/FAKE,satsuper/FAKE,daniel-chambers/FAKE,mglodack/FAKE,mfalda/FAKE,ovu/FAKE,RMCKirby/FAKE,RMCKirby/FAKE,naveensrinivasan/FAKE,pmcvtm/FAKE,mglodack/FAKE,Kazark/FAKE,rflechner/FAKE,warnergodfrey/FAKE,brianary/FAKE,leflings/FAKE,hitesh97/FAKE,pacificIT/FAKE,haithemaraissia/FAKE,neoeinstein/FAKE,gareth-evans/FAKE,daniel-chambers/FAKE,modulexcite/FAKE,Kazark/FAKE,featuresnap/FAKE,satsuper/FAKE,daniel-chambers/FAKE,molinch/FAKE,beeker/FAKE,gareth-evans/FAKE,philipcpresley/FAKE,MichalDepta/FAKE,modulexcite/FAKE,brianary/FAKE,mat-mcloughlin/FAKE,ilkerde/FAKE,jayp33/FAKE,ctaggart/FAKE,yonglehou/FAKE,haithemaraissia/FAKE,pmcvtm/FAKE,ovu/FAKE,tpetricek/FAKE,ilkerde/FAKE,darrelmiller/FAKE,rflechner/FAKE,haithemaraissia/FAKE | src/test/Test.FAKECore/SideBySideSpecification/TestSplicing.cs | src/test/Test.FAKECore/SideBySideSpecification/TestSplicing.cs | using System.IO;
using System.Xml.Linq;
using Fake.MSBuild;
using NUnit.Framework;
using Test.Git;
namespace Test.FAKECore.SideBySideSpecification
{
[TestFixture]
public class TestSplicing
{
#region Setup/Teardown
[SetUp]
public void Setup()
{
_project1 = Splicing.loadProject(@"SideBySideSpecification\Project1.txt");
}
#endregion
private XDocument _project1;
private static void CheckResult(XDocument result, string resultFileName)
{
var spliced = Splicing.normalize(result);
var expected = File.ReadAllText(resultFileName).Replace("\r\n", "\n");
spliced.Replace("\r\n", "\n").ShouldEqual(expected);
}
[Test]
public void CanSpliceNUnitReference()
{
var result = Splicing.removeAssemblyReference(Extensions.Convert<string, bool>(s => s.StartsWith("nunit")),
_project1);
CheckResult(result, @"SideBySideSpecification\Project1_WithoutNUnit.txt");
}
[Test]
public void CanSpliceTestFiles()
{
var result = Splicing.removeFiles(Extensions.Convert<string, bool>(s => s.EndsWith("Specs.cs")), _project1);
CheckResult(result, @"SideBySideSpecification\Project1_WithoutTests.txt");
}
}
} | using System.IO;
using System.Xml.Linq;
using Fake.MSBuild;
using NUnit.Framework;
using Test.Git;
namespace Test.FAKECore.SideBySideSpecification
{
[TestFixture]
public class TestSplicing
{
#region Setup/Teardown
[SetUp]
public void Setup()
{
_project1 = Splicing.loadProject(@"SideBySideSpecification\Project1.txt");
}
#endregion
private XDocument _project1;
private static void CheckResult(XDocument result, string resultFileName)
{
Splicing.normalize(result).ShouldEqual(File.ReadAllText(resultFileName));
}
[Test]
public void CanSpliceNUnitReference()
{
var result = Splicing.removeAssemblyReference(Extensions.Convert<string, bool>(s => s.StartsWith("nunit")),
_project1);
CheckResult(result, @"SideBySideSpecification\Project1_WithoutNUnit.txt");
}
[Test]
public void CanSpliceTestFiles()
{
var result = Splicing.removeFiles(Extensions.Convert<string, bool>(s => s.EndsWith("Specs.cs")), _project1);
CheckResult(result, @"SideBySideSpecification\Project1_WithoutTests.txt");
}
}
} | apache-2.0 | C# |
253d153539b59e2fa69c12151e18ebe313435243 | change version | slemvs/Excelerator | .build/VersionInfo.cs | .build/VersionInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.0.1")]
[assembly: AssemblyFileVersion("0.0.1")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")] | mit | C# |
66768c1c316d87e08aff3b088f5996ea241ea684 | Stop camera preview when navigated from the page | kennyzx/UWPBank | UWPBank/MediaPage.xaml.cs | UWPBank/MediaPage.xaml.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Capture;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace UWPBank
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MediaPage : Page
{
MediaCapture mediaCapture;
public MediaPage()
{
this.InitializeComponent();
}
private async System.Threading.Tasks.Task ReInitCamera()
{
mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync();
previewElement.Source = mediaCapture;
await mediaCapture.StartPreviewAsync();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await ReInitCamera();
Window.Current.Activated += Current_Activated;
}
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
await mediaCapture.StopPreviewAsync();
mediaCapture = null;
Window.Current.Activated -= Current_Activated;
}
private async void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
{
await ReInitCamera();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Capture;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace UWPBank
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MediaPage : Page
{
MediaCapture mediaCapture;
public MediaPage()
{
this.InitializeComponent();
}
private async System.Threading.Tasks.Task ReInitCamera()
{
mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync();
previewElement.Source = mediaCapture;
await mediaCapture.StartPreviewAsync();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await ReInitCamera();
Window.Current.Activated += Current_Activated;
}
private async void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
{
await ReInitCamera();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
Window.Current.Activated -= Current_Activated;
}
}
}
| mit | C# |
4e83e4645223d18da63ff502c2aeeeb7d9fb17e6 | update ImageShareOption | aixasz/ImageShareTemplate | ImageShareTemplate/ImageShareOption.cs | ImageShareTemplate/ImageShareOption.cs | using ImageShareTemplate.ImageProvider;
using System;
using System.Collections.Generic;
using System.Text;
namespace ImageShareTemplate
{
public class ImageShareOption
{
/// <summary>
/// The proportion horizontal ratio.
/// </summary>
public double RatioX { get; set; }
/// <summary>
/// The proportion vertical ratio.
/// </summary>
public double RatioY { get; set; }
/// <summary>
/// We have separate area to render item on main image to four quadrant.
///
/// +---------+---------+
/// | | |
/// | Block 1 | Block 2 |
/// | | |
/// +---------+---------+
/// | | |
/// | Block 3 | Block 4 |
/// | | |
/// +---------+---------+
///
/// </summary>
public IBlock Block1 { get; set; }
public IBlock Block2 { get; set; }
public IBlock Block3 { get; set; }
public IBlock Block4 { get; set; }
/// <summary>
/// Main image this will be background.
/// </summary>
public byte[] ImageSource { get; set; }
/// <summary>
/// Target image result follow provider specification.
/// </summary>
public IImageProvider ImageProvider { get; set; }
}
}
| using ImageShareTemplate.ImageProvider;
using System;
using System.Collections.Generic;
using System.Text;
namespace ImageShareTemplate
{
public class ImageShareOption
{
/// <summary>
/// The proportion horizontal ratio.
/// </summary>
public double RatioX { get; set; }
/// <summary>
/// The proportion vertical ratio.
/// </summary>
public double RatioY { get; set; }
public IBlock Block1 { get; set; }
public IBlock Block2 { get; set; }
public IBlock Block3 { get; set; }
public IBlock Block4 { get; set; }
public string MainImagePath { get; set; }
public IImageProvider ImageProvider { get; set; }
}
}
| mit | C# |
13e9af9e4de0fdb0d3b0226345903f368befa417 | Use native docker client when running under WSL | MihaMarkic/Cake.Docker | src/Cake.Docker/DockerTool.cs | src/Cake.Docker/DockerTool.cs | using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;
using System.Collections.Generic;
using System.Linq;
namespace Cake.Docker
{
/// <summary>
/// Base class for all Docker related tools.
/// </summary>
/// <typeparam name="TSettings">The settings type.</typeparam>
public abstract class DockerTool<TSettings>: Tool<TSettings>
where TSettings: ToolSettings
{
private readonly ICakeEnvironment _environment;
private readonly IFileSystem _fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="DockerTool{TSettings}"/> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
/// <param name="processRunner">The process runner.</param>
/// <param name="tools">The tools.</param>
protected DockerTool(
IFileSystem fileSystem,
ICakeEnvironment environment,
IProcessRunner processRunner,
IToolLocator tools)
: base(fileSystem, environment, processRunner, tools)
{
_fileSystem = fileSystem;
_environment = environment;
}
/// <summary>
/// Gets the name of the tool.
/// </summary>
/// <returns>The name of the tool.</returns>
protected override string GetToolName()
{
return "Docker";
}
/// <summary>
/// Gets the possible names of the tool executable.
/// </summary>
/// <returns>The tool executable name.</returns>
protected override IEnumerable<string> GetToolExecutableNames()
{
// In WSL (Windows Subsystem for Linux), both 'docker' and
// 'docker.exe' are available. The linux version of docker
// must have precedence over the windows version so that
// the native (i.e. linux) version of docker is used under WSL.
return new[] { "docker", "docker.exe" };
}
/// <summary>
///
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns></returns>
protected override IEnumerable<FilePath> GetAlternativeToolPaths(TSettings settings)
{
var path = DockerResolver.GetDockerPath(_fileSystem, _environment);
return path != null
? new[] { path }
: Enumerable.Empty<FilePath>();
}
}
}
| using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;
using System.Collections.Generic;
using System.Linq;
namespace Cake.Docker
{
/// <summary>
/// Base class for all Docker related tools.
/// </summary>
/// <typeparam name="TSettings">The settings type.</typeparam>
public abstract class DockerTool<TSettings>: Tool<TSettings>
where TSettings: ToolSettings
{
private readonly ICakeEnvironment _environment;
private readonly IFileSystem _fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="DockerTool{TSettings}"/> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
/// <param name="processRunner">The process runner.</param>
/// <param name="tools">The tools.</param>
protected DockerTool(
IFileSystem fileSystem,
ICakeEnvironment environment,
IProcessRunner processRunner,
IToolLocator tools)
: base(fileSystem, environment, processRunner, tools)
{
_fileSystem = fileSystem;
_environment = environment;
}
/// <summary>
/// Gets the name of the tool.
/// </summary>
/// <returns>The name of the tool.</returns>
protected override string GetToolName()
{
return "Docker";
}
/// <summary>
/// Gets the possible names of the tool executable.
/// </summary>
/// <returns>The tool executable name.</returns>
protected override IEnumerable<string> GetToolExecutableNames()
{
return new[] { "docker.exe", "docker" };
}
/// <summary>
///
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns></returns>
protected override IEnumerable<FilePath> GetAlternativeToolPaths(TSettings settings)
{
var path = DockerResolver.GetDockerPath(_fileSystem, _environment);
return path != null
? new[] { path }
: Enumerable.Empty<FilePath>();
}
}
}
| mit | C# |
733e90ebf14d418bb32b61bb4280043e2bf2698a | Remove unused usings | projectkudu/AzureFunctions,projectkudu/WebJobsPortal,agruning/azure-functions-ux,projectkudu/WebJobsPortal,agruning/azure-functions-ux,chunye/azure-functions-ux,agruning/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,projectkudu/WebJobsPortal,chunye/azure-functions-ux,chunye/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,chunye/azure-functions-ux,agruning/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/AzureFunctions | AzureFunctions/Trace/TracingEvents.cs | AzureFunctions/Trace/TracingEvents.cs | namespace AzureFunctions.Trace
{
public static class TracingEvents
{
// EventId = 0
public static readonly TracingEvent ErrorInGetFunctionTemplate = new TracingEvent
{
Message = "TemplatesManager.GetFunctionTemplate({templateFolderName}), {Exception}",
EventId = 0
};
// EventId = 1
public static readonly TracingEvent ErrorInGetFunctionContainer = new TracingEvent
{
Message = "AzureFunctionsController.GetFunctionContainer()",
EventId = 1
};
// EventId = 2
public static readonly TracingEvent ErrorInCreateFunctionsContainer = new TracingEvent
{
Message = "AzureFunctionsController.CreateFunctionsContainer({subscriptionId}, {location}, {serverFarmId}) {Exception}",
EventId = 2
};
// EventId = 3
public static readonly TracingEvent ErrorInCreateTrialFunctionContainer = new TracingEvent
{
Message = "CreateTrialFunctionsContainer() {Exception}",
EventId = 3
};
// EventId = 4
public static readonly TracingEvent CompletedOperationTemplate = new TracingEvent
{
Message = "Completed {TimedOperationId}: {OperationName} started {StartedTime} in {TimedOperationElapsed} ({TimeTakenMsec} ms) {OperationResult}",
EventId = 4
};
// EventId = 5
public static readonly TracingEvent UserForbidden = new TracingEvent
{
Message = "User {UserName} got 403 (Forbidden)",
EventId = 5
};
}
} | using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AzureFunctions.Trace
{
public static class TracingEvents
{
// EventId = 0
public static readonly TracingEvent ErrorInGetFunctionTemplate = new TracingEvent
{
Message = "TemplatesManager.GetFunctionTemplate({templateFolderName}), {Exception}",
EventId = 0
};
// EventId = 1
public static readonly TracingEvent ErrorInGetFunctionContainer = new TracingEvent
{
Message = "AzureFunctionsController.GetFunctionContainer()",
EventId = 1
};
// EventId = 2
public static readonly TracingEvent ErrorInCreateFunctionsContainer = new TracingEvent
{
Message = "AzureFunctionsController.CreateFunctionsContainer({subscriptionId}, {location}, {serverFarmId}) {Exception}",
EventId = 2
};
// EventId = 3
public static readonly TracingEvent ErrorInCreateTrialFunctionContainer = new TracingEvent
{
Message = "CreateTrialFunctionsContainer() {Exception}",
EventId = 3
};
// EventId = 4
public static readonly TracingEvent CompletedOperationTemplate = new TracingEvent
{
Message = "Completed {TimedOperationId}: {OperationName} started {StartedTime} in {TimedOperationElapsed} ({TimeTakenMsec} ms) {OperationResult}",
EventId = 4
};
// EventId = 5
public static readonly TracingEvent UserForbidden = new TracingEvent
{
Message = "User {UserName} got 403 (Forbidden)",
EventId = 5
};
}
} | apache-2.0 | C# |
2ad41fd040ef86903ea05a80588d1bf423f38216 | Resolve line too long message on build server | natsnudasoft/AdiePlayground | AssemblyInfoCommon.cs | AssemblyInfoCommon.cs | // <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. 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.
// </copyright>
using System.Reflection;
using System.Resources;
[assembly: NeutralResourcesLanguage("en-GB")]
[assembly: AssemblyCompany("natsnudasoft")]
[assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")]
// Version is generated on the build server.
#pragma warning disable MEN002 // Line is too long
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]
#pragma warning restore MEN002 // Line is too long
| // <copyright file="AssemblyInfoCommon.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. 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.
// </copyright>
using System.Reflection;
using System.Resources;
[assembly: NeutralResourcesLanguage("en-GB")]
[assembly: AssemblyCompany("natsnudasoft")]
[assembly: AssemblyCopyright("Copyright © Adrian John Dunstan 2016")]
// Version is generated on the build server.
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]
| apache-2.0 | C# |
0ea30fbe7a55075bbcbd021ea114b94db30f9770 | use getUniqueIndex() | yasokada/unity-160820-Inventory-UI | Assets/InventoryCS.cs | Assets/InventoryCS.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using NS_SampleData;
using NS_MyStringUtil;
/*
* - add getUniqueIndex()
* v0.2 2016 Aug. 21
* - add UpdateInfo()
* - add [MyStringUtil.cs]
* - add OpenURL()
* v0.1 2016 Aug. 21
* - add MoveColumn()
* - add MoveRow()
* - add SampleData.cs
* - add UI components (unique ID, Case No, Row, Column, About, DataSheet)
*/
public class InventoryCS : MonoBehaviour {
public InputField IF_uniqueID;
public Text T_caseNo;
public Text T_row;
public Text T_column;
public InputField IF_name;
public Text T_about;
public Text T_datasheetURL;
// TOOD: 0m > put other place to declear
const int kIndex_caseNo = 0;
const int kIndex_row = 1;
const int kIndex_column = 2;
const int kIndex_name = 3;
const int kIndex_about = 4;
const int kIndex_dataSheetURL = 5;
void Start () {
T_about.text = NS_SampleData.SampleData.GetDataOfRow (0);
}
void Update () {
}
private void UpdateInfo(string datstr) {
T_caseNo.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_caseNo);
T_row.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_row);
T_column.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_column);
IF_uniqueID.text = getUniqueIndex (T_caseNo.text, T_row.text, T_column.text);
IF_name.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_name);
T_about.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_about);
T_datasheetURL.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_dataSheetURL);
}
private string getUniqueIndex(string caseNo, string rowNo, string columnNo) {
int wrkCase = int.Parse (caseNo);
int wrkRow = int.Parse (rowNo);
int wrkCol = int.Parse (columnNo);
string res =
string.Format ("{0:0000}", wrkCase)
+ string.Format("{0:00}", wrkRow)
+ string.Format("{0:00}", wrkCol);
return res;
}
public void MoveRow(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfRow (0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfRow (1);
UpdateInfo (dtstr);
}
}
public void MoveColumn(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfColumn(0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfColumn (1);
UpdateInfo (dtstr);
T_caseNo.text = MyStringUtil.ExtractCsvColumn (dtstr, kIndex_caseNo);
T_about.text = dtstr;
}
}
public void OpenURL() {
Application.OpenURL (T_datasheetURL.text);
}
} | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using NS_SampleData;
using NS_MyStringUtil;
/*
* - add getUniqueIndex()
* v0.2 2016 Aug. 21
* - add UpdateInfo()
* - add [MyStringUtil.cs]
* - add OpenURL()
* v0.1 2016 Aug. 21
* - add MoveColumn()
* - add MoveRow()
* - add SampleData.cs
* - add UI components (unique ID, Case No, Row, Column, About, DataSheet)
*/
public class InventoryCS : MonoBehaviour {
public InputField IF_uniqueID;
public Text T_caseNo;
public Text T_row;
public Text T_column;
public InputField IF_name;
public Text T_about;
public Text T_datasheetURL;
// TOOD: 0m > put other place to declear
const int kIndex_caseNo = 0;
const int kIndex_row = 1;
const int kIndex_column = 2;
const int kIndex_name = 3;
const int kIndex_about = 4;
const int kIndex_dataSheetURL = 5;
void Start () {
T_about.text = NS_SampleData.SampleData.GetDataOfRow (0);
}
void Update () {
}
private void UpdateInfo(string datstr) {
T_caseNo.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_caseNo);
T_row.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_row);
T_column.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_column);
IF_name.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_name);
T_about.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_about);
T_datasheetURL.text = MyStringUtil.ExtractCsvColumn (datstr, kIndex_dataSheetURL);
}
private string getUniqueIndex(string caseNo, string rowNo, string columnNo) {
int wrkCase = int.Parse (caseNo);
int wrkRow = int.Parse (rowNo);
int wrkCol = int.Parse (columnNo);
string res =
string.Format ("{0:0000}", wrkCase)
+ string.Format("{0:00}", wrkRow)
+ string.Format("{0:00}", wrkCol);
return res;
}
public void MoveRow(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfRow (0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfRow (1);
UpdateInfo (dtstr);
}
}
public void MoveColumn(bool next) {
if (next == false) { // previous
string dtstr = NS_SampleData.SampleData.GetDataOfColumn(0);
UpdateInfo (dtstr);
} else {
string dtstr = NS_SampleData.SampleData.GetDataOfColumn (1);
UpdateInfo (dtstr);
T_caseNo.text = MyStringUtil.ExtractCsvColumn (dtstr, kIndex_caseNo);
T_about.text = dtstr;
}
}
public void OpenURL() {
Application.OpenURL (T_datasheetURL.text);
}
} | mit | C# |
a967ed6773c356ba080060e95f245866004b3ff0 | Fix 'no multiple zeppelins of the same type' constraint server side. | Mikuz/Battlezeppelins,Mikuz/Battlezeppelins | Battlezeppelins/Models/PlayerTable/ZeppelinType.cs | Battlezeppelins/Models/PlayerTable/ZeppelinType.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace Battlezeppelins.Models
{
public class ZeppelinType
{
public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5);
public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3);
public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2);
public static IEnumerable<ZeppelinType> Values
{
get
{
yield return MOTHER;
yield return LEET;
yield return NIBBLET;
}
}
public static ZeppelinType getByName(string name) {
foreach (ZeppelinType type in Values)
{
if (type.name == name) return type;
}
return null;
}
[JsonProperty]
public string name { get; private set; }
[JsonProperty]
public int length { get; private set; }
private ZeppelinType() { }
ZeppelinType(string name, int length)
{
this.name = name;
this.length = length;
}
public override string ToString()
{
return name;
}
public override bool Equals(object zeppelin) {
return this == (ZeppelinType)zeppelin;
}
public static bool operator==(ZeppelinType z1, ZeppelinType z2)
{
return z1.name == z2.name;
}
public static bool operator !=(ZeppelinType z1, ZeppelinType z2)
{
return z1.name != z2.name;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace Battlezeppelins.Models
{
public class ZeppelinType
{
public static readonly ZeppelinType MOTHER = new ZeppelinType("Mother", 5);
public static readonly ZeppelinType LEET = new ZeppelinType("Leet", 3);
public static readonly ZeppelinType NIBBLET = new ZeppelinType("Nibblet", 2);
public static IEnumerable<ZeppelinType> Values
{
get
{
yield return MOTHER;
yield return LEET;
yield return NIBBLET;
}
}
public static ZeppelinType getByName(string name) {
foreach (ZeppelinType type in Values)
{
if (type.name == name) return type;
}
return null;
}
[JsonProperty]
public string name { get; private set; }
[JsonProperty]
public int length { get; private set; }
private ZeppelinType() { }
ZeppelinType(string name, int length)
{
this.name = name;
this.length = length;
}
public override string ToString()
{
return name;
}
}
} | apache-2.0 | C# |
a7c2b8bac8b3579a09bd3609974ca87e86a82da8 | Revert to previous debugging method as change wasn't working correctly. | joshvera/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,rover886/CefSharp,joshvera/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,rover886/CefSharp,windygu/CefSharp,illfang/CefSharp,illfang/CefSharp,battewr/CefSharp,VioletLife/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,battewr/CefSharp,ITGlobal/CefSharp,NumbersInternational/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,Livit/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,joshvera/CefSharp,AJDev77/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,Octopus-ITSM/CefSharp,Livit/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,gregmartinhtc/CefSharp,twxstar/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,Octopus-ITSM/CefSharp,wangzheng888520/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,yoder/CefSharp,dga711/CefSharp,battewr/CefSharp,rover886/CefSharp,battewr/CefSharp,VioletLife/CefSharp,yoder/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,zhangjingpu/CefSharp,Livit/CefSharp,Octopus-ITSM/CefSharp,wangzheng888520/CefSharp,dga711/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,NumbersInternational/CefSharp,haozhouxu/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,AJDev77/CefSharp,NumbersInternational/CefSharp,windygu/CefSharp,AJDev77/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,ruisebastiao/CefSharp | CefSharp.BrowserSubprocess/Program.cs | CefSharp.BrowserSubprocess/Program.cs | // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CefSharp.Internals;
namespace CefSharp.BrowserSubprocess
{
public class Program
{
public static int Main(string[] args)
{
Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args));
int result;
using (var subprocess = Create(args))
{
//if (subprocess is CefRenderProcess)
//{
// MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
result = subprocess.Run();
}
Kernel32.OutputDebugString("BrowserSubprocess shutting down.");
return result;
}
public static CefSubProcess Create(IEnumerable<string> args)
{
const string typePrefix = "--type=";
var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix));
var type = typeArgument.Substring(typePrefix.Length);
switch (type)
{
case "renderer":
return new CefRenderProcess(args);
case "gpu-process":
return new CefGpuProcess(args);
default:
return new CefSubProcess(args);
}
}
}
}
| // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using CefSharp.Internals;
namespace CefSharp.BrowserSubprocess
{
public class Program
{
public static int Main(string[] args)
{
Kernel32.OutputDebugString("BrowserSubprocess starting up with command line: " + String.Join("\n", args));
int result;
//MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
var commandLineArgs = new List<string>(args)
{
"--renderer-startup-dialog"
};
using (var subprocess = Create(commandLineArgs.ToArray()))
{
//if (subprocess is CefRenderProcess)
//{
// MessageBox.Show("Please attach debugger now", null, MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
result = subprocess.Run();
}
Kernel32.OutputDebugString("BrowserSubprocess shutting down.");
return result;
}
public static CefSubProcess Create(IEnumerable<string> args)
{
const string typePrefix = "--type=";
var typeArgument = args.SingleOrDefault(arg => arg.StartsWith(typePrefix));
var type = typeArgument.Substring(typePrefix.Length);
switch (type)
{
case "renderer":
return new CefRenderProcess(args);
case "gpu-process":
return new CefGpuProcess(args);
default:
return new CefSubProcess(args);
}
}
}
}
| bsd-3-clause | C# |
522806fcf675265485d33b5ead87a01843b6cfae | set string option for runner | elastacloud/parquet-dotnet | src/Parquet.Runner/Program.cs | src/Parquet.Runner/Program.cs | using System;
using Parquet;
using Parquet.Data;
using LogMagic;
namespace Parquet.Runner
{
class Program
{
static void Main(string[] args)
{
L.Config
.WriteTo.PoshConsole();
DataSet ds;
using (var time = new TimeMeasure())
{
ds = ParquetReader.ReadFile(args[0], new ParquetOptions { TreatByteArrayAsString = true });
Console.WriteLine("read in {0}", time.Elapsed);
}
Console.WriteLine("has {0} rows", ds.RowCount);
//postcodes.plain.parquet - 137Mb
//debug: 26 seconds.
//release: 25 seconds.
}
}
} | using System;
using Parquet;
using Parquet.Data;
using LogMagic;
namespace Parquet.Runner
{
class Program
{
static void Main(string[] args)
{
L.Config
.WriteTo.PoshConsole();
DataSet ds;
using (var time = new TimeMeasure())
{
ds = ParquetReader.ReadFile(args[0]);
Console.WriteLine("read in {0}", time.Elapsed);
}
Console.WriteLine("has {0} rows", ds.RowCount);
//postcodes.plain.parquet - 137Mb
//debug: 26 seconds.
//release: 25 seconds.
}
}
} | mit | C# |
6552e002990d88dcc8ace02a4027fc3e0e48d857 | Fix a bug with the console arguments class | marinoscar/Luval | Code/Luval.Common/ConsoleArguments.cs | Code/Luval.Common/ConsoleArguments.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Luval.Common
{
public class ConsoleArguments
{
private List<string> _args;
public ConsoleArguments(IEnumerable<string> args)
{
_args = new List<string>(args);
}
public bool ContainsSwitch(string name)
{
return _args.Contains(name);
}
public string GetSwitchValue(string name)
{
if (!ContainsSwitch(name)) return null;
var switchIndex = _args.IndexOf(name);
if ((_args.Count - 1) < switchIndex + 1) return null;
return _args[switchIndex + 1];
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Luval.Common
{
public class ConsoleArguments
{
private List<string> _args;
public ConsoleArguments(IEnumerable<string> args)
{
_args = new List<string>(args);
}
public bool ContainsSwitch(string name)
{
return _args.Contains(name);
}
public string GetSwitchValue(string name)
{
if (!ContainsSwitch(name)) return null;
var switchIndex = _args.IndexOf(name);
if (_args.Count < switchIndex + 1) return null;
return _args[switchIndex + 1];
}
}
}
| apache-2.0 | C# |
0fd1b0876de3668e192a0136b69d108996d3d7d9 | Format object identity in result window #17 | dstarkowski/csom-inspector | CsomInspector/CsomInspector.Core/Data/Result.cs | CsomInspector/CsomInspector.Core/Data/Result.cs | using CsomInspector.Core.ObjectPaths;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CsomInspector.Core
{
public class Result
{
protected Result(Int32 actionId, IEnumerable<ResultProperty> properties)
{
ActionId = actionId;
Properties = properties;
}
public static IEnumerable<Result> FromJson(IEnumerable<JToken> tokens)
{
var resultsCount = tokens.Count() / 2;
for (int i = 0; i < resultsCount; i++)
{
var actionId = tokens
.Skip(i * 2)
.First()
.Value<Int32>();
var resultToken = tokens
.Skip(i * 2)
.Skip(1)
.First();
var properties = ResultProperty.FromJson(resultToken.Children());
yield return new Result(actionId, properties);
}
}
public Int32 ActionId { get; }
public IEnumerable<ResultProperty> Properties { get; }
}
public class ResultProperty : IObjectTreeNode
{
protected ResultProperty(String name, String value)
{
Name = name;
Value = value;
}
protected ResultProperty(String name, IEnumerable<IObjectTreeNode> children)
{
Name = name;
Children = children;
}
public IEnumerable<IObjectTreeNode> Children { get; }
public String Name { get; }
public String Value { get; }
public override String ToString()
{
if (!String.IsNullOrWhiteSpace(Value))
{
return $"{Name}: {Value}";
}
return $"{Name}";
}
public static IEnumerable<ResultProperty> FromJson(JEnumerable<JToken> tokens)
{
foreach (var token in tokens)
{
var property = token as JProperty;
var child = token.Children().FirstOrDefault();
var value = child?.ToString();
if (String.Equals(property.Name, "_ObjectIdentity_", StringComparison.InvariantCultureIgnoreCase))
{
var identity = IdentityParameter.FromIdentityString(value);
yield return new ResultProperty(property.Name, identity);
}
else
{
yield return new ResultProperty(property.Name, value);
}
}
}
}
} | using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CsomInspector.Core
{
public class Result
{
protected Result(Int32 actionId, IEnumerable<ResultProperty> properties)
{
ActionId = actionId;
Properties = properties;
}
public static IEnumerable<Result> FromJson(IEnumerable<JToken> tokens)
{
var resultsCount = tokens.Count() / 2;
for (int i = 0; i < resultsCount; i++)
{
var actionId = tokens
.Skip(i * 2)
.First()
.Value<Int32>();
var resultToken = tokens
.Skip(i * 2)
.Skip(1)
.First();
var properties = ResultProperty.FromJson(resultToken.Children());
yield return new Result(actionId, properties);
}
}
public Int32 ActionId { get; private set; }
public IEnumerable<ResultProperty> Properties { get; private set; }
}
public class ResultProperty : IObjectTreeNode
{
protected ResultProperty(String name, String value)
{
Name = name;
Value = value;
}
protected ResultProperty(String name, IEnumerable<IObjectTreeNode> children)
{
Name = name;
Children = children;
}
public IEnumerable<IObjectTreeNode> Children { get; private set; }
public String Name { get; private set; }
public String Value { get; private set; }
public override String ToString()
{
if (!String.IsNullOrWhiteSpace(Value))
{
return $"{Name}: {Value}";
}
return $"{Name}";
}
public static IEnumerable<ResultProperty> FromJson(JEnumerable<JToken> tokens)
{
foreach (var token in tokens)
{
var name = token.Path;
var child = token.Children().FirstOrDefault();
var value = child?.ToString();
yield return new ResultProperty(name, value);
}
}
}
} | mit | C# |
2ff0df6800e53b54bf163d8546413bcc5d9975fa | Support for running the app in a "portable" mode | IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner | MultiMiner.Utility/ApplicationPaths.cs | MultiMiner.Utility/ApplicationPaths.cs | using System;
using System.IO;
namespace MultiMiner.Utility
{
public static class ApplicationPaths
{
public static string AppDataPath()
{
//if running in "portable" mode
if (IsRunningInPortableMode())
{
//store files in the working directory rather than AppData
return GetWorkingDirectory();
}
else
{
string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(rootPath, "MultiMiner");
}
}
//simply check for a file named "portable" in the same folder
private static bool IsRunningInPortableMode()
{
string assemblyDirectory = GetWorkingDirectory();
string portableFile = Path.Combine(assemblyDirectory, "portable");
return File.Exists(portableFile);
}
private static string GetWorkingDirectory()
{
string assemblyFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
return Path.GetDirectoryName(assemblyFilePath);
}
}
}
| using System;
using System.IO;
namespace MultiMiner.Utility
{
public static class ApplicationPaths
{
public static string AppDataPath()
{
string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(rootPath, "MultiMiner");
}
}
}
| mit | C# |
55d42969c63e8cd68cec0884735aa9f4afa4b93f | fix codebase to comply with code analysis | hylasoft-usa/h-dependency,hylasoft-usa/h-dependency | h-dependency/tests/HDependency.Tests.cs | h-dependency/tests/HDependency.Tests.cs | using System;
using System.Collections;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Hylasoft.Dependency.Tests
{
[TestClass]
public class AccountTest
{
[TestMethod]
public void ShouldInitializeTheSingletonCorrectly()
{
// Init to true
var dep = Hdependency.Initialize(true);
Assert.AreEqual(dep, Hdependency.Provider, "the returned hdep should be the same of the singleton");
try
{
Hdependency.Initialize();
}
catch (Exception)
{
Assert.Fail("it shouldn't fail this time, since it's in test");
}
Assert.AreNotEqual(dep, Hdependency.Provider,
"the two deps now shouldn't be the same, since it's been reinitialized");
try
{
Hdependency.Initialize(true);
Assert.Fail("It should fail now because it has been not initialized in test mode before");
}
catch (InvalidOperationException)
{
//here is fine, the exception is being correctly thrown
}
}
[TestMethod]
public void ShouldGetTheRightService()
{
var dep = new Hdependency();
IEnumerable service = "test"; //a string is a valid IEnumerable, so this is possible
dep.Register<IEnumerable>(service);
Assert.AreEqual("test", dep.Get<IEnumerable>());
}
[TestMethod]
public void ShouldntRegisterTwice()
{
var dep = new Hdependency();
IEnumerable service = "test"; //a string is a valid IEnumerable, so this is possible
dep.Register<IEnumerable>(service);
try
{
dep.Register<IEnumerable>(service); //already registered
Assert.Fail();
}
catch (InvalidOperationException)
{
//here is fine, the exception is being correctly thrown
}
}
[TestMethod]
public void ShouldntRegisterWrongInterface()
{
var dep = new Hdependency();
var service = new object();
try
{
dep.Register<IEnumerable>(service); //wrong interface
Assert.Fail();
}
catch (ArgumentException)
{
//here is fine, the exception is being correctly thrown
}
}
[TestMethod]
public void ShouldThrowArgumentExceptionWhenNoService()
{
var dep = new Hdependency();
try
{
dep.Get<IEnumerable>(); //no such service
Assert.Fail();
}
catch (ArgumentException)
{
//here is fine, the exception is being correctly thrown
}
}
}
}
| using System;
using System.Collections;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Hylasoft.Dependency.Tests
{
[TestClass]
public class AccountTest
{
[TestMethod]
public void ShouldInitializeTheSingletonCorrectly()
{
// Init to true
var dep = Hdependency.Initialize(true);
Assert.AreEqual(dep, Hdependency.Provider, "the returned hdep should be the same of the singleton");
try
{
Hdependency.Initialize();
}
catch (Exception)
{
Assert.Fail("it shouldn't fail this time, since it's in test");
}
Assert.AreNotEqual(dep, Hdependency.Provider,
"the two deps now shouldn't be the same, since it's been reinitialized");
try
{
Hdependency.Initialize(true);
Assert.Fail("It should fail now because it has been not initialized in test mode before");
}
catch (InvalidOperationException e)
{
//here is fine, the exception is being correctly thrown
}
}
[TestMethod]
public void ShouldGetTheRightService()
{
var dep = new Hdependency();
IEnumerable service = "test"; //a string is a valid IEnumerable, so this is possible
dep.Register<IEnumerable>(service);
Assert.AreEqual("test", dep.Get<IEnumerable>());
}
[TestMethod]
public void ShouldntRegisterTwice()
{
var dep = new Hdependency();
IEnumerable service = "test"; //a string is a valid IEnumerable, so this is possible
dep.Register<IEnumerable>(service);
try
{
dep.Register<IEnumerable>(service); //already registered
Assert.Fail();
}
catch (InvalidOperationException)
{
//here is fine, the exception is being correctly thrown
}
}
[TestMethod]
public void ShouldntRegisterWrongInterface()
{
var dep = new Hdependency();
var service = new object();
try
{
dep.Register<IEnumerable>(service); //wrong interface
Assert.Fail();
}
catch (ArgumentException)
{
//here is fine, the exception is being correctly thrown
}
}
[TestMethod]
public void ShouldThrowArgumentExceptionWhenNoService()
{
var dep = new Hdependency();
try
{
dep.Get<IEnumerable>(); //no such service
Assert.Fail();
}
catch (ArgumentException)
{
//here is fine, the exception is being correctly thrown
}
}
}
} | mit | C# |
3cdf1c9109a6ca15ba279c52a0a9a6306312b8b4 | Support click-through in BrowserWindow | quisquous/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot | BrowserWindow.xaml.cs | BrowserWindow.xaml.cs | using CefSharp.Wpf;
using System;
using System.Windows;
using System.Windows.Interop;
using System.Runtime.InteropServices;
namespace Cactbot
{
public partial class BrowserWindow : Window
{
[DllImport("user32.dll")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public BrowserWindow()
{
InitializeComponent();
}
private bool clickable = true;
public bool Clickable
{
get { return clickable; }
set
{
if (clickable == value)
return;
IntPtr handle = new WindowInteropHelper(this).Handle;
if (handle == IntPtr.Zero)
return;
clickable = value;
const int getWindowLongExStyle = -20;
const int transparent = 0x20;
const int layered = 0x80000;
int exStyle = GetWindowLong(handle, getWindowLongExStyle);
if (clickable)
exStyle = exStyle & ~transparent & ~layered;
else
exStyle = exStyle | transparent | layered;
SetWindowLong(handle, getWindowLongExStyle, exStyle);
}
}
private void Window_Activated(object sender, System.EventArgs e)
{
// Delay until window has a handle.
Clickable = false;
// Terrible hack to fix missing content: http://stackoverflow.com/a/597055
// This is the source of the delay before the window appears.
this.Width++;
this.Width--;
}
}
}
| using CefSharp.Wpf;
using System.Windows;
using System.Windows.Interop;
namespace Cactbot
{
public partial class BrowserWindow : Window
{
public BrowserWindow()
{
InitializeComponent();
}
private void Window_Activated(object sender, System.EventArgs e)
{
// Terrible hack to fix missing content: http://stackoverflow.com/a/597055
// This is the source of the delay before the window appears.
this.Width++;
this.Width--;
}
}
}
| apache-2.0 | C# |
6f8e1844e14e3f287c167cbd83f9e9fd074429cb | fix version | Fody/PropertyChanged | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.2.0")] | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.1.5")] | mit | C# |
44c1c93e816f683fe63af8e96f0aad6b827aebb5 | Change DisabledProgramSource class to inherit ProgramSource | qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox,Wox-launcher/Wox | Plugins/Wox.Plugin.Program/Settings.cs | Plugins/Wox.Plugin.Program/Settings.cs | using System.Collections.Generic;
using System.IO;
using Wox.Plugin.Program.Programs;
namespace Wox.Plugin.Program
{
public class Settings
{
public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>();
public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>();
public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"};
public bool EnableStartMenuSource { get; set; } = true;
public bool EnableRegistrySource { get; set; } = true;
internal const char SuffixSeperator = ';';
/// <summary>
/// Contains user added folder location contents as well as all user disabled applications
/// </summary>
/// <remarks>
/// <para>Win32 class applications sets UniqueIdentifier using their full path</para>
/// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para>
/// </remarks>
public class ProgramSource
{
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public bool Enabled { get; set; } = true;
public string UniqueIdentifier { get; set; }
}
public class DisabledProgramSource : ProgramSource { }
}
}
| using System.Collections.Generic;
using System.IO;
using Wox.Plugin.Program.Programs;
namespace Wox.Plugin.Program
{
public class Settings
{
public List<ProgramSource> ProgramSources { get; set; } = new List<ProgramSource>();
public List<DisabledProgramSource> DisabledProgramSources { get; set; } = new List<DisabledProgramSource>();
public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"};
public bool EnableStartMenuSource { get; set; } = true;
public bool EnableRegistrySource { get; set; } = true;
internal const char SuffixSeperator = ';';
/// <summary>
/// Contains user added folder location contents as well as all user disabled applications
/// </summary>
/// <remarks>
/// <para>Win32 class applications sets UniqueIdentifier using their full path</para>
/// <para>UWP class applications sets UniqueIdentifier using their Application User Model ID</para>
/// </remarks>
public class ProgramSource
{
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public bool Enabled { get; set; } = true;
public string UniqueIdentifier { get; set; }
}
public class DisabledProgramSource
{
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public bool Enabled { get; set; } = true;
public string UniqueIdentifier { get; set; }
}
}
}
| mit | C# |
9622fd43680e1dc2aca2b3de080347d5b7dcec0e | Update version | bringking/mailgun_csharp | Mailgun.AspNet.Identity/Properties/AssemblyInfo.cs | Mailgun.AspNet.Identity/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mailgun API Wrapper- ASP.net Identity services")]
[assembly: AssemblyDescription("An IIdentityMessageService implemention using the mailgun_csharp API wrapper")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Charles King")]
[assembly: AssemblyProduct("Mailgun.AspNet.Identity")]
[assembly: AssemblyCopyright("Copyright Charles King © 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("c7633e64-9745-4341-b230-1e7450790ade")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0")]
[assembly: AssemblyFileVersion("0.3.0")]
[assembly: AssemblyInformationalVersion("0.3.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mailgun API Wrapper- ASP.net Identity services")]
[assembly: AssemblyDescription("An IIdentityMessageService implemention using the mailgun_csharp API wrapper")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Charles King")]
[assembly: AssemblyProduct("Mailgun.AspNet.Identity")]
[assembly: AssemblyCopyright("Copyright Charles King © 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("c7633e64-9745-4341-b230-1e7450790ade")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0")]
[assembly: AssemblyFileVersion("0.3.0")]
[assembly: AssemblyInformationalVersion("0.3.0-alpha")]
| mit | C# |
4c7f0ac1d26ae411237ee1e64c9ad603a2288747 | Update Assembly Information | Valetude/Valetude.Rollbar | Rollbar.Net/Properties/AssemblyInfo.cs | Rollbar.Net/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Rollbar.Net")]
[assembly: AssemblyDescription("C# Rollbar Payload, post it whenever and however it makes sense")]
[assembly: AssemblyCompany("Valetude LLC")]
[assembly: AssemblyProduct("Rollbar.Net")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyCulture("en-US")]
// 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("034b2c39-d11f-4285-9e1a-f423c01133cc")]
// 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: AssemblyFileVersion("1.0.*")]
| 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("Rollbar.Net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rollbar.Net")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("034b2c39-d11f-4285-9e1a-f423c01133cc")]
// 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")]
| mit | C# |
eb1a6cc8f7ca008e28409670fcfd428733cd37b4 | bump version | Fody/Equals | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fody.Equals")]
[assembly: AssemblyProduct("Fody.Equals")]
[assembly: AssemblyVersion("1.3.9")]
[assembly: AssemblyFileVersion("1.3.9")]
| using System.Reflection;
[assembly: AssemblyTitle("Fody.Equals")]
[assembly: AssemblyProduct("Fody.Equals")]
[assembly: AssemblyVersion("1.3.8")]
[assembly: AssemblyFileVersion("1.3.8")]
| mit | C# |
a241ddf597b654757d4fd3290cc008b02dc0c470 | bump version | SimonCropp/NServiceBus.Serilog | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("3.0.3")]
[assembly: AssemblyFileVersion("3.0.3")] | using System.Reflection;
[assembly: AssemblyVersion("3.0.2")]
[assembly: AssemblyFileVersion("3.0.2")] | mit | C# |
595b9e94894957fac735c5fb8bbaf3859c3fd365 | bump version | GeertvanHorrik/Fody,Fody/Fody,ColinDabritzViewpoint/Fody | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("2.0.8")]
[assembly: AssemblyFileVersion("2.0.8")] | using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("2.0.7")]
[assembly: AssemblyFileVersion("2.0.7")] | mit | C# |
a504229fb8e7924c72af6cfec64b51c610533cf2 | Extend events args | coolya/logv.http | SimpleHttpServerExtensions/AsyncStreamCopier.cs | SimpleHttpServerExtensions/AsyncStreamCopier.cs | /*
Copyright 2012 Kolja Dummann <k.dummann@gmail.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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace SimpleHttpServer
{
public class AsynStreamCopyCompleteEventArgs : EventArgs
{
readonly Stream inputStream;
readonly Stream outputStream;
public Stream InputStream { get { return inputStream; } }
public Stream OutputStream { get { return outputStream; } }
public AsynStreamCopyCompleteEventArgs(Stream input, Stream output)
{
inputStream = input;
outputStream = output;
}
}
/// <summary>
/// Copies data from one stream into another using the async pattern. Copies are done in 4k blocks.
/// </summary>
public class AsyncStreamCopier
{
readonly Stream _input;
readonly Stream _output;
byte[] buffer = new byte[4096];
/// <summary>
/// Raised when all data is copied
/// </summary>
public event EventHandler<AsynStreamCopyCompleteEventArgs> Completed;
public AsyncStreamCopier(Stream input, Stream output)
{
_input = input;
_output = output;
}
/// <summary>
/// Starts the copying
/// </summary>
public void Copy()
{
GetData();
}
void GetData()
{
_input.BeginRead(buffer, 0, buffer.Length, ReadComplete, null);
}
void ReadComplete(IAsyncResult result)
{
int bytes = _input.EndRead(result);
if (bytes == 0)
{
RaiseComplete();
return;
}
_output.Write(buffer, 0, bytes);
GetData();
}
void RaiseComplete()
{
var handler = Completed;
if (handler != null)
handler(this,new AsynStreamCopyCompleteEventArgs(_input, _output));
}
}
}
| /*
Copyright 2012 Kolja Dummann <k.dummann@gmail.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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace SimpleHttpServer
{
/// <summary>
/// Copies data from one stream into another using the async pattern. Copies are done in 4k blocks.
/// </summary>
public class AsyncStreamCopier
{
readonly Stream _input;
readonly Stream _output;
byte[] buffer = new byte[4096];
/// <summary>
/// Raised when all data is copied
/// </summary>
public event EventHandler Completed;
public AsyncStreamCopier(Stream input, Stream output)
{
_input = input;
_output = output;
}
/// <summary>
/// Starts the copying
/// </summary>
public void Copy()
{
GetData();
}
void GetData()
{
_input.BeginRead(buffer, 0, buffer.Length, ReadComplete, null);
}
void ReadComplete(IAsyncResult result)
{
int bytes = _input.EndRead(result);
if (bytes == 0)
{
RaiseComplete();
return;
}
_output.Write(buffer, 0, bytes);
GetData();
}
void RaiseComplete()
{
var handler = Completed;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
}
| apache-2.0 | C# |
b0bfc09390c3f1d1b097c889dc8dfc8c0bf133df | put x-ms-routing-name in cookie when calling auth provider | fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS | SimpleWAWS/Authentication/GoogleAuthProvider.cs | SimpleWAWS/Authentication/GoogleAuthProvider.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SimpleWAWS.Authentication
{
public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider
{
public override string GetLoginUrl(HttpContextBase context)
{
var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant();
var builder = new StringBuilder();
builder.Append("https://accounts.google.com/o/oauth2/auth");
builder.Append("?response_type=id_token");
var slot = String.Empty;
if (context.Request.QueryString["x-ms-routing-name"] != null)
// slot = $"?x-ms-routing-name={context.Request.QueryString["x-ms-routing-name"]}";
context.Response.Cookies.Add(new HttpCookie("x-ms-routing-name", context.Request.QueryString["x-ms-routing-name"]));
builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login{1}", context.Request.Headers["HOST"], slot)));
builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId);
builder.AppendFormat("&scope={0}", "email");
if (context.IsFunctionsPortalRequest())
{
builder.AppendFormat("&state={0}",
WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}{1}",
context.Request.Headers["Referer"], context.Request.Url.Query) ));
}
else
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery));
return builder.ToString();
}
protected override string GetValidAudiance()
{
return AuthSettings.GoogleAppId;
}
public override string GetIssuerName(string altSecId)
{
return "Google";
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SimpleWAWS.Authentication
{
public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider
{
public override string GetLoginUrl(HttpContextBase context)
{
var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant();
var builder = new StringBuilder();
builder.Append("https://accounts.google.com/o/oauth2/auth");
builder.Append("?response_type=id_token");
var slot = String.Empty;
if (context.Request.QueryString["x-ms-routing-name"] != null)
slot = $"?x-ms-routing-name={context.Request.QueryString["x-ms-routing-name"]}";
builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login{1}", context.Request.Headers["HOST"], slot)));
builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId);
builder.AppendFormat("&scope={0}", "email");
if (context.IsFunctionsPortalRequest())
{
builder.AppendFormat("&state={0}",
WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}{1}",
context.Request.Headers["Referer"], context.Request.Url.Query) ));
}
else
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery));
return builder.ToString();
}
protected override string GetValidAudiance()
{
return AuthSettings.GoogleAppId;
}
public override string GetIssuerName(string altSecId)
{
return "Google";
}
}
} | apache-2.0 | C# |
5f48067932e8b83cef86a9bcc472f009000a17e5 | remove unnecessary dot at end of full version string | makmu/outlook-matters,maxlmo/outlook-matters,maxlmo/outlook-matters,makmu/outlook-matters | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("outlook-matters project")]
[assembly: AssemblyProduct("OutlookMatters Addin")]
[assembly: AssemblyDescription("An Outlook-Mattermost Bridge")]
[assembly: AssemblyCopyright("Copyright © 2016 by the outlook-matters developers")]
[assembly: AssemblyTrademark("This application has no Trademark.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyVersion(Version.Current)]
[assembly: AssemblyFileVersion(Version.Current)]
[assembly: AssemblyInformationalVersion(Version.FullCurrent)]
class Version
{
// refer to http://semver.org for more information
public const string Major = "1";
public const string Minor = "0";
public const string Patch = "0";
public const string Label = ReleaseLabel.Dev;
public const string AdditionalReleaseInformation = "";
public const string Current = Major + "." + Minor + "." + Patch;
public const string FullCurrent = Current + "-" + Label + AdditionalReleaseInformation;
}
class ReleaseLabel
{
public const string Dev = "dev";
public const string ReleaseCandidate = "rc";
public const string Final = "official";
} | using System.Reflection;
[assembly: AssemblyCompany("outlook-matters project")]
[assembly: AssemblyProduct("OutlookMatters Addin")]
[assembly: AssemblyDescription("An Outlook-Mattermost Bridge")]
[assembly: AssemblyCopyright("Copyright © 2016 by the outlook-matters developers")]
[assembly: AssemblyTrademark("This application has no Trademark.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyVersion(Version.Current)]
[assembly: AssemblyFileVersion(Version.Current)]
[assembly: AssemblyInformationalVersion(Version.FullCurrent)]
class Version
{
// refer to http://semver.org for more information
public const string Major = "1";
public const string Minor = "0";
public const string Patch = "0";
public const string Label = ReleaseLabel.Dev;
public const string AdditionalReleaseInformation = "";
public const string Current = Major + "." + Minor + "." + Patch;
public const string FullCurrent = Current + "-" + Label + "." + AdditionalReleaseInformation;
}
class ReleaseLabel
{
public const string Dev = "dev";
public const string ReleaseCandidate = "rc";
public const string Final = "official";
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.