Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix when reverting a vessel so they are not fully removed from server | using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaClient.Network;
using LunaCommon.Message.Client;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
using System;
namespace LunaClient.Systems.VesselRemoveSys
{
public class VesselRemoveMessageSender : SubSystem<VesselRemoveSystem>, IMessageSender
{
public void SendMessage(IMessageData msg)
{
TaskFactory.StartNew(() => NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew<VesselCliMsg>(msg))); ;
}
/// <summary>
/// Sends a vessel remove to the server
/// </summary>
public void SendVesselRemove(Guid vesselId, bool keepVesselInRemoveList = true)
{
LunaLog.Log($"[LMP]: Removing {vesselId} from the server");
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<VesselRemoveMsgData>();
msgData.VesselId = vesselId;
msgData.AddToKillList = true;
SendMessage(msgData);
}
}
} | using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaClient.Network;
using LunaCommon.Message.Client;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
using System;
namespace LunaClient.Systems.VesselRemoveSys
{
public class VesselRemoveMessageSender : SubSystem<VesselRemoveSystem>, IMessageSender
{
public void SendMessage(IMessageData msg)
{
TaskFactory.StartNew(() => NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew<VesselCliMsg>(msg))); ;
}
/// <summary>
/// Sends a vessel remove to the server. If keepVesselInRemoveList is set to true, the vessel will be removed for good and the server
/// will skip future updates related to this vessel
/// </summary>
public void SendVesselRemove(Guid vesselId, bool keepVesselInRemoveList = true)
{
LunaLog.Log($"[LMP]: Removing {vesselId} from the server");
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<VesselRemoveMsgData>();
msgData.VesselId = vesselId;
msgData.AddToKillList = keepVesselInRemoveList;
SendMessage(msgData);
}
}
} |
Use number provider for m_flStartTime | using System;
using ValveResourceFormat.Serialization;
namespace GUI.Types.ParticleRenderer.Emitters
{
public class InstantaneousEmitter : IParticleEmitter
{
public bool IsFinished { get; private set; }
private readonly IKeyValueCollection baseProperties;
private Action particleEmitCallback;
private INumberProvider emitCount;
private float startTime;
private float time;
public InstantaneousEmitter(IKeyValueCollection baseProperties, IKeyValueCollection keyValues)
{
this.baseProperties = baseProperties;
emitCount = keyValues.GetNumberProvider("m_nParticlesToEmit");
startTime = keyValues.GetFloatProperty("m_flStartTime");
}
public void Start(Action particleEmitCallback)
{
this.particleEmitCallback = particleEmitCallback;
IsFinished = false;
time = 0;
}
public void Stop()
{
}
public void Update(float frameTime)
{
time += frameTime;
if (!IsFinished && time >= startTime)
{
var numToEmit = emitCount.NextInt(); // Get value from number provider
for (var i = 0; i < numToEmit; i++)
{
particleEmitCallback();
}
IsFinished = true;
}
}
}
}
| using System;
using ValveResourceFormat.Serialization;
namespace GUI.Types.ParticleRenderer.Emitters
{
public class InstantaneousEmitter : IParticleEmitter
{
public bool IsFinished { get; private set; }
private readonly IKeyValueCollection baseProperties;
private Action particleEmitCallback;
private INumberProvider emitCount;
private INumberProvider startTime;
private float time;
public InstantaneousEmitter(IKeyValueCollection baseProperties, IKeyValueCollection keyValues)
{
this.baseProperties = baseProperties;
emitCount = keyValues.GetNumberProvider("m_nParticlesToEmit");
startTime = keyValues.GetNumberProvider("m_flStartTime");
}
public void Start(Action particleEmitCallback)
{
this.particleEmitCallback = particleEmitCallback;
IsFinished = false;
time = 0;
}
public void Stop()
{
}
public void Update(float frameTime)
{
time += frameTime;
if (!IsFinished && time >= startTime.NextNumber())
{
var numToEmit = emitCount.NextInt(); // Get value from number provider
for (var i = 0; i < numToEmit; i++)
{
particleEmitCallback();
}
IsFinished = true;
}
}
}
}
|
Clean up---cannot utilize dynamic loading of dll in VS. | namespace LanguageServer
{
//using Options;
using System;
using System.Collections.Generic;
using System.Reflection;
public class ManualAssemblyResolver : IDisposable
{
private readonly List<Assembly> _assemblies;
public ManualAssemblyResolver()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolve);
_assemblies = new List<Assembly>();
}
public void Add(Assembly assembly)
{
_assemblies.Add(assembly);
}
public ManualAssemblyResolver(Assembly assembly)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolve);
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
_assemblies = new List<Assembly>
{
assembly
};
}
public void Dispose()
{
AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve;
}
private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
foreach (Assembly assembly in _assemblies)
{
if (args.Name == assembly.FullName)
{
return assembly;
}
}
return null;
}
}
public class GrammarDescriptionFactory
{
private static readonly IGrammarDescription _antlr = new AntlrGrammarDescription();
public static List<string> AllLanguages
{
get
{
List<string> result = new List<string>
{
_antlr.Name
};
return result;
}
}
public static IGrammarDescription Create(string ffn)
{
if (_antlr.IsFileType(ffn))
{
return _antlr;
}
return null;
}
}
}
| namespace LanguageServer
{
//using Options;
using System;
using System.Collections.Generic;
using System.Reflection;
public class GrammarDescriptionFactory
{
private static readonly IGrammarDescription _antlr = new AntlrGrammarDescription();
public static List<string> AllLanguages
{
get
{
List<string> result = new List<string>
{
_antlr.Name
};
return result;
}
}
public static IGrammarDescription Create(string ffn)
{
if (_antlr.IsFileType(ffn))
{
return _antlr;
}
return null;
}
}
}
|
Set up the basic program structure. | // -----------------------------------------------------------------------
// <copyright file="Program.cs" company="(none)">
// Copyright © 2013 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.txt for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Weave
{
internal class Program
{
private static void Main(string[] args)
{
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="Program.cs" company="(none)">
// Copyright © 2013 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.txt for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Weave
{
using System;
using System.IO;
using Weave.Parser;
internal class Program
{
private static void Main(string[] args)
{
var input = File.ReadAllText(args[0]);
var parser = new WeaveParser();
var output = parser.Parse(input);
Console.WriteLine(output);
}
}
}
|
Add year to copyright attribute. | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("NDeproxy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Rackspace")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.17.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("NDeproxy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2014 Rackspace")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.17.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
Fix null check to use string.IsNullOrEmpty. Even though unlikely, if a string.empty is passed as input it will result in an infinite loop. | namespace Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.Implementation
{
using System;
using Microsoft.ApplicationInsights.Channel;
/// <summary>
/// Utility class for sampling score generation.
/// </summary>
internal static class SamplingScoreGenerator
{
/// <summary>
/// Generates telemetry sampling score between 0 and 100.
/// </summary>
/// <param name="telemetry">Telemetry item to score.</param>
/// <returns>Item sampling score.</returns>
public static double GetSamplingScore(ITelemetry telemetry)
{
double samplingScore = 0;
if (telemetry.Context.User.Id != null)
{
samplingScore = (double)telemetry.Context.User.Id.GetSamplingHashCode() / int.MaxValue;
}
else if (telemetry.Context.Operation.Id != null)
{
samplingScore = (double)telemetry.Context.Operation.Id.GetSamplingHashCode() / int.MaxValue;
}
else
{
samplingScore = (double)WeakConcurrentRandom.Instance.Next() / ulong.MaxValue;
}
return samplingScore * 100;
}
internal static int GetSamplingHashCode(this string input)
{
if (input == null)
{
return 0;
}
while (input.Length < 8)
{
input = input + input;
}
int hash = 5381;
for (int i = 0; i < input.Length; i++)
{
hash = ((hash << 5) + hash) + (int)input[i];
}
return hash == int.MinValue ? int.MaxValue : Math.Abs(hash);
}
}
}
| namespace Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.Implementation
{
using System;
using Microsoft.ApplicationInsights.Channel;
/// <summary>
/// Utility class for sampling score generation.
/// </summary>
internal static class SamplingScoreGenerator
{
/// <summary>
/// Generates telemetry sampling score between 0 and 100.
/// </summary>
/// <param name="telemetry">Telemetry item to score.</param>
/// <returns>Item sampling score.</returns>
public static double GetSamplingScore(ITelemetry telemetry)
{
double samplingScore = 0;
if (telemetry.Context.User.Id != null)
{
samplingScore = (double)telemetry.Context.User.Id.GetSamplingHashCode() / int.MaxValue;
}
else if (telemetry.Context.Operation.Id != null)
{
samplingScore = (double)telemetry.Context.Operation.Id.GetSamplingHashCode() / int.MaxValue;
}
else
{
samplingScore = (double)WeakConcurrentRandom.Instance.Next() / ulong.MaxValue;
}
return samplingScore * 100;
}
internal static int GetSamplingHashCode(this string input)
{
if (string.IsNullOrEmpty(input))
{
return 0;
}
while (input.Length < 8)
{
input = input + input;
}
int hash = 5381;
for (int i = 0; i < input.Length; i++)
{
hash = ((hash << 5) + hash) + (int)input[i];
}
return hash == int.MinValue ? int.MaxValue : Math.Abs(hash);
}
}
}
|
Use AccessTokenConfiguration to register AuthInfo | using System;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
namespace AppHarbor
{
public class AppHarborInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
container.Register(AllTypes
.FromThisAssembly()
.BasedOn<ICommand>()
.WithService.AllInterfaces());
container.Register(Component
.For<AccessTokenConfiguration>());
container.Register(Component
.For<AppHarborApi>());
container.Register(Component
.For<AuthInfo>()
.UsingFactoryMethod(x =>
{
var token = Environment.GetEnvironmentVariable("AppHarborToken", EnvironmentVariableTarget.User);
return new AuthInfo { AccessToken = token };
}));
container.Register(Component
.For<CommandDispatcher>());
}
}
}
| using System;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
namespace AppHarbor
{
public class AppHarborInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
container.Register(AllTypes
.FromThisAssembly()
.BasedOn<ICommand>()
.WithService.AllInterfaces());
container.Register(Component
.For<AccessTokenConfiguration>());
container.Register(Component
.For<AppHarborApi>());
container.Register(Component
.For<AuthInfo>()
.UsingFactoryMethod(x =>
{
var accessTokenConfiguration = container.Resolve<AccessTokenConfiguration>();
return new AuthInfo { AccessToken = accessTokenConfiguration.GetAccessToken() };
}));
container.Register(Component
.For<CommandDispatcher>());
}
}
}
|
Fix path to enum namespace | namespace EverlastingStudent.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using EverlastingStudent.Common;
public class Difficulty
{
private ICollection<Homework> homeworks;
private ICollection<FreelanceProject> freelanceProjects;
public Difficulty()
{
this.homeworks = new HashSet<Homework>();
this.freelanceProjects = new HashSet<FreelanceProject>();
}
[Key]
public int Id { get; set; }
[Required]
public int Value { get; set; }
[Required]
public TypeOfDifficulty type { get; set; }
public virtual ICollection<Homework> Homeworks
{
get { return this.homeworks; }
set { this.homeworks = value; }
}
public virtual ICollection<FreelanceProject> FreelanceProjects
{
get { return this.freelanceProjects; }
set { this.freelanceProjects = value; }
}
}
}
| namespace EverlastingStudent.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using EverlastingStudent.Common.Models;
public class Difficulty
{
private ICollection<Homework> homeworks;
private ICollection<FreelanceProject> freelanceProjects;
public Difficulty()
{
this.homeworks = new HashSet<Homework>();
this.freelanceProjects = new HashSet<FreelanceProject>();
}
[Key]
public int Id { get; set; }
[Required]
public int Value { get; set; }
[Required]
public TypeOfDifficulty type { get; set; }
public virtual ICollection<Homework> Homeworks
{
get { return this.homeworks; }
set { this.homeworks = value; }
}
public virtual ICollection<FreelanceProject> FreelanceProjects
{
get { return this.freelanceProjects; }
set { this.freelanceProjects = value; }
}
}
}
|
Remove read ip from header | using System;
using Abp.Auditing;
using Castle.Core.Logging;
using Microsoft.AspNetCore.Http;
using Abp.Extensions;
namespace Abp.AspNetCore.Mvc.Auditing
{
public class HttpContextClientInfoProvider : IClientInfoProvider
{
public string BrowserInfo => GetBrowserInfo();
public string ClientIpAddress => GetClientIpAddress();
public string ComputerName => GetComputerName();
public ILogger Logger { get; set; }
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly HttpContext _httpContext;
/// <summary>
/// Creates a new <see cref="HttpContextClientInfoProvider"/>.
/// </summary>
public HttpContextClientInfoProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_httpContext = httpContextAccessor.HttpContext;
Logger = NullLogger.Instance;
}
protected virtual string GetBrowserInfo()
{
var httpContext = _httpContextAccessor.HttpContext ?? _httpContext;
return httpContext?.Request?.Headers?["User-Agent"];
}
protected virtual string GetClientIpAddress()
{
try
{
var httpContext = _httpContextAccessor.HttpContext ?? _httpContext;
var clientIp = httpContext?.Request?.Headers["HTTP_X_FORWARDED_FOR"].ToString();
if (clientIp.IsNullOrEmpty())
{
clientIp = httpContext?.Connection?.RemoteIpAddress?.ToString();
}
return clientIp.Remove(clientIp.IndexOf(':'));
}
catch (Exception ex)
{
Logger.Warn(ex.ToString());
}
return null;
}
protected virtual string GetComputerName()
{
return null; //TODO: Implement!
}
}
}
| using System;
using Abp.Auditing;
using Castle.Core.Logging;
using Microsoft.AspNetCore.Http;
using Abp.Extensions;
namespace Abp.AspNetCore.Mvc.Auditing
{
public class HttpContextClientInfoProvider : IClientInfoProvider
{
public string BrowserInfo => GetBrowserInfo();
public string ClientIpAddress => GetClientIpAddress();
public string ComputerName => GetComputerName();
public ILogger Logger { get; set; }
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly HttpContext _httpContext;
/// <summary>
/// Creates a new <see cref="HttpContextClientInfoProvider"/>.
/// </summary>
public HttpContextClientInfoProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_httpContext = httpContextAccessor.HttpContext;
Logger = NullLogger.Instance;
}
protected virtual string GetBrowserInfo()
{
var httpContext = _httpContextAccessor.HttpContext ?? _httpContext;
return httpContext?.Request?.Headers?["User-Agent"];
}
protected virtual string GetClientIpAddress()
{
try
{
var httpContext = _httpContextAccessor.HttpContext ?? _httpContext;
return httpContext?.Connection?.RemoteIpAddress?.ToString();
}
catch (Exception ex)
{
Logger.Warn(ex.ToString());
}
return null;
}
protected virtual string GetComputerName()
{
return null; //TODO: Implement!
}
}
}
|
Increase default timeout to 30 secs | namespace Boxed.Templates.Test
{
using System;
using System.Threading;
public static class CancellationTokenFactory
{
public static CancellationToken GetCancellationToken(TimeSpan? timeout) =>
GetCancellationToken(timeout ?? TimeSpan.FromSeconds(20));
public static CancellationToken GetCancellationToken(TimeSpan timeout) =>
new CancellationTokenSource(timeout).Token;
}
}
| namespace Boxed.Templates.Test
{
using System;
using System.Threading;
public static class CancellationTokenFactory
{
public static CancellationToken GetCancellationToken(TimeSpan? timeout) =>
GetCancellationToken(timeout ?? TimeSpan.FromSeconds(30));
public static CancellationToken GetCancellationToken(TimeSpan timeout) =>
new CancellationTokenSource(timeout).Token;
}
}
|
Add stub object storage credentials | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CenturyLinkCloudSDK.IntegrationTests
{
public static class Credentials
{
public static string Username = "";
public static string Password = "";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CenturyLinkCloudSDK.IntegrationTests
{
public static class Credentials
{
public static string Username = "";
public static string Password = "";
public static string ObjectStorageAccessKeyId = "";
public static string ObjectStorageSecretAccessKey = "";
}
}
|
Fix broken example notification after closing it and then changing options | using System.Windows.Forms;
using TweetDuck.Plugins;
using TweetDuck.Resources;
namespace TweetDuck.Core.Notification.Example{
sealed class FormNotificationExample : FormNotificationMain{
public override bool RequiresResize => true;
protected override bool CanDragWindow => Program.UserConfig.NotificationPosition == TweetNotification.Position.Custom;
protected override FormBorderStyle NotificationBorderStyle{
get{
if (Program.UserConfig.NotificationSize == TweetNotification.Size.Custom){
switch(base.NotificationBorderStyle){
case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable;
case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow;
}
}
return base.NotificationBorderStyle;
}
}
private readonly TweetNotification exampleNotification;
public FormNotificationExample(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, false){
string exampleTweetHTML = ScriptLoader.LoadResource("pages/example.html", true);
#if DEBUG
exampleTweetHTML = exampleTweetHTML.Replace("</p>", @"</p><div style='margin-top:256px'>Scrollbar test padding...</div>");
#endif
exampleNotification = TweetNotification.Example(exampleTweetHTML, 95);
}
public void ShowExampleNotification(bool reset){
if (reset){
LoadTweet(exampleNotification);
}
else{
PrepareAndDisplayWindow();
}
UpdateTitle();
}
}
}
| using System.Windows.Forms;
using TweetDuck.Core.Controls;
using TweetDuck.Plugins;
using TweetDuck.Resources;
namespace TweetDuck.Core.Notification.Example{
sealed class FormNotificationExample : FormNotificationMain{
public override bool RequiresResize => true;
protected override bool CanDragWindow => Program.UserConfig.NotificationPosition == TweetNotification.Position.Custom;
protected override FormBorderStyle NotificationBorderStyle{
get{
if (Program.UserConfig.NotificationSize == TweetNotification.Size.Custom){
switch(base.NotificationBorderStyle){
case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable;
case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow;
}
}
return base.NotificationBorderStyle;
}
}
private readonly TweetNotification exampleNotification;
public FormNotificationExample(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, false){
string exampleTweetHTML = ScriptLoader.LoadResource("pages/example.html", true);
#if DEBUG
exampleTweetHTML = exampleTweetHTML.Replace("</p>", @"</p><div style='margin-top:256px'>Scrollbar test padding...</div>");
#endif
exampleNotification = TweetNotification.Example(exampleTweetHTML, 95);
}
public override void HideNotification(){
Location = ControlExtensions.InvisibleLocation;
}
public void ShowExampleNotification(bool reset){
if (reset){
LoadTweet(exampleNotification);
}
else{
PrepareAndDisplayWindow();
}
UpdateTitle();
}
}
}
|
Allow `params` completion in lambdas | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ParamsKeywordRecommender()
: base(SyntaxKind.ParamsKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> context.SyntaxTree.IsParamsModifierContext(context.Position, context.LeftToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ParamsKeywordRecommender()
: base(SyntaxKind.ParamsKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return syntaxTree.IsParamsModifierContext(context.Position, context.LeftToken) ||
syntaxTree.IsPossibleLambdaParameterModifierContext(position, context.LeftToken, cancellationToken);
}
}
}
|
Fix crash when editing query parameters and one has a null value | using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using SolarWinds.InformationService.Contract2;
namespace SwqlStudio
{
public partial class QueryParameters : Form
{
public QueryParameters(PropertyBag queryParameters)
{
InitializeComponent();
Parameters = queryParameters;
}
public PropertyBag Parameters
{
get
{
var bag = new PropertyBag();
foreach (Pair pair in (BindingList<Pair>)dataGridView1.DataSource)
bag[pair.Key] = pair.Value;
return bag;
}
private set
{
var pairs = value.Select(pair => new Pair(pair.Key, pair.Value.ToString()));
dataGridView1.DataSource = new BindingList<Pair>(pairs.ToList()) {AllowNew = true};
}
}
}
public class Pair
{
public Pair()
{
}
public Pair(string key, string value)
{
Key = key;
Value = value;
}
public string Key { get; set; }
public string Value { get; set; }
}
}
| using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using SolarWinds.InformationService.Contract2;
namespace SwqlStudio
{
public partial class QueryParameters : Form
{
public QueryParameters(PropertyBag queryParameters)
{
InitializeComponent();
Parameters = queryParameters;
}
public PropertyBag Parameters
{
get
{
var bag = new PropertyBag();
foreach (Pair pair in (BindingList<Pair>)dataGridView1.DataSource)
bag[pair.Key] = pair.Value;
return bag;
}
private set
{
var pairs = value.Select(pair => new Pair(pair.Key, pair.Value?.ToString()));
dataGridView1.DataSource = new BindingList<Pair>(pairs.ToList()) {AllowNew = true};
}
}
}
public class Pair
{
public Pair()
{
}
public Pair(string key, string value)
{
Key = key;
Value = value;
}
public string Key { get; set; }
public string Value { get; set; }
}
}
|
Set Tentacle Instance Name variable | using System;
using Octostache;
namespace Calamari.Integration.Processes
{
public static class VariableDictionaryExtensions
{
public static void EnrichWithEnvironmentVariables(this VariableDictionary variables)
{
var environmentVariables = Environment.GetEnvironmentVariables();
foreach (var name in environmentVariables.Keys)
{
variables["env:" + name] = (environmentVariables[name] ?? string.Empty).ToString();
}
}
}
} | using System;
using Calamari.Deployment;
using Octostache;
namespace Calamari.Integration.Processes
{
public static class VariableDictionaryExtensions
{
public static void EnrichWithEnvironmentVariables(this VariableDictionary variables)
{
var environmentVariables = Environment.GetEnvironmentVariables();
foreach (var name in environmentVariables.Keys)
{
variables["env:" + name] = (environmentVariables[name] ?? string.Empty).ToString();
}
variables.Set(SpecialVariables.Tentacle.Agent.InstanceName, "#{env:TentacleInstanceName}");
}
}
} |
Update help with correct name | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
namespace JenkinsTitleUpdater
{
class Program
{
static int Main(string[] args)
{
if (args.Length == 0)
{
Usage();
return -1;
}
HtmlDocument doc = new HtmlDocument();
if (!File.Exists(args[0])) throw new ArgumentException("File does not exist " + args[0] + "\r\nWe are at " + Environment.CurrentDirectory);
doc.Load(args[0]);
HtmlNode root = doc.DocumentNode;
HtmlNode titleNode = root.ChildNodes["html"].ChildNodes["head"].ChildNodes["title"];
string buildname = " -- ";
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BUILD_DISPLAY_NAME")))
{
return -1;
}
buildname += Environment.GetEnvironmentVariable("BUILD_DISPLAY_NAME");
titleNode.InnerHtml += buildname;
doc.Save(args[0]);
return 0;
}
private static void Usage()
{
Console.WriteLine("Usage");
Console.WriteLine("Usage : CTTitleUpdater.exe full-path-to-_Layout.cshtml");
Console.WriteLine(@"Example : CTTitleUpdater.exe \..\..\src\Web.CTAP.Web\View\Shared\_Layout.cshtml");
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
namespace JenkinsTitleUpdater
{
class Program
{
static int Main(string[] args)
{
if (args.Length == 0)
{
Usage();
return -1;
}
HtmlDocument doc = new HtmlDocument();
if (!File.Exists(args[0])) throw new ArgumentException("File does not exist " + args[0] + "\r\nWe are at " + Environment.CurrentDirectory);
doc.Load(args[0]);
HtmlNode root = doc.DocumentNode;
HtmlNode titleNode = root.ChildNodes["html"].ChildNodes["head"].ChildNodes["title"];
string buildname = " -- ";
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BUILD_DISPLAY_NAME")))
{
return -1;
}
buildname += Environment.GetEnvironmentVariable("BUILD_DISPLAY_NAME");
titleNode.InnerHtml += buildname;
doc.Save(args[0]);
return 0;
}
private static void Usage()
{
Console.WriteLine("Usage");
Console.WriteLine("Usage : JenkinsTitleUpdater.exe full-path-to-_Layout.cshtml");
Console.WriteLine(@"Example : JenkinsTitleUpdater.exe \..\..\src\Web\View\Shared\_Layout.cshtml");
}
}
}
|
Fix error in comment (should have been NavStateChanged) | using System;
namespace CefSharp
{
/// <summary>
/// Event arguments to the LoadCompleted event handler set up in IWebBrowser.
/// </summary>
public class NavStateChangedEventArgs : EventArgs
{
public bool CanGoForward { get; private set; }
public bool CanGoBack { get; private set; }
public bool CanReload { get; private set; }
public NavStateChangedEventArgs(bool canGoBack, bool canGoForward, bool canReload)
{
CanGoBack = canGoBack;
CanGoForward = canGoForward;
CanReload = canReload;
}
};
/// <summary>
/// A delegate type used to listen to NavStateChanged events.
/// </summary>
public delegate void NavStateChangedEventHandler(object sender, NavStateChangedEventArgs args);
}
| using System;
namespace CefSharp
{
/// <summary>
/// Event arguments to the NavStateChanged event handler set up in IWebBrowser.
/// </summary>
public class NavStateChangedEventArgs : EventArgs
{
public bool CanGoForward { get; private set; }
public bool CanGoBack { get; private set; }
public bool CanReload { get; private set; }
public NavStateChangedEventArgs(bool canGoBack, bool canGoForward, bool canReload)
{
CanGoBack = canGoBack;
CanGoForward = canGoForward;
CanReload = canReload;
}
};
/// <summary>
/// A delegate type used to listen to NavStateChanged events.
/// </summary>
public delegate void NavStateChangedEventHandler(object sender, NavStateChangedEventArgs args);
}
|
Add function for configuring settings | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
namespace Badger.Views
{
/// <summary>
/// Interaction logic for MainView.xaml
/// </summary>
public partial class MainView : MetroWindow
{
public MainView()
{
InitializeComponent();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
namespace Badger.Views
{
/// <summary>
/// Interaction logic for MainView.xaml
/// </summary>
public partial class MainView : MetroWindow
{
public MainView()
{
InitializeComponent();
}
public void ConfigureSettings()
{
}
}
}
|
Update addin version to 0.5 |
using System;
using Mono.Addins;
using Mono.Addins.Description;
[assembly:Addin ("TypeScript",
Namespace = "MonoDevelop",
Version = "0.4",
Category = "Web Development")]
[assembly:AddinName ("TypeScript")]
[assembly:AddinDescription ("Adds TypeScript support. Updated to use TypeScript 1.4")]
[assembly:AddinDependency ("Core", "5.0")]
[assembly:AddinDependency ("Ide", "5.0")]
[assembly:AddinDependency ("SourceEditor2", "5.0")]
[assembly:AddinDependency ("Refactoring", "5.0")]
|
using System;
using Mono.Addins;
using Mono.Addins.Description;
[assembly:Addin ("TypeScript",
Namespace = "MonoDevelop",
Version = "0.5",
Category = "Web Development")]
[assembly:AddinName ("TypeScript")]
[assembly:AddinDescription ("Adds TypeScript support. Updated to use TypeScript 1.4")]
[assembly:AddinDependency ("Core", "5.0")]
[assembly:AddinDependency ("Ide", "5.0")]
[assembly:AddinDependency ("SourceEditor2", "5.0")]
[assembly:AddinDependency ("Refactoring", "5.0")]
|
Add code to allow first-person character to control more like a traditional FPS. | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CustomSimplePlayer : MonoBehaviour {
public int speed = 10;
Rigidbody rigidbody;
Vector3 velocity;
// Use this for initialization
void Start () {
rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
velocity = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized * speed;
}
private void FixedUpdate() {
rigidbody.MovePosition(rigidbody.position + velocity * Time.fixedDeltaTime);
rigidbody.rotation = Quaternion.Euler(rigidbody.rotation.eulerAngles + new Vector3(0f, 1f * Input.GetAxisRaw("Mouse X"), 0f));
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CustomSimplePlayer : MonoBehaviour {
public float speed = 10.0f;
Rigidbody rigidbody;
Vector3 velocity;
// Use this for initialization
void Start () {
Cursor.lockState = CursorLockMode.Locked;
rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
//velocity = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized * speed;
// replaced above code with:
float forwardAndBackward = Input.GetAxisRaw("Vertical") * speed;
float strafe = Input.GetAxisRaw("Horizontal") * speed;
forwardAndBackward *= Time.deltaTime;
strafe *= Time.deltaTime;
transform.Translate(strafe, 0, forwardAndBackward);
// The position of this if statement matters.
// If you put this in the beginning of the Update function, the code will not get to "velocity", and it will keep on staing on this if statement.
if (Input.GetKeyDown("Escape"))
Cursor.lockState = CursorLockMode.None;
}
private void FixedUpdate() {
// Commented this out because the code in Update() made this redundant.
//rigidbody.MovePosition(rigidbody.position + velocity * Time.fixedDeltaTime);
rigidbody.rotation = Quaternion.Euler(rigidbody.rotation.eulerAngles + new Vector3(0f, 1f * Input.GetAxisRaw("Mouse X"), 0f));
}
} |
Fix an animation bug with Endless Sandwiches | using System.Collections.Generic;
using HarryPotterUnity.Cards.Generic;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Spells.Charms
{
[UsedImplicitly]
public class EndlessSandwiches : GenericSpell {
protected override void SpellAction(List<GenericCard> targets)
{
while (Player.Hand.Cards.Count < 7)
{
Player.Deck.DrawCard();
}
}
}
}
| using System.Collections.Generic;
using HarryPotterUnity.Cards.Generic;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Spells.Charms
{
[UsedImplicitly]
public class EndlessSandwiches : GenericSpell {
protected override void SpellAction(List<GenericCard> targets)
{
int amountCardsToDraw = 7 - Player.Hand.Cards.Count;
var cardsToDraw = new List<GenericCard>();
while (amountCardsToDraw-- > 0)
{
cardsToDraw.Add( Player.Deck.TakeTopCard() );
}
Player.Hand.AddAll(cardsToDraw);
}
}
}
|
Update the properties test with new-style accessor syntax | using System;
public struct Vector2
{
public Vector2(double X, double Y)
{
this.x = X;
this.Y = Y;
}
private double x;
public double X { get { return x; } private set { x = value; } }
public double Y { get; private set; }
public double this[int i]
{
get { return i == 1 ? Y : X; }
private set
{
if (i == 1)
Y = value;
else
X = value;
}
}
public double this[long i] => i == 1 ? Y : X;
public double LengthSquared
{
get { return X * X + Y * Y; }
}
public double Length => Math.Sqrt(LengthSquared);
}
public static class Program
{
public static void Main(string[] Args)
{
var vec = new Vector2(3, 4);
Console.WriteLine(vec.X);
Console.WriteLine(vec.Y);
Console.WriteLine(vec[0]);
Console.WriteLine(vec[1]);
Console.WriteLine(vec[0L]);
Console.WriteLine(vec[1L]);
Console.WriteLine(vec.LengthSquared);
Console.WriteLine(vec.Length);
}
}
| using System;
public struct Vector2
{
public Vector2(double X, double Y)
{
this.x = X;
this.Y = Y;
}
private double x;
public double X { get { return x; } private set { x = value; } }
public double Y { get; private set; }
public double this[int i]
{
get { return i == 1 ? Y : X; }
private set
{
if (i == 1)
Y = value;
else
X = value;
}
}
public double this[uint i]
{
get => this[(int)i];
private set => this[(uint)i] = value;
}
public double this[long i] => i == 1 ? Y : X;
public double LengthSquared
{
get { return X * X + Y * Y; }
}
public double Length => Math.Sqrt(LengthSquared);
}
public static class Program
{
public static void Main(string[] Args)
{
var vec = new Vector2(3, 4);
Console.WriteLine(vec.X);
Console.WriteLine(vec.Y);
Console.WriteLine(vec[0]);
Console.WriteLine(vec[1]);
Console.WriteLine(vec[0L]);
Console.WriteLine(vec[1L]);
Console.WriteLine(vec.LengthSquared);
Console.WriteLine(vec.Length);
}
}
|
Fix inverted result from Into(ModelState) | namespace Mios.Validation.Mvc {
using System.Collections.Generic;
using System.Web.Mvc;
public static class ModelStateDictionaryExtensions {
public static void AddErrors(this ModelStateDictionary modelState, IEnumerable<ValidationError> errors) {
foreach(var error in errors) {
modelState.AddModelError(error.Key, error.Message);
}
}
public static bool Into(this IEnumerable<ValidationError> errors, ModelStateDictionary modelState) {
var found = false;
foreach(var error in errors) {
modelState.AddModelError(error.Key, error.Message);
found = true;
}
return found;
}
}
}
| namespace Mios.Validation.Mvc {
using System.Collections.Generic;
using System.Web.Mvc;
public static class ModelStateDictionaryExtensions {
public static void AddErrors(this ModelStateDictionary modelState, IEnumerable<ValidationError> errors) {
foreach(var error in errors) {
modelState.AddModelError(error.Key, error.Message);
}
}
public static bool Into(this IEnumerable<ValidationError> errors, ModelStateDictionary modelState) {
var found = false;
foreach(var error in errors) {
modelState.AddModelError(error.Key, error.Message);
found = true;
}
return !found;
}
}
}
|
Add unit tests for simple single and multiple property resolution | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Pather.CSharp.UnitTests
{
// This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class ResolverTests
{
public ResolverTests()
{
}
[Fact]
public void Test()
{
var r = new Resolver();
}
}
}
| using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Pather.CSharp.UnitTests
{
// This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class ResolverTests
{
public ResolverTests()
{
}
[Fact]
public void SinglePropertyResolution()
{
var value = "1";
var r = new Resolver();
var o = new { Property = value };
var result = r.Resolve(o, "Property");
result.Should().Be(value);
}
[Fact]
public void MultiplePropertyResolution()
{
var value = "1";
var r = new Resolver();
var o = new { Property1 = new { Property2 = value } };
var result = r.Resolve(o, "Property1.Property2");
result.Should().Be(value);
}
}
}
|
Add Type Forwarder for New Appender | using System.Runtime.CompilerServices;
[assembly:TypeForwardedTo(typeof(Gelf4Net.Layout.GelfLayout))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.GelfHttpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.GelfUdpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.AsyncGelfUdpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.GelfAmqpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.AsyncGelfAmqpAppender))]
| using System.Runtime.CompilerServices;
[assembly:TypeForwardedTo(typeof(Gelf4Net.Layout.GelfLayout))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.GelfHttpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.AsyncGelfHttpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.GelfUdpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.AsyncGelfUdpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.GelfAmqpAppender))]
[assembly:TypeForwardedTo(typeof(Gelf4Net.Appender.AsyncGelfAmqpAppender))]
|
Return even information in string for error reporting | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Substructio.Logging
{
public interface IErrorReporting
{
void ReportError(Exception e);
void ReportMessage(string message);
}
public class NullErrorReporting : IErrorReporting
{
public void ReportError(Exception e) { }
public void ReportMessage(string message) { }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Substructio.Logging
{
public interface IErrorReporting
{
string ReportError(Exception e);
string ReportMessage(string message);
}
public class NullErrorReporting : IErrorReporting
{
public string ReportError(Exception e) { return ""; }
public string ReportMessage(string message) { return ""; }
}
}
|
Fix actual contingent table structure | @inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<ContingentViewModel>
@using DotNetNuke.Web.Mvc.Helpers
@using R7.University.EduProgramProfiles.ViewModels
<td itemprop="eduCode">@Model.EduProgramProfile.EduProgram.Code</td>
<td itemprop="eduName">@Model.EduProgramProfileTitle</td>
<td itemprop="eduLevel">@Model.EduProgramProfile.EduLevel.Title</td>
<td itemprop="eduForm">@Model.EduFormTitle</td>
<td>@Model.Year.Year</td>
<td>@Model.ActualFB</td>
<td>@Model.ActualRB</td>
<td>@Model.ActualMB</td>
<td>@Model.ActualBC</td> | @inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<ContingentViewModel>
@using DotNetNuke.Web.Mvc.Helpers
@using R7.University.EduProgramProfiles.ViewModels
<td itemprop="eduCode">@Model.EduProgramProfile.EduProgram.Code</td>
<td itemprop="eduName">@Model.EduProgramProfileTitle</td>
<td itemprop="eduLevel">@Model.EduProgramProfile.EduLevel.Title</td>
<td itemprop="eduForm">@Model.EduFormTitle</td>
<td>@Model.ActualFB</td>
<td>@Model.ActualRB</td>
<td>@Model.ActualMB</td>
<td>@Model.ActualBC</td> |
Enable exceptions for this test case to speculatively fix the build bots. | // RUN: %check_clang_tidy %s hicpp-exception-baseclass %t
namespace std {
class exception {};
} // namespace std
class derived_exception : public std::exception {};
class non_derived_exception {};
void problematic() {
try {
throw int(42); // Built in is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
} catch (int e) {
}
throw int(42); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'
try {
throw non_derived_exception(); // Some class is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
} catch (non_derived_exception &e) {
}
throw non_derived_exception(); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
}
void allowed_throws() {
try {
throw std::exception(); // Ok
} catch (std::exception &e) { // Ok
}
throw std::exception();
try {
throw derived_exception(); // Ok
} catch (derived_exception &e) { // Ok
}
throw derived_exception(); // Ok
}
| // RUN: %check_clang_tidy %s hicpp-exception-baseclass %t -- -- -fcxx-exceptions
namespace std {
class exception {};
} // namespace std
class derived_exception : public std::exception {};
class non_derived_exception {};
void problematic() {
try {
throw int(42); // Built in is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
} catch (int e) {
}
throw int(42); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'
try {
throw non_derived_exception(); // Some class is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
} catch (non_derived_exception &e) {
}
throw non_derived_exception(); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
}
void allowed_throws() {
try {
throw std::exception(); // Ok
} catch (std::exception &e) { // Ok
}
throw std::exception();
try {
throw derived_exception(); // Ok
} catch (derived_exception &e) { // Ok
}
throw derived_exception(); // Ok
}
|
Handle a little bug with empty files. | #include "mapped_file.h"
#include <exception/os.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
namespace sasm { namespace utils {
mapped_file::~mapped_file()
{
if (_is_mapped)
unmap();
}
void mapped_file::map()
{
int fd;
struct stat buf;
char* begin;
if ((fd = open(get_path(), O_RDONLY)) == -1)
throw sasm::exception::os("open", get_path());
if (fstat(fd, &buf) == -1)
throw sasm::exception::os("fstat");
if ((begin = (char*) mmap(NULL, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
throw sasm::exception::os("mmap");
close(fd);
_is_mapped = true;
_begin = begin;
_size = buf.st_size;
}
void mapped_file::unmap()
{
if (munmap((void*) _begin, _size) == -1)
throw sasm::exception::os("munmap");
_is_mapped = false;
}
const char* mapped_file::get_path() const
{
return _path.c_str();
}
}}
| #include "mapped_file.h"
#include <exception/elf.h>
#include <exception/os.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
namespace sasm { namespace utils {
mapped_file::~mapped_file()
{
if (_is_mapped)
unmap();
}
void mapped_file::map()
{
int fd;
struct stat buf;
char* begin;
if ((fd = open(get_path(), O_RDONLY)) == -1)
throw sasm::exception::os("open", get_path());
if (fstat(fd, &buf) == -1)
throw sasm::exception::os("fstat");
if (buf.st_size == 0)
throw sasm::exception::elf(_path.c_str(), "invalid ELF file");
if ((begin = (char*) mmap(NULL, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
throw sasm::exception::os("mmap");
close(fd);
_is_mapped = true;
_begin = begin;
_size = buf.st_size;
}
void mapped_file::unmap()
{
if (munmap((void*) _begin, _size) == -1)
throw sasm::exception::os("munmap");
_is_mapped = false;
}
const char* mapped_file::get_path() const
{
return _path.c_str();
}
}}
|
Remove confusing transpose() in setLinSpaced() docs. | VectorXf v;
v.setLinSpaced(5,0.5f,1.5f).transpose();
cout << v << endl;
| VectorXf v;
v.setLinSpaced(5,0.5f,1.5f);
cout << v << endl;
|
Mark another test as flaky | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <mutex>
// class recursive_timed_mutex;
// void lock();
#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>
#include <iostream>
std::recursive_timed_mutex m;
typedef std::chrono::system_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;
void f()
{
time_point t0 = Clock::now();
m.lock();
time_point t1 = Clock::now();
m.lock();
m.unlock();
m.unlock();
ns d = t1 - t0 - ms(250);
assert(d < ms(50)); // within 50ms
}
int main()
{
m.lock();
std::thread t(f);
std::this_thread::sleep_for(ms(250));
m.unlock();
t.join();
}
| //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// FLAKY_TEST.
// <mutex>
// class recursive_timed_mutex;
// void lock();
#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>
#include <iostream>
std::recursive_timed_mutex m;
typedef std::chrono::system_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;
void f()
{
time_point t0 = Clock::now();
m.lock();
time_point t1 = Clock::now();
m.lock();
m.unlock();
m.unlock();
ns d = t1 - t0 - ms(250);
assert(d < ms(50)); // within 50ms
}
int main()
{
m.lock();
std::thread t(f);
std::this_thread::sleep_for(ms(250));
m.unlock();
t.join();
}
|
Send correct exit code on test failure. |
#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include "SystemTest.h"
int main(int argc, char* argv[])
{
CppUnit::TestResult controller;
CppUnit::TestResultCollector result;
controller.addListener(&result);
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest( suite );
runner.run(controller);
// Change the default outputter to a compiler error format
// outputter
std::ofstream xmlFileOut("cpptestresults.xml");
CppUnit::XmlOutputter xmlOut(&result, xmlFileOut);
xmlOut.write();
// Return error code 1 if the one of test failed.
return result.testFailuresTotal() ? 0 : 1;
}
|
#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include "SystemTest.h"
int main(int argc, char* argv[])
{
CppUnit::TestResult controller;
CppUnit::TestResultCollector result;
controller.addListener(&result);
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest( suite );
runner.run(controller);
// Change the default outputter to a compiler error format
// outputter
std::ofstream xmlFileOut("cpptestresults.xml");
CppUnit::XmlOutputter xmlOut(&result, xmlFileOut);
xmlOut.write();
// Return error code 1 if the one of test failed.
return result.testFailuresTotal() ? 1 : 0 ;
}
|
Make early exits, when active, more efficient | #include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
pushall(h,i,j)
b <- 0
#if IMUL_EARLY_EXITS
i <- d == 0
i <- c == 0 + i
i <- i <> 0
jnzrel(i, L_done)
#endif
h <- 1
j <- d >> 31 // save sign bit in j
j <- -j // convert sign to flag
d <- d ^ j // adjust multiplier
d <- d - j
L_top:
// use constant 1 in h to combine instructions
i <- d & h - 1
i <- c &~ i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d <> 0
jnzrel(i, L_top)
b <- b ^ j // adjust product for signed math
b <- b - j
L_done:
popall(h,i,j)
ret
| #include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
#if IMUL_EARLY_EXITS
b <- c == 0
d <- d &~ b // d = (c == 0) ? 0 : d
b <- d <> 0
jzrel(b, L_done)
#endif
pushall(h,i,j)
b <- 0
h <- 1
j <- d >> 31 // save sign bit in j
j <- -j // convert sign to flag
d <- d ^ j // adjust multiplier
d <- d - j
L_top:
// use constant 1 in h to combine instructions
i <- d & h - 1
i <- c &~ i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d <> 0
jnzrel(i, L_top)
b <- b ^ j // adjust product for signed math
b <- b - j
popall(h,i,j)
L_done:
ret
|
Use progran name as default log entry prefix. | /** \file SysLog.h
* \brief Declaration of class SysLog.
* \author Dr. Johannes Ruscheinski
*/
/*
* Copyright 2020 University Library of Tübingen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SysLog.h"
SysLog::SysLog(const std::string &message_prefix, const int option, const int facility) {
::openlog(message_prefix.c_str(), option, facility);
::setlogmask(LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_INFO);
}
SysLog::~SysLog() {
::closelog();
}
void SysLog::log(const LogLevel level, const std::string &message) {
::syslog(level, "%s", message.c_str());
}
| /** \file SysLog.h
* \brief Declaration of class SysLog.
* \author Dr. Johannes Ruscheinski
*/
/*
* Copyright 2020 University Library of Tübingen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SysLog.h"
SysLog::SysLog(const std::string &message_prefix, const int option, const int facility) {
::openlog(message_prefix.empty() ? nullptr : message_prefix.c_str(), option, facility);
::setlogmask(LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_INFO);
}
SysLog::~SysLog() {
::closelog();
}
void SysLog::log(const LogLevel level, const std::string &message) {
::syslog(level, "%s", message.c_str());
}
|
Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues. | Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to replace m by its own transpose." << endl;
cout << "If we do m = m.transpose(), then m becomes:" << endl;
m = m.transpose() * 1;
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl;
m = M;
m = m.transpose().eval();
cout << m << endl << "which is right." << endl;
| Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to copy a column into a row." << endl;
cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl;
m.col(1) = m.row(0);
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl;
m = M;
m.col(1) = m.row(0).eval();
cout << m << endl << "which is right." << endl;
|
Fix a syscall number for 64-bit arm | #define SYS_CLOCK_GETTIME 263
#include "linux_clock.cpp"
| #ifdef BITS_64
#define SYS_CLOCK_GETTIME 113
#endif
#ifdef BITS_32
#define SYS_CLOCK_GETTIME 263
#endif
#include "linux_clock.cpp"
|
Check idle state for Ozone platform | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/idle.h"
#include "base/basictypes.h"
#if defined(USE_X11)
#include "chrome/browser/idle_query_x11.h"
#endif
#if !defined(OS_CHROMEOS)
#include "chrome/browser/screensaver_window_finder_x11.h"
#endif
void CalculateIdleTime(IdleTimeCallback notify) {
#if defined(USE_X11)
chrome::IdleQueryX11 idle_query;
notify.Run(idle_query.IdleTime());
#endif
}
bool CheckIdleStateIsLocked() {
// Usually the screensaver is used to lock the screen, so we do not need to
// check if the workstation is locked.
#if defined(OS_CHROMEOS)
return false;
#else
return ScreensaverWindowFinder::ScreensaverWindowExists();
#endif
}
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/idle.h"
#include "base/basictypes.h"
#if defined(USE_X11)
#include "chrome/browser/idle_query_x11.h"
#endif
#if !defined(OS_CHROMEOS)
#include "chrome/browser/screensaver_window_finder_x11.h"
#endif
void CalculateIdleTime(IdleTimeCallback notify) {
#if defined(USE_X11)
chrome::IdleQueryX11 idle_query;
notify.Run(idle_query.IdleTime());
#endif
}
bool CheckIdleStateIsLocked() {
// Usually the screensaver is used to lock the screen, so we do not need to
// check if the workstation is locked.
#if defined(OS_CHROMEOS)
return false;
#elif defined(USE_OZONE)
return false;
#else
return ScreensaverWindowFinder::ScreensaverWindowExists();
#endif
}
|
Remove stale CHECK lines that should have been included in r277478 | // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <windows.h>
HANDLE done;
DWORD CALLBACK work_item(LPVOID) {
int subscript = -1;
volatile char stack_buffer[42];
stack_buffer[subscript] = 42;
// CHECK: AddressSanitizer: stack-buffer-underflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T1
// CHECK: {{#0 .* work_item.*queue_user_work_item_report.cc}}:[[@LINE-3]]
// CHECK: Address [[ADDR]] is located in stack of thread T1 at offset {{.*}} in frame
// CHECK: work_item
SetEvent(done);
return 0;
}
int main(int argc, char **argv) {
done = CreateEvent(0, false, false, "job is done");
if (!done)
return 1;
// CHECK-NOT: Thread T1 created
QueueUserWorkItem(&work_item, nullptr, 0);
if (WAIT_OBJECT_0 != WaitForSingleObject(done, 10 * 1000))
return 2;
}
| // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <windows.h>
HANDLE done;
DWORD CALLBACK work_item(LPVOID) {
int subscript = -1;
volatile char stack_buffer[42];
stack_buffer[subscript] = 42;
// CHECK: AddressSanitizer: stack-buffer-underflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T1
// CHECK: {{#0 .* work_item.*queue_user_work_item_report.cc}}:[[@LINE-3]]
SetEvent(done);
return 0;
}
int main(int argc, char **argv) {
done = CreateEvent(0, false, false, "job is done");
if (!done)
return 1;
// CHECK-NOT: Thread T1 created
QueueUserWorkItem(&work_item, nullptr, 0);
if (WAIT_OBJECT_0 != WaitForSingleObject(done, 10 * 1000))
return 2;
}
|
Fix broken synth reg A gen | #include <stdint.h>
#include "receiver.h"
Receiver::Receiver(
uint8_t spiClockPin,
uint8_t spiDataPin,
uint8_t spiSelectPin
) {
this->driver.init(spiClockPin, spiDataPin, spiSelectPin);
}
void Receiver::setFrequency(uint16_t frequency) {
uint16_t flO = (frequency - 479) / 2;
uint16_t regN = frequency / 32;
uint16_t regA = frequency % 32;
uint16_t synthRegB = (regN << 7) | regA;
this->driver.setSynthRegisterB(synthRegB);
}
| #include <stdint.h>
#include "receiver.h"
Receiver::Receiver(
uint8_t spiClockPin,
uint8_t spiDataPin,
uint8_t spiSelectPin
) {
this->driver.init(spiClockPin, spiDataPin, spiSelectPin);
}
void Receiver::setFrequency(uint16_t frequency) {
uint16_t fLo = (frequency - 479) / 2;
uint16_t regN = fLo / 32;
uint16_t regA = fLo % 32;
uint16_t synthRegB = (regN << 7) | regA;
this->driver.setSynthRegisterB(synthRegB);
}
|
Fix to avoid empty files. Could still be improved, but it is enough for now. | // Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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.
#include <ReadData.hpp>
namespace AstroData {
RingBufferError::RingBufferError() {}
RingBufferError::~RingBufferError() throw () {}
const char * RingBufferError::what() const throw() {
return ("Impossible to read from the PSRDada ring buffer.");
}
void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) {
unsigned int nrChannels = 0;
std::ifstream input;
input.open(inputFileName);
while ( !input.eof() ) {
unsigned int channel = 0;
input >> channel;
if ( channel < observation.getNrChannels() ) {
zappedChannels[channel] = 1;
nrChannels++;
}
}
input.close();
observation.setNrZappedChannels(nrChannels);
}
} // AstroData
| // Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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.
#include <ReadData.hpp>
namespace AstroData {
RingBufferError::RingBufferError() {}
RingBufferError::~RingBufferError() throw () {}
const char * RingBufferError::what() const throw() {
return ("Impossible to read from the PSRDada ring buffer.");
}
void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) {
unsigned int nrChannels = 0;
std::ifstream input;
input.open(inputFileName);
while ( !input.eof() ) {
unsigned int channel = observation.getNrChannels();
input >> channel;
if ( channel < observation.getNrChannels() ) {
zappedChannels[channel] = 1;
nrChannels++;
}
}
input.close();
observation.setNrZappedChannels(nrChannels);
}
} // AstroData
|
Add actual documentation link into calibration checker output | // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Felix Exner exner@fzi.de
* \date 2019-06-14
*
*/
//----------------------------------------------------------------------
#include <ur_robot_driver/ur/calibration_checker.h>
namespace ur_driver
{
CalibrationChecker::CalibrationChecker(const std::string& expected_hash)
: expected_hash_(expected_hash), checked_(false)
{
}
bool CalibrationChecker::consume(std::shared_ptr<primary_interface::PrimaryPackage> product)
{
auto kin_info = std::dynamic_pointer_cast<primary_interface::KinematicsInfo>(product);
if (kin_info != nullptr)
{
// LOG_INFO("%s", product->toString().c_str());
//
if (kin_info->toHash() != expected_hash_)
{
LOG_ERROR("The calibration parameters of the connected robot don't match the ones from the given kinematics "
"config file. Please be aware that this can lead to critical inaccuracies of tcp positions. Use the "
"ur_calibration tool to extract the correct calibration from the robot and pass that into the "
"description. See [TODO Link to documentation] for details.");
}
else
{
LOG_INFO("Calibration checked successfully.");
}
checked_ = true;
}
return true;
}
} // namespace ur_driver
| // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Felix Exner exner@fzi.de
* \date 2019-06-14
*
*/
//----------------------------------------------------------------------
#include <ur_robot_driver/ur/calibration_checker.h>
namespace ur_driver
{
CalibrationChecker::CalibrationChecker(const std::string& expected_hash)
: expected_hash_(expected_hash), checked_(false)
{
}
bool CalibrationChecker::consume(std::shared_ptr<primary_interface::PrimaryPackage> product)
{
auto kin_info = std::dynamic_pointer_cast<primary_interface::KinematicsInfo>(product);
if (kin_info != nullptr)
{
// LOG_INFO("%s", product->toString().c_str());
//
if (kin_info->toHash() != expected_hash_)
{
LOG_ERROR("The calibration parameters of the connected robot don't match the ones from the given kinematics "
"config file. Please be aware that this can lead to critical inaccuracies of tcp positions. Use the "
"ur_calibration tool to extract the correct calibration from the robot and pass that into the "
"description. See "
"[https://github.com/UniversalRobots/Universal_Robots_ROS_Driver#extract-calibration-information] for "
"details.");
}
else
{
LOG_INFO("Calibration checked successfully.");
}
checked_ = true;
}
return true;
}
} // namespace ur_driver
|
Speed up ASan unit tests by turning off symbolication | //===-- asan_test_main.cc -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"
int main(int argc, char **argv) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| //===-- asan_test_main.cc -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"
// Default ASAN_OPTIONS for the unit tests. Let's turn symbolication off to
// speed up testing (unit tests don't use it anyway).
extern "C" const char* __asan_default_options() {
return "symbolize=false";
}
int main(int argc, char **argv) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Load the denoiser module after initializing OSPRay | // Copyright 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "GLFWOSPRayWindow.h"
#include "example_common.h"
using namespace ospray;
using rkcommon::make_unique;
int main(int argc, const char *argv[])
{
bool denoiser = ospLoadModule("denoiser") == OSP_NO_ERROR;
initializeOSPRay(argc, argv);
auto glfwOSPRayWindow =
make_unique<GLFWOSPRayWindow>(vec2i(1024, 768), denoiser);
glfwOSPRayWindow->mainLoop();
glfwOSPRayWindow.reset();
ospShutdown();
return 0;
}
| // Copyright 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "GLFWOSPRayWindow.h"
#include "example_common.h"
using namespace ospray;
using rkcommon::make_unique;
int main(int argc, const char *argv[])
{
initializeOSPRay(argc, argv);
bool denoiser = ospLoadModule("denoiser") == OSP_NO_ERROR;
auto glfwOSPRayWindow =
make_unique<GLFWOSPRayWindow>(vec2i(1024, 768), denoiser);
glfwOSPRayWindow->mainLoop();
glfwOSPRayWindow.reset();
ospShutdown();
return 0;
}
|
Fix plugin data refreshing to work again. | // Copyright (c) 2008 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
#include "config.h"
#include "PluginData.h"
#include "PluginInfoStore.h"
#undef LOG
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"
namespace WebCore {
static bool refreshData = false;
void PluginData::initPlugins()
{
std::vector<WebPluginInfo> plugins;
if (!webkit_glue::GetPlugins(refreshData, &plugins))
return;
refreshData = false;
PluginInfoStore c;
for (size_t i = 0; i < plugins.size(); ++i) {
PluginInfo* info = c.createPluginInfoForPluginAtIndex(i);
m_plugins.append(info);
}
}
void PluginData::refresh()
{
// When next we initialize a PluginData, it'll be fresh.
refreshData = true;
}
}
| // Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// 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 Google Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
// "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 COPYRIGHT
// OWNER OR 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.
#include "config.h"
#include "PluginData.h"
#include "PluginInfoStore.h"
namespace WebCore {
void PluginData::initPlugins()
{
PluginInfoStore c;
for (size_t i = 0; i < c.pluginCount(); ++i)
m_plugins.append(c.createPluginInfoForPluginAtIndex(i));
}
void PluginData::refresh()
{
refreshPlugins(true);
}
}
|
Test was restored, interval [<v>-1,<v>+1] was set for hue, saturation and value. | #include <gtest/gtest.h>
#include "photoeffects.hpp"
using namespace cv;
TEST(photoeffects, SepiaFakeTest) {
Mat src(10, 10, CV_8UC1), dst;
EXPECT_EQ(0, sepia(src, dst));
}
TEST(photoeffects, SepiaFailTest) {
Mat src(10, 10, CV_8UC3), dst;
EXPECT_EQ(1, sepia(src, dst));
}
/*
TEST(photoeffects, SepiaTest) {
Mat src(10, 10, CV_8UC1), dst, hsvDst;
vector<Mat> channels(3);
EXPECT_EQ(0, sepia(src, dst));
cvtColor(dst, hsvDst, CV_BGR2HSV);
split(hsvDst, channels);
EXPECT_EQ(src.at<uchar>(0, 0) + 20, channels[2].at<uchar>(0, 0));
}
*/
| #include <gtest/gtest.h>
#include "photoeffects.hpp"
using namespace cv;
TEST(photoeffects, SepiaFakeTest) {
Mat src(10, 10, CV_8UC1), dst;
EXPECT_EQ(0, sepia(src, dst));
}
TEST(photoeffects, SepiaFailTest) {
Mat src(10, 10, CV_8UC3), dst;
EXPECT_EQ(1, sepia(src, dst));
}
TEST(photoeffects, SepiaTest) {
Mat src(10, 10, CV_8UC1), dst, hsvDst;
vector<Mat> channels(3);
EXPECT_EQ(0, sepia(src, dst));
cvtColor(dst, hsvDst, CV_BGR2HSV);
split(hsvDst, channels);
EXPECT_LE(19 - 1, channels[0].at<uchar>(0, 0)); // hue = 19
EXPECT_GE(19 + 1, channels[0].at<uchar>(0, 0));
EXPECT_LE(78 - 1, channels[1].at<uchar>(0, 0)); // saturation = 78
EXPECT_GE(78 + 1, channels[1].at<uchar>(0, 0));
EXPECT_LE(src.at<uchar>(0, 0) + 20 - 1, channels[2].at<uchar>(0, 0));
EXPECT_GE(src.at<uchar>(0, 0) + 20 + 1, channels[2].at<uchar>(0, 0));
}
|
Add more iterator concept ordering tests. | /**
* Test suite for the iterator_concepts_ordering.hpp header.
*/
#include <duck/detail/iterator_concepts_ordering.hpp>
#include <boost/mpl/assert.hpp>
BOOST_MPL_ASSERT((duck::is_more_specific_than<
duck::BidirectionalIterator,
duck::RandomAccessIterator>));
BOOST_MPL_ASSERT((duck::is_more_specific_than<
duck::IncrementableIterator,
duck::RandomAccessIterator>));
BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
duck::RandomAccessIterator,
duck::BidirectionalIterator>));
BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
duck::RandomAccessIterator,
duck::IncrementableIterator>));
BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
duck::ForwardIterator,
duck::ForwardIterator>));
| /**
* Test suite for the iterator_concepts_ordering.hpp header.
*/
#include <duck/detail/iterator_concepts_ordering.hpp>
#include <boost/mpl/assert.hpp>
BOOST_MPL_ASSERT((duck::is_more_specific_than<
duck::BidirectionalIterator,
duck::RandomAccessIterator>));
BOOST_MPL_ASSERT((duck::is_more_specific_than<
duck::IncrementableIterator,
duck::RandomAccessIterator>));
BOOST_MPL_ASSERT((duck::is_more_specific_than<
duck::ForwardIterator,
duck::RandomAccessIterator>));
BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
duck::RandomAccessIterator,
duck::BidirectionalIterator>));
BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
duck::RandomAccessIterator,
duck::IncrementableIterator>));
BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
duck::ForwardIterator,
duck::ForwardIterator>));
BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
duck::RandomAccessIterator,
duck::ForwardIterator>));
|
Check vs Remove - not so not so clear | #include <vector>
#include <iostream>
#include <algorithm>
#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
int main()
{
std::vector<int> myValues;
for ( long int i=0L; i<100000000L; ++i )
myValues.push_back(i%3);
int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
int sum = 0;
for ( unsigned int i=0; i<myValues.size(); ++i )
{
#ifdef CHECK_VALUES
if ( myValues[i] != 2 )
{
#endif
sum += myValues[i];
#ifdef CHECK_VALUES
}
#endif
}
}
| #include <vector>
#include <iostream>
#include <algorithm>
#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
int main()
{
std::vector<int> myValues;
for ( long int i=0L; i<10000000L; ++i )
myValues.push_back(i%3);
int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
const int iterations = 100;
for ( int iteration=0; iteration < iterations; ++iteration )
{
int sum = 0;
for ( unsigned int i=0; i<myValues.size(); ++i )
{
#ifdef CHECK_VALUES
if ( myValues[i] != 2 )
{
#endif
sum += myValues[i];
#ifdef CHECK_VALUES
}
#endif
}
}
}
|
Make change parallel to guide | #include <proton/default_container.hpp>
#include <proton/messaging_handler.hpp>
#include <string>
class ExampleHandler: public proton::messaging_handler {
std::string url_;
// The container has started
void on_container_start(proton::container&) override {
}
// A message can be sent
void on_sendable(proton::sender&) override {
}
// A message is received
void on_message(proton::delivery&, proton::message&) override {
}
public:
ExampleHandler(const std::string& url) : url_(url) {}
};
int main() {
ExampleHandler h("localhost");
proton::default_container(h).run();
}
| #include <proton/default_container.hpp>
#include <proton/messaging_handler.hpp>
#include <string>
class ExampleHandler: public proton::messaging_handler {
std::string url_;
// The container has started
void on_container_start(proton::container& c) override {
}
// A message can be sent
void on_sendable(proton::sender& s) override {
}
// A message is received
void on_message(proton::delivery& d, proton::message& m) override {
}
public:
ExampleHandler(const std::string& url) : url_(url) {}
};
int main() {
ExampleHandler h("localhost");
proton::default_container(h).run();
}
|
Fix compilation error in the focus manager by returning NULL from unimplemented function. | // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/focus_manager.h"
#include "base/logging.h"
namespace views {
void FocusManager::ClearNativeFocus() {
NOTIMPLEMENTED();
}
void FocusManager::FocusNativeView(gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
// static
FocusManager* FocusManager::GetFocusManagerForNativeView(
gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
} // namespace views
| // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/focus_manager.h"
#include "base/logging.h"
namespace views {
void FocusManager::ClearNativeFocus() {
NOTIMPLEMENTED();
}
void FocusManager::FocusNativeView(gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
// static
FocusManager* FocusManager::GetFocusManagerForNativeView(
gfx::NativeView native_view) {
NOTIMPLEMENTED();
return NULL;
}
} // namespace views
|
Remove test that compared an empty string to bool | #include "TestCommon.h"
USING_NAMESPACE_KAI
struct TestString : TestCommon
{
protected:
void AddrequiredClasses() override
{
Reg().AddClass<bool>();
Reg().AddClass<int>();
Reg().AddClass<String>();
}
};
TEST_F(TestString, TestBoolean)
{
Pointer<String> s0 = Reg().New<String>("foo");
ASSERT_TRUE(s0.GetClass()->Boolean(s0.GetStorageBase()));
*s0 = "";
ASSERT_FALSE(s0.GetClass()->Boolean(s0.GetStorageBase()));
}
TEST_F(TestString, TestCompare)
{
Pointer<String> s0 = Reg().New<String>("a");
Pointer<String> s1 = Reg().New<String>("a");
ASSERT_TRUE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
*s1 = "b";
ASSERT_FALSE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
ASSERT_TRUE(s0.GetClass()->Less(s0.GetStorageBase(), s1.GetStorageBase()));
ASSERT_FALSE(s0.GetClass()->Greater(s0.GetStorageBase(), s1.GetStorageBase()));
}
TEST_F(TestString, TestConcat)
{
}
TEST_F(TestString, TestLength)
{
}
TEST_F(TestString, TestStringStreamInsert)
{
}
TEST_F(TestString, TestStringStreamExtract)
{
}
| #include "TestCommon.h"
USING_NAMESPACE_KAI
struct TestString : TestCommon
{
protected:
void AddrequiredClasses() override
{
Reg().AddClass<bool>();
Reg().AddClass<int>();
Reg().AddClass<String>();
}
};
TEST_F(TestString, TestCompare)
{
Pointer<String> s0 = Reg().New<String>("a");
Pointer<String> s1 = Reg().New<String>("a");
ASSERT_TRUE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
*s1 = "b";
ASSERT_FALSE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
ASSERT_TRUE(s0.GetClass()->Less(s0.GetStorageBase(), s1.GetStorageBase()));
ASSERT_FALSE(s0.GetClass()->Greater(s0.GetStorageBase(), s1.GetStorageBase()));
}
TEST_F(TestString, TestConcat)
{
}
TEST_F(TestString, TestLength)
{
}
TEST_F(TestString, TestStringStreamInsert)
{
}
TEST_F(TestString, TestStringStreamExtract)
{
}
|
Set org name and app name | #include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
| #include <QApplication>
#include "mainwindow.h"
const QString APP_ORGNAME = "PepperNote";
const QString APP_APPNAME = "PepperNote";
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationName(APP_ORGNAME);
QCoreApplication::setApplicationName(APP_APPNAME);
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
Add explicit <string> include to byteswap test | /*
* Copyright 2015 - 2017 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <map>
#include <ox/std/std.hpp>
using namespace std;
using namespace ox::std;
template<typename T>
int testBigEndianAdapt(string str) {
auto i = (T) stoull(str, nullptr, 16);
return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}
map<string, int(*)(string)> tests = {
{
{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
},
};
int main(int argc, const char **args) {
int retval = -1;
if (argc > 1) {
auto testName = args[1];
string testArg = args[2];
if (tests.find(testName) != tests.end()) {
retval = tests[testName](testArg);
}
}
return retval;
}
| /*
* Copyright 2015 - 2017 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <map>
#include <string>
#include <ox/std/std.hpp>
using namespace std;
using namespace ox::std;
template<typename T>
int testBigEndianAdapt(string str) {
auto i = (T) stoull(str, nullptr, 16);
return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}
map<string, int(*)(string)> tests = {
{
{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
},
};
int main(int argc, const char **args) {
int retval = -1;
if (argc > 1) {
auto testName = args[1];
string testArg = args[2];
if (tests.find(testName) != tests.end()) {
retval = tests[testName](testArg);
}
}
return retval;
}
|
Fix missing member initialization on Mac OS | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <errno.h>
#include "bin/utils.h"
OSError::OSError() {
set_code(errno);
SetMessage(strerror(errno));
}
| // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <errno.h>
#include "bin/utils.h"
OSError::OSError() : code_(0), message_(NULL) {
set_code(errno);
SetMessage(strerror(errno));
}
|
Remove dependency on importing std into global namespace. | #include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <assert.h>
using namespace std;
set<string> done;
void dump_header(string header) {
if (done.find(header) != done.end()) return;
done.insert(header);
FILE *f = fopen(header.c_str(), "r");
if (f == NULL) {
fprintf(stderr, "Could not open header %s.\n", header.c_str());
exit(1);
}
char line[1024];
while (fgets(line, 1024, f)) {
if (strncmp(line, "#include \"", 10) == 0) {
char *sub_header = line + 10;
for (int i = 0; i < 1014; i++) {
if (sub_header[i] == '"') sub_header[i] = 0;
}
size_t slash_pos = header.rfind('/');
std::string path;
if (slash_pos != std::string::npos)
path = header.substr(0, slash_pos + 1);
dump_header(path + sub_header);
} else {
fputs(line, stdout);
}
}
fclose(f);
}
int main(int argc, char **headers) {
for (int i = 1; i < argc; i++) {
dump_header(headers[i]);
}
return 0;
}
| #include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <assert.h>
std::set<std::string> done;
void dump_header(std::string header) {
if (done.find(header) != done.end()) return;
done.insert(header);
FILE *f = fopen(header.c_str(), "r");
if (f == NULL) {
fprintf(stderr, "Could not open header %s.\n", header.c_str());
exit(1);
}
char line[1024];
while (fgets(line, 1024, f)) {
if (strncmp(line, "#include \"", 10) == 0) {
char *sub_header = line + 10;
for (int i = 0; i < 1014; i++) {
if (sub_header[i] == '"') sub_header[i] = 0;
}
size_t slash_pos = header.rfind('/');
std::string path;
if (slash_pos != std::string::npos)
path = header.substr(0, slash_pos + 1);
dump_header(path + sub_header);
} else {
fputs(line, stdout);
}
}
fclose(f);
}
int main(int argc, char **headers) {
for (int i = 1; i < argc; i++) {
dump_header(headers[i]);
}
return 0;
}
|
Fix bug when timing is not set inc hannel | #include "channel.h"
#include "timing/timingfactory.h"
class Channel::Private
{
public:
Private()
: id(0)
{
}
int id;
QString target;
QString certificate;
TimingPtr timing;
};
Channel::Channel()
: d(new Private)
{
}
Channel::Channel(const int &id, const QString &target, const QString &certificate, const TimingPtr &timing)
: d(new Private)
{
d->id = id;
d->target = target;
d->certificate = certificate;
d->timing = timing;
}
Channel::~Channel()
{
delete d;
}
ChannelPtr Channel::fromVariant(const QVariant &variant)
{
QVariantMap hash = variant.toMap();
return ChannelPtr(new Channel(hash.value("id").toInt(),
hash.value("target").toString(),
hash.value("certificate").toString(),
TimingFactory::timingFromVariant(hash.value("timing"))));
}
QVariant Channel::toVariant() const
{
QVariantMap hash;
hash.insert("id", d->id);
hash.insert("target", d->target);
hash.insert("certificate", d->certificate);
hash.insert("timing", d->timing->toVariant());
return hash;
}
void Channel::setTarget(const QString &target)
{
d->target = target;
}
QString Channel::target() const
{
return d->target;
}
TimingPtr Channel::timing() const
{
return d->timing;
}
| #include "channel.h"
#include "timing/timingfactory.h"
class Channel::Private
{
public:
Private()
: id(0)
{
}
int id;
QString target;
QString certificate;
TimingPtr timing;
};
Channel::Channel()
: d(new Private)
{
}
Channel::Channel(const int &id, const QString &target, const QString &certificate, const TimingPtr &timing)
: d(new Private)
{
d->id = id;
d->target = target;
d->certificate = certificate;
d->timing = timing;
}
Channel::~Channel()
{
delete d;
}
ChannelPtr Channel::fromVariant(const QVariant &variant)
{
QVariantMap hash = variant.toMap();
return ChannelPtr(new Channel(hash.value("id").toInt(),
hash.value("target").toString(),
hash.value("certificate").toString(),
TimingFactory::timingFromVariant(hash.value("timing"))));
}
QVariant Channel::toVariant() const
{
QVariantMap hash;
hash.insert("id", d->id);
hash.insert("target", d->target);
hash.insert("certificate", d->certificate);
if(d->timing)
{
hash.insert("timing", d->timing->toVariant());
}
return hash;
}
void Channel::setTarget(const QString &target)
{
d->target = target;
}
QString Channel::target() const
{
return d->target;
}
TimingPtr Channel::timing() const
{
return d->timing;
}
|
Add basic command line flag handling using cppassist/cmdline |
int main(int argc, char* argv[])
{
} | #include <iostream>
#include <string>
#include <cppassist/cmdline/ArgumentParser.h>
int main(int argc, char* argv[])
{
cppassist::ArgumentParser argParser;
argParser.parse(argc, argv);
auto inFileName = argParser.value("--input");
auto outFileName = argParser.value("--output");
auto outFileType = outFileName.substr(outFileName.find_last_of('.') + 1);
auto fromGeneratedKernel = argParser.isSet("-k");
if (fromGeneratedKernel)
{
std::cout << "Converting kernel \"" << inFileName << "\" to output file \"" << outFileName << "\" (type: " << outFileType << ")" <<std::endl;
}
else
{
std::cout << "Using kernel description \"" << inFileName << "\" to generate kernel \"" << outFileName << "\" (type: " << outFileType << ")" << std::endl;
}
} |
Set TopLeft button text as QtChronos | #include "headers/mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
ui->setupUi(this);
/***************************************************************************
* Create and set the settings button on the top left of the tabs
**************************************************************************/
buttonSettings = new QPushButton();
ui->tabWidget->setCornerWidget(buttonSettings, Qt::TopLeftCorner);
setupMenu();
connect(buttonSettings, SIGNAL(clicked()),
this, SLOT(openMenu()));
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::setupMenu() {
menuSettings = new QMenu(this);
menuSettings->addAction("&File");
menuSettings->addAction("&Help");
QAction* aSettings = menuSettings->addAction("&Settings");
connect(aSettings, SIGNAL(triggered()),
this, SLOT(openSettings()));
menuSettings->addSeparator();
// Quit action
QAction* aQuit = menuSettings->addAction("&Quit");
this->addAction(aQuit);
aQuit->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
connect(aQuit, SIGNAL(triggered()),
this, SLOT(close()));
}
void MainWindow::openMenu() {
menuSettings->exec(buttonSettings->mapToGlobal(QPoint(0, buttonSettings->height())));
}
void MainWindow::openSettings() {
OptionsWindow* settings = new OptionsWindow(this);
settings->show();
}
| #include "headers/mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
ui->setupUi(this);
/***************************************************************************
* Create and set the settings button on the top left of the tabs
**************************************************************************/
buttonSettings = new QPushButton();
buttonSettings->setText(QString("QtChronos"));
ui->tabWidget->setCornerWidget(buttonSettings, Qt::TopLeftCorner);
setupMenu();
connect(buttonSettings, SIGNAL(clicked()),
this, SLOT(openMenu()));
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::setupMenu() {
menuSettings = new QMenu(this);
menuSettings->addAction("&File");
menuSettings->addAction("&Help");
QAction* aSettings = menuSettings->addAction("&Settings");
connect(aSettings, SIGNAL(triggered()),
this, SLOT(openSettings()));
menuSettings->addSeparator();
// Quit action
QAction* aQuit = menuSettings->addAction("&Quit");
this->addAction(aQuit);
aQuit->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
connect(aQuit, SIGNAL(triggered()),
this, SLOT(close()));
}
void MainWindow::openMenu() {
menuSettings->exec(buttonSettings->mapToGlobal(QPoint(0, buttonSettings->height())));
}
void MainWindow::openSettings() {
OptionsWindow* settings = new OptionsWindow(this);
settings->show();
}
|
Update recently-added test to use new __c11_ form of atomic builtins. | // RUN: %clang_cc1 %s -emit-llvm -o - -triple=i686-apple-darwin9 | FileCheck %s
struct A {
_Atomic(int) i;
A(int j);
void v(int j);
};
// Storing to atomic values should be atomic
// CHECK: store atomic i32
void A::v(int j) { i = j; }
// Initialising atomic values should not be atomic
// CHECK-NOT: store atomic
A::A(int j) : i(j) {}
struct B {
int i;
B(int x) : i(x) {}
};
_Atomic(B) b;
// CHECK: define void @_Z11atomic_initR1Ai
void atomic_init(A& a, int i) {
// CHECK-NOT: atomic
__atomic_init(&b, B(i));
}
| // RUN: %clang_cc1 %s -emit-llvm -o - -triple=i686-apple-darwin9 | FileCheck %s
struct A {
_Atomic(int) i;
A(int j);
void v(int j);
};
// Storing to atomic values should be atomic
// CHECK: store atomic i32
void A::v(int j) { i = j; }
// Initialising atomic values should not be atomic
// CHECK-NOT: store atomic
A::A(int j) : i(j) {}
struct B {
int i;
B(int x) : i(x) {}
};
_Atomic(B) b;
// CHECK: define void @_Z11atomic_initR1Ai
void atomic_init(A& a, int i) {
// CHECK-NOT: atomic
__c11_atomic_init(&b, B(i));
}
|
Clear spurious timing code from bounds_interence | #include <Halide.h>
#include <sys/time.h>
using namespace Halide;
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
int main(int argc, char **argv) {
Func f, g, h; Var x, y;
h(x) = x;
g(x) = h(x-1) + h(x+1);
f(x, y) = (g(x-1) + g(x+1)) + y;
h.root();
g.root();
if (use_gpu()) {
f.cudaTile(x, y, 16, 16);
g.cudaTile(x, 128);
h.cudaTile(x, 128);
}
Image<int> out = f.realize(32, 32);
for (int y = 0; y < 32; y++) {
for (int x = 0; x < 32; x++) {
if (out(x, y) != x*4 + y) {
printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
| #include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
Func f, g, h; Var x, y;
h(x) = x;
g(x) = h(x-1) + h(x+1);
f(x, y) = (g(x-1) + g(x+1)) + y;
h.root();
g.root();
if (use_gpu()) {
f.cudaTile(x, y, 16, 16);
g.cudaTile(x, 128);
h.cudaTile(x, 128);
}
Image<int> out = f.realize(32, 32);
for (int y = 0; y < 32; y++) {
for (int x = 0; x < 32; x++) {
if (out(x, y) != x*4 + y) {
printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
|
Add a missing target requirement. | // RUN: rm -rf %t
// RUN: pp-trace -ignore FileChanged,MacroDefined %s -x objective-c++ -undef -target x86_64 -std=c++11 -fmodules -fcxx-modules -fmodules-cache-path=%t -I%S -I%S/Input | FileCheck --strict-whitespace %s
// CHECK: ---
@import Level1A;
// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT: Path: [{Name: Level1A, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}]
// CHECK-NEXT: Imported: Level1A
@import Level1B.Level2B;
// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT: Path: [{Name: Level1B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}, {Name: Level2B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:17"}]
// CHECK-NEXT: Imported: Level2B
// CHECK-NEXT: - Callback: EndOfMainFile
// CHECK-NEXT: ...
| // RUN: rm -rf %t
// RUN: pp-trace -ignore FileChanged,MacroDefined %s -x objective-c++ -undef -target x86_64 -std=c++11 -fmodules -fcxx-modules -fmodules-cache-path=%t -I%S -I%S/Input | FileCheck --strict-whitespace %s
// REQUIRES: x86-registered-target
// CHECK: ---
@import Level1A;
// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT: Path: [{Name: Level1A, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}]
// CHECK-NEXT: Imported: Level1A
@import Level1B.Level2B;
// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT: Path: [{Name: Level1B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}, {Name: Level2B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:17"}]
// CHECK-NEXT: Imported: Level2B
// CHECK-NEXT: - Callback: EndOfMainFile
// CHECK-NEXT: ...
|
Set console log level to debug | #include "spaghetti/logger.h"
namespace spaghetti::log {
Logger g_loggerConsole{};
Logger g_loggerFile{};
void init()
{
if (!g_loggerConsole) g_loggerConsole = spdlog::stdout_color_mt("console");
if (!g_loggerFile) g_loggerFile = spdlog::basic_logger_mt("file", "spaghetti.log");
spdlog::set_pattern("[%Y.%m.%d %H:%M:%S.%e] [%n] [%L] %v");
}
Loggers get()
{
return { g_loggerConsole, g_loggerFile };
}
} // namespace spaghetti::log
| #include "spaghetti/logger.h"
namespace spaghetti::log {
Logger g_loggerConsole{};
Logger g_loggerFile{};
void init()
{
if (!g_loggerConsole) g_loggerConsole = spdlog::stdout_color_mt("console");
if (!g_loggerFile) g_loggerFile = spdlog::basic_logger_mt("file", "spaghetti.log");
spdlog::set_pattern("[%Y.%m.%d %H:%M:%S.%e] [%n] [%L] %v");
g_loggerConsole->set_level(spdlog::level::debug);
}
Loggers get()
{
return { g_loggerConsole, g_loggerFile };
}
} // namespace spaghetti::log
|
Fix some more debugging fallout | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libone project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <string>
#include <librevenge-stream/librevenge-stream.h>
#include <unordered_map>
#include <iostream>
#include <iostream>
#include <iomanip>
#include "StringInStorageBuffer.h"
#include "libone_utils.h"
namespace libone {
void StringInStorageBuffer::parse(librevenge::RVNGInputStream *input) {
std::stringstream stream;
length = readU32(input);
std::vector<char> string;
char *buf = (char *) readNBytes(input, length*2);
string.assign(buf, buf+length*2);
ustring = librevenge::RVNGString((char *) &string[0]);
ONE_DEBUG_MSG(("read length1 %lu length2 %lu string1 %s string2 %s end\n", length, ustring.len(), &string[0], ustring.cstr()));
}
std::string StringInStorageBuffer::to_string() {
return ustring.cstr();
}
}
| /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libone project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <string>
#include <librevenge-stream/librevenge-stream.h>
#include <unordered_map>
#include <iostream>
#include <iostream>
#include <iomanip>
#include "StringInStorageBuffer.h"
#include "libone_utils.h"
namespace libone {
void StringInStorageBuffer::parse(librevenge::RVNGInputStream *input) {
std::stringstream stream;
length = readU32(input);
std::vector<char> string;
char *buf = (char *) readNBytes(input, length*2);
string.assign(buf, buf+length*2);
ustring = librevenge::RVNGString((char *) &string[0]);
ONE_DEBUG_MSG(("read length1 %u length2 %u string1 %s string2 %s end\n", length, ustring.len(), &string[0], ustring.cstr()));
}
std::string StringInStorageBuffer::to_string() {
return ustring.cstr();
}
}
|
Set focus on password field | #include "authdialog.h"
#include <qconnman/manager.h>
#include <qconnman/agent.h>
#include <QDebug>
AuthDialog::AuthDialog(Manager *manager, QWidget *parent):
QDialog(parent),
m_manager(manager)
{
ui.setupUi(this);
connect(ui.showPassword, SIGNAL(toggled(bool)), SLOT(showPassword(bool)));
}
int AuthDialog::exec()
{
Agent *agent = qobject_cast<Agent *>(QObject::sender());
Agent::InputRequest *request = agent->currentInputRequest();
ui.label->setText(trUtf8("This network requires a %1 password to connect. Please enter the password bellow.")
.arg(m_manager->service(request->service)->security().join("").toUpper()));
int result = QDialog::exec();
if (result == QDialog::Accepted)
request->response.passphrase = ui.password->text();
else
request->cancel = true;
return result;
}
void AuthDialog::showPassword(bool checked)
{
if (!checked)
ui.password->setEchoMode(QLineEdit::Password);
else
ui.password->setEchoMode(QLineEdit::Normal);
}
| #include "authdialog.h"
#include <qconnman/manager.h>
#include <qconnman/agent.h>
#include <QDebug>
AuthDialog::AuthDialog(Manager *manager, QWidget *parent):
QDialog(parent),
m_manager(manager)
{
ui.setupUi(this);
connect(ui.showPassword, SIGNAL(toggled(bool)), SLOT(showPassword(bool)));
}
int AuthDialog::exec()
{
Agent *agent = qobject_cast<Agent *>(QObject::sender());
Agent::InputRequest *request = agent->currentInputRequest();
ui.password->clear();
ui.password->setFocus();
ui.label->setText(trUtf8("This network requires a %1 password to connect. Please enter the password bellow.")
.arg(m_manager->service(request->service)->security().join("").toUpper()));
int result = QDialog::exec();
if (result == QDialog::Accepted)
request->response.passphrase = ui.password->text();
else
request->cancel = true;
return result;
}
void AuthDialog::showPassword(bool checked)
{
if (!checked)
ui.password->setEchoMode(QLineEdit::Password);
else
ui.password->setEchoMode(QLineEdit::Normal);
}
|
Remove problemanic on VS test | // Copyright 2017, Dawid Kurek, <dawikur@gmail.com>
#include "lel/operation/unary.hpp"
#include "gtest/gtest.h"
TEST(unary_test, logical_not_can_be_used_in_constexpr) {
std::logical_not<> logical_not;
static_assert(logical_not(false), "");
}
TEST(unary_test, indirection_can_be_used_in_constexpr) {
LeL::Operation::__Indirection indirection;
int const val = 5;
static_assert(indirection(&val) == 5, "");
}
| // Copyright 2017, Dawid Kurek, <dawikur@gmail.com>
#include "lel/operation/unary.hpp"
#include "gtest/gtest.h"
TEST(unary_test, logical_not_can_be_used_in_constexpr) {
std::logical_not<> logical_not;
static_assert(logical_not(false), "");
}
|
Add glfw window to texture demo |
#include <iostream>
#include <texturebased/polarmapped.h>
int main(int /*argc*/, char* /*argv*/[])
{
// TODO: glfw
return 0;
}
|
#include <iostream>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <glbinding/Binding.h>
#include <glbinding/gl/gl.h>
#include <globjects/globjects.h>
using namespace gl;
void error(int errnum, const char * errmsg)
{
std::cerr << errnum << ": " << errmsg << std::endl;
}
void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*mods*/)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, 1);
}
int main(int, char *[])
{
if (!glfwInit())
return 1;
glfwSetErrorCallback(error);
glfwDefaultWindowHints();
#ifdef SYSTEM_DARWIN
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
GLFWwindow * window = glfwCreateWindow(640, 480, "Texture Demo", nullptr, nullptr);
if (!window)
{
glfwTerminate();
return -1;
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
glbinding::Binding::initialize(false); // only resolve functions that are actually used (lazy)
globjects::init();
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
|
Add sleep of 16 milliseconds for reduce framerate (High framerate make than my GPU do sharp creepy sound) | #include "ImwWindowManagerDX11.h"
#include "ImwPlatformWindowDX11.h"
#include <imgui_impl_dx11.h>
using namespace ImWindow;
ImwWindowManagerDX11::ImwWindowManagerDX11()
{
ImwPlatformWindowDX11::InitDX11();
}
ImwWindowManagerDX11::~ImwWindowManagerDX11()
{
ImwPlatformWindowDX11::ShutdownDX11();
//ImGui_ImplDX11_Shutdown();
}
void ImwWindowManagerDX11::InternalRun()
{
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Update();
}
}
ImwPlatformWindow* ImwWindowManagerDX11::CreatePlatformWindow(bool bMain, ImwPlatformWindow* pParent, bool bDragWindow)
{
ImwPlatformWindowDX11* pWindow = new ImwPlatformWindowDX11(bMain, bDragWindow);
ImwTest(pWindow->Init(pParent));
return (ImwPlatformWindow*)pWindow;
}
ImVec2 ImwWindowManagerDX11::GetCursorPos()
{
POINT oPoint;
::GetCursorPos(&oPoint);
return ImVec2(oPoint.x, oPoint.y);
} | #include "ImwWindowManagerDX11.h"
#include "ImwPlatformWindowDX11.h"
#include <imgui_impl_dx11.h>
using namespace ImWindow;
ImwWindowManagerDX11::ImwWindowManagerDX11()
{
ImwPlatformWindowDX11::InitDX11();
}
ImwWindowManagerDX11::~ImwWindowManagerDX11()
{
ImwPlatformWindowDX11::ShutdownDX11();
//ImGui_ImplDX11_Shutdown();
}
void ImwWindowManagerDX11::InternalRun()
{
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Update();
Sleep(16);
}
}
ImwPlatformWindow* ImwWindowManagerDX11::CreatePlatformWindow(bool bMain, ImwPlatformWindow* pParent, bool bDragWindow)
{
ImwPlatformWindowDX11* pWindow = new ImwPlatformWindowDX11(bMain, bDragWindow);
ImwTest(pWindow->Init(pParent));
return (ImwPlatformWindow*)pWindow;
}
ImVec2 ImwWindowManagerDX11::GetCursorPos()
{
POINT oPoint;
::GetCursorPos(&oPoint);
return ImVec2(oPoint.x, oPoint.y);
} |
Create element for recorder endpoint | /*
* RecorderEndPoint.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <mparisdiaz@gmail.com>
* Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "RecorderEndPoint.hpp"
namespace kurento
{
RecorderEndPoint::RecorderEndPoint (std::shared_ptr<MediaManager> parent, const std::string &uri)
: UriEndPoint (parent, uri, UriEndPointType::type::RECORDER_END_POINT)
{
}
RecorderEndPoint::~RecorderEndPoint() throw ()
{
}
} // kurento
| /*
* RecorderEndPoint.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <mparisdiaz@gmail.com>
* Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "RecorderEndPoint.hpp"
namespace kurento
{
RecorderEndPoint::RecorderEndPoint (std::shared_ptr<MediaManager> parent, const std::string &uri)
: UriEndPoint (parent, uri, UriEndPointType::type::RECORDER_END_POINT)
{
gchar *name;
name = getIdStr ();
element = gst_element_factory_make ("recorderendpoint", name);
g_free (name);
g_object_ref (element);
gst_bin_add (GST_BIN (parent->element), element);
gst_element_sync_state_with_parent (element);
}
RecorderEndPoint::~RecorderEndPoint() throw ()
{
gst_bin_remove (GST_BIN (parent->element), element);
gst_element_set_state (element, GST_STATE_NULL);
g_object_unref (element);
}
} // kurento
|
Include platform header before determining OS | // This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/detail/macros.h>
#if defined(VSNRAY_OS_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#endif
#include "util.h"
unsigned visionaray::get_num_processors()
{
#if defined(VSNRAY_OS_WIN32)
SYSTEM_INFO sysinfo;
GetNativeSystemInfo(&sysinfo);
return static_cast<unsigned>(sysinfo.dwNumberOfProcessors);
#else
return static_cast<unsigned>(sysconf(_SC_NPROCESSORS_ONLN));
#endif
}
| // This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/detail/macros.h>
#include <visionaray/detail/platform.h>
#if defined(VSNRAY_OS_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#endif
#include "util.h"
unsigned visionaray::get_num_processors()
{
#if defined(VSNRAY_OS_WIN32)
SYSTEM_INFO sysinfo;
GetNativeSystemInfo(&sysinfo);
return static_cast<unsigned>(sysinfo.dwNumberOfProcessors);
#else
return static_cast<unsigned>(sysconf(_SC_NPROCESSORS_ONLN));
#endif
}
|
Remove unnecessary zeroing out of output buffer | #include <iostream>
#include "floaxie/dtoa.h"
using namespace std;
using namespace floaxie;
int main(int, char**)
{
double pi = 0.1;
char buffer[128];
for (int i = 0; i < 128; ++i)
buffer[i] = 0;
dtoa(pi, buffer);
std::cout << "pi: " << pi << ", buffer: " << buffer << std::endl;
return 0;
}
| #include <iostream>
#include "floaxie/dtoa.h"
using namespace std;
using namespace floaxie;
int main(int, char**)
{
double pi = 0.1;
char buffer[128];
dtoa(pi, buffer);
std::cout << "pi: " << pi << ", buffer: " << buffer << std::endl;
return 0;
}
|
Fix compilation issue on older mac (< 10.12) | /*
* System Call getentropy(2)
* (C) 2017 Alexander Bluhm (genua GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/getentropy.h>
#if defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_SOLARIS)
#include <unistd.h>
#else
#include <sys/random.h>
#endif
namespace Botan {
/**
* Gather 256 bytes entropy from getentropy(2). Note that maximum
* buffer size is limited to 256 bytes. On OpenBSD this does neither
* block nor fail.
*/
size_t Getentropy::poll(RandomNumberGenerator& rng)
{
secure_vector<uint8_t> buf(256);
if(::getentropy(buf.data(), buf.size()) == 0)
{
rng.add_entropy(buf.data(), buf.size());
return buf.size() * 8;
}
return 0;
}
}
| /*
* System Call getentropy(2)
* (C) 2017 Alexander Bluhm (genua GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/getentropy.h>
#if defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_SOLARIS)
#include <unistd.h>
#else
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
// Allows successful compilation on macOS older than 10.12: Provides a missing typedef for `u_int`.
#include <sys/types.h>
#endif
#include <sys/random.h>
#endif
namespace Botan {
/**
* Gather 256 bytes entropy from getentropy(2). Note that maximum
* buffer size is limited to 256 bytes. On OpenBSD this does neither
* block nor fail.
*/
size_t Getentropy::poll(RandomNumberGenerator& rng)
{
secure_vector<uint8_t> buf(256);
if(::getentropy(buf.data(), buf.size()) == 0)
{
rng.add_entropy(buf.data(), buf.size());
return buf.size() * 8;
}
return 0;
}
}
|
Fix bug where directories would fail to open when recursing | //
// src/utils/directory.cc
// tbd
//
// Created by inoahdev on 10/17/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include "directory.h"
namespace utils {
directory::open_result directory::open(const char *path) {
dir = opendir(path);
if (!dir) {
return open_result::failed_to_open_directory;
}
this->path = path;
return open_result::ok;
}
directory::open_result directory::open(const std::string &path) {
dir = opendir(path.data());
if (!dir) {
return open_result::failed_to_open_directory;
}
this->path = path;
return open_result::ok;
}
directory::~directory() noexcept {
if (dir != nullptr) {
closedir(dir);
dir = nullptr;
}
}
}
| //
// src/utils/directory.cc
// tbd
//
// Created by inoahdev on 10/17/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include "directory.h"
namespace utils {
directory::open_result directory::open(const char *path) {
this->path = path;
this->dir = opendir(path);
if (!dir) {
return open_result::failed_to_open_directory;
}
return open_result::ok;
}
directory::open_result directory::open(const std::string &path) {
this->path = path;
this->dir = opendir(path.data());
if (!dir) {
return open_result::failed_to_open_directory;
}
return open_result::ok;
}
directory::~directory() noexcept {
if (dir != nullptr) {
closedir(dir);
dir = nullptr;
}
}
}
|
Remove a line included to test the parser. | #include "robobo.h"
#include "configuration.cpp"
#include "servercapab.cpp"
#include "socket.cpp"
std::string input, command, currentNick;
std::vector<std::string> inputParams;
bool registered;
int main(int argc, char** argv) {
ConfigReader config;
Socket bot_socket (config.getServer(), config.getPort());
bot_socket.sendMsg("NICK :RoBoBo");
bot_socket.sendMsg("USER RoBoBo here " + config.getServer() + " :RoBoBo-IRC-BoBo IRC Bot");
currentNick = "RoBoBo";
while (true) {
if (!bot_socket.isConnected()) {
bot_socket.closeConnection();
std::cout << "Disconnected from server." << std::endl;
return 0;
}
input = bot_socket.receive();
std::cout << input << std::endl;
inputParams.clear();
inputParams = bot_socket.parseLine(input);
command = inputParams[1];
std::cout << "Command/Numeric: " << command << std::endl;
if (command == "001")
registered = true;
if (command == "005")
handleCapab(inputParams);
if (command == "433" && !registered) {
currentNick += "_";
bot_socket.sendMsg("NICK :" + currentNick);
}
}
} | #include "robobo.h"
#include "configuration.cpp"
#include "servercapab.cpp"
#include "socket.cpp"
std::string input, command, currentNick;
std::vector<std::string> inputParams;
bool registered;
int main(int argc, char** argv) {
ConfigReader config;
Socket bot_socket (config.getServer(), config.getPort());
bot_socket.sendMsg("NICK :RoBoBo");
bot_socket.sendMsg("USER RoBoBo here " + config.getServer() + " :RoBoBo-IRC-BoBo IRC Bot");
currentNick = "RoBoBo";
while (true) {
if (!bot_socket.isConnected()) {
bot_socket.closeConnection();
std::cout << "Disconnected from server." << std::endl;
return 0;
}
input = bot_socket.receive();
std::cout << input << std::endl;
inputParams.clear();
inputParams = bot_socket.parseLine(input);
command = inputParams[1];
if (command == "001")
registered = true;
if (command == "005")
handleCapab(inputParams);
if (command == "433" && !registered) {
currentNick += "_";
bot_socket.sendMsg("NICK :" + currentNick);
}
}
} |
Apply initial transform in --skr mode. | #include "DMRecordTask.h"
#include "DMUtil.h"
#include "DMWriteTask.h"
#include "SkCommandLineFlags.h"
#include "SkRecording.h"
DEFINE_bool(skr, false, "If true, run SKR tests.");
namespace DM {
RecordTask::RecordTask(const Task& parent, skiagm::GM* gm, SkBitmap reference)
: CpuTask(parent)
, fName(UnderJoin(parent.name().c_str(), "skr"))
, fGM(gm)
, fReference(reference)
{}
void RecordTask::draw() {
// Record the GM into an SkRecord.
EXPERIMENTAL::SkRecording recording(fReference.width(), fReference.height());
fGM->draw(recording.canvas());
SkAutoTDelete<const EXPERIMENTAL::SkPlayback> playback(recording.releasePlayback());
// Draw the SkRecord back into a bitmap.
SkBitmap bitmap;
SetupBitmap(fReference.colorType(), fGM.get(), &bitmap);
SkCanvas target(bitmap);
playback->draw(&target);
if (!BitmapsEqual(bitmap, fReference)) {
this->fail();
this->spawnChild(SkNEW_ARGS(WriteTask, (*this, bitmap)));
}
}
bool RecordTask::shouldSkip() const {
return !FLAGS_skr;
}
} // namespace DM
| #include "DMRecordTask.h"
#include "DMUtil.h"
#include "DMWriteTask.h"
#include "SkCommandLineFlags.h"
#include "SkRecording.h"
DEFINE_bool(skr, false, "If true, run SKR tests.");
namespace DM {
RecordTask::RecordTask(const Task& parent, skiagm::GM* gm, SkBitmap reference)
: CpuTask(parent)
, fName(UnderJoin(parent.name().c_str(), "skr"))
, fGM(gm)
, fReference(reference)
{}
void RecordTask::draw() {
// Record the GM into an SkRecord.
EXPERIMENTAL::SkRecording recording(fReference.width(), fReference.height());
recording.canvas()->concat(fGM->getInitialTransform());
fGM->draw(recording.canvas());
SkAutoTDelete<const EXPERIMENTAL::SkPlayback> playback(recording.releasePlayback());
// Draw the SkRecord back into a bitmap.
SkBitmap bitmap;
SetupBitmap(fReference.colorType(), fGM.get(), &bitmap);
SkCanvas target(bitmap);
playback->draw(&target);
if (!BitmapsEqual(bitmap, fReference)) {
this->fail();
this->spawnChild(SkNEW_ARGS(WriteTask, (*this, bitmap)));
}
}
bool RecordTask::shouldSkip() const {
return !FLAGS_skr;
}
} // namespace DM
|
Make deleted special member functions private. | // http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/
// http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics
#include <iostream>
class CSingleton final {
public:
static CSingleton& GetInstance();
int getValue() const { return mValue; }
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
CSingleton(CSingleton&&) = delete;
CSingleton& operator=(CSingleton&&) = delete;
private:
CSingleton() = default;
~CSingleton() = default;
int mValue = 0;
};
CSingleton& CSingleton::GetInstance() {
static CSingleton instance;
return instance;
}
int main() {
auto const value{CSingleton::GetInstance().getValue()};
std::cout << value << '\n';
}
| // http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/
// http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics
#include <iostream>
class CSingleton final {
public:
static CSingleton& GetInstance() {
static CSingleton instance;
return instance;
}
int getValue() const { return mValue; }
private:
CSingleton() = default;
~CSingleton() = default;
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
CSingleton(CSingleton&&) = delete;
CSingleton& operator=(CSingleton&&) = delete;
int mValue = 0;
};
int main() {
auto const value{CSingleton::GetInstance().getValue()};
std::cout << value << '\n';
}
|
Update to use static versions. | #include"qca.h"
#include<stdio.h>
int main(int argc, char **argv)
{
QCA::Initializer init;
QCString cs = (argc >= 2) ? argv[1] : "hello";
if( !QCA::isSupported("sha1") )
printf("SHA1 not supported!\n");
else {
QCA::SHA1 sha1Hash;
QString result = sha1Hash.hashToString(cs);
printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
}
if( !QCA::isSupported("md5") )
printf("MD5 not supported!\n");
else {
QCA::MD5 md5Hash;
QString result = md5Hash.hashToString(cs);
printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
}
return 0;
}
| #include"qca.h"
#include<stdio.h>
int main(int argc, char **argv)
{
QCA::Initializer init;
QCString cs = (argc >= 2) ? argv[1] : "hello";
if( !QCA::isSupported("sha1") )
printf("SHA1 not supported!\n");
else {
QString result = QCA::SHA1().hashToString(cs);
printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
}
if( !QCA::isSupported("md5") )
printf("MD5 not supported!\n");
else {
QString result = QCA::MD5().hashToString(cs);
printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
}
return 0;
}
|
Update Problem 8 test case | #include "catch.hpp"
#include "StringToInteger.hpp"
TEST_CASE("String To Integer") {
Solution s;
SECTION("Normal tests") {
REQUIRE(s.myAtoi("1") == 1);
}
SECTION("Normal tests 2") {
REQUIRE(s.myAtoi(" 010") == 10);
}
}
| #include "catch.hpp"
#include "StringToInteger.hpp"
TEST_CASE("String To Integer") {
Solution s;
SECTION("Normal tests") {
REQUIRE(s.myAtoi("1") == 1);
REQUIRE(s.myAtoi("378") == 378);
REQUIRE(s.myAtoi("-239") == -239);
REQUIRE(s.myAtoi("+832") == 832);
}
SECTION("Boundary tests") {
REQUIRE(s.myAtoi("-2147483648") == -2147483648);
REQUIRE(s.myAtoi("-2147483649") == -2147483648);
REQUIRE(s.myAtoi("2147483647") == 2147483647);
REQUIRE(s.myAtoi("2147483648") == 2147483647);
}
SECTION("Format tests") {
REQUIRE(s.myAtoi("asdfasf") == 0);
REQUIRE(s.myAtoi("--124") == 0);
REQUIRE(s.myAtoi("++4") == 0);
REQUIRE(s.myAtoi(" +110?_+120__") == 110);
}
}
|
Change entity test to use fixtures |
#include "component.h"
#include "entity.h"
#include "gtest/gtest.h"
/*
class TestC : public aronnax::Component {
public:
void update(aronnax::Entity &entity, const uint32_t dt)
{
return;
}
std::string getType()
{
return "TestComponent";
}
};
class EntityTest : public testing::Test {
protected:
virtual void SetUp() {
}
// Declares the variables your tests want to use.
aronnax::Components cla_;
aronnax::Entity ea_;
};
*/
TEST(Entity, DefaultConstructor) {
const aronnax::Components cla_;
const aronnax::Entity ea_(cla_);
EXPECT_EQ(0, ea_.pos.x) << "Constructs with position as 0 by default";
EXPECT_EQ(0, ea_.pos.y);
EXPECT_EQ(0, ea_.box.x);
EXPECT_EQ(0, ea_.box.y);
EXPECT_EQ(0, ea_.v.x);
EXPECT_EQ(0, ea_.v.y);
}
|
#include "component.h"
#include "entity.h"
#include "gtest/gtest.h"
/*
class TestC : public aronnax::Component {
public:
void update(aronnax::Entity &entity, const uint32_t dt)
{
return;
}
std::string getType()
{
return "TestComponent";
}
};
*/
class EntityTest : public testing::Test {
protected:
virtual void SetUp() {
ea_ = new aronnax::Entity(cla_);
}
// Declares the variables your tests want to use.
aronnax::Components cla_;
aronnax::Entity* ea_;
};
TEST_F(EntityTest, DefaultConstructor) {
EXPECT_EQ(0, ea_->pos.x) << "Constructs with position as 0 by default";
EXPECT_EQ(0, ea_->pos.y);
EXPECT_EQ(0, ea_->box.x);
EXPECT_EQ(0, ea_->box.y);
EXPECT_EQ(0, ea_->v.x);
EXPECT_EQ(0, ea_->v.y);
}
|
Fix incorrect operator in OrderingInfo | #include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>
OrderingInfo::OrderingInfo(const TranspTable* tt) {
_tt = tt;
_ply = 0;
std::memset(_history, 0, sizeof(_history));
}
void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
_history[color][from][to] += depth^2;
}
int OrderingInfo::getHistory(Color color, int from, int to) const {
return _history[color][from][to];
}
void OrderingInfo::incrementPly() {
_ply++;
}
void OrderingInfo::deincrementPly() {
_ply--;
}
int OrderingInfo::getPly() const {
return _ply;
}
const TranspTable* OrderingInfo::getTt() const {
return _tt;
}
void OrderingInfo::updateKillers(int ply, Move move) {
_killer2[ply] = _killer1[ply];
_killer1[ply] = move;
}
Move OrderingInfo::getKiller1(int ply) const {
return _killer1[ply];
}
Move OrderingInfo::getKiller2(int ply) const {
return _killer2[ply];
} | #include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>
OrderingInfo::OrderingInfo(const TranspTable* tt) {
_tt = tt;
_ply = 0;
std::memset(_history, 0, sizeof(_history));
}
void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
_history[color][from][to] += depth*depth;
}
int OrderingInfo::getHistory(Color color, int from, int to) const {
return _history[color][from][to];
}
void OrderingInfo::incrementPly() {
_ply++;
}
void OrderingInfo::deincrementPly() {
_ply--;
}
int OrderingInfo::getPly() const {
return _ply;
}
const TranspTable* OrderingInfo::getTt() const {
return _tt;
}
void OrderingInfo::updateKillers(int ply, Move move) {
_killer2[ply] = _killer1[ply];
_killer1[ply] = move;
}
Move OrderingInfo::getKiller1(int ply) const {
return _killer1[ply];
}
Move OrderingInfo::getKiller2(int ply) const {
return _killer2[ply];
} |
Use proper base 64 encoding for the watermark | #include <utils/unique_alias.hpp>
#include <atomic>
#include <chrono>
#include <sstream>
static std::atomic<int> __counter(0);
utils::unique_alias::unique_alias()
{
std::ostringstream s;
s << "benchmarks-"
<< std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count()
<< "-" << __counter++ << "-000000";
_string = s.str();
}
void utils::unique_alias::set_watermark(unsigned long iteration)
{
size_t index = _string.size();
for (int digit = 0; digit < 6; digit++)
{
_string[--index] = '0' + (iteration & 63);
iteration /= 64;
}
}
| #include <utils/unique_alias.hpp>
#include <atomic>
#include <chrono>
#include <sstream>
static std::atomic<int> __counter(0);
static const char __base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
utils::unique_alias::unique_alias()
{
std::ostringstream s;
s << "benchmarks-"
<< std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count()
<< "-" << __counter++ << "-AAAAAA"; // reserve 6 chars for the watermark
_string = s.str();
}
void utils::unique_alias::set_watermark(unsigned long iteration)
{
size_t index = _string.size();
for (int digit = 0; digit < 6; digit++)
{
_string[--index] = __base64[iteration & 63];
iteration /= 64;
}
}
|
Add '<', '=', '>' as search delimeters. | #include "utf8_string.hpp"
#include "../std/iterator.hpp"
#include "../3party/utfcpp/source/utf8/unchecked.h"
namespace utf8_string
{
bool Split(string const & str, vector<string> & out, IsDelimiterFuncT f)
{
out.clear();
string::const_iterator curr = str.begin();
string::const_iterator end = str.end();
string word;
back_insert_iterator<string> inserter = back_inserter(word);
while (curr != end)
{
uint32_t symbol = ::utf8::unchecked::next(curr);
if (f(symbol))
{
if (!word.empty())
{
out.push_back(word);
word.clear();
inserter = back_inserter(word);
}
}
else
{
inserter = utf8::unchecked::append(symbol, inserter);
}
}
if (!word.empty())
out.push_back(word);
return !out.empty();
}
bool IsSearchDelimiter(uint32_t symbol)
{
// latin table optimization
if (symbol >= ' ' && symbol < '0')
return true;
switch (symbol)
{
case ':':
case ';':
case '[':
case ']':
case '\\':
case '^':
case '_':
case '`':
case '{':
case '}':
case '|':
case '~':
case 0x0336:
return true;
}
return false;
}
}
| #include "utf8_string.hpp"
#include "../std/iterator.hpp"
#include "../3party/utfcpp/source/utf8/unchecked.h"
namespace utf8_string
{
bool Split(string const & str, vector<string> & out, IsDelimiterFuncT f)
{
out.clear();
string::const_iterator curr = str.begin();
string::const_iterator end = str.end();
string word;
back_insert_iterator<string> inserter = back_inserter(word);
while (curr != end)
{
uint32_t symbol = ::utf8::unchecked::next(curr);
if (f(symbol))
{
if (!word.empty())
{
out.push_back(word);
word.clear();
inserter = back_inserter(word);
}
}
else
{
inserter = utf8::unchecked::append(symbol, inserter);
}
}
if (!word.empty())
out.push_back(word);
return !out.empty();
}
bool IsSearchDelimiter(uint32_t symbol)
{
// latin table optimization
if (symbol >= ' ' && symbol < '0')
return true;
switch (symbol)
{
case ':':
case ';':
case '<':
case '=':
case '>':
case '[':
case ']':
case '\\':
case '^':
case '_':
case '`':
case '{':
case '}':
case '|':
case '~':
case 0x0336:
return true;
}
return false;
}
}
|
Add a test case for operator * | // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/observable.h>
class ObservableTest:
public testing::Test
{};
TEST_F(ObservableTest, SimpleAssignmentCheck) {
autowiring::observable<int> ob;
bool hit = false;
ob.onChanged += [&hit] { hit = true; };
ob = 2;
ASSERT_TRUE(hit) << "OnChanged handler not hit when the observable value was modified";
}
TEST_F(ObservableTest, BeforeAndAfter) {
autowiring::observable<int> ob;
ob = 8;
bool hit = false;
ob.onChanged += [&hit] { hit = true; };
int obBefore = 0;
int obAfter = 0;
ob.onBeforeChanged += [&] (const int& before, const int& after) {
obBefore = before;
obAfter = after;
};
ob = 9;
ASSERT_TRUE(hit) << "Change notification not raised";
ASSERT_EQ(8, obBefore) << "\"Before\" value in onBeforeChanged was not correct";
ASSERT_EQ(9, obAfter) << "\"AfFter\" value in onBeforeChanged was not correct";
}
| // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/observable.h>
class ObservableTest:
public testing::Test
{};
TEST_F(ObservableTest, SimpleAssignmentCheck) {
autowiring::observable<int> ob;
bool hit = false;
ob.onChanged += [&hit] { hit = true; };
ob = 2;
ASSERT_TRUE(hit) << "OnChanged handler not hit when the observable value was modified";
ASSERT_EQ(2, *ob) << "operator * gives an incorrect value";
}
TEST_F(ObservableTest, BeforeAndAfter) {
autowiring::observable<int> ob;
ob = 8;
bool hit = false;
ob.onChanged += [&hit] { hit = true; };
int obBefore = 0;
int obAfter = 0;
ob.onBeforeChanged += [&] (const int& before, const int& after) {
obBefore = before;
obAfter = after;
};
ob = 9;
ASSERT_TRUE(hit) << "Change notification not raised";
ASSERT_EQ(8, obBefore) << "\"Before\" value in onBeforeChanged was not correct";
ASSERT_EQ(9, obAfter) << "\"AfFter\" value in onBeforeChanged was not correct";
}
|
Add some headers so we can use NanoVG to render NanoSVG. | #include "SVGImage.h"
#define NANOSVG_IMPLEMENTATION
#include <nanosvg.h>
SVGImage::SVGImage() : _nanoSvgImage(nullptr) {
}
SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() {
open(path);
}
SVGImage::~SVGImage() {
if (_nanoSvgImage) {
::nsvgDelete(_nanoSvgImage);
}
_nanoSvgImage = nullptr;
}
bool SVGImage::open(const boost::filesystem::path &path) {
_nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f);
return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes);
}
void SVGImage::draw() {
}
| #include "SVGImage.h"
#define NANOSVG_IMPLEMENTATION
#include <nanosvg.h>
#include <nanovg.h>
// XXX This is bad, but easy.
#define NANOVG_GL_IMPLEMENTATION
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2platform.h>
#include <nanovg_gl.h>
#include <nanovg.c>
SVGImage::SVGImage() : _nanoSvgImage(nullptr) {
}
SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() {
open(path);
}
SVGImage::~SVGImage() {
if (_nanoSvgImage) {
::nsvgDelete(_nanoSvgImage);
}
_nanoSvgImage = nullptr;
}
bool SVGImage::open(const boost::filesystem::path &path) {
_nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f);
return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes);
}
void SVGImage::draw() {
}
|
Remove bit field logic where not necessary |
#include <cppfs/FileEventHandler.h>
#include <cppfs/FileHandle.h>
namespace cppfs
{
FileEventHandler::FileEventHandler()
{
}
FileEventHandler::~FileEventHandler()
{
}
void FileEventHandler::onFileEvent(FileHandle & fh, FileEvent event)
{
if (event & FileCreated) {
onFileCreated(fh);
} else if (event & FileRemoved) {
onFileRemoved(fh);
} else if (event & FileModified) {
onFileModified(fh);
}
}
void FileEventHandler::onFileCreated(FileHandle &)
{
}
void FileEventHandler::onFileRemoved(FileHandle &)
{
}
void FileEventHandler::onFileModified(FileHandle &)
{
}
} // namespace cppfs
|
#include <cppfs/FileEventHandler.h>
#include <cppfs/FileHandle.h>
namespace cppfs
{
FileEventHandler::FileEventHandler()
{
}
FileEventHandler::~FileEventHandler()
{
}
void FileEventHandler::onFileEvent(FileHandle & fh, FileEvent event)
{
switch (event) {
case FileCreated:
onFileCreated(fh);
break;
case FileRemoved:
onFileRemoved(fh);
break;
case FileModified:
onFileModified(fh);
break;
default:
break;
}
}
void FileEventHandler::onFileCreated(FileHandle &)
{
}
void FileEventHandler::onFileRemoved(FileHandle &)
{
}
void FileEventHandler::onFileModified(FileHandle &)
{
}
} // namespace cppfs
|
Add example of creating BC for Laplaces eqn | #include "LinearEllipticPDE.hpp"
double f1(Point const & point) {
return point.x() * point.x();
}
double f2(Point const & point) {
return point.y() * point.y();
}
int main() {
// laplace
ConstTensor I(3, 0.);
I(0, 0) = I(1, 1) = I(2, 2) = 1.;
LinearEllipticPDE LaplacesEquation3D(I, 0., zeroFunc);
std::cout << "div(D grad u) = f, D:" << '\n';
LaplacesEquation3D.diffusionTensor().save(std::cout);
std::cout << "f(0, 0, 0): " << LaplacesEquation3D.forceTerm(Point()) << std::endl;
// my problem example
Tensor D(2);
//D.load(std::cin);
D(0, 0) = f1;
D(1, 1) = f2;
D(0, 1) = zeroFunc;
NonLinearEllipticPDE MyEqn2D(D, f1, zeroFunc);
Point dummy(1., 2.);
std::cout << "Coeff of u_{xx}, u_{yy} etc. at (1, 2):" << '\n';
MyEqn2D.diffusionTensor(dummy).save(std::cout);
std::cout << "gamma(1, 2): " << MyEqn2D.gamma(dummy) << '\n'
<< "f(1, 2): " << MyEqn2D.forceTerm(dummy) << std::endl;
return 0;
} | #include "LinearEllipticPDE.hpp"
#include "BC.hpp"
double g(Point const & point) { // u = g on Г
return point.x() * point.y();
}
int main() {
// Laplace's eqn on the plane
ConstTensor I(2, 0.);
I(0, 0) = I(1, 1) = 1.;
LinearEllipticPDE LaplacesEquation2D(I, 0., zeroFunc);
BC myBC(g); // simple Dirichlet problem
std::cout << "u(2, 3) = " << myBC.dirichlet(Point(2., 3.)) << std::endl;
return 0;
} |
Fix wrong animation of boss arm | #include "level.hpp"
using namespace engine;
void Level::load(){
for(auto game_object : objects){
std::cout << "Loading " << game_object->name << std::endl;
game_object->load();
for(auto hit : game_object->get_hitboxes()){
hit->initialize();
}
}
}
void Level::free(){
for(auto game_object : objects){
std::cout << "Freeing" << game_object->name << std::endl;
game_object->free();
}
EventHandler::listeners.clear();
}
void Level::draw(){
for(auto game_object : objects){
if(game_object->is_active()){
game_object->draw();
}
}
}
| #include "level.hpp"
#include <iostream>
using namespace engine;
void Level::load(){
for(auto game_object : objects){
std::cout << "Loading " << game_object->name << std::endl;
game_object->load();
for(auto hit : game_object->get_hitboxes()){
hit->initialize();
}
}
}
void Level::free(){
for(auto game_object : objects){
std::cout << "Freeing" << game_object->name << std::endl;
game_object->free();
}
EventHandler::listeners.clear();
}
void Level::draw(){
for(auto game_object : objects){
if(game_object->is_active()){
if(game_object->name == "arm_left"){
game_object->set_actual_animation(game_object->animations["left_arm"]);
}
game_object->draw();
}
}
}
|
Add test scene with test scene system. | //
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//
#include "stdafx.h"
#include <Kioto.h>
#include <windows.h>
void OnEngineInited()
{
Kioto::Scene* scene = new Kioto::Scene();
Kioto::SetScene(scene);
OutputDebugStringA("init engine");
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int nCmdShow)
{
Kioto::KiotoMain(hInstance, prevInstance, cmdLine, nCmdShow, L"Kioto game", OnEngineInited);
return 0;
}
| //
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//
#include "stdafx.h"
#include <Kioto.h>
#include <windows.h>
class TestScene : public Kioto::Scene
{
public:
~TestScene()
{
}
};
class TestSceneSystem : public Kioto::SceneSystem
{
public:
void Update(float32 dt) override
{
}
~TestSceneSystem()
{
}
};
void OnEngineInited()
{
Kioto::Scene* scene = new TestScene();
scene->AddSystem(new TestSceneSystem{});
Kioto::SetScene(scene);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int nCmdShow)
{
Kioto::KiotoMain(hInstance, prevInstance, cmdLine, nCmdShow, L"Kioto game", OnEngineInited);
return 0;
}
|
Allow repeated input to reset frame counter | #include "InputHandler.h"
#include "SFML/Window.hpp"
#include "SFData.h"
Player::Direction InputHandler::LastInput;
int InputHandler::InputTime;
bool InputHandler::WindowClosed = false;
void InputHandler::PollEvents()
{
sf::Event event;
while (SFData::Window->pollEvent(event))
{
switch (event.type)
{
case sf::Event::KeyPressed:
Player::Direction newInput = -1;
switch (event.key.code)
{
case sf::Keyboard::W:
newInput = Player::Up;
break;
case sf::Keyboard::A:
newInput = Player::Left;
break;
case sf::Keyboard::S:
newInput = Player::Down;
break;
case sf::Keyboard::D:
newInput = Player::Right;
break;
default:
continue;
}
if (newInput != LastInput)
{
LastInput = newInput;
InputTime = -1;
}
break;
case sf::Event::Closed:
WindowClosed = true;
break;
}
}
InputTime++;
}
| #include "InputHandler.h"
#include "SFML/Window.hpp"
#include "SFData.h"
Player::Direction InputHandler::LastInput;
int InputHandler::InputTime;
bool InputHandler::WindowClosed = false;
void InputHandler::PollEvents()
{
sf::Event event;
while (SFData::Window->pollEvent(event))
{
switch (event.type)
{
case sf::Event::KeyPressed:
Player::Direction newInput = (Player::Direction)-1;
switch (event.key.code)
{
case sf::Keyboard::W:
newInput = Player::Up;
break;
case sf::Keyboard::A:
newInput = Player::Left;
break;
case sf::Keyboard::S:
newInput = Player::Down;
break;
case sf::Keyboard::D:
newInput = Player::Right;
break;
default:
continue;
}
LastInput = newInput;
InputTime = -1;
break;
case sf::Event::Closed:
WindowClosed = true;
break;
}
}
InputTime++;
}
|
Add missing initialization of ManagedThread::run_state_ | #include "vm/vm.hpp"
#include "util/thread.hpp"
#include "gc/managed.hpp"
#include "shared_state.hpp"
namespace rubinius {
thread::ThreadData<ManagedThread*> _current_thread;
ManagedThread::ManagedThread(uint32_t id, SharedState& ss, ManagedThread::Kind kind)
: shared_(ss)
, kind_(kind)
, name_(kind == eRuby ? "<ruby>" : "<system>")
, id_(id)
{}
ManagedThread* ManagedThread::current() {
return _current_thread.get();
}
void ManagedThread::set_current(ManagedThread* th) {
th->os_thread_ = pthread_self();
_current_thread.set(th);
}
}
| #include "vm/vm.hpp"
#include "util/thread.hpp"
#include "gc/managed.hpp"
#include "shared_state.hpp"
namespace rubinius {
thread::ThreadData<ManagedThread*> _current_thread;
ManagedThread::ManagedThread(uint32_t id, SharedState& ss, ManagedThread::Kind kind)
: shared_(ss)
, kind_(kind)
, name_(kind == eRuby ? "<ruby>" : "<system>")
, run_state_(eIndependent)
, id_(id)
{}
ManagedThread* ManagedThread::current() {
return _current_thread.get();
}
void ManagedThread::set_current(ManagedThread* th) {
th->os_thread_ = pthread_self();
_current_thread.set(th);
}
}
|
Work around a build error in a very hackish way. | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone/wayland/inputs/input_method_event_filter.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_factory.h"
namespace ozonewayland {
////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, public:
WaylandInputMethodEventFilter::WaylandInputMethodEventFilter()
: input_method_(ui::CreateInputMethod(this, NULL)) {
// TODO(yusukes): Check if the root window is currently focused and pass the
// result to Init().
input_method_->Init(true);
}
WaylandInputMethodEventFilter::~WaylandInputMethodEventFilter()
{
}
////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, ui::InputMethodDelegate implementation:
bool WaylandInputMethodEventFilter::DispatchKeyEventPostIME(
const base::NativeEvent& event)
{
}
bool WaylandInputMethodEventFilter::DispatchFabricatedKeyEventPostIME(
ui::EventType type,
ui::KeyboardCode key_code,
int flags)
{
}
} // namespace ozonewayland
| // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone/wayland/inputs/input_method_event_filter.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_factory.h"
namespace ozonewayland {
////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, public:
WaylandInputMethodEventFilter::WaylandInputMethodEventFilter()
: input_method_(ui::CreateInputMethod(this, 0)) {
// TODO(yusukes): Check if the root window is currently focused and pass the
// result to Init().
input_method_->Init(true);
}
WaylandInputMethodEventFilter::~WaylandInputMethodEventFilter()
{
}
////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, ui::InputMethodDelegate implementation:
bool WaylandInputMethodEventFilter::DispatchKeyEventPostIME(
const base::NativeEvent& event)
{
}
bool WaylandInputMethodEventFilter::DispatchFabricatedKeyEventPostIME(
ui::EventType type,
ui::KeyboardCode key_code,
int flags)
{
}
} // namespace ozonewayland
|
Make a full json buffer first | #include "../http/client-channel.hh"
#include "http-call.hh"
#include "json.hh"
namespace mimosa
{
namespace rpc
{
bool httpCall(const std::string &url,
const google::protobuf::Message &request,
google::protobuf::Message *response)
{
http::ClientChannel cc;
http::RequestWriter::Ptr rw = new http::RequestWriter(cc);
/* request header */
rw->setUrl(url);
rw->setMethod(http::kMethodPost);
rw->setProto(1, 1);
rw->setContentLength(request.ByteSize());
rw->setContentType("application/json");
if (!rw->sendRequest())
return false;
/* request body (JSON) */
jsonEncode(rw.get(), request);
/* decode response */
auto rr = rw->response();
if (!rr)
return false;
if (response)
jsonDecode(rr.get(), response);
return true;
}
}
}
| #include "../stream/string-stream.hh"
#include "../stream/copy.hh"
#include "../http/client-channel.hh"
#include "http-call.hh"
#include "json.hh"
namespace mimosa
{
namespace rpc
{
bool httpCall(const std::string &url,
const google::protobuf::Message &request,
google::protobuf::Message *response)
{
http::ClientChannel cc;
http::RequestWriter::Ptr rw = new http::RequestWriter(cc);
/* request body (JSON) */
stream::StringStream::Ptr data = new stream::StringStream;
jsonEncode(data.get(), request);
/* request header */
rw->setUrl(url);
rw->setMethod(http::kMethodPost);
rw->setProto(1, 1);
rw->setContentType("application/json");
rw->setContentLength(data->str().size());
if (!rw->sendRequest())
return false;
stream::copy(*data, *rw);
/* decode response */
auto rr = rw->response();
if (!rr)
return false;
if (response)
jsonDecode(rr.get(), response);
return true;
}
}
}
|
Add a RUN: line so this test doesn't fail. | // %llvmgcc %s -S -o -
namespace std {
class exception { };
class type_info {
public:
virtual ~type_info();
};
}
namespace __cxxabiv1 {
class __si_class_type_info : public std::type_info {
~__si_class_type_info();
};
}
class recursive_init: public std::exception {
public:
virtual ~recursive_init() throw ();
};
recursive_init::~recursive_init() throw() { }
| // RUN: %llvmgcc %s -S -o -
namespace std {
class exception { };
class type_info {
public:
virtual ~type_info();
};
}
namespace __cxxabiv1 {
class __si_class_type_info : public std::type_info {
~__si_class_type_info();
};
}
class recursive_init: public std::exception {
public:
virtual ~recursive_init() throw ();
};
recursive_init::~recursive_init() throw() { }
|
Make a test independent of the default check set. | // RUN: clang-tidy %s -- --serialize-diagnostics %t | FileCheck %s
// CHECK: :[[@LINE+1]]:12: error: expected ';' after struct [clang-diagnostic-error]
struct A {}
| // RUN: clang-tidy -checks=-*,llvm-namespace-comment %s -- -serialize-diagnostics %t | FileCheck %s
// CHECK: :[[@LINE+1]]:12: error: expected ';' after struct [clang-diagnostic-error]
struct A {}
|
Simplify this due to changes in the tblgen side | //===- AlphaSubtarget.cpp - Alpha Subtarget Information ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Andrew Lenharth and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Alpha specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "AlphaSubtarget.h"
#include "Alpha.h"
#include "llvm/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/SubtargetFeature.h"
#include "AlphaGenSubtarget.inc"
using namespace llvm;
enum {
FeatureKVSize = sizeof(FeatureKV) / sizeof(SubtargetFeatureKV),
SubTypeKVSize = sizeof(SubTypeKV) / sizeof(SubtargetFeatureKV)
};
AlphaSubtarget::AlphaSubtarget(const Module &M, const std::string &FS)
: HasF2I(false), HasCT(false) {
std::string CPU = "generic";
uint32_t Bits =
SubtargetFeatures::Parse(FS, CPU,
SubTypeKV, SubTypeKVSize,
FeatureKV, FeatureKVSize);
HasF2I = (Bits & FeatureFIX) != 0;
HasCT = (Bits & FeatureCIX) != 0;
}
| //===- AlphaSubtarget.cpp - Alpha Subtarget Information ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Andrew Lenharth and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Alpha specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "AlphaSubtarget.h"
#include "Alpha.h"
#include "AlphaGenSubtarget.inc"
using namespace llvm;
AlphaSubtarget::AlphaSubtarget(const Module &M, const std::string &FS)
: HasF2I(false), HasCT(false) {
std::string CPU = "generic";
uint32_t Bits =
SubtargetFeatures::Parse(FS, CPU,
SubTypeKV, SubTypeKVSize,
FeatureKV, FeatureKVSize);
HasF2I = (Bits & FeatureFIX) != 0;
HasCT = (Bits & FeatureCIX) != 0;
}
|
Update libraries to reflect screen hardware change | #include "lcd.h"
#include <TFT.h> // Arduino LCD library
// pin definition for LCD
#define LCD_CS 10
#define LCD_DC 9
#define LCD_RST 8
namespace LCD {
TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST);
void setup() {
// initialize the display
TFTscreen.begin();
// clear the screen with a black background
TFTscreen.background(0, 0, 0);
// set the font color to white
TFTscreen.stroke(255, 255, 255);
}
void clearScreen() {
// clear the screen to show refreshed data
TFTscreen.background(0, 0, 0);
}
void displayTemp(int tempInt) {
char tempChar[6];
snprintf(tempChar, sizeof tempChar, "%d", tempInt);
// print temp text
TFTscreen.text(tempChar, 0, 20);
}
}
| #include "display.h"
#include "sensor.h"
#include <LiquidCrystal.h> // Arduino LCD library
#include <Arduino.h> // enables use of byte pics
// pin definition for LCD
#define LCD_CS 10
#define LCD_DC 9
#define LCD_RST 8
namespace LCD {
TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST);
void setup() {
// initialize the display
TFTscreen.begin();
// clear the screen with a black background
TFTscreen.background(0, 0, 0);
// set the font color to white
TFTscreen.stroke(255, 255, 255);
}
void clearScreen() {
// clear the screen to show refreshed data
TFTscreen.background(0, 0, 0);
}
void displayTemp(int tempInt) {
char tempChar[6];
snprintf(tempChar, sizeof tempChar, "%d", tempInt);
// print temp text
TFTscreen.text(tempChar, 0, 20);
}
}
|
Allow connections from the same user to DevTools server socket | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/browser/android/devtools_auth.h"
#include "base/logging.h"
namespace content {
bool CanUserConnectToDevTools(uid_t uid, gid_t gid) {
struct passwd* creds = getpwuid(uid);
if (!creds || !creds->pw_name) {
LOG(WARNING) << "DevTools: can't obtain creds for uid " << uid;
return false;
}
if (gid == uid &&
(strcmp("root", creds->pw_name) == 0 || // For rooted devices
strcmp("shell", creds->pw_name) == 0)) { // For non-rooted devices
return true;
}
LOG(WARNING) << "DevTools: connection attempt from " << creds->pw_name;
return false;
}
} // namespace content
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/browser/android/devtools_auth.h"
#include <unistd.h>
#include <sys/types.h>
#include "base/logging.h"
namespace content {
bool CanUserConnectToDevTools(uid_t uid, gid_t gid) {
struct passwd* creds = getpwuid(uid);
if (!creds || !creds->pw_name) {
LOG(WARNING) << "DevTools: can't obtain creds for uid " << uid;
return false;
}
if (gid == uid &&
(strcmp("root", creds->pw_name) == 0 || // For rooted devices
strcmp("shell", creds->pw_name) == 0 || // For non-rooted devices
uid == getuid())) { // From processes signed with the same key
return true;
}
LOG(WARNING) << "DevTools: connection attempt from " << creds->pw_name;
return false;
}
} // namespace content
|
Fix compilation error in HDD's unittest | #include "../src/utility.h"
#include "../src/HDD/HardDrive.h"
void unittest(){
const size_t emptyOff = 0x80120;
HDD first(1,true);
first.init();
int data[1000];
for(int i = 0 ; i < 1000 ; ++i){
data[i] = i;
}
first.writeaddr(emptyOff,&data,4*1000);
int res;
first.readaddr(emptyOff + 4 *42,&res,4);
printf("%d\n",res);
first.readaddr(emptyOff + 4 *999,&res,4);
printf("%d\n",res);
res = 45;
first.writeaddr(emptyOff + 4 *537,&res,4);
first.readaddr(emptyOff + 4 *753,&res,4);
printf("%d\n",res);
first.readaddr(emptyOff + 4 *537,&res,4);
printf("%d\n",res);
}
| #include "../src/utility.h"
#include "../src/HDD/HardDrive.h"
void unittest(){
const size_t emptyOff = 0x80120;
HDD::HDD first(1,true);
first.init();
int data[1000];
for(int i = 0 ; i < 1000 ; ++i){
data[i] = i;
}
first.writeaddr(emptyOff,&data,4*1000);
int res;
first.readaddr(emptyOff + 4 *42,&res,4);
printf("%d\n",res);
first.readaddr(emptyOff + 4 *999,&res,4);
printf("%d\n",res);
res = 45;
first.writeaddr(emptyOff + 4 *537,&res,4);
first.readaddr(emptyOff + 4 *753,&res,4);
printf("%d\n",res);
first.readaddr(emptyOff + 4 *537,&res,4);
printf("%d\n",res);
}
|
Disable test that is failing on linux trybots. | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/test/base/ui_test_utils.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
ExtensionPointerLockAccessFail) {
// Test that pointer lock cannot be accessed from an extension without
// permission.
ASSERT_TRUE(RunPlatformAppTest("pointer_lock/no_permission")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
ExtensionPointerLockAccessPass) {
// Test that pointer lock can be accessed from an extension with permission.
ASSERT_TRUE(RunPlatformAppTest("pointer_lock/has_permission")) << message_;
}
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/test/base/ui_test_utils.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
ExtensionPointerLockAccessFail) {
// Test that pointer lock cannot be accessed from an extension without
// permission.
ASSERT_TRUE(RunPlatformAppTest("pointer_lock/no_permission")) << message_;
}
// http://crbug.com/223447
#if defined(OS_LINUX)
#define MAYBE_ExtensionPointerLockAccessPass \
DISABLED_ExtensionPointerLockAccessPass
#else
#define MAYBE_ExtensionPointerLockAccessPass ExtensionPointerLockAccessPass
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
MAYBE_ExtensionPointerLockAccessPass) {
// Test that pointer lock can be accessed from an extension with permission.
ASSERT_TRUE(RunPlatformAppTest("pointer_lock/has_permission")) << message_;
}
|
Add fileExists and fileSize expression functions | #include "stdafx.h"
#include "ExpressionFunctions.h"
#include "Misc.h"
#include "Common.h"
ExpressionValue expressionFunctionEndianness(const std::vector<ExpressionValue>& parameters)
{
Endianness endianness = g_fileManager->getEndianness();
ExpressionValue result;
result.type = ExpressionValueType::String;
switch (endianness)
{
case Endianness::Little:
result.strValue = L"little";
break;
case Endianness::Big:
result.strValue = L"big";
break;
}
return result;
}
const ExpressionFunctionMap expressionFunctions = {
{ L"endianness", { &expressionFunctionEndianness, 0, 0 } },
};
| #include "stdafx.h"
#include "ExpressionFunctions.h"
#include "Misc.h"
#include "Common.h"
ExpressionValue expFuncEndianness(const std::vector<ExpressionValue>& parameters)
{
Endianness endianness = g_fileManager->getEndianness();
ExpressionValue result;
result.type = ExpressionValueType::String;
switch (endianness)
{
case Endianness::Little:
result.strValue = L"little";
break;
case Endianness::Big:
result.strValue = L"big";
break;
}
return result;
}
ExpressionValue expFuncFileExists(const std::vector<ExpressionValue>& parameters)
{
ExpressionValue result;
if (parameters[0].isString() == false)
{
Logger::queueError(Logger::Error,L"Invalid parameter");
return result;
}
std::wstring fileName = getFullPathName(parameters[0].strValue);
result.type = ExpressionValueType::Integer;
result.intValue = fileExists(fileName) ? 1 : 0;
return result;
}
ExpressionValue expFuncFileSize(const std::vector<ExpressionValue>& parameters)
{
ExpressionValue result;
if (parameters[0].isString() == false)
{
Logger::queueError(Logger::Error,L"Invalid parameter");
return result;
}
std::wstring fileName = getFullPathName(parameters[0].strValue);
result.type = ExpressionValueType::Integer;
result.intValue = fileSize(fileName);
return result;
}
const ExpressionFunctionMap expressionFunctions = {
{ L"endianness", { &expFuncEndianness, 0, 0 } },
{ L"fileexists", { &expFuncFileExists, 1, 1 } },
{ L"filesize", { &expFuncFileSize, 1, 1 } },
};
|
Fix gl error debug print. |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLConfig.h"
#include "GrGLInterface.h"
void GrGLClearErr(const GrGLInterface* gl) {
while (GR_GL_NO_ERROR != gl->fGetError()) {}
}
void GrGLCheckErr(const GrGLInterface* gl,
const char* location,
const char* call) {
uint32_t err = GR_GL_GET_ERROR(gl);
if (GR_GL_NO_ERROR != err) {
GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl));
if (NULL != location) {
GrPrintf(" at\n\t%s", location);
}
if (NULL != call) {
GrPrintf("\n\t\t%s", call);
}
GrPrintf("\n");
}
}
void GrGLResetRowLength(const GrGLInterface* gl) {
if (gl->supportsDesktop()) {
GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
}
}
///////////////////////////////////////////////////////////////////////////////
#if GR_GL_LOG_CALLS
bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif
#if GR_GL_CHECK_ERROR
bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLConfig.h"
#include "GrGLInterface.h"
void GrGLClearErr(const GrGLInterface* gl) {
while (GR_GL_NO_ERROR != gl->fGetError()) {}
}
void GrGLCheckErr(const GrGLInterface* gl,
const char* location,
const char* call) {
uint32_t err = GR_GL_GET_ERROR(gl);
if (GR_GL_NO_ERROR != err) {
GrPrintf("---- glGetError %x", err);
if (NULL != location) {
GrPrintf(" at\n\t%s", location);
}
if (NULL != call) {
GrPrintf("\n\t\t%s", call);
}
GrPrintf("\n");
}
}
void GrGLResetRowLength(const GrGLInterface* gl) {
if (gl->supportsDesktop()) {
GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
}
}
///////////////////////////////////////////////////////////////////////////////
#if GR_GL_LOG_CALLS
bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif
#if GR_GL_CHECK_ERROR
bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif
|
Disable some shared lock tests | #include <Pith/Config.hpp>
#include <Pith/LockGuard.hpp>
#include <Pith/SharedLock.hpp>
#include <gtest/gtest.h>
using namespace Pith;
TEST(SharedLock, multipleShared) {
SharedLock lock;
SharedLockGuard<SharedLock> shared1(lock);
EXPECT_TRUE(trySharedLock(lock));
}
TEST(SharedLock, failToTakeExclusive) {
SharedLock lock;
SharedLockGuard<SharedLock> shared(lock);
EXPECT_FALSE(tryExclusiveLock(lock));
}
TEST(SharedLock, exclusiveThenShared) {
SharedLock lock;
{
ExclusiveLockGuard<SharedLock> exclusive(lock);
EXPECT_TRUE(lock.isLocked<Access::EXCLUSIVE>());
}
EXPECT_FALSE(lock.isLocked<Access::EXCLUSIVE>());
{
SharedLockGuard<SharedLock> shared(lock);
EXPECT_TRUE(lock.isLocked<Access::SHARED>());
}
EXPECT_FALSE(lock.isLocked<Access::SHARED>());
} | #include <Pith/Config.hpp>
#include <Pith/LockGuard.hpp>
#include <Pith/SharedLock.hpp>
#include <gtest/gtest.h>
using namespace Pith;
TEST(SharedLock, multipleShared) {
SharedLock lock;
SharedLockGuard<SharedLock> shared1(lock);
EXPECT_TRUE(trySharedLock(lock));
}
TEST(SharedLock, DISABLED_failToTakeExclusive) {
SharedLock lock;
SharedLockGuard<SharedLock> shared(lock);
EXPECT_FALSE(tryExclusiveLock(lock));
}
TEST(SharedLock, DISABLED_exclusiveThenShared) {
SharedLock lock;
{
ExclusiveLockGuard<SharedLock> exclusive(lock);
EXPECT_TRUE(lock.isLocked<Access::EXCLUSIVE>());
}
EXPECT_FALSE(lock.isLocked<Access::EXCLUSIVE>());
{
SharedLockGuard<SharedLock> shared(lock);
EXPECT_TRUE(lock.isLocked<Access::SHARED>());
}
EXPECT_FALSE(lock.isLocked<Access::SHARED>());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.