conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
=======
[HttpGet]
[Route("{id:guid}", Name = nameof(GetProduct))]
public ActionResult<Product> GetProduct(Guid id)
{
return ProductStub().FirstOrDefault(x => x.Id == id);
}
private IEnumerable<Product> ProductStub()
{
return new List<Product>
{
new Product
{
Id = Guid.NewGuid(),
Name = "Product 1",
Desc = "This is a product 1",
Price = 100.54,
Rating = new Rating
{
Id = Guid.NewGuid(),
Rate = 4.5,
Count = 100
}
},
new Product
{
Id = Guid.NewGuid(),
Name = "Product 2",
Desc = "This is a product 2",
Price = 120.30,
Rating = new Rating
{
Id = Guid.NewGuid(),
Rate = 3,
Count = 20
}
},
new Product
{
Id = Guid.NewGuid(),
Name = "Product 3",
Desc = "This is a product 3",
Price = 2.30,
Rating = new Rating
{
Id = Guid.NewGuid(),
Rate = 3,
Count = 20
}
}
};
}
private List<LinkItem> CreateLinksForCollection(Criterion criterion, int totalCount)
{
var links = new List<LinkItem>();
// self
links.Add(
new LinkItem(_urlHelper.Link(nameof(GetAllProducts), new
{
pagecount = criterion.PageSize,
page = criterion.CurrentPage,
orderby = criterion.SortBy
}), "self", "GET"));
links.Add(new LinkItem(_urlHelper.Link(nameof(GetAllProducts), new
{
pagecount = criterion.PageSize,
page = 1,
orderby = criterion.SortBy
}), "first", "GET"));
links.Add(new LinkItem(_urlHelper.Link(nameof(GetAllProducts), new
{
pagecount = criterion.PageSize,
page = criterion.GetTotalPages(totalCount),
orderby = criterion.SortBy
}), "last", "GET"));
if (criterion.HasNext(totalCount))
{
links.Add(new LinkItem(_urlHelper.Link(nameof(GetAllProducts), new
{
pagecount = criterion.PageSize,
page = criterion.CurrentPage + 1,
orderby = criterion.SortBy
}), "next", "GET"));
}
if (criterion.HasPrevious())
{
links.Add(new LinkItem(_urlHelper.Link(nameof(GetAllProducts), new
{
pagecount = criterion.PageSize,
page = criterion.CurrentPage - 1,
orderby = criterion.SortBy
}), "previous", "GET"));
}
return links;
}
private dynamic ExpandSingleFoodItem(Product item)
{
var links = GetLinks(item.Id);
var resourceToReturn = item.ToDynamic() as IDictionary<string, object>;
resourceToReturn.Add("links", links);
return resourceToReturn;
}
private IEnumerable<LinkItem> GetLinks(Guid id)
{
var links = new List<LinkItem>();
links.Add(
new LinkItem(_urlHelper.Link(nameof(GetProduct), new { id }),
"self",
"GET"));
return links;
}
}
>>>>>>> |
<<<<<<<
//TODO: probably completely remove
public static string TrimGraphQLTypes(this string name)
{
return _trimPattern.Replace(name, string.Empty).Trim();
}
=======
/// <summary>
/// Removes brackets and exclamation points from a GraphQL type name -- for example,
/// converts <c>[Int!]</c> to <c>Int</c>
/// </summary>
public static string TrimGraphQLTypes(this string name) => name.Trim().Trim(_bangs);
>>>>>>>
/// <summary>
/// Removes brackets and exclamation points from a GraphQL type name -- for example,
/// converts <c>[Int!]</c> to <c>Int</c>
/// </summary>
public static string TrimGraphQLTypes(this string name) => name.Trim().Trim(_bangs);
<<<<<<<
private static readonly string[] _foundNull = new[] { "Expected non-null value, found null" };
public static string[] IsValidLiteralValue(this IGraphType type, IValue valueAst, ISchema schema)
=======
/// <summary>
/// Validates that the specified AST value is valid for the specified scalar or input graph type.
/// Graph types that are lists or non-null types are handled appropriately by this method.
/// Returns a list of strings representing the errors encountered while validating the value.
/// </summary>
public static IEnumerable<string> IsValidLiteralValue(this IGraphType type, IValue valueAst, ISchema schema)
>>>>>>>
private static readonly string[] _foundNull = new[] { "Expected non-null value, found null" };
/// <summary>
/// Validates that the specified AST value is valid for the specified scalar or input graph type.
/// Graph types that are lists or non-null types are handled appropriately by this method.
/// Returns a list of strings representing the errors encountered while validating the value.
/// </summary>
public static string[] IsValidLiteralValue(this IGraphType type, IValue valueAst, ISchema schema) |
<<<<<<<
private static readonly Type[] _typedContainers = { typeof(IEnumerable<>), typeof(List<>), typeof(IList<>), typeof(ICollection<>), typeof(IReadOnlyCollection<>) };
=======
private static readonly Type[] _typedContainers = new [] { typeof(IEnumerable<>), typeof(List<>), typeof(IList<>), typeof(ICollection<>), typeof(IReadOnlyCollection<>) };
/// <summary>
/// Returns whether or not the given <paramref name="type"/> implements <paramref name="genericType"/>
/// by testing itself, and then recursively up it's base types hierarchy.
/// </summary>
/// <param name="type">Type to test.</param>
/// <param name="genericType">Type to test for.</param>
/// <returns>
/// <c>true</c> if the indicated type implements <paramref name="genericType"/>; otherwise, <c>false</c>.
/// </returns>
public static bool ImplementsGenericType(this Type type, Type genericType)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
{
return true;
}
var interfaceTypes = type.GetInterfaces();
foreach (var it in interfaceTypes)
{
if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)
{
return true;
}
}
var baseType = type.BaseType;
return baseType == null ? false : ImplementsGenericType(baseType, genericType);
}
>>>>>>>
private static readonly Type[] _typedContainers = { typeof(IEnumerable<>), typeof(List<>), typeof(IList<>), typeof(ICollection<>), typeof(IReadOnlyCollection<>) };
/// <summary>
/// Returns whether or not the given <paramref name="type"/> implements <paramref name="genericType"/>
/// by testing itself, and then recursively up it's base types hierarchy.
/// </summary>
/// <param name="type">Type to test.</param>
/// <param name="genericType">Type to test for.</param>
/// <returns>
/// <c>true</c> if the indicated type implements <paramref name="genericType"/>; otherwise, <c>false</c>.
/// </returns>
public static bool ImplementsGenericType(this Type type, Type genericType)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
{
return true;
}
var interfaceTypes = type.GetInterfaces();
foreach (var it in interfaceTypes)
{
if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)
{
return true;
}
}
var baseType = type.BaseType;
return baseType == null ? false : ImplementsGenericType(baseType, genericType);
} |
<<<<<<<
=======
/// <inheritdoc/>
public override string CollectTypes(TypeCollectionContext context)
{
var innerType = context.ResolveType(Type);
ResolvedType = innerType;
var name = innerType.CollectTypes(context);
context.AddType(name, innerType, context);
return $"{name}!";
}
/// <inheritdoc/>
>>>>>>>
/// <inheritdoc/> |
<<<<<<<
=======
[Obsolete]
public Func<string> AnonOperationNotAloneMessage => () =>
"This anonymous operation must be the only defined operation.";
/// <summary>
/// Returns a static instance of this validation rule.
/// </summary>
>>>>>>>
/// <summary>
/// Returns a static instance of this validation rule.
/// </summary> |
<<<<<<<
public string Symbol { get; set; }
public decimal Bid { get; set; }
public decimal Ask { get; set; }
public decimal Mid { get; set; }
public DateTime ValueDate { get; set; }
public long CreationTimestamp { get; set; }
=======
[ProtoMember(1)]
public string symbol { get; set; }
[ProtoMember(2)]
public decimal bid { get; set; }
[ProtoMember(3)]
public decimal ask { get; set; }
[ProtoMember(4)]
public decimal mid { get; set; }
[ProtoMember(5)]
public DateTime valueDate { get; set; }
[ProtoMember(6)]
public long creationTimestamp { get; set; }
>>>>>>>
[ProtoMember(1)]
public string Symbol { get; set; }
[ProtoMember(2)]
public decimal Bid { get; set; }
[ProtoMember(3)]
public decimal Ask { get; set; }
[ProtoMember(4)]
public decimal Mid { get; set; }
[ProtoMember(5)]
public DateTime ValueDate { get; set; }
[ProtoMember(6)]
public long CreationTimestamp { get; set; } |
<<<<<<<
InitializeFactories();
var uri = "ws://127.0.0.1:8080/ws";
var realm = "com.weareadaptive.reactivetrader";
=======
>>>>>>>
InitializeFactories();
<<<<<<<
_eventStoreConnection = GetEventStoreConnection(args.Contains("es"), args.Contains("init-es")).Result;
_conn = BrokerConnectionFactory.Create(uri, realm);
=======
var eventStoreConnection = GetEventStoreConnection(config.EventStore, args.Contains("es"), args.Contains("init-es")).Result;
>>>>>>>
// We should only be using the launcher during development, so hard code this to use the dev config
var config = ServiceConfiguration.FromArgs(args);
_eventStoreConnection = GetEventStoreConnection(config.EventStore, args.Contains("es"), args.Contains("init-es")).Result;
_conn = BrokerConnectionFactory.Create(config.Broker);
<<<<<<<
=======
var broker = BrokerFactory.Create(config.Broker);
>>>>>>>
<<<<<<<
ReferenceDataHelper.PopulateRefData(eventStore.Connection).Wait();
=======
ReferenceDataWriterLauncher.PopulateRefData(eventStoreConnection).Wait();
>>>>>>>
ReferenceDataHelper.PopulateRefData(eventStoreConnection).Wait(); |
<<<<<<<
using Adaptive.ReactiveTrader.EventStore;
=======
using EventStore.ClientAPI;
using System;
using System.Net;
>>>>>>>
using Adaptive.ReactiveTrader.EventStore;
using EventStore.ClientAPI;
using System;
using System.Net;
<<<<<<<
var memoryEventStore = new NetworkEventStore();
ReferenceDataWriterLauncher.Run(memoryEventStore).RunSynchronously();
=======
var connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113));
connection.ConnectAsync().Wait();
var repository = new CurrencyPairRepository(connection);
if (args.Length > 0)
{
switch (args[0])
{
case "populate":
Console.WriteLine("Populating Event Store...");
new CurrencyPairInitializer(repository).WriteInitialEventsAsync().Wait();
Console.WriteLine("Completed");
break;
case "modify":
Console.WriteLine("Press a key to deactivate GBPJPY");
Console.ReadKey();
repository.Deactivate("GBPJPY");
Console.WriteLine("Press a key to activate it again");
Console.ReadKey();
repository.Activate("GBPJPY");
break;
}
}
Console.WriteLine("Press a key to exit");
Console.ReadKey();
>>>>>>>
var eventStore = new NetworkEventStore();
var repository = new CurrencyPairRepository(eventStore);
if (args.Length > 0)
{
switch (args[0])
{
case "populate":
Console.WriteLine("Populating Event Store...");
new CurrencyPairInitializer(repository).WriteInitialEventsAsync().Wait();
Console.WriteLine("Completed");
break;
case "modify":
Console.WriteLine("Press a key to deactivate GBPJPY");
Console.ReadKey();
repository.Deactivate("GBPJPY");
Console.WriteLine("Press a key to activate it again");
Console.ReadKey();
repository.Activate("GBPJPY");
break;
}
}
Console.WriteLine("Press a key to exit");
Console.ReadKey(); |
<<<<<<<
}, 2, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
<<<<<<<
}, 1, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
}, 1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
}, 1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
<<<<<<<
var results = new[] { new EagerTensor() };
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
"Fill", name, new IntPtr[]
{
dims as EagerTensor,
value as EagerTensor
}, 2, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
var results = EagerTensorPass.Create();
var inputs = EagerTensorPass.From(dims, value);
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
"Fill", name,
inputs.Points, inputs.Length,
null, null,
results.Points, results.Length);
>>>>>>>
var results = EagerTensorPass.Create();
var inputs = EagerTensorPass.From(dims, value);
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
"Fill", name,
inputs.Points, inputs.Length,
null, null,
results.Points, results.Length));
<<<<<<<
}, 2, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
<<<<<<<
}, 2, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
<<<<<<<
}, 2, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
}, 2,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
<<<<<<<
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
=======
var attrs = new object[]
{
"begin_mask", begin_mask,
"end_mask", end_mask,
"ellipsis_mask", ellipsis_mask,
"new_axis_mask", new_axis_mask,
"shrink_axis_mask", shrink_axis_mask
};
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
>>>>>>>
var attrs = new object[]
{
"begin_mask", begin_mask,
"end_mask", end_mask,
"ellipsis_mask", ellipsis_mask,
"new_axis_mask", new_axis_mask,
"shrink_axis_mask", shrink_axis_mask
};
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
<<<<<<<
op => wrap_tfe_src.SetOpAttrs(op,
"begin_mask", begin_mask,
"end_mask", end_mask,
"ellipsis_mask", ellipsis_mask,
"new_axis_mask", new_axis_mask,
"shrink_axis_mask", shrink_axis_mask),
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
wrap_tfe_src.SetOpAttrs2(attrs),
op => wrap_tfe_src.SetOpAttrs(op, attrs),
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
wrap_tfe_src.SetOpAttrs2(attrs),
op => wrap_tfe_src.SetOpAttrs(op, attrs),
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length)); |
<<<<<<<
switch (type.Name)
{
case "Single":
nd.SetData(values.Select(x => (float)x).ToArray());
break;
case "NDArray":
// nd.SetData<NDArray>(values.ToArray());
//NDArray[] arr = new NDArray[values.Count];
//for (int i=0; i<values.Count; i++)
NDArray[] arr = values.Select(x => (NDArray)x).ToArray();
nd = new NDArray(arr);
break;
default:
break;
}
=======
nd.SetData(values.ToArray());
>>>>>>>
switch (type.Name)
{
case "Single":
nd.SetData(values.Select(x => (float)x).ToArray());
break;
case "NDArray":
NDArray[] arr = values.Select(x => (NDArray)x).ToArray();
nd = new NDArray(arr);
break;
default:
break;
} |
<<<<<<<
}, 1, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
}, 1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
}, 1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
<<<<<<<
}, 1, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
}, 1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
}, 1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length)); |
<<<<<<<
var results = new[] { new EagerTensor() };
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
=======
var results = EagerTensorPass.Create();
var inputs = EagerTensorPass.From(resource, value);
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
>>>>>>>
var results = EagerTensorPass.Create();
var inputs = EagerTensorPass.From(resource, value);
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
<<<<<<<
new IntPtr[]
{
resource as EagerTensor,
value as EagerTensor
}, 2, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
inputs.Points, inputs.Length,
null, null,
results.Points, results.Length);
>>>>>>>
inputs.Points, inputs.Length,
null, null,
results.Points, results.Length));
<<<<<<<
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
=======
var inputs = EagerTensorPass.From(resource, value);
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
>>>>>>>
var inputs = EagerTensorPass.From(resource, value);
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
<<<<<<<
new IntPtr[]
{
resource as EagerTensor,
value as EagerTensor
}, 2, null,
null, 0));
=======
inputs.Points, inputs.Length,
null, null,
null, 0);
>>>>>>>
inputs.Points, inputs.Length,
null, null,
null, 0));
<<<<<<<
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
=======
var inputs = EagerTensorPass.From(resource, value);
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
>>>>>>>
var inputs = EagerTensorPass.From(resource, value);
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
<<<<<<<
new IntPtr[]
{
resource as EagerTensor,
value as EagerTensor
}, 2, null,
null, 0));
=======
inputs.Points, inputs.Length,
null, null,
null, 0);
>>>>>>>
inputs.Points, inputs.Length,
null, null,
null, 0));
<<<<<<<
1, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
>>>>>>>
1,
null, null,
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
<<<<<<<
var results = new[] { new EagerTensor() };
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
=======
var results = EagerTensorPass.Create();
var attrs = new object[]
{
"container", container,
"shared_name", shared_name,
"dtype", dtype,
"shape", shape.dims
};
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
>>>>>>>
var results = EagerTensorPass.Create();
var attrs = new object[]
{
"container", container,
"shared_name", shared_name,
"dtype", dtype,
"shape", shape.dims
};
using Status status = new Status(c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
<<<<<<<
op => wrap_tfe_src.SetOpAttrs(op,
"container", container,
"shared_name", shared_name,
"dtype", dtype,
"shape", shape.dims),
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length));
=======
wrap_tfe_src.SetOpAttrs2(attrs),
op => wrap_tfe_src.SetOpAttrs(op, attrs),
results.Points, results.Length);
>>>>>>>
wrap_tfe_src.SetOpAttrs2(attrs),
op => wrap_tfe_src.SetOpAttrs(op, attrs),
results.Points, results.Length)); |
<<<<<<<
/// Returns expression builder for rule's dependencies.
/// </summary>
/// <returns>Dependencies expression builder.</returns>
protected IDependencyExpression Dependency()
{
return new DependencyExpression(_builder);
}
/// <summary>
=======
/// Sets rule's priority.
/// Priority value set at this level overrides the value specified via <see cref="PriorityAttribute"/> attribute.
/// </summary>
/// <param name="value">Priority value.</param>
protected void Priority(int value)
{
_builder.Priority(value);
}
/// <summary>
>>>>>>>
/// Returns expression builder for rule's dependencies.
/// </summary>
/// <returns>Dependencies expression builder.</returns>
protected IDependencyExpression Dependency()
{
return new DependencyExpression(_builder);
}
/// <summary>
/// Sets rule's priority.
/// Priority value set at this level overrides the value specified via <see cref="PriorityAttribute"/> attribute.
/// </summary>
/// <param name="value">Priority value.</param>
protected void Priority(int value)
{
_builder.Priority(value);
}
/// <summary> |
<<<<<<<
const string streamId = "stream";
var events = new[]
{
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\""),
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\"")
};
await eventStore.AppendToStream(streamId, ExpectedVersion.NoStream, events);
=======
const string streamId = "stream";
await eventStore.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamEvents(1));
await eventStore.DeleteStream(streamId);
>>>>>>>
const string streamId = "stream";
await eventStore.AppendToStream(streamId, ExpectedVersion.NoStream, CreateNewStreamEvents(1));
await eventStore.DeleteStream(streamId);
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\""),
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\"")
};
await eventStore.AppendToStream(streamId, ExpectedVersion.NoStream, events);
<<<<<<<
const string streamId = "stream";
var events = new[]
{
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\""),
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\"")
};
await eventStore.AppendToStream(streamId, ExpectedVersion.NoStream, events);
=======
const string streamId = "notexist";
const int expectedVersion = 1;
>>>>>>>
const string streamId = "notexist";
const int expectedVersion = 1;
const string streamId = "stream";
var events = new[]
{
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\""),
new NewStreamEvent(Guid.NewGuid(), "type", "\"data\"", "\"headers\"")
};
await eventStore.AppendToStream(streamId, ExpectedVersion.NoStream, events); |
<<<<<<<
Nodes = pathmapClass.Nodes.Get()[pathmapObject];
Segments = pathmapClass.Segments.Get()[pathmapObject];
Attributes = pathmapClass.Attributes.Get()[pathmapObject];
=======
// Set nodes and segments.
Nodes = pathmapClass.Nodes.Get()[pathmapObject];
Segments = pathmapClass.Segments.Get()[pathmapObject];
// Get the resolve info component.
resolveInfo = actionSet.Translate.DeltinScript.GetComponent<ResolveInfoComponent>();
>>>>>>>
Nodes = pathmapClass.Nodes.Get()[pathmapObject];
Segments = pathmapClass.Segments.Get()[pathmapObject];
Attributes = pathmapClass.Attributes.Get()[pathmapObject];
// Get the resolve info component.
resolveInfo = actionSet.Translate.DeltinScript.GetComponent<ResolveInfoComponent>();
<<<<<<<
=======
if (useAttributes)
{
if (!reverseAttributes)
actionSet.AddAction(parentAttributeInfo.SetVariable(
value: Element.TernaryConditional(
new V_Compare(
current.GetVariable(),
Operators.Equal,
Node1(forBuilder.IndexValue)
),
Node2Attribute(forBuilder.IndexValue),
Node1Attribute(forBuilder.IndexValue)
),
index: neighborIndex.Get()
));
else
actionSet.AddAction(parentAttributeInfo.SetVariable(
value: Element.TernaryConditional(
new V_Compare(
current.GetVariable(),
Operators.Equal,
Node1(forBuilder.IndexValue)
),
Node1Attribute(forBuilder.IndexValue),
Node2Attribute(forBuilder.IndexValue)
),
index: neighborIndex.Get()
));
}
>>>>>>>
<<<<<<<
private Element GetConnectedSegments(Element segments, Element currentIndex) => Element.Part<V_FilteredArray>(
segments,
// Make sure one of the segments nodes is the current node.
Element.Part<V_ArrayContains>(
BothNodes(new V_ArrayElement()),
currentIndex
)
);
=======
private Element GetConnectedSegments(Element currentIndex)
{
Element currentSegmentCheck = new V_ArrayElement();
Element useAttribute;
if (!reverseAttributes)
useAttribute = Element.TernaryConditional(
new V_Compare(Node1(currentSegmentCheck), Operators.Equal, currentIndex),
Node2Attribute(currentSegmentCheck),
Node1Attribute(currentSegmentCheck)
);
else
useAttribute = Element.TernaryConditional(
new V_Compare(Node1(currentSegmentCheck), Operators.Equal, currentIndex),
Node1Attribute(currentSegmentCheck),
Node2Attribute(currentSegmentCheck)
);
Element isValid;
if (useAttributes)
isValid = Element.Part<V_ArrayContains>(
Element.Part<V_Append>(attributes, new V_Number(0)),
useAttribute
);
else
isValid = new V_Compare(useAttribute, Operators.Equal, new V_Number(0));
return Element.Part<V_FilteredArray>(
Segments,
Element.Part<V_And>(
// Make sure one of the segments nodes is the current node.
Element.Part<V_ArrayContains>(
BothNodes(currentSegmentCheck),
currentIndex
),
isValid
)
);
}
>>>>>>>
private Element GetConnectedSegments(Element segments, Element currentIndex) => Element.Part<V_FilteredArray>(
segments,
// Make sure one of the segments nodes is the current node.
Element.Part<V_ArrayContains>(
BothNodes(new V_ArrayElement()),
currentIndex
)
);
<<<<<<<
private static Element BothNodes(Element segment) => Element.CreateAppendArray(Node1(segment), Node2(segment));
public static Element Node1(Element segment) => Element.Part<V_XOf>(segment);
public static Element Node2(Element segment) => Element.Part<V_YOf>(segment);
=======
public static Element BothNodes(Element segment) => Element.CreateAppendArray(Node1(segment), Node2(segment));
public static Element Node1(Element segment) => Element.Part<V_RoundToInteger>(Element.Part<V_XOf>(segment), EnumData.GetEnumValue(Rounding.Down));
public static Element Node2(Element segment) => Element.Part<V_RoundToInteger>(Element.Part<V_YOf>(segment), EnumData.GetEnumValue(Rounding.Down));
public static Element Node1Attribute(Element segment) => Element.Part<V_RoundToInteger>(
(Element.Part<V_XOf>(segment) % 1) * 100,
EnumData.GetEnumValue(Rounding.Nearest)
);
public static Element Node2Attribute(Element segment) => Element.Part<V_RoundToInteger>(
(Element.Part<V_YOf>(segment) % 1) * 100,
EnumData.GetEnumValue(Rounding.Nearest)
);
>>>>>>>
public static Element BothNodes(Element segment) => Element.CreateAppendArray(Node1(segment), Node2(segment));
public static Element Node1(Element segment) => Element.Part<V_XOf>(segment);
public static Element Node2(Element segment) => Element.Part<V_YOf>(segment); |
<<<<<<<
using Deltin.Deltinteger.Debugger;
using Deltin.Deltinteger.Debugger.Protocol;
=======
using Deltin.Deltinteger.Decompiler.TextToElement;
using Deltin.Deltinteger.Decompiler.ElementToCode;
>>>>>>>
using Deltin.Deltinteger.Debugger;
using Deltin.Deltinteger.Debugger.Protocol;
using Deltin.Deltinteger.Decompiler.TextToElement;
using Deltin.Deltinteger.Decompiler.ElementToCode;
<<<<<<<
private readonly ClipboardListener _debugger;
private PathMap lastMap;
=======
private Pathmap lastMap;
>>>>>>>
private readonly ClipboardListener _debugger;
private Pathmap lastMap;
<<<<<<<
// debugger variables
options.OnRequest<VariablesArgs, DBPVariable[]>("debugger.getVariables", args => Task<DBPVariable[]>.Run(() => {
if (_debugger.VariableCollection != null)
return _debugger.VariableCollection.GetVariables(args);
return null;
}));
// debugger evaluate
options.OnRequest<EvaluateArgs, EvaluateResponse>("debugger.evaluate", args => Task<EvaluateResponse>.Run(() => {
return _debugger.VariableCollection?.Evaluate(args);
}));
=======
// Decompile insert
options.OnRequest<object>("decompile.insert", () => Task.Run(() =>
{
try
{
var workshop = new ConvertTextToElement(Clipboard.GetText()).Get();
var code = new WorkshopDecompiler(workshop, new OmitLobbySettingsResolver(), new CodeFormattingOptions()).Decompile();
object result = new {success = true, code = code};
return result;
}
catch (Exception ex)
{
object result = new {success = false, code = ex.ToString()};
return result;
}
}));
>>>>>>>
// debugger variables
options.OnRequest<VariablesArgs, DBPVariable[]>("debugger.getVariables", args => Task<DBPVariable[]>.Run(() => {
if (_debugger.VariableCollection != null)
return _debugger.VariableCollection.GetVariables(args);
return null;
}));
// debugger evaluate
options.OnRequest<EvaluateArgs, EvaluateResponse>("debugger.evaluate", args => Task<EvaluateResponse>.Run(() => {
return _debugger.VariableCollection?.Evaluate(args);
}));
// Decompile insert
options.OnRequest<object>("decompile.insert", () => Task.Run(() =>
{
try
{
var workshop = new ConvertTextToElement(Clipboard.GetText()).Get();
var code = new WorkshopDecompiler(workshop, new OmitLobbySettingsResolver(), new CodeFormattingOptions()).Decompile();
object result = new {success = true, code = code};
return result;
}
catch (Exception ex)
{
object result = new {success = false, code = ex.ToString()};
return result;
}
})); |
<<<<<<<
current = IndexedVar.AssignInternalVarExt(context.VarCollection, null, "Dijkstra: Current", context.IsGlobal);
IndexedVar distances = IndexedVar.AssignInternalVar (context.VarCollection, null, "Dijkstra: Distances", context.IsGlobal);
unvisited = IndexedVar.AssignInternalVar (context.VarCollection, null, "Dijkstra: Unvisited", context.IsGlobal);
IndexedVar connectedSegments = IndexedVar.AssignInternalVarExt(context.VarCollection, null, "Dijkstra: Connected Segments", context.IsGlobal);
IndexedVar neighborIndex = IndexedVar.AssignInternalVarExt(context.VarCollection, null, "Dijkstra: Neighbor Index", context.IsGlobal);
IndexedVar neighborDistance = IndexedVar.AssignInternalVarExt(context.VarCollection, null, "Dijkstra: Distance", context.IsGlobal);
parentArray = IndexedVar.AssignInternalVar (context.VarCollection, null, "Dijkstra: Parent Array", context.IsGlobal);
if (useAttributes)
parentAttributeInfo = IndexedVar.AssignInternalVar(context.VarCollection, null, "Dijkstra: Parent Attribute Info", context.IsGlobal);
=======
current = actionSet.VarCollection.Assign("Dijkstra: Current", actionSet.IsGlobal, true);
IndexReference distances = actionSet.VarCollection.Assign("Dijkstra: Distances", actionSet.IsGlobal, false);
unvisited = actionSet.VarCollection.Assign("Dijkstra: Unvisited", actionSet.IsGlobal, false);
IndexReference connectedSegments = actionSet.VarCollection.Assign("Dijkstra: Connected Segments", actionSet.IsGlobal, true);
IndexReference neighborIndex = actionSet.VarCollection.Assign("Dijkstra: Neighbor Index", actionSet.IsGlobal, true);
IndexReference neighborDistance = actionSet.VarCollection.Assign("Dijkstra: Distance", actionSet.IsGlobal, true);
parentArray = actionSet.VarCollection.Assign("Dijkstra: Parent Array", actionSet.IsGlobal, false);
>>>>>>>
current = actionSet.VarCollection.Assign("Dijkstra: Current", actionSet.IsGlobal, true);
IndexReference distances = actionSet.VarCollection.Assign("Dijkstra: Distances", actionSet.IsGlobal, false);
unvisited = actionSet.VarCollection.Assign("Dijkstra: Unvisited", actionSet.IsGlobal, false);
IndexReference connectedSegments = actionSet.VarCollection.Assign("Dijkstra: Connected Segments", actionSet.IsGlobal, true);
IndexReference neighborIndex = actionSet.VarCollection.Assign("Dijkstra: Neighbor Index", actionSet.IsGlobal, true);
IndexReference neighborDistance = actionSet.VarCollection.Assign("Dijkstra: Distance", actionSet.IsGlobal, true);
parentArray = actionSet.VarCollection.Assign("Dijkstra: Parent Array", actionSet.IsGlobal, false);
if (useAttributes)
parentAttributeInfo = actionSet.VarCollection.Assign("Dijkstra: Parent Attribute Info", actionSet.IsGlobal, false);
<<<<<<<
protected void Backtrack(Element destination, IndexedVar finalPath, IndexedVar finalPathAttributes)
=======
protected void Backtrack(Element destination, IndexReference finalPath)
>>>>>>>
protected void Backtrack(Element destination, IndexReference finalPath, IndexReference finalPathAttributes)
<<<<<<<
finalNode = IndexedVar.AssignInternalVarExt(context.VarCollection, null, "Dijkstra: Last", context.IsGlobal);
finalPath = IndexedVar.AssignInternalVar (context.VarCollection, null, "Dijkstra: Final Path", context.IsGlobal);
finalPathAttributes = IndexedVar.AssignInternalVar (context.VarCollection, null, "Dijkstra: Final Path Attributes", context.IsGlobal);
context.Actions.AddRange(finalNode.SetVariable(lastNode));
context.Actions.AddRange(finalPath.SetVariable(new V_EmptyArray()));
=======
finalNode = actionSet.VarCollection.Assign("Dijkstra: Last", actionSet.IsGlobal, true);
finalPath = actionSet.VarCollection.Assign("Dijkstra: Final Path", actionSet.IsGlobal, false);
actionSet.AddAction(finalNode.SetVariable(lastNode));
actionSet.AddAction(finalPath.SetVariable(new V_EmptyArray()));
>>>>>>>
finalNode = actionSet.VarCollection.Assign("Dijkstra: Last", actionSet.IsGlobal, true);
finalPath = actionSet.VarCollection.Assign("Dijkstra: Final Path", actionSet.IsGlobal, false);
if (useAttributes)
finalPathAttributes = actionSet.VarCollection.Assign("Dijkstra: Final Path Attributes", actionSet.IsGlobal, false);
actionSet.AddAction(finalNode.SetVariable(lastNode));
actionSet.AddAction(finalPath.SetVariable(new V_EmptyArray()));
<<<<<<<
Backtrack(finalNode.GetVariable(), finalPath, finalPathAttributes);
=======
Backtrack((Element)finalNode.GetVariable(), finalPath);
>>>>>>>
Backtrack((Element)finalNode.GetVariable(), finalPath, finalPathAttributes);
<<<<<<<
public DijkstraMultiSource(TranslateRule context, PathfinderInfo pathfinderInfo, PathMapVar pathmap, Element players, Element destination, Element attributes) : base(context, pathmap, destination, attributes, true)
=======
public DijkstraMultiSource(ActionSet actionSet, PathfinderInfo pathfinderInfo, Element pathmapObject, Element players, Element destination) : base(actionSet, pathmapObject, destination, true)
>>>>>>>
public DijkstraMultiSource(ActionSet actionSet, PathfinderInfo pathfinderInfo, Element pathmapObject, Element players, Element destination, Element attributes) : base(actionSet, pathmapObject, destination, attributes, true)
<<<<<<<
IndexedVar finalPath = IndexedVar.AssignInternalVar(context.VarCollection, null, "Dijkstra: Final Path", context.IsGlobal);
IndexedVar finalPathAttributes = IndexedVar.AssignInternalVar(context.VarCollection, null, "Dijkstra: Final Path Attributes", context.IsGlobal);
=======
IndexReference finalPath = actionSet.VarCollection.Assign("Dijkstra: Final Path", actionSet.IsGlobal, false);
>>>>>>>
IndexReference finalPath = actionSet.VarCollection.Assign("Dijkstra: Final Path", actionSet.IsGlobal, false);
IndexReference finalPathAttributes = actionSet.VarCollection.Assign("Dijkstra: Final Path Attributes", actionSet.IsGlobal, false);
<<<<<<<
Pathfind(context, pathfinderInfo, finalPath.GetVariable(), assignPlayerPaths.IndexValue, position, finalPathAttributes.GetVariable());
=======
Pathfind(actionSet, pathfinderInfo, (Element)finalPath.GetVariable(), assignPlayerPaths.IndexValue, position);
>>>>>>>
Pathfind(actionSet, pathfinderInfo, (Element)finalPath.GetVariable(), assignPlayerPaths.IndexValue, position, (Element)finalPathAttributes.GetVariable()); |
<<<<<<<
public DefinedType(ParseInfo parseInfo, Scope scope, DeltinScriptParser.Type_defineContext typeContext, List<IApplyBlock> applyBlocks) : base(typeContext.name.Text)
=======
public DefinedType(ParseInfo parseInfo, Scope scope, DeltinScriptParser.Type_defineContext typeContext) : base(typeContext.name.Text)
>>>>>>>
public DefinedType(ParseInfo parseInfo, Scope scope, DeltinScriptParser.Type_defineContext typeContext) : base(typeContext.name.Text)
<<<<<<<
=======
staticScope = parseInfo.TranslateInfo.GlobalScope.Child("class " + Name);
staticScope.GroupCatch = true;
objectScope = staticScope.Child("class " + Name);
objectScope.This = this;
// Todo: Static methods/macros.
foreach (var definedMethod in typeContext.define_method())
{
var newMethod = new DefinedMethod(parseInfo, UseScope(false), definedMethod, this);
}
foreach (var macroContext in typeContext.define_macro())
{
DeltinScript.GetMacro(parseInfo, UseScope(false), macroContext);
}
>>>>>>>
<<<<<<<
applyBlocks.Add((DefinedConstructor)Constructors[i]);
=======
>>>>>>>
<<<<<<<
Var newVar = Var.CreateVarFromContext(VariableDefineType.InClass, parseInfo, definedVariable);
newVar.Finalize(operationalScope);
if (!newVar.Static)
{
objectVariables.Add(new ObjectVariable(newVar));
serveObjectScope.CopyVariable(newVar);
}
else
{
objectVariables.Add(new ObjectVariable(newVar));
staticScope.CopyVariable(newVar);
}
=======
Var newVar = new ClassVariable(objectScope, staticScope, new DefineContextHandler(parseInfo, definedVariable));
if (!newVar.Static) objectVariables.Add(new ObjectVariable(newVar));
>>>>>>>
Var newVar = new ClassVariable(operationalScope, staticScope, new DefineContextHandler(parseInfo, definedVariable));
if (!newVar.Static)
{
objectVariables.Add(new ObjectVariable(newVar));
serveObjectScope.CopyVariable(newVar);
}
else
{
objectVariables.Add(new ObjectVariable(newVar));
staticScope.CopyVariable(newVar);
} |
<<<<<<<
public DijkstraBase(ActionSet actionSet, Element pathmapObject, Element position, Element attributes, bool reversed)
=======
protected static bool assignExtended = false;
public DijkstraBase(ActionSet actionSet, Element pathmapObject, Element position, bool reversed)
>>>>>>>
protected static bool assignExtended = false;
public DijkstraBase(ActionSet actionSet, Element pathmapObject, Element position, Element attributes, bool reversed)
<<<<<<<
if (useAttributes)
actionSet.AddAction(parentAttributeInfo.SetVariable(
Element.TernaryConditional(
new V_Compare(
current.GetVariable(),
Operators.Equal,
Node1(forBuilder.IndexValue)
),
Node1Attribute(forBuilder.IndexValue),
Node2Attribute(forBuilder.IndexValue)
),
null,
(Element)neighborIndex.GetVariable()
));
ifBuilder.Finish();
=======
actionSet.AddAction(new A_End());
>>>>>>>
if (useAttributes)
actionSet.AddAction(parentAttributeInfo.SetVariable(
Element.TernaryConditional(
new V_Compare(
current.GetVariable(),
Operators.Equal,
Node1(forBuilder.IndexValue)
),
Node1Attribute(forBuilder.IndexValue),
Node2Attribute(forBuilder.IndexValue)
),
null,
(Element)neighborIndex.GetVariable()
));
actionSet.AddAction(new A_End());
<<<<<<<
actionSet.AddAction(finalPath.SetVariable(Element.Part<V_Append>(first, second)));
if (useAttributes)
actionSet.AddAction(finalPathAttributes.SetVariable(Element.Part<V_Append>(firstAttribute, secondAttribute)));
actionSet.AddAction(current.SetVariable(Element.Part<V_ValueInArray>(parentArray.GetVariable(), current.GetVariable()) - 1));
backtrack.Finish();
=======
// For debugging generated path.
// actionSet.AddAction(Element.Part<A_CreateEffect>(
// Element.Part<V_AllPlayers>(),
// EnumData.GetEnumValue(Effect.Orb),
// EnumData.GetEnumValue(Color.SkyBlue),
// next,
// new V_Number(0.5),
// EnumData.GetEnumValue(EffectRev.VisibleTo)
// ));
actionSet.AddAction(ArrayBuilder<Element>.Build(
finalPath.SetVariable(Element.Part<V_Append>(first, second)),
current.SetVariable(Element.Part<V_ValueInArray>(parentArray.GetVariable(), current.GetVariable()) - 1)
));
actionSet.AddAction(new A_End());
>>>>>>>
// For debugging generated path.
// actionSet.AddAction(Element.Part<A_CreateEffect>(
// Element.Part<V_AllPlayers>(),
// EnumData.GetEnumValue(Effect.Orb),
// EnumData.GetEnumValue(Color.SkyBlue),
// next,
// new V_Number(0.5),
// EnumData.GetEnumValue(EffectRev.VisibleTo)
// ));
actionSet.AddAction(finalPath.SetVariable(Element.Part<V_Append>(first, second)));
if (useAttributes)
actionSet.AddAction(finalPathAttributes.SetVariable(Element.Part<V_Append>(firstAttribute, secondAttribute)));
actionSet.AddAction(current.SetVariable(Element.Part<V_ValueInArray>(parentArray.GetVariable(), current.GetVariable()) - 1));
actionSet.AddAction(new A_End()); |
<<<<<<<
using (await _sessionsLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
{
return _sessions.Where(s => s.Value.IsConnected).Select(s => new ConnectedMqttClient
{
ClientId = s.Value.ClientId,
ProtocolVersion = s.Value.ProtocolVersion,
LastPacketReceived = s.Value.KeepAliveMonitor.LastPacketReceived,
LastNonKeepAlivePacketReceived = s.Value.KeepAliveMonitor.LastNonKeepAlivePacketReceived,
PendingApplicationMessages = s.Value.PendingMessagesQueue.Count
}).ToList();
}
=======
var result = new List<IMqttClientSessionStatus>();
foreach (var session in _sessions)
{
var status = new MqttClientSessionStatus(this, session.Value);
session.Value.FillStatus(status);
result.Add(status);
}
return Task.FromResult((IList<IMqttClientSessionStatus>)result);
>>>>>>>
var result = new List<IMqttClientSessionStatus>();
foreach (var session in _sessions)
{
var status = new MqttClientSessionStatus(this, session.Value);
session.Value.FillStatus(status);
result.Add(status);
}
return Task.FromResult((IList<IMqttClientSessionStatus>)result);
<<<<<<<
using (await _sessionsLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
{
if (!_sessions.TryGetValue(clientId, out var session))
{
throw new InvalidOperationException($"Client session '{clientId}' is unknown.");
}
await session.UnsubscribeAsync(topicFilters).ConfigureAwait(false);
}
=======
if (!_sessions.TryGetValue(clientId, out var session))
{
throw new InvalidOperationException($"Client session '{clientId}' is unknown.");
}
return session.UnsubscribeAsync(topicFilters);
}
public void DeleteSession(string clientId)
{
_sessions.TryRemove(clientId, out _);
_logger.Verbose("Session for client '{0}' deleted.", clientId);
>>>>>>>
if (!_sessions.TryGetValue(clientId, out var session))
{
throw new InvalidOperationException($"Client session '{clientId}' is unknown.");
}
return session.UnsubscribeAsync(topicFilters);
}
public void DeleteSession(string clientId)
{
_sessions.TryRemove(clientId, out _);
_logger.Verbose("Session for client '{0}' deleted.", clientId);
<<<<<<<
=======
_sessionPreparationLock?.Dispose();
>>>>>>>
_sessionPreparationLock?.Dispose();
<<<<<<<
using (await _sessionsLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
=======
await _sessionPreparationLock.EnterAsync(CancellationToken.None).ConfigureAwait(false);
try
>>>>>>>
using (await _sessionPreparationLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
<<<<<<<
=======
finally
{
_sessionPreparationLock.Exit();
}
>>>>>>>
<<<<<<<
Server.OnApplicationMessageReceived(senderClientSession?.ClientId, applicationMessage);
}
catch (Exception exception)
{
_logger.Error(exception, "Error while processing application message");
}
using (await _sessionsLock.LockAsync(CancellationToken.None).ConfigureAwait(false))
{
=======
>>>>>>>
<<<<<<<
=======
catch (Exception exception)
{
_logger.Error(exception, "Error while processing application message");
}
>>>>>>>
catch (Exception exception)
{
_logger.Error(exception, "Error while processing application message");
} |
<<<<<<<
public void Dispose()
{
}
=======
>>>>>>> |
<<<<<<<
using System.Linq;
using MegaMan.Common.Entities;
=======
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
>>>>>>>
using System.IO;
using System.Linq;
using System.Windows.Media.Imaging;
using MegaMan.Common.Entities; |
<<<<<<<
_addEnrageItem = false;
_numberTimer.Refresh();
N(nameof(RhombEnrageTimerText));
//N(nameof(EnrageHistory));
=======
_numberTimer.Refresh();
N(nameof(EnrageHistory));
>>>>>>>
_addEnrageItem = false;
_numberTimer.Refresh();
N(nameof(RhombEnrageTimerText));
//N(nameof(EnrageHistory));
<<<<<<<
_addEnrageItem = true;
=======
_serverSentEnrage = false;
>>>>>>>
_addEnrageItem = true;
_serverSentEnrage = false; |
<<<<<<<
new[] { posParam, moveParam, sprParam, inputParam, collParam, ladderParam, timerParam, varsParam, healthParam, weaponParam, stParam, lifeParam, playerXParam, playerYParam, gravParam, randParam, playerParam },
=======
new[] { posParam, moveParam, sprParam, inputParam, collParam, ladderParam, timerParam, healthParam, weaponParam, stParam, lifeParam, playerXParam, playerYParam, playerXAbsParam, playerYAbsParam, gravParam, randParam, playerParam },
>>>>>>>
new[] { posParam, moveParam, sprParam, inputParam, collParam, ladderParam, timerParam, varsParam, healthParam, weaponParam, stParam, lifeParam, playerXParam, playerYParam, playerXAbsParam, playerYAbsParam, gravParam, randParam, playerParam },
<<<<<<<
null, null, null, null, null, null, null, null, null, null, 0, 0, 0, 0,
=======
null, null, null, null, null, null, null, null, null, 0, 0, 0, 0, 0, 0,
>>>>>>>
null, null, null, null, null, null, null, null, null, null, 0, 0, 0, 0, 0, 0, |
<<<<<<<
writer.WriteStartElement("Movement");
writer.WriteElementString("Flying", info.Flying.ToString());
=======
writer.WriteElementString("Floating", info.Floating.ToString());
>>>>>>>
writer.WriteStartElement("Movement");
writer.WriteElementString("Floating", info.Floating.ToString()); |
<<<<<<<
using System.Xml.Serialization;
=======
>>>>>>>
<<<<<<<
using MegaMan.IO.Xml;
=======
using MegaMan.Engine.Forms.MenuControllers;
using MegaMan.Engine.Forms.Settings;
using MegaMan.IO.Xml;
>>>>>>>
using MegaMan.Engine.Forms.MenuControllers;
using MegaMan.Engine.Forms.Settings;
using MegaMan.IO.Xml;
<<<<<<<
=======
this.Hide();
customNtscForm.StartPosition = FormStartPosition.Manual;
keyform.StartPosition = FormStartPosition.Manual;
loadConfigForm.StartPosition = FormStartPosition.Manual;
deleteConfigsForm.StartPosition = FormStartPosition.Manual;
>>>>>>>
this.Hide();
customNtscForm.StartPosition = FormStartPosition.Manual;
keyform.StartPosition = FormStartPosition.Manual;
loadConfigForm.StartPosition = FormStartPosition.Manual;
deleteConfigsForm.StartPosition = FormStartPosition.Manual;
<<<<<<<
try
=======
LoadGlobalConfigValues();
LoadCurrentConfig();
string autoLoadGame = settingsService.GetAutoLoadGame();
if (autoLoadGame != null)
>>>>>>>
try |
<<<<<<<
public List<BaseEventTrigger> EventTriggers;
=======
public List<IEventTrigger> EventTriggers { get; set; }
>>>>>>>
public List<BaseEventTrigger> EventTriggers { get; set; }
<<<<<<<
TriggerList.Children.Add(new EventTriggerUserControl(this, trigger));
=======
//TODO: add event trigger user controls
////TriggerList.Children.Add(new TimeTriggerUserControl(trigger));
>>>>>>>
TriggerList.Children.Add(new EventTriggerUserControl(this, trigger)); |
<<<<<<<
private CustomEffectsCollection _customEffects;
private readonly EventTriggersCollection _eventTriggersCollection;
=======
private readonly CustomEffectsCollection _customEffects;
private readonly EventsCollection _events;
>>>>>>>
private readonly CustomEffectsCollection _customEffects;
private readonly EventTriggersCollection _eventTriggersCollection; |
<<<<<<<
using NUnit.Framework;
using ServiceStack.ServiceModel.Serialization;
using ServiceStack.ServiceModel.Tests.DataContracts.Operations;
using ServiceStack.Text;
=======
>>>>>>>
using ServiceStack.Text;
<<<<<<<
[Test]
public void KVP_Serializer_fills_public_fields()
{
using (JsConfig.With(includePublicFields:true))
{
var valueMap = new Dictionary<string, string> { { "FirstName", "james" }, { "LastName", "bond" }, { "FullName", "james bond" } };
var result = (CustomerWithFields)KeyValueDataContractDeserializer.Instance.Parse(valueMap, typeof(CustomerWithFields));
Assert.That(result.FirstName, Is.EqualTo("james"));
Assert.That(result.LastName, Is.EqualTo("bond"));
}
}
}
=======
[Test]
public void KVP_Serializer_fills_public_fields()
{
var valueMap = new Dictionary<string, string> { { "FirstName", "james" }, { "LastName", "bond" }, { "FullName", "james bond" } };
var result = (CustomerWithFields)KeyValueDataContractDeserializer.Instance.Parse(valueMap, typeof(CustomerWithFields));
Assert.That(result.FirstName, Is.EqualTo("james"));
Assert.That(result.LastName, Is.EqualTo("bond"));
}
}
>>>>>>>
[Test]
public void KVP_Serializer_fills_public_fields()
{
var valueMap = new Dictionary<string, string> { { "FirstName", "james" }, { "LastName", "bond" }, { "FullName", "james bond" } };
var result = (CustomerWithFields)KeyValueDataContractDeserializer.Instance.Parse(valueMap, typeof(CustomerWithFields));
Assert.That(result.FirstName, Is.EqualTo("james"));
Assert.That(result.LastName, Is.EqualTo("bond"));
}
} |
<<<<<<<
#if !NETCORE_SUPPORT
=======
[Explicit("Requires MongoDB Dependency")]
>>>>>>>
#if !NETCORE_SUPPORT
[Explicit("Requires MongoDB Dependency")] |
<<<<<<<
=======
>>>>>>>
<<<<<<<
=======
public void UpdateThirdPartyCamera(ServerAction action) {
if (action.thirdPartyCameraId <= thirdPartyCameras.Count) {
Camera thirdPartyCamera = thirdPartyCameras.ToArray()[action.thirdPartyCameraId];
thirdPartyCamera.gameObject.transform.eulerAngles = action.rotation;
thirdPartyCamera.gameObject.transform.position = action.position;
}
readyToEmit = true;
}
private void addAgent(ServerAction action) {
>>>>>>>
public void UpdateThirdPartyCamera(ServerAction action) {
if (action.thirdPartyCameraId <= thirdPartyCameras.Count) {
Camera thirdPartyCamera = thirdPartyCameras.ToArray()[action.thirdPartyCameraId];
thirdPartyCamera.gameObject.transform.eulerAngles = action.rotation;
thirdPartyCamera.gameObject.transform.position = action.position;
}
readyToEmit = true;
}
private void addAgent(ServerAction action) {
<<<<<<<
private void addImageForm(WWWForm form, BaseFPSAgentController agent, bool renderCamera) {
=======
private void addThirdPartyCameraImageForm(WWWForm form, Camera camera) {
RenderTexture.active = camera.activeTexture;
camera.Render ();
form.AddBinaryData("image-thirdParty-camera", captureScreen());
}
private void addImageForm(WWWForm form, DiscreteRemoteFPSAgentController agent) {
>>>>>>>
private void addThirdPartyCameraImageForm(WWWForm form, Camera camera) {
RenderTexture.active = camera.activeTexture;
camera.Render ();
form.AddBinaryData("image-thirdParty-camera", captureScreen());
}
private void addImageForm(WWWForm form, BaseFPSAgentController agent) {
<<<<<<<
private void addDepthImageForm(WWWForm form, BaseFPSAgentController agent) {
if (this.renderDepthImage) {
if (!agent.imageSynthesis.hasCapturePass ("_depth")) {
Debug.LogError ("Depth image not available - returning empty image");
}
byte[] bytes = agent.imageSynthesis.Encode ("_depth");
form.AddBinaryData ("image_depth", bytes);
}
}
private void addObjectImageForm(WWWForm form, BaseFPSAgentController agent, ref MetadataWrapper metadata) {
=======
private void addObjectImageForm(WWWForm form, DiscreteRemoteFPSAgentController agent, ref MetadataWrapper metadata) {
>>>>>>>
private void addDepthImageForm(WWWForm form, BaseFPSAgentController agent) {
if (this.renderDepthImage) {
if (!agent.imageSynthesis.hasCapturePass ("_depth")) {
Debug.LogError ("Depth image not available - returning empty image");
}
byte[] bytes = agent.imageSynthesis.Encode ("_depth");
form.AddBinaryData ("image_depth", bytes);
}
}
private void addObjectImageForm(WWWForm form, BaseFPSAgentController agent, ref MetadataWrapper metadata) {
<<<<<<<
private void addClassImageForm (WWWForm form, BaseFPSAgentController agent) {
if (this.renderClassImage) {
if (!agent.imageSynthesis.hasCapturePass ("_class")) {
Debug.LogError ("class image not available - sending empty image");
=======
private void addImageSynthesisImageForm(WWWForm form, DiscreteRemoteFPSAgentController agent, bool flag, string captureName, string fieldName)
{
if (flag) {
if (!agent.imageSynthesis.hasCapturePass (captureName)) {
Debug.LogError (captureName + " not available - sending empty image");
>>>>>>>
private void addImageSynthesisImageForm(WWWForm form, BaseFPSAgentController agent, bool flag, string captureName, string fieldName)
{
if (flag) {
if (!agent.imageSynthesis.hasCapturePass (captureName)) {
Debug.LogError (captureName + " not available - sending empty image"); |
<<<<<<<
public GameObject[] TargetCircles = null;
#if UNITY_EDITOR
private List<Bounds> gizmobounds = new List<Bounds>();
#endif
//change visibility check to use this distance when looking down
//protected float DownwardViewDistance = 2.0f;
=======
public GameObject[] TargetCircles = null;
#if UNITY_EDITOR
//for debug draw of axis aligned bounds for sim objects
private List<Bounds> gizmobounds = new List<Bounds>();
#endif
>>>>>>>
public GameObject[] TargetCircles = null;
#if UNITY_EDITOR
private List<Bounds> gizmobounds = new List<Bounds>();
#endif
//change visibility check to use this distance when looking down
//protected float DownwardViewDistance = 2.0f;
<<<<<<<
if(simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup) //|| simObj.PrimaryProperty == SimObjPrimaryProperty.Moveable)
{
objMeta.objectOrientedBoundingBox = GenerateObjectOrientedBoundingBox(simObj);
}
//return world axis aligned bounds for this sim object
objMeta.axisAlignedBoundingBox = GenerateAxisAlignedBoundingBox(simObj);
=======
if(simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup) //|| simObj.PrimaryProperty == SimObjPrimaryProperty.Moveable)
{
objMeta.objectOrientedBoundingBox = GenerateObjectOrientedBoundingBox(simObj);
}
//return world axis aligned bounds for this sim object
objMeta.axisAlignedBoundingBox = GenerateAxisAlignedBoundingBox(simObj);
>>>>>>>
if(simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup) //|| simObj.PrimaryProperty == SimObjPrimaryProperty.Moveable)
{
objMeta.objectOrientedBoundingBox = GenerateObjectOrientedBoundingBox(simObj);
}
//return world axis aligned bounds for this sim object
objMeta.axisAlignedBoundingBox = GenerateAxisAlignedBoundingBox(simObj);
<<<<<<<
#if UNITY_EDITOR
//debug draw bounds reset list
gizmobounds.Clear();
#endif
=======
#if UNITY_EDITOR
//debug draw bounds reset list
gizmobounds.Clear();
#endif
>>>>>>>
#if UNITY_EDITOR
//debug draw bounds reset list
gizmobounds.Clear();
#endif
<<<<<<<
protected static bool CheckIfVisibilityPointInViewport(SimObjPhysics sop, Transform point, Camera agentCamera, bool includeInvisible) {
=======
protected bool CheckIfVisibilityPointInViewport(SimObjPhysics sop, Transform point, Camera agentCamera, bool includeInvisible)
{
>>>>>>>
protected bool CheckIfVisibilityPointInViewport(SimObjPhysics sop, Transform point, Camera agentCamera, bool includeInvisible)
{
<<<<<<<
float raycastDistance = Vector3.Distance(point.position, agentCamera.transform.position) + 1.0f;
=======
float distFromPointToCamera = Vector3.Distance(point.position, m_Camera.transform.position);
float raycastDistance = distFromPointToCamera + 0.5f;
if(raycastDistance > maxVisibleDistance)
{
raycastDistance = maxVisibleDistance + 0.5f;
}
LayerMask mask = (1 << 8) | (1 << 9) | (1 << 10);
//change mask if its a floor so it ignores the receptacle trigger boxes on the floor
if(sop.Type == SimObjType.Floor)
mask = (1 << 8) | (1 << 10);
>>>>>>>
float distFromPointToCamera = Vector3.Distance(point.position, m_Camera.transform.position);
float raycastDistance = distFromPointToCamera + 0.5f;
if(raycastDistance > maxVisibleDistance)
{
raycastDistance = maxVisibleDistance + 0.5f;
}
LayerMask mask = (1 << 8) | (1 << 9) | (1 << 10);
//change mask if its a floor so it ignores the receptacle trigger boxes on the floor
if(sop.Type == SimObjType.Floor)
mask = (1 << 8) | (1 << 10);
<<<<<<<
public override void RotateRight(ServerAction controlCommand) {
// TODO change this function to take values other than 90 or -90
if (CheckIfAgentCanTurn(90)||controlCommand.forceAction) {
DefaultAgentHand(controlCommand);
base.RotateRight(controlCommand);
} else {
actionFinished(false);
=======
//for use with each of the 8 corners of a picked up object's bounding box - returns an array of Vector3 points along the arc of the rotation for a given starting point
//given a starting Vector3, rotate about an origin point for a total given angle. maxIncrementAngle is the maximum value of the increment between points on the arc.
//if leftOrRight is true - rotate around Y (rotate left/right), false - rotate around X (look up/down)
private Vector3[] GenerateArcPoints(Vector3 startingPoint, Vector3 origin, float angle, string dir)
{
float incrementAngle = angle/10f; //divide the total amount we are rotating by 10 to get 10 points on the arc
Vector3[] arcPoints = new Vector3[11]; //we just always want 10 points in addition to our starting corner position (11 total) to check against per corner
float currentIncrementAngle;
if (dir == "left") //Yawing left (Rotating across XZ plane around Y-pivot)
{
for (int i = 0; i < arcPoints.Length; i++)
{
currentIncrementAngle = i * -incrementAngle;
//move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
//rotate the rotPoint around the origin the current increment's angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.up, currentIncrementAngle);
//set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
//arcPoints[i] = RotatePointAroundPivot(startingPoint, origin, new Vector3(0, currentIncrementAngle, 0));
>>>>>>>
//for use with each of the 8 corners of a picked up object's bounding box - returns an array of Vector3 points along the arc of the rotation for a given starting point
//given a starting Vector3, rotate about an origin point for a total given angle. maxIncrementAngle is the maximum value of the increment between points on the arc.
//if leftOrRight is true - rotate around Y (rotate left/right), false - rotate around X (look up/down)
private Vector3[] GenerateArcPoints(Vector3 startingPoint, Vector3 origin, float angle, string dir)
{
float incrementAngle = angle/10f; //divide the total amount we are rotating by 10 to get 10 points on the arc
Vector3[] arcPoints = new Vector3[11]; //we just always want 10 points in addition to our starting corner position (11 total) to check against per corner
float currentIncrementAngle;
if (dir == "left") //Yawing left (Rotating across XZ plane around Y-pivot)
{
for (int i = 0; i < arcPoints.Length; i++)
{
currentIncrementAngle = i * -incrementAngle;
//move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
//rotate the rotPoint around the origin the current increment's angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.up, currentIncrementAngle);
//set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
//arcPoints[i] = RotatePointAroundPivot(startingPoint, origin, new Vector3(0, currentIncrementAngle, 0));
<<<<<<<
public override void RotateLeft(ServerAction controlCommand) {
// TODO change this function to take values other than 90 or -90
if (CheckIfAgentCanTurn(-90)||controlCommand.forceAction) {
DefaultAgentHand(controlCommand);
base.RotateLeft(controlCommand);
=======
else if(dir =="up") //Pitching up(Rotating across YZ plane around X-pivot)
{
for (int i = 0; i < arcPoints.Length; i++)
{
//reverse the increment angle because of the right handedness orientation of the local x-axis
currentIncrementAngle = i * -incrementAngle;
//move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
//rotate the rotPoint around the origin the current increment's angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.right, currentIncrementAngle);
//set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
//arcPoints[i] = RotatePointAroundPivot(startingPoint, origin, new Vector3(0, currentIncrementAngle, 0));
}
}
>>>>>>>
else if(dir =="up") //Pitching up(Rotating across YZ plane around X-pivot)
{
for (int i = 0; i < arcPoints.Length; i++)
{
//reverse the increment angle because of the right handedness orientation of the local x-axis
currentIncrementAngle = i * -incrementAngle;
//move the rotPoint to the current corner's position
rotPoint.transform.position = startingPoint;
//rotate the rotPoint around the origin the current increment's angle, relative to the correct axis
rotPoint.transform.RotateAround(origin, transform.right, currentIncrementAngle);
//set the current arcPoint's vector3 to the rotated point
arcPoints[i] = rotPoint.transform.position;
//arcPoints[i] = RotatePointAroundPivot(startingPoint, origin, new Vector3(0, currentIncrementAngle, 0));
}
}
<<<<<<<
public void RotateRightSmooth(ServerAction controlCommand) {
if (CheckIfAgentCanTurn(90)) {
DefaultAgentHand(controlCommand);
StartCoroutine(InterpolateRotation(this.GetRotateQuaternion(1), controlCommand.timeStep));
} else {
actionFinished(false);
}
}
public void RotateLeftSmooth(ServerAction controlCommand) {
if (CheckIfAgentCanTurn(-90)) {
DefaultAgentHand(controlCommand);
StartCoroutine(InterpolateRotation(this.GetRotateQuaternion(-1), controlCommand.timeStep));
} else {
actionFinished(false);
}
}
//checks if agent is clear to rotate left/right without object in hand hitting anything
public bool CheckIfAgentCanTurn(int direction) {
bool result = true;
=======
return arcPoints;
}
//checks if agent is clear to rotate left/right/up/down some number of degrees while holding an object
public bool CheckIfAgentCanRotate(string direction, float degrees) {
>>>>>>>
return arcPoints;
}
public void RotateRightSmooth(ServerAction controlCommand) {
if (CheckIfAgentCanTurn(90)) {
DefaultAgentHand(controlCommand);
StartCoroutine(InterpolateRotation(this.GetRotateQuaternion(1), controlCommand.timeStep));
} else {
actionFinished(false);
}
}
public void RotateLeftSmooth(ServerAction controlCommand) {
if (CheckIfAgentCanTurn(-90)) {
DefaultAgentHand(controlCommand);
StartCoroutine(InterpolateRotation(this.GetRotateQuaternion(-1), controlCommand.timeStep));
} else {
actionFinished(false);
}
}
//checks if agent is clear to rotate left/right/up/down some number of degrees while holding an object
public bool CheckIfAgentCanRotate(string direction, float degrees) {
<<<<<<<
if (!continuousMode) {
this.snapToGrid();
}
=======
//ignore snap to grid if forceAction = true, this allows true diagonal movement off the grid if rotated at non-orthogonal angles
if(!forceAction)
this.snapToGrid();
>>>>>>>
this.snapToGrid();
<<<<<<<
Vector3 center = cc.transform.position + cc.center;//make sure to offset this by cc.center since we shrank the capsule size
=======
Vector3 center = cc.transform.position + cc.center;
>>>>>>>
Vector3 center = cc.transform.position + cc.center;//make sure to offset this by cc.center since we shrank the capsule size
<<<<<<<
override public Vector3[] getReachablePositions(float gridMultiplier = 1.0f, int maxStepCount = 10000) { //max step count represents a 100m * 100m room. Adjust this value later if we end up making bigger rooms?
=======
//from given position in worldspace, raycast straight down and return a point of any surface hit
//useful for getting a worldspace coordinate on the floor given any point in space.
public Vector3 GetSurfacePointBelowPosition(Vector3 position)
{
Vector3 point = Vector3.zero;
//raycast down from the position like 10m and see if you hit anything. If nothing hit, return the original position and an error message?
RaycastHit hit;
if(Physics.Raycast(position, Vector3.down, out hit, 10f, (1<<8 | 1<<10), QueryTriggerInteraction.Ignore))
{
point = hit.point;
return point;
}
//nothing hit, return the original position?
else
{
return position;
}
}
override public Vector3[] getReachablePositions(float gridMultiplier = 1.0f, int maxStepCount = 10000) {
>>>>>>>
//from given position in worldspace, raycast straight down and return a point of any surface hit
//useful for getting a worldspace coordinate on the floor given any point in space.
public Vector3 GetSurfacePointBelowPosition(Vector3 position)
{
Vector3 point = Vector3.zero;
//raycast down from the position like 10m and see if you hit anything. If nothing hit, return the original position and an error message?
RaycastHit hit;
if(Physics.Raycast(position, Vector3.down, out hit, 10f, (1<<8 | 1<<10), QueryTriggerInteraction.Ignore))
{
point = hit.point;
return point;
}
//nothing hit, return the original position?
else
{
return position;
}
}
override public Vector3[] getReachablePositions(float gridMultiplier = 1.0f, int maxStepCount = 10000) {
<<<<<<<
//default maxStepCount to scale based on gridSize
if (stepsTaken > Math.Floor(maxStepCount/gridSize * gridSize)) {
=======
if (stepsTaken > maxStepCount) {
>>>>>>>
//default maxStepCount to scale based on gridSize
if (stepsTaken > Math.Floor(maxStepCount/gridSize * gridSize)) { |
<<<<<<<
primaryAgent.ProcessControlCommand (action.dynamicServerAction);
=======
Time.fixedDeltaTime = action.fixedDeltaTime.GetValueOrDefault(Time.fixedDeltaTime);
if (action.targetFrameRate > 0) {
Application.targetFrameRate = action.targetFrameRate;
}
primaryAgent.ProcessControlCommand (action);
>>>>>>>
primaryAgent.ProcessControlCommand (action.dynamicServerAction);
Time.fixedDeltaTime = action.fixedDeltaTime.GetValueOrDefault(Time.fixedDeltaTime);
if (action.targetFrameRate > 0) {
Application.targetFrameRate = action.targetFrameRate;
}
<<<<<<<
=======
public void registerAsThirdPartyCamera(Camera camera) {
this.thirdPartyCameras.Add(camera);
// camera.gameObject.AddComponent(typeof(ImageSynthesis));
}
// If fov is <= min or > max, return defaultVal, else return fov
private float ClampFieldOfView(float fov, float defaultVal = 90f, float min = 0f, float max = 180f) {
return (fov <= min || fov > max) ? defaultVal : fov;
}
>>>>>>>
public void registerAsThirdPartyCamera(Camera camera) {
this.thirdPartyCameras.Add(camera);
// camera.gameObject.AddComponent(typeof(ImageSynthesis));
}
// If fov is <= min or > max, return defaultVal, else return fov
private float ClampFieldOfView(float fov, float defaultVal = 90f, float min = 0f, float max = 180f) {
return (fov <= min || fov > max) ? defaultVal : fov;
}
<<<<<<<
[MessagePackObject(keyAsPropertyName: true)]
=======
public class JointMetadata {
public string name;
public Vector3 position;
public Vector3 rootRelativePosition;
public Vector4 rotation;
public Vector4 rootRelativeRotation;
public Vector4 localRotation;
}
[Serializable]
public class ArmMetadata {
//public Vector3 handTarget;
//joints 1 to 4, joint 4 is the wrist and joint 1 is the base that never moves
public JointMetadata[] joints;
//all objects currently held by the hand sphere
public List<String> HeldObjects;
//all sim objects that are both pickupable and inside the hand sphere
public List<String> PickupableObjectsInsideHandSphere;
//world coordinates of the center of the hand's sphere
public Vector3 HandSphereCenter;
//current radius of the hand sphere
public float HandSphereRadius;
}
[Serializable]
>>>>>>>
[MessagePackObject(keyAsPropertyName: true)]
public class JointMetadata {
public string name;
public Vector3 position;
public Vector3 rootRelativePosition;
public Vector4 rotation;
public Vector4 rootRelativeRotation;
public Vector4 localRotation;
}
[Serializable]
public class ArmMetadata {
//public Vector3 handTarget;
//joints 1 to 4, joint 4 is the wrist and joint 1 is the base that never moves
public JointMetadata[] joints;
//all objects currently held by the hand sphere
public List<String> HeldObjects;
//all sim objects that are both pickupable and inside the hand sphere
public List<String> PickupableObjectsInsideHandSphere;
//world coordinates of the center of the hand's sphere
public Vector3 HandSphereCenter;
//current radius of the hand sphere
public float HandSphereRadius;
}
[Serializable] |
<<<<<<<
public int actionDuration = 3;
private int defaultScreenWidth = 300;
private int defaultScreenHeight = 300;
=======
public int actionDuration = 3;
// private int defaultScreenWidth = 300;
// private int defaultScreenHeight = 300;
>>>>>>>
public int actionDuration = 3;
<<<<<<<
protected virtual void Awake()
{
=======
protected virtual void Awake() {
Application.targetFrameRate = 300;
QualitySettings.vSyncCount = 0;
>>>>>>>
protected virtual void Awake()
{
Application.targetFrameRate = 300;
QualitySettings.vSyncCount = 0;
<<<<<<<
m_StepCycle = 0f;
m_NextStep = m_StepCycle / 2f;
=======
>>>>>>>
<<<<<<<
m_MouseLook.Init(transform, m_Camera.transform);
ObjectTriggers = new Hashtable();
=======
ObjectTriggers = new Hashtable ();
>>>>>>>
<<<<<<<
protected bool closeSimObj(SimObj so)
{
=======
protected bool closeSimObj(SimObj so)
{
>>>>>>>
protected bool closeSimObj(SimObj so)
{
<<<<<<<
}
else if (so.IsAnimated)
{
res = updateAnimState(so.Animator, false);
=======
}
else if (so.IsAnimated)
{
res = updateAnimState (so.Animator, false);
>>>>>>>
}
else if (so.IsAnimated)
{
res = updateAnimState(so.Animator, false);
<<<<<<<
}
else if (so.IsAnimated)
{
res = updateAnimState(so.Animator, true);
=======
}
else if (so.IsAnimated)
{
res = updateAnimState (so.Animator, true);
>>>>>>>
}
else if (so.IsAnimated)
{
res = updateAnimState(so.Animator, true);
<<<<<<<
protected void ProcessControlCommand(string msg)
{
Debug.Log("Procssing control commands: " + msg);
=======
protected void ProcessControlCommand(string msg) {
//Debug.Log ("Procssing control commands: " + msg);
>>>>>>>
protected void ProcessControlCommand(string msg)
{
<<<<<<<
lastPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
Debug.Log("sending message: " + this.name);
System.Reflection.MethodInfo method = this.GetType().GetMethod(controlCommand.action);
=======
lastPosition = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
System.Reflection.MethodInfo method = this.GetType ().GetMethod (controlCommand.action);
>>>>>>>
lastPosition = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
System.Reflection.MethodInfo method = this.GetType ().GetMethod (controlCommand.action); |
<<<<<<<
if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return;
=======
CheckVelikMark(p);
if (!p.TargetId.IsMe()) return;
>>>>>>>
if (!p.TargetId.IsMe()) return;
<<<<<<<
if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return;
=======
CheckVelikMark(p);
if (!p.TargetId.IsMe()) return;
>>>>>>>
if (!p.TargetId.IsMe()) return;
<<<<<<<
if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return;
=======
CheckVelikMark(p);
if (!p.TargetId.IsMe()) return;
>>>>>>>
if (!p.TargetId.IsMe()) return; |
<<<<<<<
//ignore the trigger boxes the agent is using to check rotation, otherwise the object is colliding
else if (other.tag != "Player")
=======
//this is hitting something else so it must be colliding at this point!
if (other.tag != "Player")
>>>>>>>
//this is hitting something else so it must be colliding at this point!
else if (other.tag != "Player") |
<<<<<<<
if (agentCollides || handObjectCollides || tooMuchYMovement) {
=======
if(Arm != null)
{
if(Arm.IsArmColliding())
{
errorMessage = "Mid Level Arm is actively clipping with some geometry in the environment. TeleportFull failes in this position.";
armCollides = true;
}
}
if (agentCollides || handObjectCollides || armCollides) {
>>>>>>>
if(Arm != null)
{
if(Arm.IsArmColliding())
{
errorMessage = "Mid Level Arm is actively clipping with some geometry in the environment. TeleportFull failes in this position.";
armCollides = true;
}
}
if (agentCollides || handObjectCollides || armCollides || tooMuchYMovement) {
<<<<<<<
actionFinished(true);
}
=======
snapAgentToGrid();
//reset arm colliders on actionFinish
ToggleArmColliders(Arm, false);
actionFinished(true);
>>>>>>>
//reset arm colliders on actionFinish
ToggleArmColliders(Arm, false);
actionFinished(true);
} |
<<<<<<<
// Extra stuff
private Dictionary<string, SimObjPhysics> uniqueIdToSimObjPhysics = new Dictionary<string, SimObjPhysics>();
[SerializeField] public string[] objectIdsInBox = new string[0];
[SerializeField] protected bool inTopLevelView = false;
[SerializeField] protected Vector3 lastLocalCameraPosition;
[SerializeField] protected Quaternion lastLocalCameraRotation;
[SerializeField] protected float cameraOrthSize;
protected Dictionary<string, Dictionary<int, Material[]>> maskedObjects = new Dictionary<string, Dictionary<int, Material[]>>();
protected float[,,] flatSurfacesOnGrid = new float[0,0,0];
protected float[,] distances = new float[0,0];
protected float[,,] normals = new float[0,0,0];
protected bool[,] isOpenableGrid = new bool[0,0];
protected string[] segmentedObjectIds = new string[0];
[SerializeField] protected Vector3 standingLocalCameraPosition;
protected HashSet<int> initiallyDisabledRenderers = new HashSet<int>();
//set this to true to ignore interactable point checks. In this case, all actions only require an object to be Visible and
//will NOT require both visibility AND a path from the hand to the object's Interaction points.
//[SerializeField] private bool IgnoreInteractableFlag = false;
=======
>>>>>>>
// Extra stuff
private Dictionary<string, SimObjPhysics> uniqueIdToSimObjPhysics = new Dictionary<string, SimObjPhysics>();
[SerializeField] public string[] objectIdsInBox = new string[0];
[SerializeField] protected bool inTopLevelView = false;
[SerializeField] protected Vector3 lastLocalCameraPosition;
[SerializeField] protected Quaternion lastLocalCameraRotation;
[SerializeField] protected float cameraOrthSize;
protected Dictionary<string, Dictionary<int, Material[]>> maskedObjects = new Dictionary<string, Dictionary<int, Material[]>>();
protected float[,,] flatSurfacesOnGrid = new float[0,0,0];
protected float[,] distances = new float[0,0];
protected float[,,] normals = new float[0,0,0];
protected bool[,] isOpenableGrid = new bool[0,0];
protected string[] segmentedObjectIds = new string[0];
[SerializeField] protected Vector3 standingLocalCameraPosition;
protected HashSet<int> initiallyDisabledRenderers = new HashSet<int>();
<<<<<<<
private ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simObj) {
ObjectMetadata objMeta = new ObjectMetadata();
GameObject o = simObj.gameObject;
objMeta.name = o.name;
objMeta.position = o.transform.position;
objMeta.rotation = o.transform.eulerAngles;
objMeta.objectType = Enum.GetName(typeof(SimObjType), simObj.Type);
objMeta.receptacle = simObj.ReceptacleTriggerBoxes != null && simObj.ReceptacleTriggerBoxes.Length != 0;
objMeta.openable = simObj.IsOpenable;
if (objMeta.openable) {
objMeta.isopen = simObj.IsOpen;
}
objMeta.pickupable = simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup;
objMeta.objectId = simObj.UniqueID;
objMeta.visible = simObj.isVisible;
// TODO: bounds necessary?
// Bounds bounds = simObj.Bounds;
// this.bounds3D = new [] {
// bounds.min.x,
// bounds.min.y,
// bounds.min.z,
// bounds.max.x,
// bounds.max.y,
// bounds.max.z,
// };
return objMeta;
}
private ObjectMetadata[] generateObjectMetadata()
{
// Encode these in a json string and send it to the server
SimObjPhysics[] simObjects = GameObject.FindObjectsOfType<SimObjPhysics>();
int numObj = simObjects.Length;
List<ObjectMetadata> metadata = new List<ObjectMetadata>();
Dictionary<string, List<string>> parentReceptacles = new Dictionary<string, List<string>> ();
for (int k = 0; k < numObj; k++) {
SimObjPhysics simObj = simObjects[k];
if (this.excludeObject(simObj.UniqueID)) {
continue;
}
ObjectMetadata meta = ObjectMetadataFromSimObjPhysics(simObj);
if (meta.receptacle)
{
List<string> receptacleObjectIds = simObj.Contains();
foreach (string oid in receptacleObjectIds)
{
if (!parentReceptacles.ContainsKey(oid)) {
parentReceptacles[oid] = new List<string>();
}
parentReceptacles[oid].Add(simObj.UniqueID);
}
meta.receptacleObjectIds = receptacleObjectIds.ToArray();
meta.receptacleCount = meta.receptacleObjectIds.Length;
}
meta.distance = Vector3.Distance(transform.position, simObj.gameObject.transform.position);
metadata.Add(meta);
}
foreach (ObjectMetadata meta in metadata) {
if (parentReceptacles.ContainsKey (meta.objectId)) {
meta.parentReceptacles = parentReceptacles[meta.objectId].ToArray();
}
}
return metadata.ToArray();
}
private T[] flatten2DimArray<T>(T[,] array) {
int nrow = array.GetLength(0);
int ncol = array.GetLength(1);
T[] flat = new T[nrow * ncol];
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
flat[i * ncol + j] = array[i, j];
}
}
return flat;
}
private T[] flatten3DimArray<T>(T[,,] array) {
int n0 = array.GetLength(0);
int n1 = array.GetLength(1);
int n2 = array.GetLength(2);
T[] flat = new T[n0 * n1 * n2];
for (int i = 0; i < n0; i++) {
for (int j = 0; j < n1; j++) {
for (int k = 0; k < n2; k++) {
flat[i * n1 * n2 + j * n2 + k] = array[i, j, k];
}
}
}
return flat;
}
public override MetadataWrapper generateMetadataWrapper()
{
// AGENT METADATA
ObjectMetadata agentMeta = new ObjectMetadata();
agentMeta.name = "agent";
agentMeta.position = transform.position;
agentMeta.rotation = transform.eulerAngles;
agentMeta.cameraHorizon = m_Camera.transform.rotation.eulerAngles.x;
if (agentMeta.cameraHorizon > 180) {
agentMeta.cameraHorizon -= 360;
}
// OTHER METADATA
MetadataWrapper metaMessage = new MetadataWrapper();
metaMessage.agent = agentMeta;
metaMessage.sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
metaMessage.objects = generateObjectMetadata();
metaMessage.collided = collidedObjects.Length > 0;
metaMessage.collidedObjects = collidedObjects;
metaMessage.screenWidth = Screen.width;
metaMessage.screenHeight = Screen.height;
metaMessage.cameraPosition = m_Camera.transform.position;
metaMessage.cameraOrthSize = cameraOrthSize;
cameraOrthSize = -1f;
metaMessage.fov = m_Camera.fieldOfView;
metaMessage.isStanding = (m_Camera.transform.localPosition - standingLocalCameraPosition).magnitude < 0.1f;
metaMessage.lastAction = lastAction;
metaMessage.lastActionSuccess = lastActionSuccess;
metaMessage.errorMessage = errorMessage;
if (errorCode != ServerActionErrorCode.Undefined) {
metaMessage.errorCode = Enum.GetName(typeof(ServerActionErrorCode), errorCode);
}
List<InventoryObject> ios = new List<InventoryObject>();
if (ItemInHand != null) {
SimObjPhysics so = ItemInHand.GetComponent<SimObjPhysics>();
InventoryObject io = new InventoryObject();
io.objectId = so.UniqueID;
io.objectType = Enum.GetName (typeof(SimObjType), so.Type);
ios.Add(io);
}
metaMessage.inventoryObjects = ios.ToArray();
// HAND
metaMessage.hand = new HandMetadata();
metaMessage.hand.position = AgentHand.transform.position;
metaMessage.hand.localPosition = AgentHand.transform.localPosition;
metaMessage.hand.rotation = AgentHand.transform.eulerAngles;
metaMessage.hand.localRotation = AgentHand.transform.localEulerAngles;
// EXTRAS
metaMessage.flatSurfacesOnGrid = flatten3DimArray(flatSurfacesOnGrid);
metaMessage.distances = flatten2DimArray(distances);
metaMessage.normals = flatten3DimArray(normals);
metaMessage.isOpenableGrid = flatten2DimArray(isOpenableGrid);
metaMessage.segmentedObjectIds = segmentedObjectIds;
metaMessage.objectIdsInBox = objectIdsInBox;
// Resetting things
flatSurfacesOnGrid = new float[0,0,0];
distances = new float[0,0];
normals = new float[0,0,0];
isOpenableGrid = new bool[0,0];
segmentedObjectIds = new string[0];
objectIdsInBox = new string[0];
return metaMessage;
}
// public string UniqueIDOfClosestInteractableObject()
//{
// string objectID = null;
// foreach (SimObjPhysics o in VisibleSimObjPhysics)
// {
// if(o.isInteractable == true && o.PrimaryProperty == SimObjPrimaryProperty.CanPickup)
// {
// objectID = o.UniqueID;
// // print(objectID);
// break;
// }
// }
// return objectID;
//}
=======
>>>>>>>
private ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simObj) {
ObjectMetadata objMeta = new ObjectMetadata();
GameObject o = simObj.gameObject;
objMeta.name = o.name;
objMeta.position = o.transform.position;
objMeta.rotation = o.transform.eulerAngles;
objMeta.objectType = Enum.GetName(typeof(SimObjType), simObj.Type);
objMeta.receptacle = simObj.ReceptacleTriggerBoxes != null && simObj.ReceptacleTriggerBoxes.Length != 0;
objMeta.openable = simObj.IsOpenable;
if (objMeta.openable) {
objMeta.isopen = simObj.IsOpen;
}
objMeta.pickupable = simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup;
objMeta.objectId = simObj.UniqueID;
objMeta.visible = simObj.isVisible;
// TODO: bounds necessary?
// Bounds bounds = simObj.Bounds;
// this.bounds3D = new [] {
// bounds.min.x,
// bounds.min.y,
// bounds.min.z,
// bounds.max.x,
// bounds.max.y,
// bounds.max.z,
// };
return objMeta;
}
private ObjectMetadata[] generateObjectMetadata()
{
// Encode these in a json string and send it to the server
SimObjPhysics[] simObjects = GameObject.FindObjectsOfType<SimObjPhysics>();
int numObj = simObjects.Length;
List<ObjectMetadata> metadata = new List<ObjectMetadata>();
Dictionary<string, List<string>> parentReceptacles = new Dictionary<string, List<string>> ();
for (int k = 0; k < numObj; k++) {
SimObjPhysics simObj = simObjects[k];
if (this.excludeObject(simObj.UniqueID)) {
continue;
}
ObjectMetadata meta = ObjectMetadataFromSimObjPhysics(simObj);
if (meta.receptacle)
{
List<string> receptacleObjectIds = simObj.Contains();
foreach (string oid in receptacleObjectIds)
{
if (!parentReceptacles.ContainsKey(oid)) {
parentReceptacles[oid] = new List<string>();
}
parentReceptacles[oid].Add(simObj.UniqueID);
}
meta.receptacleObjectIds = receptacleObjectIds.ToArray();
meta.receptacleCount = meta.receptacleObjectIds.Length;
}
meta.distance = Vector3.Distance(transform.position, simObj.gameObject.transform.position);
metadata.Add(meta);
}
foreach (ObjectMetadata meta in metadata) {
if (parentReceptacles.ContainsKey (meta.objectId)) {
meta.parentReceptacles = parentReceptacles[meta.objectId].ToArray();
}
}
return metadata.ToArray();
}
private T[] flatten2DimArray<T>(T[,] array) {
int nrow = array.GetLength(0);
int ncol = array.GetLength(1);
T[] flat = new T[nrow * ncol];
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
flat[i * ncol + j] = array[i, j];
}
}
return flat;
}
private T[] flatten3DimArray<T>(T[,,] array) {
int n0 = array.GetLength(0);
int n1 = array.GetLength(1);
int n2 = array.GetLength(2);
T[] flat = new T[n0 * n1 * n2];
for (int i = 0; i < n0; i++) {
for (int j = 0; j < n1; j++) {
for (int k = 0; k < n2; k++) {
flat[i * n1 * n2 + j * n2 + k] = array[i, j, k];
}
}
}
return flat;
}
public override MetadataWrapper generateMetadataWrapper()
{
// AGENT METADATA
ObjectMetadata agentMeta = new ObjectMetadata();
agentMeta.name = "agent";
agentMeta.position = transform.position;
agentMeta.rotation = transform.eulerAngles;
agentMeta.cameraHorizon = m_Camera.transform.rotation.eulerAngles.x;
if (agentMeta.cameraHorizon > 180) {
agentMeta.cameraHorizon -= 360;
}
// OTHER METADATA
MetadataWrapper metaMessage = new MetadataWrapper();
metaMessage.agent = agentMeta;
metaMessage.sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
metaMessage.objects = generateObjectMetadata();
metaMessage.collided = collidedObjects.Length > 0;
metaMessage.collidedObjects = collidedObjects;
metaMessage.screenWidth = Screen.width;
metaMessage.screenHeight = Screen.height;
metaMessage.cameraPosition = m_Camera.transform.position;
metaMessage.cameraOrthSize = cameraOrthSize;
cameraOrthSize = -1f;
metaMessage.fov = m_Camera.fieldOfView;
metaMessage.isStanding = (m_Camera.transform.localPosition - standingLocalCameraPosition).magnitude < 0.1f;
metaMessage.lastAction = lastAction;
metaMessage.lastActionSuccess = lastActionSuccess;
metaMessage.errorMessage = errorMessage;
if (errorCode != ServerActionErrorCode.Undefined) {
metaMessage.errorCode = Enum.GetName(typeof(ServerActionErrorCode), errorCode);
}
List<InventoryObject> ios = new List<InventoryObject>();
if (ItemInHand != null) {
SimObjPhysics so = ItemInHand.GetComponent<SimObjPhysics>();
InventoryObject io = new InventoryObject();
io.objectId = so.UniqueID;
io.objectType = Enum.GetName (typeof(SimObjType), so.Type);
ios.Add(io);
}
metaMessage.inventoryObjects = ios.ToArray();
// HAND
metaMessage.hand = new HandMetadata();
metaMessage.hand.position = AgentHand.transform.position;
metaMessage.hand.localPosition = AgentHand.transform.localPosition;
metaMessage.hand.rotation = AgentHand.transform.eulerAngles;
metaMessage.hand.localRotation = AgentHand.transform.localEulerAngles;
// EXTRAS
metaMessage.flatSurfacesOnGrid = flatten3DimArray(flatSurfacesOnGrid);
metaMessage.distances = flatten2DimArray(distances);
metaMessage.normals = flatten3DimArray(normals);
metaMessage.isOpenableGrid = flatten2DimArray(isOpenableGrid);
metaMessage.segmentedObjectIds = segmentedObjectIds;
metaMessage.objectIdsInBox = objectIdsInBox;
// Resetting things
flatSurfacesOnGrid = new float[0,0,0];
distances = new float[0,0];
normals = new float[0,0,0];
isOpenableGrid = new bool[0,0];
segmentedObjectIds = new string[0];
objectIdsInBox = new string[0];
return metaMessage;
} |
<<<<<<<
using System.Net;
=======
using System.Text.RegularExpressions;
>>>>>>>
using System.Net;
using System.Text.RegularExpressions;
<<<<<<<
var redirectUri = WebUtility.UrlDecode(request.RedirectUri);
=======
var redirectUri = request.RedirectUri;
>>>>>>>
var redirectUri = request.RedirectUri; |
<<<<<<<
using RhinoInside.Revit.Convert.Geometry;
=======
using RhinoInside.Revit.External.DB.Extensions;
>>>>>>>
using RhinoInside.Revit.Convert.Geometry;
using RhinoInside.Revit.External.DB.Extensions;
<<<<<<<
var centerCurve = wallInstance.Location as DB.LocationCurve;
DA.SetData("Center Curve", centerCurve.Curve.ToCurve());
=======
DA.SetData("Center Curve", wallInstance.GetCenterCurve());
>>>>>>>
DA.SetData("Center Curve", wallInstance.GetCenterCurve()); |
<<<<<<<
[TestMethod, Timeout(TestTimeout)]
public void WriteLockAsyncSynchronousReleaseAllowsOtherWriters() {
var testComplete = new ManualResetEventSlim(); // deliberately synchronous
var firstLockReleased = new AsyncManualResetEvent();
var firstLockTask = Task.Run(async delegate {
using (await this.asyncLock.WriteLockAsync()) {
}
// Synchronously block until the test is complete.
firstLockReleased.Set();
Assert.IsTrue(testComplete.Wait(AsyncDelay));
});
var secondLockTask = Task.Run(async delegate {
await firstLockReleased;
using (await this.asyncLock.WriteLockAsync()) {
}
});
Assert.IsTrue(secondLockTask.Wait(TestTimeout));
testComplete.Set();
Assert.IsTrue(firstLockTask.Wait(TestTimeout)); // rethrow any exceptions
}
#endregion
#region WriteLock tests
=======
>>>>>>>
[TestMethod, Timeout(TestTimeout)]
public void WriteLockAsyncSynchronousReleaseAllowsOtherWriters() {
var testComplete = new ManualResetEventSlim(); // deliberately synchronous
var firstLockReleased = new AsyncManualResetEvent();
var firstLockTask = Task.Run(async delegate {
using (await this.asyncLock.WriteLockAsync()) {
}
// Synchronously block until the test is complete.
firstLockReleased.Set();
Assert.IsTrue(testComplete.Wait(AsyncDelay));
});
var secondLockTask = Task.Run(async delegate {
await firstLockReleased;
using (await this.asyncLock.WriteLockAsync()) {
}
});
Assert.IsTrue(secondLockTask.Wait(TestTimeout));
testComplete.Set();
Assert.IsTrue(firstLockTask.Wait(TestTimeout)); // rethrow any exceptions
} |
<<<<<<<
#pragma warning disable AvoidAsyncSuffix // Avoid Async suffix
internal bool IsAsync { get; }
#pragma warning restore AvoidAsyncSuffix // Avoid Async suffix
=======
internal bool IsAsync { get; set; }
>>>>>>>
internal bool IsAsync { get; } |
<<<<<<<
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal Task QueueNeedProcessEvent {
get {
using (NoMessagePumpSyncContext.Default.Apply()) {
this.owner.Context.SyncContextLock.EnterUpgradeableReadLock();
try {
if (this.queueNeedProcessEvent == null) {
this.owner.Context.SyncContextLock.EnterWriteLock();
try {
// We pass in allowInliningWaiters: true,
// since we control all waiters and their continuations
// are be benign, and it makes it more efficient.
this.queueNeedProcessEvent = new AsyncManualResetEvent(allowInliningAwaiters: true);
}
finally {
this.owner.Context.SyncContextLock.ExitWriteLock();
}
}
return this.queueNeedProcessEvent.WaitAsync();
}
finally {
this.owner.Context.SyncContextLock.ExitUpgradeableReadLock();
}
}
}
}
=======
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal Task DequeuerResetEvent {
get {
using (NoMessagePumpSyncContext.Default.Apply()) {
lock (this.owner.Context.SyncContextLock) {
if (this.dequeuerResetState == null) {
// We pass in allowInliningWaiters: true,
// since we control all waiters and their continuations
// are be benign, and it makes it more efficient.
this.dequeuerResetState = new AsyncManualResetEvent(allowInliningAwaiters: true);
}
return this.dequeuerResetState.WaitAsync();
}
}
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal Task EnqueuedNotify {
get {
using (NoMessagePumpSyncContext.Default.Apply()) {
lock (this.owner.Context.SyncContextLock) {
var queue = this.ApplicableQueue;
if (queue != null) {
return queue.EnqueuedNotify;
}
// We haven't created an applicable queue yet. Return null,
// and our caller will call us back when DequeuerResetEvent is signaled.
return null;
}
}
}
}
>>>>>>>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal Task QueueNeedProcessEvent {
get {
using (NoMessagePumpSyncContext.Default.Apply()) {
lock (this.owner.Context.SyncContextLock) {
if (this.queueNeedProcessEvent == null) {
// We pass in allowInliningWaiters: true,
// since we control all waiters and their continuations
// are be benign, and it makes it more efficient.
this.queueNeedProcessEvent = new AsyncManualResetEvent(allowInliningAwaiters: true);
}
return this.queueNeedProcessEvent.WaitAsync();
}
}
}
}
<<<<<<<
Assumes.True(this.owner.Context.SyncContextLock.IsReadLockHeld || this.owner.Context.SyncContextLock.IsWriteLockHeld);
=======
Assumes.True(Monitor.IsEntered(this.owner.Context.SyncContextLock));
>>>>>>>
Assumes.True(Monitor.IsEntered(this.owner.Context.SyncContextLock));
<<<<<<<
AsyncManualResetEvent queueNeedProcessEvent = null;
this.owner.Context.SyncContextLock.EnterWriteLock();
try {
=======
AsyncManualResetEvent dequeuerResetState = null;
lock (this.owner.Context.SyncContextLock) {
>>>>>>>
AsyncManualResetEvent queueNeedProcessEvent = null;
lock (this.owner.Context.SyncContextLock) {
<<<<<<<
// Always arrange to pulse the event since folks waiting
// will likely want to know that the JoinableTask has completed.
queueNeedProcessEvent = this.queueNeedProcessEvent;
CleanupDependingSynchronousTask();
}
} finally {
this.owner.Context.SyncContextLock.ExitWriteLock();
=======
// Always arrange to pulse the dequeuer event since folks waiting
// will likely want to know that the JoinableTask has completed.
dequeuerResetState = this.dequeuerResetState;
}
>>>>>>>
// Always arrange to pulse the event since folks waiting
// will likely want to know that the JoinableTask has completed.
queueNeedProcessEvent = this.queueNeedProcessEvent;
CleanupDependingSynchronousTask();
}
<<<<<<<
this.owner.Context.SyncContextLock.EnterUpgradeableReadLock();
try {
if (this.IsCompleted) {
=======
var applicableJobs = new HashSet<JoinableTask>();
lock (this.owner.Context.SyncContextLock) {
if (this.IsCompleted) {
>>>>>>>
lock (this.owner.Context.SyncContextLock) {
if (this.IsCompleted) {
<<<<<<<
tryAgainAfter = this.QueueNeedProcessEvent;
return false;
} finally {
this.owner.Context.SyncContextLock.ExitUpgradeableReadLock();
=======
// Check all queues to see if any have immediate work.
foreach (var job in applicableJobs) {
if (job.TryDequeue(out work)) {
tryAgainAfter = null;
return true;
}
}
// None of the queues had work to do right away. Create a task that will complete when
// our caller should try again.
var wakeUpTasks = new List<Task>(applicableJobs.Count * 2);
foreach (var job in applicableJobs) {
wakeUpTasks.Add(job.DequeuerResetEvent);
var enqueuedTask = job.EnqueuedNotify;
if (enqueuedTask != null) {
wakeUpTasks.Add(enqueuedTask);
}
}
work = null;
// As an optimization, avoid a call to Task.WhenAny
// in the common case that we have just one task to
// wait for. It avoids a Task<Task> allocation.
// NOTICE: this optimization *does* mean we could
// return a Task that might fault or cancel, whereas
// Task.WhenAny tasks never do. But at present,
// the optimization is worthwhile and the tasks we
// include in the list above are only expected to
// complete successfully.
// And besides, our caller can deal with faulted tasks.
tryAgainAfter = wakeUpTasks.Count == 1
? wakeUpTasks[0]
: Task.WhenAny(wakeUpTasks);
return false;
>>>>>>>
tryAgainAfter = this.QueueNeedProcessEvent;
return false;
<<<<<<<
List<AsyncManualResetEvent> tasksNeedNotify = null;
this.owner.Context.SyncContextLock.EnterWriteLock();
try {
=======
AsyncManualResetEvent dequeuerResetState = null;
lock (this.owner.Context.SyncContextLock) {
>>>>>>>
List<AsyncManualResetEvent> tasksNeedNotify = null;
lock (this.owner.Context.SyncContextLock) { |
<<<<<<<
[Fact]
public async Task AllowReleaseAfterDispose()
{
using (await this.lck.EnterAsync().ConfigureAwait(false))
{
this.lck.Dispose();
}
}
[Fact]
public async Task DisposeDoesNotAffectEnter()
{
var first = this.lck.EnterAsync();
Assert.Equal(TaskStatus.RanToCompletion, first.Status);
var second = this.lck.EnterAsync();
Assert.False(second.IsCompleted);
this.lck.Dispose();
using (await first)
{
}
using (await second)
{
}
}
=======
/// <summary>
/// Verifies that the semaphore is entered in the order the requests are made.
/// </summary>
[Fact]
public async Task SemaphoreAwaitersAreQueued()
{
var holder = await this.lck.EnterAsync();
const int waiterCount = 5;
var cts = new CancellationTokenSource[waiterCount];
var waiters = new Task<AsyncSemaphore.Releaser>[waiterCount];
for (int i = 0; i < waiterCount; i++)
{
cts[i] = new CancellationTokenSource();
waiters[i] = this.lck.EnterAsync(cts[i].Token);
}
Assert.All(waiters, waiter => Assert.False(waiter.IsCompleted));
const int canceledWaiterIndex = 2;
cts[canceledWaiterIndex].Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => waiters[canceledWaiterIndex]).WithCancellation(this.TimeoutToken);
for (int i = 0; i < waiterCount; i++)
{
Assert.Equal(i == canceledWaiterIndex, waiters[i].IsCompleted);
}
holder.Dispose();
for (int i = 0; i < waiterCount; i++)
{
if (i == canceledWaiterIndex)
{
continue;
}
// Assert that all subsequent waiters have not yet entered the semaphore.
Assert.All(waiters.Skip(i + 1), w => Assert.True(w == waiters[canceledWaiterIndex] || !w.IsCompleted));
// Now accept and exit the semaphore.
using (await waiters[i].WithCancellation(this.TimeoutToken))
{
// We got the semaphore and will release it.
}
}
}
>>>>>>>
/// <summary>
/// Verifies that the semaphore is entered in the order the requests are made.
/// </summary>
[Fact]
public async Task SemaphoreAwaitersAreQueued()
{
var holder = await this.lck.EnterAsync();
const int waiterCount = 5;
var cts = new CancellationTokenSource[waiterCount];
var waiters = new Task<AsyncSemaphore.Releaser>[waiterCount];
for (int i = 0; i < waiterCount; i++)
{
cts[i] = new CancellationTokenSource();
waiters[i] = this.lck.EnterAsync(cts[i].Token);
}
Assert.All(waiters, waiter => Assert.False(waiter.IsCompleted));
const int canceledWaiterIndex = 2;
cts[canceledWaiterIndex].Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => waiters[canceledWaiterIndex]).WithCancellation(this.TimeoutToken);
for (int i = 0; i < waiterCount; i++)
{
Assert.Equal(i == canceledWaiterIndex, waiters[i].IsCompleted);
}
holder.Dispose();
for (int i = 0; i < waiterCount; i++)
{
if (i == canceledWaiterIndex)
{
continue;
}
// Assert that all subsequent waiters have not yet entered the semaphore.
Assert.All(waiters.Skip(i + 1), w => Assert.True(w == waiters[canceledWaiterIndex] || !w.IsCompleted));
// Now accept and exit the semaphore.
using (await waiters[i].WithCancellation(this.TimeoutToken))
{
// We got the semaphore and will release it.
}
}
}
[Fact]
public async Task AllowReleaseAfterDispose()
{
using (await this.lck.EnterAsync().ConfigureAwait(false))
{
this.lck.Dispose();
}
}
[Fact]
public async Task DisposeDoesNotAffectEnter()
{
var first = this.lck.EnterAsync();
Assert.Equal(TaskStatus.RanToCompletion, first.Status);
var second = this.lck.EnterAsync();
Assert.False(second.IsCompleted);
this.lck.Dispose();
using (await first)
{
}
using (await second)
{
}
} |
<<<<<<<
loopStarts = LoopDetection.FindLoops(methodInterpreter.MidRepresentation);
found = false;
foreach (var loopStart in loopStarts)
{
var loopEnd = LoopDetection.GetEndLoop(methodInterpreter.MidRepresentation.LocalOperations, loopStart);
var allDefinedVariables = GetAllDefinedVariables(methodInterpreter.MidRepresentation, loopStart, loopEnd);
var allInvariantInstructions = GetAllInvariantInstructions(methodInterpreter.MidRepresentation, loopStart, loopEnd,
allDefinedVariables);
if (allInvariantInstructions.Count == 0)
continue;
PerformMoveInstructions(methodInterpreter.MidRepresentation, loopStart, allInvariantInstructions);
methodInterpreter.MidRepresentation.UpdateUseDef();
Result = true;
found = true;
break;
}
=======
var loopEnd = LoopDetection.GetEndLoop(methodInterpreter.MidRepresentation.LocalOperations, loopStart);
var allDefinedVariables = GetAllDefinedVariables(methodInterpreter.MidRepresentation, loopStart, loopEnd);
var allInvariantInstructions = GetAllInvariantInstructions(methodInterpreter.MidRepresentation, loopStart, loopEnd,
allDefinedVariables);
if (allInvariantInstructions.Count == 0)
continue;
PerformMoveInstructions(methodInterpreter.MidRepresentation, loopStart, allInvariantInstructions);
Result = true;
return;
>>>>>>>
var loopEnd = LoopDetection.GetEndLoop(methodInterpreter.MidRepresentation.LocalOperations, loopStart);
var allDefinedVariables = GetAllDefinedVariables(methodInterpreter.MidRepresentation, loopStart, loopEnd);
var allInvariantInstructions = GetAllInvariantInstructions(methodInterpreter.MidRepresentation, loopStart, loopEnd,
allDefinedVariables);
if (allInvariantInstructions.Count == 0)
continue;
PerformMoveInstructions(methodInterpreter.MidRepresentation, loopStart, allInvariantInstructions);
methodInterpreter.MidRepresentation.UpdateUseDef();
Result = true;
return; |
<<<<<<<
using JustDecompile.API.Core;
=======
using System.Windows.Forms;
using JustDecompile.API.Core;
>>>>>>>
using JustDecompile.API.Core;
using System.Windows.Forms;
using JustDecompile.API.Core;
<<<<<<<
internal class ModuleDefinitionContextMenu : MenuItemBase
{
public ModuleDefinitionContextMenu(IEventAggregator eventAggregator)
: base(eventAggregator)
{
}
public override void AddMenuItems()
{
base.AddMenuItems();
this.MenuItems.Add(new MenuItem { Header = "Inject assembly reference", Command = new DelegateCommand(OnAssemblyReferenceClass) });
this.MenuItems.Add(new MenuItem { Header = "Inject resource", Command = new DelegateCommand(OnResourceClass) });
this.MenuItems.Add(new MenuSeparator());
this.MenuItems.Add(new MenuItem { Header = "Save as...", Command = new DelegateCommand(OnSaveAs) });
this.MenuItems.Add(new MenuItem { Header = "Reload", Command = new DelegateCommand(OnReaload) });
this.MenuItems.Add(new MenuItem { Header = "Rename", Command = new DelegateCommand(OnRename) });
this.MenuItems.Add(new MenuItem { Header = "Verify", Command = new DelegateCommand(OnVerify) });
}
private string GetFilePath()
{
if (this.StudioPackage.SelectedTreeViewItem == null)
{
return string.Empty;
}
switch (this.StudioPackage.SelectedTreeViewItem.TreeNodeType)
{
case TreeNodeType.AssemblyDefinition:
return ((IAssemblyDefinitionTreeViewItem)this.StudioPackage.SelectedTreeViewItem).AssemblyDefinition.MainModule.FilePath;
case TreeNodeType.AssemblyModuleDefinition:
return ((IAssemblyModuleDefinitionTreeViewItem)this.StudioPackage.SelectedTreeViewItem).ModuleDefinition.FilePath;
default:
return string.Empty;
}
}
private void OnAssemblyReferenceClass()
{
StudioPackage.Inject(EInjectType.AssemblyReference);
}
private void OnReaload()
{
StudioPackage.ReloadAssembly();
}
private void OnRename()
{
StudioPackage.Rename();
}
private void OnResourceClass()
{
StudioPackage.Inject(EInjectType.Resource);
}
private void OnSaveAs()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
bool saveAssembly = AssemblyHelper.TrySaveAssembly(assemblyDefinition, getOrginalFilePath);
if (saveAssembly)
{
foreach (ITreeViewItem item in JustDecompileCecilStudioPackage.UpdatedItems)
{
item.TreeNodeVisuals.SetForeground(null);
}
}
}
}
private void OnVerify()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
AssemblyHelper.VerifyAssembly(assemblyDefinition, getOrginalFilePath);
}
}
}
=======
internal class ModuleDefinitionContextMenu : MenuItemBase
{
public ModuleDefinitionContextMenu(IEventAggregator eventAggregator)
: base(eventAggregator)
{
}
public override void AddMenuItems()
{
base.AddMenuItems();
this.MenuItems.Add(new MenuItem { Header = "Inject assembly reference", Command = new DelegateCommand(OnAssemblyReferenceClass) });
this.MenuItems.Add(new MenuItem { Header = "Inject resource", Command = new DelegateCommand(OnResourceClass) });
this.MenuItems.Add(new MenuSeparator());
this.MenuItems.Add(new MenuItem { Header = "Save and reload", Command = new DelegateCommand(OnSave) });
this.MenuItems.Add(new MenuItem { Header = "Save as...", Command = new DelegateCommand(OnSaveAs) });
this.MenuItems.Add(new MenuItem { Header = "Reload", Command = new DelegateCommand(OnReaload) });
this.MenuItems.Add(new MenuItem { Header = "Rename", Command = new DelegateCommand(OnRename) });
this.MenuItems.Add(new MenuItem { Header = "Verify", Command = new DelegateCommand(OnVerify) });
}
private void OnSave()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
AssemblyHelper.SaveAssemblyInPlace(assemblyDefinition, getOrginalFilePath);
// 9/18/2014 - Robert McGinley ([email protected])
// Update each modified item in the assembly to it's normal color
foreach (ITreeViewItem item in JustDecompileCecilStudioPackage.UpdatedItems)
{
item.TreeNodeVisuals.SetForeground(null);
}
}
}
private string GetFilePath()
{
if (this.StudioPackage.SelectedTreeViewItem == null)
{
return string.Empty;
}
switch (this.StudioPackage.SelectedTreeViewItem.TreeNodeType)
{
case TreeNodeType.AssemblyDefinition:
return ((IAssemblyDefinitionTreeViewItem)this.StudioPackage.SelectedTreeViewItem).AssemblyDefinition.MainModule.FilePath;
case TreeNodeType.AssemblyModuleDefinition:
return ((IAssemblyModuleDefinitionTreeViewItem)this.StudioPackage.SelectedTreeViewItem).ModuleDefinition.FilePath;
default:
return string.Empty;
}
}
private void OnAssemblyReferenceClass()
{
StudioPackage.Inject(EInjectType.AssemblyReference);
}
private void OnReaload()
{
StudioPackage.ReloadAssembly();
}
private void OnRename()
{
StudioPackage.Rename();
}
private void OnResourceClass()
{
StudioPackage.Inject(EInjectType.Resource);
}
private void OnSaveAs()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
AssemblyHelper.SaveAssembly(assemblyDefinition, getOrginalFilePath);
// 9/18/2014 - Robert McGinley ([email protected])
// Update each modified item in the assembly to it's normal color
foreach (ITreeViewItem item in JustDecompileCecilStudioPackage.UpdatedItems)
{
item.TreeNodeVisuals.SetForeground(null);
}
}
}
private void OnVerify()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
AssemblyHelper.VerifyAssembly(assemblyDefinition, getOrginalFilePath);
}
}
}
>>>>>>>
internal class ModuleDefinitionContextMenu : MenuItemBase
{
public ModuleDefinitionContextMenu(IEventAggregator eventAggregator)
: base(eventAggregator)
{
}
public override void AddMenuItems()
{
base.AddMenuItems();
this.MenuItems.Add(new MenuItem { Header = "Inject assembly reference", Command = new DelegateCommand(OnAssemblyReferenceClass) });
this.MenuItems.Add(new MenuItem { Header = "Inject resource", Command = new DelegateCommand(OnResourceClass) });
this.MenuItems.Add(new MenuSeparator());
this.MenuItems.Add(new MenuItem { Header = "Save and reload", Command = new DelegateCommand(OnSave) });
this.MenuItems.Add(new MenuItem { Header = "Save as...", Command = new DelegateCommand(OnSaveAs) });
this.MenuItems.Add(new MenuItem { Header = "Reload", Command = new DelegateCommand(OnReaload) });
this.MenuItems.Add(new MenuItem { Header = "Rename", Command = new DelegateCommand(OnRename) });
this.MenuItems.Add(new MenuItem { Header = "Verify", Command = new DelegateCommand(OnVerify) });
}
private void OnSave()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
AssemblyHelper.SaveAssemblyInPlace(assemblyDefinition, getOrginalFilePath);
// 9/18/2014 - Robert McGinley ([email protected])
// Update each modified item in the assembly to it's normal color
foreach (ITreeViewItem item in JustDecompileCecilStudioPackage.UpdatedItems)
{
item.TreeNodeVisuals.SetForeground(null);
}
}
}
private string GetFilePath()
{
if (this.StudioPackage.SelectedTreeViewItem == null)
{
return string.Empty;
}
switch (this.StudioPackage.SelectedTreeViewItem.TreeNodeType)
{
case TreeNodeType.AssemblyDefinition:
return ((IAssemblyDefinitionTreeViewItem)this.StudioPackage.SelectedTreeViewItem).AssemblyDefinition.MainModule.FilePath;
case TreeNodeType.AssemblyModuleDefinition:
return ((IAssemblyModuleDefinitionTreeViewItem)this.StudioPackage.SelectedTreeViewItem).ModuleDefinition.FilePath;
default:
return string.Empty;
}
}
private void OnAssemblyReferenceClass()
{
StudioPackage.Inject(EInjectType.AssemblyReference);
}
private void OnReaload()
{
StudioPackage.ReloadAssembly();
}
private void OnRename()
{
StudioPackage.Rename();
}
private void OnResourceClass()
{
StudioPackage.Inject(EInjectType.Resource);
}
private void OnSaveAs()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
AssemblyHelper.SaveAssembly(assemblyDefinition, getOrginalFilePath);
// 9/18/2014 - Robert McGinley ([email protected])
// Update each modified item in the assembly to it's normal color
foreach (ITreeViewItem item in JustDecompileCecilStudioPackage.UpdatedItems)
{
item.TreeNodeVisuals.SetForeground(null);
}
}
}
}
}
private void OnVerify()
{
AssemblyDefinition assemblyDefinition = StudioPackage.GetCurrentAssemblyDefinition();
string getOrginalFilePath = GetFilePath();
if (!string.IsNullOrEmpty(getOrginalFilePath))
{
AssemblyHelper.VerifyAssembly(assemblyDefinition, getOrginalFilePath);
}
}
} |
<<<<<<<
using System.IO;
=======
using System;
using System.IO;
using System.Linq;
using System.Net;
>>>>>>>
using System.IO;
using System.Net;
<<<<<<<
return embeddedResource ?? new EmbeddedResource(GetType().Assembly, uiPath);
=======
if (resourceStream == null)
return new HttpResponseMessage(HttpStatusCode.NotFound);
HttpContent content = new StreamContent(resourceStream);
if (uiPath == "index.html")
content = CustomizeIndexContent(content);
content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeFor(uiPath));
return new HttpResponseMessage { Content = content };
>>>>>>>
return embeddedResource ?? new EmbeddedResource(GetType().Assembly, uiPath);
}
private HttpContent ContentFor(HttpRequestMessage request, EmbeddedResource embeddedResource)
{
var stream = embeddedResource.GetStream();
var content = embeddedResource.MediaType.StartsWith("text/")
? new StreamContent(ApplyConfigExpressions(stream, request))
: new StreamContent(stream);
content.Headers.ContentType = new MediaTypeHeaderValue(embeddedResource.MediaType);
return content; |
<<<<<<<
Console.WriteLine("Prime numbers: ");
var len = 1000000;
var pr = new Action(() =>
{
var primes = AddPrimes(len);
Console.Write(primes);
Console.WriteLine("Simpler Example: ");
});
pr();
}
private static int AddPrimes(int len)
{
var primes = 0;
for (var i = 2; i < len; i++)
{
if (i%2 == 0)
continue;
var isPrime = true;
for (var j = 2; j*j <= i; j++)
{
if (i%j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
primes++;
}
return primes;
=======
Console.WriteLine("NBody");
int n = 500000;
NBodySystem bodies = new NBodySystem();
Console.WriteLine(bodies.Energy());
for (int i = 0; i < n; i++) bodies.Advance(0.01);
Console.WriteLine(bodies.Energy());
>>>>>>>
Console.WriteLine("NBody");
int n = 500000;
NBodySystem bodies = new NBodySystem();
Console.WriteLine(bodies.Energy());
for (int i = 0; i < n; i++) bodies.Advance(0.01);
Console.WriteLine(bodies.Energy());
Console.WriteLine("Simpler Example: ");
});
pr(); |
<<<<<<<
return BeginLifetimeScope(tag, NoConfiguration);
=======
CheckNotDisposed();
CheckTagIsUnique(tag);
var registry = new CopyOnWriteRegistry(ComponentRegistry, () => CreateScopeRestrictedRegistry(tag, NoConfiguration));
var scope = new LifetimeScope(registry, this, tag);
scope.Disposer.AddInstanceForDisposal(registry);
RaiseBeginning(scope);
return scope;
}
private void CheckTagIsUnique(object tag)
{
ISharingLifetimeScope parentScope = this;
while (parentScope != RootLifetimeScope)
{
if (parentScope.Tag.Equals(tag))
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, LifetimeScopeResources.DuplicateTagDetected, tag));
}
parentScope = parentScope.ParentLifetimeScope;
}
>>>>>>>
return BeginLifetimeScope(tag, NoConfiguration);
}
private void CheckTagIsUnique(object tag)
{
ISharingLifetimeScope parentScope = this;
while (parentScope != RootLifetimeScope)
{
if (parentScope.Tag.Equals(tag))
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, LifetimeScopeResources.DuplicateTagDetected, tag));
}
parentScope = parentScope.ParentLifetimeScope;
} |
<<<<<<<
[Fact]
public void Decorator_Keyed_Generic()
{
BenchmarkRunner.Run<Decorators.KeyedGenericBenchmark>();
}
[Fact]
public void Decorator_Keyed_Nested()
{
BenchmarkRunner.Run<Decorators.KeyedNestedBenchmark>();
}
[Fact]
public void Decorator_Keyed_Simple()
{
BenchmarkRunner.Run<Decorators.KeyedSimpleBenchmark>();
}
[Fact]
public void Decorator_Keyless_Generic()
{
BenchmarkRunner.Run<Decorators.KeylessGenericBenchmark>();
}
[Fact]
public void Decorator_Keyless_Nested()
{
BenchmarkRunner.Run<Decorators.KeylessNestedBenchmark>();
}
[Fact]
public void Decorator_Keyless_Nested_Lambda()
{
BenchmarkRunner.Run<Decorators.KeylessNestedLambdaBenchmark>();
}
[Fact]
public void Decorator_Keyless_Simple()
{
BenchmarkRunner.Run<Decorators.KeylessSimpleBenchmark>();
}
[Fact]
public void Decorator_Keyless_Simple_Lambda()
{
BenchmarkRunner.Run<Decorators.KeylessSimpleLambdaBenchmark>();
}
=======
[Fact]
public void EnumerableResolve()
{
BenchmarkRunner.Run<EnumerableResolveBenchmark>();
}
>>>>>>>
[Fact]
public void Decorator_Keyed_Generic()
{
BenchmarkRunner.Run<Decorators.KeyedGenericBenchmark>();
}
[Fact]
public void Decorator_Keyed_Nested()
{
BenchmarkRunner.Run<Decorators.KeyedNestedBenchmark>();
}
[Fact]
public void Decorator_Keyed_Simple()
{
BenchmarkRunner.Run<Decorators.KeyedSimpleBenchmark>();
}
[Fact]
public void Decorator_Keyless_Generic()
{
BenchmarkRunner.Run<Decorators.KeylessGenericBenchmark>();
}
[Fact]
public void Decorator_Keyless_Nested()
{
BenchmarkRunner.Run<Decorators.KeylessNestedBenchmark>();
}
[Fact]
public void Decorator_Keyless_Nested_Lambda()
{
BenchmarkRunner.Run<Decorators.KeylessNestedLambdaBenchmark>();
}
[Fact]
public void Decorator_Keyless_Simple()
{
BenchmarkRunner.Run<Decorators.KeylessSimpleBenchmark>();
}
[Fact]
public void Decorator_Keyless_Simple_Lambda()
{
BenchmarkRunner.Run<Decorators.KeylessSimpleLambdaBenchmark>();
}
[Fact]
public void EnumerableResolve()
{
BenchmarkRunner.Run<EnumerableResolveBenchmark>();
} |
<<<<<<<
private readonly ConcurrentDictionary<IComponentRegistration, IEnumerable<IComponentRegistration>> _decorators
= new ConcurrentDictionary<IComponentRegistration, IEnumerable<IComponentRegistration>>();
private readonly IRegisteredServicesTracker _registeredServicesTracker;
=======
/// <summary>
/// Protects instance variables from concurrent access.
/// </summary>
private readonly object _synchRoot = new object();
/// <summary>
/// External registration sources.
/// </summary>
private readonly List<IRegistrationSource> _dynamicRegistrationSources = new List<IRegistrationSource>();
/// <summary>
/// All registrations.
/// </summary>
private readonly List<IComponentRegistration> _registrations = new List<IComponentRegistration>();
/// <summary>
/// Keeps track of the status of registered services.
/// </summary>
private readonly ConcurrentDictionary<Service, ServiceRegistrationInfo> _serviceInfo = new ConcurrentDictionary<Service, ServiceRegistrationInfo>();
/// <summary>
/// Initializes a new instance of the <see cref="ComponentRegistry"/> class.
/// </summary>
public ComponentRegistry()
: this(new Dictionary<string, object>())
{
}
>>>>>>>
private readonly ConcurrentDictionary<IComponentRegistration, IEnumerable<IComponentRegistration>> _decorators
= new ConcurrentDictionary<IComponentRegistration, IEnumerable<IComponentRegistration>>();
private readonly IRegisteredServicesTracker _registeredServicesTracker;
<<<<<<<
/// <inheritdoc />
public IEnumerable<IComponentRegistration> DecoratorsFor(IComponentRegistration registration)
{
if (registration == null) throw new ArgumentNullException(nameof(registration));
return _decorators.GetOrAdd(registration, r =>
{
var result = new List<IComponentRegistration>();
foreach (var service in r.Services)
{
if (service is DecoratorService || !(service is IServiceWithType swt)) continue;
var decoratorService = new DecoratorService(swt.ServiceType);
var decoratorRegistrations = _registeredServicesTracker.RegistrationsFor(decoratorService);
result.AddRange(decoratorRegistrations);
}
return result.OrderBy(d => d.GetRegistrationOrder()).ToArray();
});
}
=======
>>>>>>> |
<<<<<<<
using Autofac.Features.Decorators;
=======
using Autofac.Builder;
>>>>>>>
using Autofac.Builder;
using Autofac.Features.Decorators; |
<<<<<<<
public async Task TestDirectoryWithExistingDirectoryNameCreation(bool fileExists, bool dirExists)
=======
public void TestDirectoryWithExistingNodeNameCreation(bool fileExists, bool dirExists)
>>>>>>>
public async Task TestDirectoryWithExistingNodeNameCreation(bool fileExists, bool dirExists)
<<<<<<<
public async Task TestDirectoryWithExistingFileNameCreation()
{
var directoryServiceMock = new Mock<IDirectoryService>();
var fileServiceMock = new Mock<IFileService>();
fileServiceMock
.Setup(m => m.CheckIfExists(NewDirectoryPath))
.Returns(true);
var pathServiceMock = new Mock<IPathService>();
pathServiceMock
.Setup(m => m.Combine(DirectoryPath, DirectoryName))
.Returns(NewDirectoryPath);
var dialog = new CreateDirectoryDialogViewModel(
directoryServiceMock.Object, fileServiceMock.Object, pathServiceMock.Object);
await dialog.ActivateAsync(new CreateNodeNavigationParameter(DirectoryPath));
dialog.DirectoryName = DirectoryName;
Assert.False(dialog.CreateCommand.CanExecute(null));
}
[Fact]
public async Task TestDirectoryCreation()
=======
public void TestDirectoryCreation()
>>>>>>>
public async Task TestDirectoryCreation() |
<<<<<<<
AssemblyScanner = new AssemblyScanner(concreteTypeExtractor, CompositionRootTypeExtractor, CompositionRootExecutor);
PropertyDependencySelector = options.EnablePropertyInjection
? (IPropertyDependencySelector) new PropertyDependencySelector(new PropertySelector())
: new PropertyDependencyDisabler();
=======
GenericArgumentMapper = new GenericArgumentMapper();
AssemblyScanner = new AssemblyScanner(concreteTypeExtractor, CompositionRootTypeExtractor, CompositionRootExecutor, GenericArgumentMapper);
PropertyDependencySelector = new PropertyDependencySelector(new PropertySelector());
>>>>>>>
PropertyDependencySelector = options.EnablePropertyInjection
? (IPropertyDependencySelector) new PropertyDependencySelector(new PropertySelector())
: new PropertyDependencyDisabler();
GenericArgumentMapper = new GenericArgumentMapper();
AssemblyScanner = new AssemblyScanner(concreteTypeExtractor, CompositionRootTypeExtractor, CompositionRootExecutor, GenericArgumentMapper); |
<<<<<<<
=======
public string ForeignKey
{
get { return attributes.Get(x => x.ForeignKey); }
set { attributes.Set(x => x.ForeignKey, value); }
}
public int Length
{
get { return attributes.Get(x => x.Length); }
set { attributes.Set(x => x.Length, value); }
}
public string EntityName
{
get { return attributes.Get(x => x.EntityName); }
set { attributes.Set(x => x.EntityName, value); }
}
public int Offset
{
get { return attributes.Get(x => x.Offset); }
set { attributes.Set(x => x.Offset, value); }
}
public bool IsManyToMany { get; set; }
>>>>>>>
public int Offset
{
get { return attributes.Get(x => x.Offset); }
set { attributes.Set(x => x.Offset, value); }
} |
<<<<<<<
=======
if (mapping.IsManyToMany)
WriteManyToManyIndex(mapping);
else
if (mapping.HasValue(x => x.Offset))
WriteListIndex(mapping);
else
WriteIndex(mapping);
}
void WriteIndex(IndexMapping mapping)
{
>>>>>>>
if (mapping.HasValue(x => x.Offset))
WriteListIndex(mapping);
else
WriteIndex(mapping);
}
void WriteIndex(IndexMapping mapping)
{
<<<<<<<
=======
void WriteListIndex(IndexMapping mapping)
{
var element = document.AddElement("list-index");
element.WithAtt("base", mapping.Offset);
}
void WriteManyToManyIndex(IndexMapping mapping)
{
var element = document.AddElement("index-many-to-many");
if (mapping.HasValue(x => x.Type))
element.WithAtt("class", mapping.Type);
if (mapping.HasValue(x => x.EntityName))
element.WithAtt("entity-name", mapping.EntityName);
if (mapping.HasValue(x => x.ForeignKey))
element.WithAtt("foreign-key", mapping.ForeignKey);
}
>>>>>>>
void WriteListIndex(IndexMapping mapping)
{
var element = document.AddElement("list-index");
element.WithAtt("base", mapping.Offset);
} |
<<<<<<<
public IDictionary<string, string> UnmigratedAttributes
{
get { return unmigratedAttributes; }
}
public Type ContainingEntityType
{
get { return attributes.Get(x => x.ContainingEntityType); }
set { attributes.Set(x => x.ContainingEntityType, value); }
}
=======
>>>>>>>
public Type ContainingEntityType
{
get { return attributes.Get(x => x.ContainingEntityType); }
set { attributes.Set(x => x.ContainingEntityType, value); }
}
<<<<<<<
public string Access
{
get { return attributes.Get(x => x.Access); }
set { attributes.Set(x => x.Access, value); }
}
public PropertyInfo PropertyInfo { get; set; }
public IEnumerable<ColumnMapping> Columns
{
get { return columns; }
}
=======
>>>>>>> |
<<<<<<<
=======
private readonly IPublicHolidays _holidayCalendar;
>>>>>>>
<<<<<<<
=======
this._holidayCalendar = holidayCalendar;
>>>>>>>
<<<<<<<
this.ObservedDate = observedDate;
=======
this.Name = name;
}
/// <summary>
/// The previous working day for the holiday
/// </summary>
public DateTime PreviousWorkingDay
{
get { return _holidayCalendar.PreviousWorkingDay(HolidayDate); }
>>>>>>>
this.ObservedDate = observedDate;
<<<<<<<
public DateTime ObservedDate { get; set; }
=======
public DateTime NextWorkingDay
{
get { return _holidayCalendar.NextWorkingDay(HolidayDate); }
}
>>>>>>>
public DateTime ObservedDate { get; set; } |
<<<<<<<
=======
using FluentNHibernate.Mapping.Builders;
>>>>>>>
<<<<<<<
=======
using FluentNHibernate.Utils;
>>>>>>>
<<<<<<<
private readonly IList<FilterPart> childFilters = new List<FilterPart>();
private readonly Type entity;
=======
private readonly IList<FilterMapping> childFilters = new List<FilterMapping>();
>>>>>>>
private readonly IList<FilterPart> childFilters = new List<FilterPart>();
<<<<<<<
private IndexManyToManyPart manyToManyIndex;
private IndexPart index;
private readonly ColumnMappingCollection<ManyToManyPart<TChild>> childKeyColumns;
private readonly ColumnMappingCollection<ManyToManyPart<TChild>> parentKeyColumns;
private readonly Type childType;
private Type valueType;
private bool isTernary;
=======
readonly AttributeStore sharedColumnAttributes = new AttributeStore();
>>>>>>>
private IndexManyToManyPart manyToManyIndex;
private IndexPart index;
private readonly ColumnMappingCollection<ManyToManyPart<TChild>> childKeyColumns;
private readonly ColumnMappingCollection<ManyToManyPart<TChild>> parentKeyColumns;
private readonly Type childType;
private Type valueType;
private bool isTernary; |
<<<<<<<
EnsureDictionary();
manyToManyIndex = new IndexManyToManyPart();
=======
manyToManyIndex = new IndexManyToManyPart(typeof(ManyToManyPart<TChild>));
>>>>>>>
EnsureDictionary();
manyToManyIndex = new IndexManyToManyPart(typeof(ManyToManyPart<TChild>)); |
<<<<<<<
}
/// <summary>
/// Returns a list of folders found at current path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static List<string> folders(this string path)
=======
}
public static List<string> folders(this string path, bool recursive = false)
>>>>>>>
} /// <summary>
/// Returns a list of folders found at current path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static List<string> folders(this string path, bool recursive = false)
<<<<<<<
/// <summary>
/// Returns a list of folders found at current path.
/// </summary>
/// <param name="path"></param>
/// <param name="recursive">
/// This flag specifies whether the search operation should include all subdirectories or only the current directory.
/// </param>
/// <returns></returns>
public static List<string> folders(this string path, bool recursive)
=======
public static List<string> folders(this string path, string searchPattern, bool recursive = false)
>>>>>>>
public static List<string> folders(this string path, string searchPattern, bool recursive = false) |
<<<<<<<
using FluentNHibernate.Testing.DomainModel;
=======
using FluentNHibernate.Testing.Testing;
>>>>>>>
using FluentNHibernate.Testing.DomainModel;
using FluentNHibernate.Testing.Testing;
<<<<<<<
var compositeElementMapping = new CompositeElementMapping();
compositeElementMapping.AddProperty(new PropertyMapping(typeof(Record)));
=======
var mapping = new CompositeElementMapping();
mapping.AddReference(new ManyToOneMapping());
>>>>>>>
var mapping = new CompositeElementMapping();
mapping.AddReference(new ManyToOneMapping()); |
<<<<<<<
IEnumerable<Permission> permissions = _permissions.GetPermissions("Folder", file.FolderId).ToList();
file.Folder.Permissions = _permissions.EncodePermissions(permissions);
=======
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Folder, file.FolderId).ToList();
file.Folder.Permissions = _permissions.EncodePermissions(file.FolderId, permissions);
>>>>>>>
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Folder, file.FolderId).ToList();
file.Folder.Permissions = _permissions.EncodePermissions(permissions); |
<<<<<<<
IEnumerable<Permission> permissions = _permissions.GetPermissions("Page", page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(permissions);
=======
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Page, page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(page.PageId, permissions);
>>>>>>>
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Page, page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(permissions);
<<<<<<<
IEnumerable<Permission> permissions = _permissions.GetPermissions("Page", page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(permissions);
=======
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Page, page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(page.PageId, permissions);
>>>>>>>
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Page, page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(permissions);
<<<<<<<
IEnumerable<Permission> permissions = _permissions.GetPermissions("Page", page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(permissions);
=======
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Page, page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(page.PageId, permissions);
>>>>>>>
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Page, page.PageId).ToList();
page.Permissions = _permissions.EncodePermissions(permissions); |
<<<<<<<
IEnumerable<Permission> permissions = _permissions.GetPermissions("Folder", folder.FolderId).ToList();
folder.Permissions = _permissions.EncodePermissions(permissions);
=======
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Folder, folder.FolderId).ToList();
folder.Permissions = _permissions.EncodePermissions(folder.FolderId, permissions);
>>>>>>>
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Folder, folder.FolderId).ToList();
folder.Permissions = _permissions.EncodePermissions(permissions);
<<<<<<<
IEnumerable<Permission> permissions = _permissions.GetPermissions("Folder", folder.FolderId).ToList();
folder.Permissions = _permissions.EncodePermissions(permissions);
=======
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Folder, folder.FolderId).ToList();
folder.Permissions = _permissions.EncodePermissions(folder.FolderId, permissions);
>>>>>>>
IEnumerable<Permission> permissions = _permissions.GetPermissions(EntityNames.Folder, folder.FolderId).ToList();
folder.Permissions = _permissions.EncodePermissions(permissions); |
<<<<<<<
if(comboJoysticks.SelectedItem != null && (errmsg = VJoy.Acquire(uint.Parse(comboJoysticks.SelectedItem.ToString()))) != null) {
=======
Type readerType;
if(comboJoysticks.SelectedItem != null && (errmsg = VJoy.Acquire(uint.Parse(comboJoysticks.SelectedItem.ToString()))) != null) {
>>>>>>>
if(comboJoysticks.SelectedItem != null && (errmsg = VJoy.Acquire(uint.Parse(comboJoysticks.SelectedItem.ToString()))) != null) {
<<<<<<<
=======
serialReader = (SerialReader)Activator.CreateInstance(readerType);
>>>>>>> |
<<<<<<<
_dataFeed.RemoveSubscription(member.Symbol);
// remove symbol mappings for symbols removed from universes
SymbolCache.TryRemove(member.Symbol);
=======
foreach (var configuration in universe.GetSubscriptions(member))
{
_dataFeed.RemoveSubscription(configuration);
}
>>>>>>>
foreach (var configuration in universe.GetSubscriptions(member))
{
_dataFeed.RemoveSubscription(configuration);
}
// remove symbol mappings for symbols removed from universes
SymbolCache.TryRemove(member.Symbol); |
<<<<<<<
Compression.Zip(filename, data, Compression.CreateZipEntryName(_symbol.Value, _securityType, time, _resolution, _dataType));
Log.Trace("LeanDataWriter.Write(): Created: " + data);
=======
Compression.Zip(data, fileName, Compression.CreateZipEntryName(_symbol, _securityType, time, _resolution, _dataType));
Log.Trace("LeanDataWriter.Write(): Created: " + fileName);
>>>>>>>
Compression.Zip(data, fileName, Compression.CreateZipEntryName(_symbol.Value, _securityType, time, _resolution, _dataType));
Log.Trace("LeanDataWriter.Write(): Created: " + fileName);
<<<<<<<
file = Path.Combine(baseDirectory, _resolution.ToString().ToLower(), _symbol.ToString().ToLower(), Compression.CreateZipFileName(_symbol.Value, _securityType, time, _resolution));
=======
>>>>>>>
file = Path.Combine(baseDirectory, _resolution.ToString().ToLower(), _symbol.ToString().ToLower(), Compression.CreateZipFileName(_symbol, _securityType, time, _resolution)); |
<<<<<<<
var cached = CachedOrderIDs
.Where(o => o.Value.BrokerId.Contains(message.MakerOrderId) || o.Value.BrokerId.Contains(message.TakerOrderId))
.ToList();
=======
EmitTradeTick(message);
var cached = CachedOrderIDs.Where(o => o.Value.BrokerId.Contains(message.MakerOrderId) || o.Value.BrokerId.Contains(message.TakerOrderId));
>>>>>>>
EmitTradeTick(message);
var cached = CachedOrderIDs
.Where(o => o.Value.BrokerId.Contains(message.MakerOrderId) || o.Value.BrokerId.Contains(message.TakerOrderId))
.ToList(); |
<<<<<<<
var security = algo.AddSecurity(SecurityType.Forex, "BTCUSD", Resolution.Hour, Market.GDAX, false, 3.3m, true);
=======
var security = algo.AddSecurity(SecurityType.Crypto, "BTCUSD", Resolution.Hour, Market.Bitfinex, false, 3.3m, true);
>>>>>>>
var security = algo.AddSecurity(SecurityType.Crypto, "BTCUSD", Resolution.Hour, Market.GDAX, false, 3.3m, true);
<<<<<<<
var security = algo.AddSecurity(SecurityType.Forex, "BTCUSD", Resolution.Hour, Market.GDAX, false, 3.3m, true);
=======
var security = algo.AddSecurity(SecurityType.Crypto, "BTCUSD", Resolution.Hour, Market.Bitfinex, false, 3.3m, true);
>>>>>>>
var security = algo.AddSecurity(SecurityType.Crypto, "BTCUSD", Resolution.Hour, Market.GDAX, false, 3.3m, true);
<<<<<<<
var security = algo.AddSecurity(SecurityType.Forex, "BTCUSD", Resolution.Hour, Market.GDAX, false, 3.3m, true);
=======
var security = algo.AddSecurity(SecurityType.Crypto, "BTCUSD", Resolution.Hour, Market.Bitfinex, false, 3.3m, true);
>>>>>>>
var security = algo.AddSecurity(SecurityType.Crypto, "BTCUSD", Resolution.Hour, Market.GDAX, false, 3.3m, true); |
<<<<<<<
using System.Collections.Concurrent;
=======
using QuantConnect.Securities.Future;
>>>>>>>
using System.Collections.Concurrent;
using QuantConnect.Securities.Future; |
<<<<<<<
ProjectFinder.AssociateProjectWith(selectedProjectName, fileNames);
=======
var selectedProjectId = projectNameDialog.GetSelectedProjectId();
_projectFinder.AssociateProjectWith(selectedProjectName, fileNames);
>>>>>>>
var selectedProjectId = projectNameDialog.GetSelectedProjectId();
ProjectFinder.AssociateProjectWith(selectedProjectName, fileNames); |
<<<<<<<
=======
/// True if the data type has OHLC properties, even if dynamic data
public readonly bool IsTradeBar;
/// True if the data type has a Volume property, even if it is dynamic data
public readonly bool HasVolume;
>>>>>>>
/// True if the data type has OHLC properties, even if dynamic data
public readonly bool IsTradeBar;
/// True if the data type has a Volume property, even if it is dynamic data
public readonly bool HasVolume;
<<<<<<<
=======
case Resolution.Minute:
Increment = TimeSpan.FromMinutes(1);
break;
>>>>>>>
case Resolution.Minute:
Increment = TimeSpan.FromMinutes(1);
break;
<<<<<<<
case Resolution.Minute:
default:
Increment = TimeSpan.FromMinutes(1);
break;
=======
default:
throw new InvalidEnumArgumentException("Unexpected Resolution: " + resolution);
>>>>>>>
default:
throw new InvalidEnumArgumentException("Unexpected Resolution: " + resolution); |
<<<<<<<
Backtesting,
/// Use a brokerage for live/paper trading in realtime
Brokerage,
=======
Backtesting
/*
>>>>>>>
Backtesting,
/// Use a brokerage for live/paper trading in realtime
Brokerage,
/* |
<<<<<<<
[Fact]
public void ReadWithDefaultColumnsShouldHandleFirstRowAsRowData()
{
var lines = new[] { "not,a,row,header", "second,row,is,data", "third,row,is,data" };
var content = string.Join("\n", lines);
var reader = new StringReader(content);
var headers = new[] { "header1", "header2", "header3", "header4" };
var data = Reader.Read(reader, defaultColumns: headers);
Assert.Equal(headers, data.ColumnNames);
var enumerator = data.Rows.GetEnumerator();
int rowCount = 0;
foreach (var expectedRow in lines)
{
enumerator.MoveNext();
var value = string.Join(",", enumerator.Current.Values);
Assert.Equal(expectedRow, value);
rowCount++;
}
Assert.Equal(lines.Length, rowCount);
}
=======
[Fact]
public void ReadFromStreamWithDefaultColumnsShouldHandleFirstRowAsRowData()
{
DataTableBuilder builder = new DataTableBuilder();
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
var rows = new[] { "first,row,is,data", "second,row,is,johnny", "second,row,was,laura", };
foreach (var row in rows)
{
sw.WriteLine(row);
}
sw.Flush();
stream.Seek(0, SeekOrigin.Begin);
try
{
var lazy = builder.ReadLazy(stream, rows[0].Split(','));
Assert.Equal(rows[0].Split(','), lazy.ColumnNames);
var rowEnumerator = rows.Skip(0).GetEnumerator();
rowEnumerator.MoveNext();
var rowCount = 0;
foreach (var row in lazy.Rows)
{
Assert.Equal(rowEnumerator.Current, string.Join(",", row.Values));
rowEnumerator.MoveNext();
rowCount++;
}
Assert.Equal(rows.Length, rowCount);
}
finally
{
sw.Dispose();
stream.Dispose();
}
}
[Fact]
public void ReadFromTextReaderWithDefaultColumnsShouldHandleFirstRowAsRowData()
{
// arrange
var tmpFile = Path.GetTempFileName();
var rows = new[] { "first,row,is,data", "second,row,is,johnny", "second,row,was,laura", };
using (var sw = new StreamWriter(tmpFile))
{
foreach (var row in rows)
{
sw.WriteLine(row);
}
sw.Flush();
}
// act
try
{
var builder = new DataTableBuilder();
var lazy = builder.ReadLazy(tmpFile, rows[0].Split(','));
Assert.Equal(rows[0].Split(','), lazy.ColumnNames);
var rowEnumerator = rows.Skip(0).GetEnumerator();
rowEnumerator.MoveNext();
var rowCount = 0;
// assert
foreach (var row in lazy.Rows)
{
Assert.Equal(rowEnumerator.Current, string.Join(",", row.Values));
rowEnumerator.MoveNext();
rowCount++;
}
Assert.Equal(rows.Length, rowCount);
}
finally
{
// cleanup
File.Delete(tmpFile);
}
}
>>>>>>>
[Fact]
public void ReadWithDefaultColumnsShouldHandleFirstRowAsRowData()
{
var lines = new[] { "not,a,row,header", "second,row,is,data", "third,row,is,data" };
var content = string.Join("\n", lines);
var reader = new StringReader(content);
var headers = new[] { "header1", "header2", "header3", "header4" };
var data = Reader.Read(reader, defaultColumns: headers);
Assert.Equal(headers, data.ColumnNames);
var enumerator = data.Rows.GetEnumerator();
int rowCount = 0;
foreach (var expectedRow in lines)
{
enumerator.MoveNext();
var value = string.Join(",", enumerator.Current.Values);
Assert.Equal(expectedRow, value);
rowCount++;
}
Assert.Equal(lines.Length, rowCount);
}
[Fact]
public void ReadFromStreamWithDefaultColumnsShouldHandleFirstRowAsRowData()
{
DataTableBuilder builder = new DataTableBuilder();
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
var rows = new[] { "first,row,is,data", "second,row,is,johnny", "second,row,was,laura", };
foreach (var row in rows)
{
sw.WriteLine(row);
}
sw.Flush();
stream.Seek(0, SeekOrigin.Begin);
try
{
var lazy = builder.ReadLazy(stream, rows[0].Split(','));
Assert.Equal(rows[0].Split(','), lazy.ColumnNames);
var rowEnumerator = rows.Skip(0).GetEnumerator();
rowEnumerator.MoveNext();
var rowCount = 0;
foreach (var row in lazy.Rows)
{
Assert.Equal(rowEnumerator.Current, string.Join(",", row.Values));
rowEnumerator.MoveNext();
rowCount++;
}
Assert.Equal(rows.Length, rowCount);
}
finally
{
sw.Dispose();
stream.Dispose();
}
}
[Fact]
public void ReadFromTextReaderWithDefaultColumnsShouldHandleFirstRowAsRowData()
{
// arrange
var tmpFile = Path.GetTempFileName();
var rows = new[] { "first,row,is,data", "second,row,is,johnny", "second,row,was,laura", };
using (var sw = new StreamWriter(tmpFile))
{
foreach (var row in rows)
{
sw.WriteLine(row);
}
sw.Flush();
}
// act
try
{
var builder = new DataTableBuilder();
var lazy = builder.ReadLazy(tmpFile, rows[0].Split(','));
Assert.Equal(rows[0].Split(','), lazy.ColumnNames);
var rowEnumerator = rows.Skip(0).GetEnumerator();
rowEnumerator.MoveNext();
var rowCount = 0;
// assert
foreach (var row in lazy.Rows)
{
Assert.Equal(rowEnumerator.Current, string.Join(",", row.Values));
rowEnumerator.MoveNext();
rowCount++;
}
Assert.Equal(rows.Length, rowCount);
}
finally
{
// cleanup
File.Delete(tmpFile);
}
} |
<<<<<<<
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SynthesisAPI.PreferenceManager;
=======
>>>>>>>
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
<<<<<<<
public static void TestDirectory()
{
Directory dir = new Directory("directory", TestGuid, Permissions.PublicRead);
FileSystem.AddResource("/modules", dir);
Directory test_dir = (Directory)FileSystem.Traverse("/modules/directory");
Console.WriteLine(ReferenceEquals(test_dir, dir));
Directory root = (Directory)test_dir.Traverse("../..");
Console.WriteLine(ReferenceEquals(root, FileSystem.RootNode));
}
public static void TestRawEntry()
{
RawEntry raw_entry = new RawEntry("test.txt", TestGuid, Permissions.PublicRead, "/controller/TestApi/test.txt");
FileSystem.AddResource("/modules", raw_entry);
raw_entry.Load();
string str = Encoding.UTF8.GetString(raw_entry.SharedStream.ReadBytes(30));
Console.WriteLine("\"" + str + "\"");
raw_entry.SharedStream.WriteBytes("Goodbye World!");
raw_entry.SharedStream.SetStreamPosition(0);
str = Encoding.UTF8.GetString(raw_entry.SharedStream.ReadBytes(30));
Console.WriteLine(str);
}
public static void TestSavingPreferences()
{
PreferenceManager.SetPreference("test_api", "name", "Hunter Barclay");
PreferenceManager.SetPreference("test_api", "age", 17);
PreferenceManager.SetPreference("test_api", "some_float", 1.5837f);
PreferenceManager.Save("test-prefs-2.json");
}
public static void TestLoadingPreferences()
{
PreferenceManager.SetPreference("test_api", "name", "Gerald");
PreferenceManager.Load("test-prefs-2.json", overrideChanges: false);
string name = PreferenceManager.GetPreference<string>("test_api", "name");
int age = PreferenceManager.GetPreference<int>("test_api", "age");
float someFloat = PreferenceManager.GetPreference<float>("test_api", "some_float");
Console.WriteLine(string.Format("Name: {0}\nAge: {1}\nSome Float: {2}", name, age, someFloat));
}
=======
>>>>>>> |
<<<<<<<
// We will need these
public List<List<UnityRigidNode>> PWMAssignments;
public Dictionary<List<int>, UnityRigidNode> SolenoidAssignments;
public float speed = 5;
public int[] motors = { 1, 2, 3, 4 };
RigidNode_Base skeleton;
unityPacket udp = new unityPacket();
List<Vector3> unityWheelData = new List<Vector3>();
string filePath = "C:/Users/t_waggn/Documents/Skeleton/Skeleton/";
public enum WheelPositions
{
FL = 1,
FR = 2,
BL = 3,
BR = 4
}
=======
// We will need these
public List<List<UnityRigidNode>> PWMAssignments;
public float speed = 5;
public int[] motors = { 1, 2, 3, 4 };
RigidNode_Base skeleton;
unityPacket udp = new unityPacket();
List<Vector3> unityWheelData = new List<Vector3>();
// int robots = 0;
string filePath = "C:/Users/" + Environment.UserName + "/Documents/Skeleton/";
public enum WheelPositions
{
FL = 1,
FR = 2,
BL = 3,
BR = 4
}
/*
>>>>>>>
// We will need these
public List<List<UnityRigidNode>> PWMAssignments;
public float speed = 5;
public int[] motors = { 1, 2, 3, 4 };
RigidNode_Base skeleton;
unityPacket udp = new unityPacket();
List<Vector3> unityWheelData = new List<Vector3>();
// int robots = 0;
string filePath = "C:/Users/" + Environment.UserName + "/Documents/Skeleton/";
public enum WheelPositions
{
FL = 1,
FR = 2,
BL = 3,
BR = 4
}
<<<<<<<
DriveJoints.UpdateAllMotors(skeleton, packet.dio);
DriveJoints.UpdateSolenoids(skeleton, packet.solenoid);
=======
DriveJoints.UpdateAllMotors(skeleton, packet.dio);
>>>>>>>
DriveJoints.UpdateAllMotors(skeleton, packet.dio);
DriveJoints.UpdateSolenoids(skeleton, packet.solenoid); |
<<<<<<<
pwm[0] +=
(InputControl.GetButton(Controls.buttons.forward) ? SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.backward) ? -SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.left) ? -SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.right) ? SPEED_ARROW_PWM : 0.0f);
pwm[1] +=
(InputControl.GetButton(Controls.buttons.forward) ? SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.backward) ? -SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.left) ? SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.right) ? -SPEED_ARROW_PWM : 0.0f);
pwm[2] +=
(InputControl.GetButton(Controls.buttons.pwm2Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm2Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[3] +=
(InputControl.GetButton(Controls.buttons.pwm3Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm3Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[4] +=
(InputControl.GetButton(Controls.buttons.pwm4Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm4Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[5] +=
(InputControl.GetButton(Controls.buttons.pwm5Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm5Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[6] +=
(InputControl.GetButton(Controls.buttons.pwm6Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm6Neg)) ? -SPEED_ARROW_PWM : 0f;
#region Old Controls: 2017 and Older
//Old ControlKeys; accessing keys assigned in ResetDefaults() method in Controls.cs script
//pwm[0] +=
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Forward]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Backward]) ? -SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Left]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Right]) ? -SPEED_ARROW_PWM : 0.0f);
//pwm[1] +=
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Forward]) ? -SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Backward]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Left]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Right]) ? -SPEED_ARROW_PWM : 0.0f);
//pwm[2] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm2Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm2Neg]) ? -SPEED_ARROW_PWM : 0f;
//pwm[3] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm3Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm3Neg]) ? -SPEED_ARROW_PWM : 0f;
//pwm[4] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm4Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm4Neg]) ? -SPEED_ARROW_PWM : 0f;
//pwm[5] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm5Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm5Plus]) ? -SPEED_ARROW_PWM : 0f;
//pwm[6] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm6Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm6Plus]) ? -SPEED_ARROW_PWM : 0f;
#endregion
=======
if (Input.anyKey)
{
pwm[0] +=
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Forward]) ? -SPEED_ARROW_PWM : 0.0f) +
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Backward]) ? SPEED_ARROW_PWM : 0.0f) +
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Left]) ? -SPEED_ARROW_PWM : 0.0f) +
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Right]) ? SPEED_ARROW_PWM : 0.0f);
pwm[1] +=
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Forward]) ? SPEED_ARROW_PWM : 0.0f) +
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Backward]) ? -SPEED_ARROW_PWM : 0.0f) +
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Left]) ? -SPEED_ARROW_PWM : 0.0f) +
(Input.GetKey(Controls.ControlKey[(int)Controls.Control.Right]) ? SPEED_ARROW_PWM : 0.0f);
pwm[2] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm2Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm2Neg]) ? -SPEED_ARROW_PWM : 0f;
pwm[3] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm3Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm3Neg]) ? -SPEED_ARROW_PWM : 0f;
pwm[4] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm4Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm4Neg]) ? -SPEED_ARROW_PWM : 0f;
pwm[5] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm5Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm5Plus]) ? -SPEED_ARROW_PWM : 0f;
pwm[6] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm6Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm6Plus]) ? -SPEED_ARROW_PWM : 0f;
}
>>>>>>>
pwm[0] +=
(InputControl.GetButton(Controls.buttons.forward) ? -SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.backward) ? SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.left) ? -SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.right) ? SPEED_ARROW_PWM : 0.0f);
pwm[1] +=
(InputControl.GetButton(Controls.buttons.forward) ? SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.backward) ? -SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.left) ? -SPEED_ARROW_PWM : 0.0f) +
(InputControl.GetButton(Controls.buttons.right) ? SPEED_ARROW_PWM : 0.0f);
pwm[2] +=
(InputControl.GetButton(Controls.buttons.pwm2Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm2Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[3] +=
(InputControl.GetButton(Controls.buttons.pwm3Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm3Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[4] +=
(InputControl.GetButton(Controls.buttons.pwm4Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm4Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[5] +=
(InputControl.GetButton(Controls.buttons.pwm5Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm5Neg)) ? -SPEED_ARROW_PWM : 0f;
pwm[6] +=
(InputControl.GetButton(Controls.buttons.pwm6Plus)) ? SPEED_ARROW_PWM :
(InputControl.GetButton(Controls.buttons.pwm6Neg)) ? -SPEED_ARROW_PWM : 0f;
#region Old Controls: 2017 and Older
//Old ControlKeys; accessing keys assigned in ResetDefaults() method in Controls.cs script
//pwm[0] +=
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Forward]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Backward]) ? -SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Left]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Right]) ? -SPEED_ARROW_PWM : 0.0f);
//pwm[1] +=
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Forward]) ? -SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Backward]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Left]) ? SPEED_ARROW_PWM : 0.0f) +
// (Input.GetKey(Controls.ControlKey[(int)Controls.Control.Right]) ? -SPEED_ARROW_PWM : 0.0f);
//pwm[2] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm2Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm2Neg]) ? -SPEED_ARROW_PWM : 0f;
//pwm[3] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm3Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm3Neg]) ? -SPEED_ARROW_PWM : 0f;
//pwm[4] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm4Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm4Neg]) ? -SPEED_ARROW_PWM : 0f;
//pwm[5] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm5Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm5Plus]) ? -SPEED_ARROW_PWM : 0f;
//pwm[6] += Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm6Plus]) ? SPEED_ARROW_PWM : Input.GetKey(Controls.ControlKey[(int)Controls.Control.pwm6Plus]) ? -SPEED_ARROW_PWM : 0f;
#endregion |
<<<<<<<
RigidNode_Base Skeleton = ExportSkeleteonLite(InventorManager.Instance.ComponentOccurrences.OfType<ComponentOccurrence>().ToList());
=======
InventorManager.Instance.UserInterfaceManager.UserInteractionDisabled = true;
>>>>>>>
<<<<<<<
/// The lightweight equivalent of the 'Add From Inventor' button in the <see cref="ExporterForm"/>. Used in <see cref="ExportMeshesLite(RigidNode_Base)"/>
/// </summary>
/// <param name="occurrences"></param>
/// <returns></returns>
public RigidNode_Base ExportSkeleteonLite(List<ComponentOccurrence> occurrences)
{
if (occurrences.Count == 0)
{
throw new ArgumentException("ERROR: 0 Occurrences passed to ExportSkeletonLite", "occurrences");
}
#region CenterJoints
int NumCentered = 0;
LiteExporterForm.Instance.SetProgress(NumCentered, occurrences.Count, "Centering Joints");
foreach (ComponentOccurrence component in occurrences)
{
Exporter.CenterAllJoints(component);
NumCentered++;
LiteExporterForm.Instance.SetProgress(NumCentered, occurrences.Count);
}
#endregion
#region Build Models
//Getting Rigid Body Info...
LiteExporterForm.Instance.SetProgress("Getting Rigid Body Info...");
NameValueMap RigidGetOptions = InventorManager.Instance.TransientObjects.CreateNameValueMap();
RigidGetOptions.Add("DoubleBearing", false);
RigidBodyResults RawRigidResults = InventorManager.Instance.AssemblyDocument.ComponentDefinition.RigidBodyAnalysis(RigidGetOptions);
CustomRigidResults RigidResults = new CustomRigidResults(RawRigidResults);
//Building Model...
LiteExporterForm.Instance.SetProgress("Building Model...");
RigidBodyCleaner.CleanGroundedBodies(RigidResults);
RigidNode baseNode = RigidBodyCleaner.BuildAndCleanDijkstra(RigidResults);
#endregion
#region Cleaning Up
//Cleaning Up...
LiteExporterForm.Instance.SetProgress("Cleaning Up...");
List<RigidNode_Base> nodes = new List<RigidNode_Base>();
baseNode.ListAllNodes(nodes);
foreach (RigidNode_Base node in nodes)
{
node.ModelFileName = ((RigidNode)node).group.ToString();
node.ModelFullID = node.GetModelID();
}
#endregion
return baseNode;
}
/// <summary>
=======
>>>>>>> |
<<<<<<<
public static Inventor.Application INVENTOR_APPLICATION;
public static void LoadInventorInstance()
{
if (INVENTOR_APPLICATION != null) return;
try
{
INVENTOR_APPLICATION = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");
}
catch (COMException e)
{
Console.WriteLine(e);
throw new Exception("Could not get a running instance of Inventor");
}
}
public static void ReleaseInventorInstance()
{
if (INVENTOR_APPLICATION == null) return;
try
{
Marshal.ReleaseComObject(INVENTOR_APPLICATION);
}
catch (COMException e)
{
Console.WriteLine(e);
throw new Exception("Could not release Inventor (Is it already closed?)");
}
finally
{
INVENTOR_APPLICATION = null;
}
}
=======
>>>>>>> |
<<<<<<<
Physics.gravity = new Vector3(0,-9.8f,0);
string homePath = (System.Environment.OSVersion.Platform == PlatformID.Unix || System.Environment.OSVersion.Platform == PlatformID.MacOSX) ? System.Environment.GetEnvironmentVariable("HOME") : System.Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
//Now you can use a default directory to load all of the files
Directory.CreateDirectory(homePath + "/Documents/Skeleton/Skeleton/");
string path = homePath + "/Documents/Skeleton/Skeleton/";
List<RigidNode_Base> names = new List<RigidNode_Base>();
RigidNode_Base.NODE_FACTORY = delegate()
{
return new UnityRigidNode();
};
skeleton = BXDJSkeleton.ReadSkeleton(homePath + "/Documents/Skeleton/Skeleton/skeleton.bxdj");
skeleton.ListAllNodes(names);
foreach (RigidNode_Base node in names)
=======
if (GUI.Button (new Rect (10, 10, 90, 30), "Load Model"))
>>>>>>>
Physics.gravity = new Vector3(0,-9.8f,0);
string homePath = (System.Environment.OSVersion.Platform == PlatformID.Unix || System.Environment.OSVersion.Platform == PlatformID.MacOSX) ? System.Environment.GetEnvironmentVariable("HOME") : System.Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
//Now you can use a default directory to load all of the files
Directory.CreateDirectory(homePath + "/Documents/Skeleton/Skeleton/");
string path = homePath + "/Documents/Skeleton/Skeleton/";
List<RigidNode_Base> names = new List<RigidNode_Base>();
RigidNode_Base.NODE_FACTORY = delegate()
{
return new UnityRigidNode();
};
skeleton = BXDJSkeleton.ReadSkeleton(homePath + "/Documents/Skeleton/Skeleton/skeleton.bxdj");
skeleton.ListAllNodes(names);
foreach (RigidNode_Base node in names)
if (GUI.Button (new Rect (10, 10, 90, 30), "Load Model")) |
<<<<<<<
private FixedQueue<List<ContactDescriptor>> contactPoints;
//Indicate different state (begin reset, resetting, end reset)
private bool resetting;
private bool beginReset;
=======
//Flags to tell different types of reset
private bool isResettingOrientation;
private bool isResetting;
>>>>>>>
private FixedQueue<List<ContactDescriptor>> contactPoints;
//Flags to tell different types of reset
private bool isResettingOrientation;
private bool isResetting;
<<<<<<<
resetting = false;
beginReset = false;
contactPoints = new FixedQueue<List<ContactDescriptor>>(Tracker.Length);
=======
isResettingOrientation = false;
>>>>>>>
contactPoints = new FixedQueue<List<ContactDescriptor>>(Tracker.Length);
isResettingOrientation = false;
<<<<<<<
if (!beginReset && !resetting && Input.GetKey(KeyCode.Space))
=======
if (!isResetting)
>>>>>>>
if (!isResetting && Input.GetKey(KeyCode.Space))
<<<<<<<
//For Ultrasonic testing purposes
//ultraSensorObject = GameObject.Find("node_0.bxda");
//ultraSensor = ultraSensorObject.AddComponent<UltraSensor>();
=======
nodeToRobotOffset = robotObject.transform.GetChild(0).transform.position - robotObject.transform.position;
>>>>>>>
//For Ultrasonic testing purposes
//ultraSensorObject = GameObject.Find("node_0.bxda");
//ultraSensor = ultraSensorObject.AddComponent<UltraSensor>();
nodeToRobotOffset = robotObject.transform.GetChild(0).transform.position - robotObject.transform.position;
<<<<<<<
private void UpdateTrackers()
{
int numSteps = physicsWorld.frameCount - lastFrameCount;
if (tracking)
{
// numSteps should only == 1 or 0, but if it's ever > 1 the system won't break.
for (int i = 0; i < numSteps; i++)
{
foreach (Tracker t in Trackers)
t.AddState();
List<ContactDescriptor> frameContacts = null;
int numManifolds = physicsWorld.world.Dispatcher.NumManifolds;
for (int j = 0; j < numManifolds; j++)
{
PersistentManifold contactManifold = physicsWorld.world.Dispatcher.GetManifoldByIndexInternal(j);
BRigidBody obA = (BRigidBody)contactManifold.Body0.UserObject;
BRigidBody obB = (BRigidBody)contactManifold.Body1.UserObject;
if (!obA.gameObject.name.StartsWith("node") && !obB.gameObject.name.StartsWith("node"))
continue;
List<ContactDescriptor> manifoldContacts = new List<ContactDescriptor>();
int numContacts = contactManifold.NumContacts;
if (numContacts == 0)
continue;
for (int k = 0; k < numContacts; k++)
{
ManifoldPoint cp = contactManifold.GetContactPoint(k);
manifoldContacts.Add(new ContactDescriptor
{
AppliedImpulse = cp.AppliedImpulse,
Position = (cp.PositionWorldOnA + cp.PositionWorldOnB) * 0.5f
});
}
ContactDescriptor consolidatedContact;
if (obA.gameObject.name.StartsWith("node"))
consolidatedContact = new ContactDescriptor
{
RobotBody = obA,
OtherBody = obB,
};
else
consolidatedContact = new ContactDescriptor
{
RobotBody = obB,
OtherBody = obA
};
foreach (ContactDescriptor cd in manifoldContacts)
{
consolidatedContact.AppliedImpulse += cd.AppliedImpulse;
consolidatedContact.Position += cd.Position;
}
consolidatedContact.Position /= numContacts;
if (frameContacts == null)
frameContacts = new List<ContactDescriptor>();
frameContacts.Add(consolidatedContact);
}
contactPoints.Add(frameContacts);
}
}
lastFrameCount += numSteps;
}
=======
/// <summary>
/// Return the robot to robotStartPosition and destroy extra game pieces
/// </summary>
/// <param name="resetTransform"></param>
>>>>>>>
private void UpdateTrackers()
{
int numSteps = physicsWorld.frameCount - lastFrameCount;
if (tracking)
{
// numSteps should only == 1 or 0, but if it's ever > 1 the system won't break.
for (int i = 0; i < numSteps; i++)
{
foreach (Tracker t in Trackers)
t.AddState();
List<ContactDescriptor> frameContacts = null;
int numManifolds = physicsWorld.world.Dispatcher.NumManifolds;
for (int j = 0; j < numManifolds; j++)
{
PersistentManifold contactManifold = physicsWorld.world.Dispatcher.GetManifoldByIndexInternal(j);
BRigidBody obA = (BRigidBody)contactManifold.Body0.UserObject;
BRigidBody obB = (BRigidBody)contactManifold.Body1.UserObject;
if (!obA.gameObject.name.StartsWith("node") && !obB.gameObject.name.StartsWith("node"))
continue;
List<ContactDescriptor> manifoldContacts = new List<ContactDescriptor>();
int numContacts = contactManifold.NumContacts;
if (numContacts == 0)
continue;
for (int k = 0; k < numContacts; k++)
{
ManifoldPoint cp = contactManifold.GetContactPoint(k);
manifoldContacts.Add(new ContactDescriptor
{
AppliedImpulse = cp.AppliedImpulse,
Position = (cp.PositionWorldOnA + cp.PositionWorldOnB) * 0.5f
});
}
ContactDescriptor consolidatedContact;
if (obA.gameObject.name.StartsWith("node"))
consolidatedContact = new ContactDescriptor
{
RobotBody = obA,
OtherBody = obB,
};
else
consolidatedContact = new ContactDescriptor
{
RobotBody = obB,
OtherBody = obA
};
foreach (ContactDescriptor cd in manifoldContacts)
{
consolidatedContact.AppliedImpulse += cd.AppliedImpulse;
consolidatedContact.Position += cd.Position;
}
consolidatedContact.Position /= numContacts;
if (frameContacts == null)
frameContacts = new List<ContactDescriptor>();
frameContacts.Add(consolidatedContact);
}
contactPoints.Add(frameContacts);
}
}
lastFrameCount += numSteps;
}
/// <summary>
/// Return the robot to robotStartPosition and destroy extra game pieces
/// </summary>
/// <param name="resetTransform"></param>
<<<<<<<
contactPoints.Clear(null);
resetting = false;
=======
t.Tracking = true;
}
>>>>>>>
foreach (RigidNode n in rootNode.ListAllNodes())
{
RigidBody r = (RigidBody)n.MainObject.GetComponent<BRigidBody>().GetCollisionObject();
r.LinearVelocity = r.AngularVelocity = BulletSharp.Math.Vector3.Zero;
r.LinearFactor = r.AngularFactor = BulletSharp.Math.Vector3.Zero;
if (!resetTransform)
continue;
BulletSharp.Math.Matrix newTransform = r.WorldTransform;
newTransform.Origin = (robotStartPosition + n.ComOffset).ToBullet();
newTransform.Basis = BulletSharp.Math.Matrix.Identity;
r.WorldTransform = newTransform;
}
RotateRobot(robotStartOrientation);
foreach (GameObject g in extraElements)
UnityEngine.Object.Destroy(g);
if (isResetting)
{
Debug.Log("is resetting!");
}
}
/// <summary>
/// Can move robot around in this state, update robotStartPosition if hit enter
/// </summary>
void Resetting()
{
if (Input.GetMouseButton(1))
{
//Transform rotation along the horizontal plane
Vector3 rotation = new Vector3(0f,
Input.GetKey(KeyCode.RightArrow) ? ResetVelocity : Input.GetKey(KeyCode.LeftArrow) ? -ResetVelocity : 0f,
0f);
if (!rotation.Equals(Vector3.zero))
RotateRobot(rotation);
}
else
{
//Transform position
Vector3 transposition = new Vector3(
Input.GetKey(KeyCode.RightArrow) ? ResetVelocity : Input.GetKey(KeyCode.LeftArrow) ? -ResetVelocity : 0f,
0f,
Input.GetKey(KeyCode.UpArrow) ? ResetVelocity : Input.GetKey(KeyCode.DownArrow) ? -ResetVelocity : 0f);
if (!transposition.Equals(Vector3.zero))
TransposeRobot(transposition);
}
//Update robotStartPosition when hit enter
if (Input.GetKey(KeyCode.Return))
{
robotStartOrientation = ((RigidNode)rootNode.ListAllNodes()[0]).MainObject.GetComponent<BRigidBody>().GetCollisionObject().WorldTransform.Basis;
robotStartPosition = robotObject.transform.GetChild(0).transform.position - nodeToRobotOffset;
//Debug.Log(robotStartPosition);
EndReset();
}
}
/// <summary>
/// Put robot back down and switch back to normal state
/// </summary>
void EndReset()
{
isResetting = false;
isResettingOrientation = false;
foreach (RigidNode n in rootNode.ListAllNodes())
{
RigidBody r = (RigidBody)n.MainObject.GetComponent<BRigidBody>().GetCollisionObject();
r.LinearFactor = r.AngularFactor = BulletSharp.Math.Vector3.One;
}
foreach (Tracker t in UnityEngine.Object.FindObjectsOfType<Tracker>()) {
t.Clear();
contactPoints.Clear(null);
} |
<<<<<<<
using System.Threading;
using System.Threading.Tasks;
=======
using SynthesisAPI.Utilities;
>>>>>>>
using System.Threading;
using System.Threading.Tasks;
using SynthesisAPI.Utilities;
<<<<<<<
/// <summary>
/// Loads a JSON file asynchronously and loads preference data
/// </summary>
/// <param name="overrideChanges">Load regardless of unsaved data</param>
/// <returns>Whether or not the load executed successfully</returns>
public static Task<bool> LoadAsync(bool overrideChanges = false) => Task<bool>.Factory.StartNew(() => Load(overrideChanges));
=======
private static void ImportPreferencesAsset()
{
if (Instance.Asset == null)
{
using var _ = ApiCallSource.ForceInternalCall();
Instance.Asset = AssetManager.AssetManager.ImportOrCreateInner<JsonAsset>("text/json",
VirtualFilePath.Path, VirtualFilePath.Name,
Permissions.PublicReadWrite, VirtualFilePath.Name)!;
if(Instance.Asset == null)
{
throw new Exception("Failed to create preferences.json");
}
}
}
>>>>>>>
/// <summary>
/// Loads a JSON file asynchronously and loads preference data
/// </summary>
/// <param name="overrideChanges">Load regardless of unsaved data</param>
/// <returns>Whether or not the load executed successfully</returns>
public static Task<bool> LoadAsync(bool overrideChanges = false) => Task<bool>.Factory.StartNew(() => Load(overrideChanges));
private static void ImportPreferencesAsset()
{
using var _ = ApiCallSource.ForceInternalCall();
Instance.ImportPreferencesAsset();
}
<<<<<<<
Instance.Asset.Serialize(Instance.Preferences);
Instance.Asset.SaveToFile();
=======
using var _ = ApiCallSource.StartExternalCall();
return SaveInner();
}
public static bool SaveInner()
{
ImportPreferencesAsset();
Instance.Asset?.SerializeInner(Instance.Preferences);
Instance.Asset?.SaveToFileInner();
>>>>>>>
using var _ = ApiCallSource.StartExternalCall();
return SaveInner();
}
public static bool SaveInner()
{
ImportPreferencesAsset();
Instance.Asset?.SerializeInner(Instance.Preferences);
Instance.Asset?.SaveToFileInner(); |
<<<<<<<
#nullable enable
Component? AddComponentToScene(uint entity, Type t);
void RemoveComponentFromScene(uint entity, Type t);
=======
Component GetComponent(Type t, uint entity);
TComponent GetComponent<TComponent>(uint entity) where TComponent : Component;
List<Component> GetComponents(uint entity);
T CreateUnityType<T>(params object[] args) where T : class;
VisualTreeAsset GetDefaultUIAsset(string assetName);
#region UI
// TUnityType InstantiateFocusable<TUnityType>() where TUnityType : UnityEngine.UIElements.Focusable;
UnityEngine.UIElements.VisualElement GetRootVisualElement();
#endregion
>>>>>>>
#nullable enable
Component? AddComponentToScene(uint entity, Type t);
void RemoveComponentFromScene(uint entity, Type t);
T CreateUnityType<T>(params object[] args) where T : class;
VisualTreeAsset GetDefaultUIAsset(string assetName);
#region UI
// TUnityType InstantiateFocusable<TUnityType>() where TUnityType : UnityEngine.UIElements.Focusable;
UnityEngine.UIElements.VisualElement GetRootVisualElement();
#endregion |
<<<<<<<
reloadRobotInFrames = -1;
showStatWindow = true;
=======
reloadInFrames = -1;
showStatWindow = false;
showHelpWindow = true;
>>>>>>>
reloadRobotInFrames = -1;
showStatWindow = false;
showHelpWindow = true;
<<<<<<<
HotkeysWindow();
gui.AddWindow ("Exit", new DialogWindow ("Exit?", "Yes", "No"), (object o) =>
=======
/*gui.AddWindow ("Switch Field", new DialogWindow("Switch Field",
"Aerial Asssist (2014)", "Recycle Rush (2015)"), (object o) =>
{
gui.guiVisible = false;
switch ((int) o)
{
case 0:
SetField(FieldType.FRC_2014);
break;
case 1:
SetField(FieldType.FRC_2015);
break;
}
});*/
gui.AddWindow ("Quit Simulation", new DialogWindow ("Exit?", "Yes", "No"), (object o) =>
>>>>>>>
gui.AddWindow ("Quit Simulation", new DialogWindow ("Exit?", "Yes", "No"), (object o) =>
<<<<<<<
if (fieldLoaded)
{
// The Menu bottom on the top left corner
GUI.Window (1, new Rect (3, 0, 100, 25),
(int windowID) =>
{
if (GUI.Button (new Rect (0, 0, 100, 25), "Menu"))
gui.EscPressed ();
=======
// The Menu bottom on the top left corner
GUI.Window (1, new Rect (0, 0, gui.GetSidebarWidth(), 25),
(int windowID) =>
{
if (GUI.Button (new Rect (0, 0, gui.GetSidebarWidth(), 25), "Menu"))
gui.EscPressed();
>>>>>>>
if (fieldLoaded)
{
// The Menu bottom on the top left corner
GUI.Window (1, new Rect (0, 0, gui.GetSidebarWidth(), 25),
(int windowID) =>
{
if (GUI.Button (new Rect (0, 0, gui.GetSidebarWidth(), 25), "Menu"))
gui.EscPressed ();
<<<<<<<
if (fieldBrowser == null) {
fieldBrowser = new FileBrowser ("Load Field", false);
fieldBrowser.Active = true;
fieldBrowser.OnComplete += (object obj) =>
{
fieldBrowser.Active = true;
string fileLocation = (string) obj;
// If dir was selected...
if (File.Exists(fileLocation + "\\definition.bxdf"))
{
fileLocation += "\\definition.bxdf";
}
DirectoryInfo parent = Directory.GetParent(fileLocation);
if (parent != null && parent.Exists && File.Exists(parent.FullName + "\\definition.bxdf"))
{
this.filePath = parent.FullName + "\\";
activeField = new GameObject("Field");
FieldDefinition_Base.FIELDDEFINITION_FACTORY = delegate()
{
return new UnityFieldDefinition();
};
Debug.Log (filePath);
field = (UnityFieldDefinition)BXDFProperties.ReadProperties(filePath + "definition.bxdf");
field.CreateTransform(activeField.transform);
field.CreateMesh(filePath + "mesh.bxda");
fieldLoaded = true;
fieldBrowser.Active = false;
TryLoadRobot();
reloadRobotInFrames = -1;
}
else
{
UserMessageManager.Dispatch("Invalid selection!", 10f);
}
};
}
=======
if (showHelpWindow && Input.GetMouseButtonUp (0) && !auxFunctions.MouseInWindow (helpWindowRect) && !auxFunctions.MouseInWindow (helpButtonRect))
showHelpWindow = false;
gui.guiBackgroundVisible = showHelpWindow;
gui.Render();
>>>>>>>
if (fieldBrowser == null) {
fieldBrowser = new FileBrowser ("Load Field", false);
fieldBrowser.Active = true;
fieldBrowser.OnComplete += (object obj) =>
{
fieldBrowser.Active = true;
string fileLocation = (string) obj;
// If dir was selected...
if (File.Exists(fileLocation + "\\definition.bxdf"))
{
fileLocation += "\\definition.bxdf";
}
DirectoryInfo parent = Directory.GetParent(fileLocation);
if (parent != null && parent.Exists && File.Exists(parent.FullName + "\\definition.bxdf"))
{
this.filePath = parent.FullName + "\\";
activeField = new GameObject("Field");
FieldDefinition_Base.FIELDDEFINITION_FACTORY = delegate()
{
return new UnityFieldDefinition();
};
Debug.Log (filePath);
field = (UnityFieldDefinition)BXDFProperties.ReadProperties(filePath + "definition.bxdf");
field.CreateTransform(activeField.transform);
field.CreateMesh(filePath + "mesh.bxda");
fieldLoaded = true;
fieldBrowser.Active = false;
TryLoadRobot();
reloadRobotInFrames = -1;
}
else
{
UserMessageManager.Dispatch("Invalid selection!", 10f);
}
};
}
if (showHelpWindow && Input.GetMouseButtonUp (0) && !auxFunctions.MouseInWindow (helpWindowRect) && !auxFunctions.MouseInWindow (helpButtonRect))
showHelpWindow = false;
gui.guiBackgroundVisible = showHelpWindow;
<<<<<<<
activeRobot.transform.localPosition = new Vector3(0f, 0.25f, 0f);
=======
//activeRobot.transform.localPosition = new Vector3(2.5f, 1f, -2.25f);
activeRobot.transform.localPosition = new Vector3(2f, 0f, 0f);
>>>>>>>
activeRobot.transform.localPosition = new Vector3(1f, 1f, -0.5f); |
<<<<<<<
=======
=======
/* public static void UpdateAllWheels(RigidNode_Base skeleton, unityPacket.OutputStatePacket.DIOModule[] modules)
{
float[] pwm = modules[0].pwmValues;
List<RigidNode_Base> test = new List<RigidNode_Base>();
skeleton.ListAllNodes(test);
*/
>>>>>>>
<<<<<<<
=======
>>>>>>>
<<<<<<<
public static void updateSolenoids(RigidNode_Base skeleton, unityPacket.OutputStatePacket.SolenoidModule[] solenoidModules)
{
byte packet = solenoidModules [0].state;
List<RigidNode_Base> listOfNodes = new List<RigidNode_Base>();
skeleton.ListAllNodes(listOfNodes);
foreach (RigidNode_Base subBase in listOfNodes)
{
UnityRigidNode unityNode = (UnityRigidNode)subBase;
// Make sure piston and skeletalJoint exist
// If the rigidNodeBase contains a bumper_pneumatic joint driver (meaning that its a solenoid)
if (subBase != null && subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null && (subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC || subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.RELAY_PNEUMATIC))
=======
public static void updateSolenoids(RigidNode_Base skeleton, unityPacket.OutputStatePacket.SolenoidModule[] solenoidModules)
{
byte packet = solenoidModules[0].state;
>>>>>>>
public static void updateSolenoids(RigidNode_Base skeleton, unityPacket.OutputStatePacket.SolenoidModule[] solenoidModules)
{
byte packet = solenoidModules [0].state;
<<<<<<<
UnityRigidNode unityNode = (UnityRigidNode)subBase;
// If the rigidNodeBase contains a bumper_pneumatic joint driver (meaning that its a solenoid)
<<<<<<< HEAD
if (subBase.GetSkeletalJoint() != null && (subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC || subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.RELAY_PNEUMATIC))
{
// We use bitwise operators to check if the port is open.
=======
if (subBase != null && subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null && subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC)
{
//It will shift the 1 over based on the port number, so it will take port 3 and check if it has a value of 1 or 0 at the third bit. This allows us to check if the state is "on" or "off"
>>>>>>> origin/stressTesting-Skunk
=======
///Debug.Log(subBase==null?"null":subBase.ToString());
//if (subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null)
//{
UnityRigidNode unityNode = (UnityRigidNode)subBase;
// Make sure piston and skeletalJoint exist
// If the rigidNodeBase contains a bumper_pneumatic joint driver (meaning that its a solenoid)
if (subBase != null && subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null && (subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC || subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.RELAY_PNEUMATIC))
=======
public static void UpdateSolenoids(RigidNode_Base skeleton, byte packet)
{
//if ///Debug.Log(subBase==null?"null":subBase.ToString());
(subBase != null && subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null && (subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC || subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.RELAY_PNEUMATIC))
>>>>>>> /mnt/batch/tasks/workitems/adfv2-General_1/job-1/0163f3c5-7c52-45ec-82b2-46f68befeb89/wd/.temp/athenacommon/9621e877-0e6f-452f-a802-a7e3d516306d.cs
{
<<<<<<< /mnt/batch/tasks/workitems/adfv2-General_1/job-1/0163f3c5-7c52-45ec-82b2-46f68befeb89/wd/.temp/athenacommon/f89690df-3ba5-4e8e-9a3b-edf6db9773de.cs
// It will use bitwise operators to check if the port is open (see wiki for full explanation).
=======
// It will use bitwise operators to check if the port is open.
/* Full Explanation:
* bool StateX is a boolean that will return True if port X is open
* the packet is the byte we take as input
* The "1 << subBase.GetSkeletalJoint().cDriver.portA" does the following:
* It gets the port numbers for solenoid A (and subtracts 1 from it so that the solenoid port is base 0 instead of base 0)
* And then it uses bitwise operators to create a byte
* It does this by shifting the integer 1 over to the left by the value of port A.
* Heres an example of the bitwise lefshift operators in use: "1 << 5" will result in 100000.
* So in our case, if port = 3,
* "1 << subBase.GetSkeletalJoint().cDriver.portA - 1"
* = "1 << 3 - 1"
* = "1 << 2"
* = 100 --- which is also a bit
* Now that is has that information, it compares that byte to the packet the function recieves using the & operator
* Here is how the & operator works:
* "The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0." - msdn.microsoft.com
* So if the bit of the first operand is "1111"
* And the bit of the second operand is "1010"
* The resulting bit will be: "1010"
* As you can see, it oompares the data in each bit, and if they both match (in our case, if they both are 1) at the given position,
* The resulting byte will have a 1 at the given position. If they don't match however, the result at the given will be 0.
* So in our case, if the byte at solenoid port 0 (the first bit) has a value of 1 in our packet, and our code is checking to see if port 1 is open, the following operation is executed: "00000001 & 00000001".
* This will result in a byte value of "00000001".
* Now, since bits can evaluate to integers, a byte that results in a value greater than 0 indicates that the byte contains a bit with a value of 1 as opposed to 0.
* In our case, that would indicate that the solenoid port we checked for with the bitwise & operator is open.
*/(subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null)
//{
UnityRigidNode unityNode = (UnityRigidNode)subBase;
// Make sure piston and skeletalJoint exist
// If the rigidNodeBase contains a bumper_pneumatic joint driver (meaning that its a solenoid)
if
public static void updateSolenoids(RigidNode_Base skeleton, unityPacket.OutputStatePacket.SolenoidModule[] solenoidModules)
{
byte packet = solenoidModules[0].state;
List<RigidNode_Base> listOfNodes = new List<RigidNode_Base>();
skeleton.ListAllNodes(listOfNodes);
foreach (RigidNode_Base subBase in listOfNodes)
{
UnityRigidNode unityNode = (UnityRigidNode)subBase;
// If the rigidNodeBase contains a bumper_pneumatic joint driver (meaning that its a solenoid)
// if (subBase.GetSkeletalJoint() != null && (subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC || subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.RELAY_PNEUMATIC))
// {
// // We use bitwise operators to check if the port is open.
if (subBase != null && subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null && subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC)
{
//It will shift the 1 over based on the port number, so it will take port 3 and check if it has a value of 1 or 0 at the third bit. This allows us to check if the state is "on" or "off"
>>>>>>>
UnityRigidNode unityNode = (UnityRigidNode)subBase;
// Make sure piston and skeletalJoint exist
// If the rigidNodeBase contains a bumper_pneumatic joint driver (meaning that its a solenoid)
if (subBase != null && subBase.GetSkeletalJoint() != null && subBase.GetSkeletalJoint().cDriver != null && (subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.BUMPER_PNEUMATIC || subBase.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.RELAY_PNEUMATIC))
{
// It will use bitwise operators to check if the port is open (see wiki for full explanation). |
<<<<<<<
AnalyticsUtils.LogPage("Joint Editor");
=======
UnsupportedComponentsForm.CheckUnsupportedComponents(RobotDataManager.RobotBaseNode.ListAllNodes());
>>>>>>>
AnalyticsUtils.LogPage("Joint Editor");
UnsupportedComponentsForm.CheckUnsupportedComponents(RobotDataManager.RobotBaseNode.ListAllNodes()); |
<<<<<<<
private DirectoryInfo tempSelection;
=======
string path = FB.FileBrowser.OpenSingleFolder("Open Folder", Environment.SpecialFolder.ApplicationData + "//synthesis//Fields");
>>>>>>>
private DirectoryInfo tempSelection;
string path = FB.FileBrowser.OpenSingleFolder("Open Folder", Environment.SpecialFolder.ApplicationData + "//synthesis//Fields");
<<<<<<<
void Init(string windowTitle, string defaultDirectory, bool allowEsc = true)
{
title = windowTitle;
_allowEsc = allowEsc;
}
/// <summary>
/// Renders the window if it is active.
/// </summary>
public void Render()
{
FileBrowserWindow();
}
// return the file string from OpenSingleFolder()
public void OpenSingleFolder()
{
//Debug.Log("OpenSingleFolder");
directoryPath = FileBrowser.OpenSingleFolder("Open Folder");
//Debug.Log("Selected folder: " + path);
RebuildList(directoryPath);
}
=======
>>>>>>>
void Init(string windowTitle, string defaultDirectory, bool allowEsc = true)
{
title = windowTitle;
_allowEsc = allowEsc;
}
/// <summary>
/// Renders the window if it is active.
/// </summary>
public void Render()
{
FileBrowserWindow();
}
// return the file string from OpenSingleFolder()
public void OpenSingleFolder()
{
//Debug.Log("OpenSingleFolder");
directoryPath = FileBrowser.OpenSingleFolder("Open Folder");
//Debug.Log("Selected folder: " + path);
RebuildList(directoryPath);
} |
<<<<<<<
if (guiFadeIntensity > 0)
=======
UserMessageManager.Render();
if (guiFadeIntensity > 0 && guiVisible)
>>>>>>>
if (guiFadeIntensity > 0 && guiVisible) |
<<<<<<<
=======
public static bool inputPanelOn = false;
/// <summary>
/// Link the SimUI to main state
/// </summary>
private void Awake()
{
StateMachine.Instance.Link<MainState>(this);
}
>>>>>>>
public static bool inputPanelOn = false;
<<<<<<<
if (!exitPanel.activeSelf) MainMenuExit("open");
else MainMenuExit("cancel");
=======
if (StateMachine.Instance.CurrentState.GetType().Equals(typeof(MainState)))
{
if (!exitPanel.activeSelf)
{
bool a = false;
foreach (GameObject o in panels)
{
if (o.activeSelf)
{
a = true;
break;
}
}
if (a)
{
EndOtherProcesses();
}
else
{
MainMenuExit("open");
}
}
else
{
MainMenuExit("cancel");
}
}
>>>>>>>
if (!exitPanel.activeSelf)
{
bool a = false;
foreach (GameObject o in panels)
{
if (o.activeSelf)
{
a = true;
break;
}
}
if (a)
{
EndOtherProcesses();
}
else
{
MainMenuExit("open");
}
}
else
{
MainMenuExit("cancel");
}
<<<<<<<
=======
if (KeyButton.Binded() && inputPanelOn)
{
ShowBindedInfoPanel();
}
>>>>>>>
if (KeyButton.Binded() && inputPanelOn)
{
ShowBindedInfoPanel();
}
<<<<<<<
State.BeginRobotReset();
=======
camera.SwitchCameraState(new DynamicCamera.OverviewState(camera));
DynamicCamera.MovingEnabled = true;
main.BeginRobotReset();
>>>>>>>
camera.SwitchCameraState(new DynamicCamera.OverviewState(camera));
DynamicCamera.MovingEnabled = true;
State.BeginRobotReset(); |
<<<<<<<
private Renderer meshRenderer;
=======
private MeshRenderer meshRenderer;
>>>>>>>
private MeshRenderer meshRenderer;
<<<<<<<
private LastState lastState = new LastState();
private readonly ExposedList<Material> submeshMaterials = new ExposedList<Material>();
private readonly ExposedList<Submesh> submeshes = new ExposedList<Submesh>();
public void RequestMeshUpdate() {
meshUpdateRequested = true;
}
=======
private readonly List<Material> submeshMaterials = new List<Material>();
private readonly List<Submesh> submeshes = new List<Submesh>();
private SkeletonUtilitySubmeshRenderer[] submeshRenderers;
>>>>>>>
private readonly ExposedList<Material> submeshMaterials = new ExposedList<Material>();
private readonly ExposedList<Submesh> submeshes = new ExposedList<Submesh>();
private SkeletonUtilitySubmeshRenderer[] submeshRenderers;
private LastState lastState = new LastState();
public void RequestMeshUpdate() {
meshUpdateRequested = true;
}
<<<<<<<
if (meshRenderer != null)
meshRenderer.sharedMaterial = null;
=======
meshRenderer = GetComponent<MeshRenderer>();
if (meshRenderer != null) meshRenderer.sharedMaterial = null;
>>>>>>>
meshRenderer = GetComponent<MeshRenderer>();
if (meshRenderer != null) meshRenderer.sharedMaterial = null;
<<<<<<<
if ((lastMaterial != null && lastMaterial.GetInstanceID() != material.GetInstanceID()) ||
(submeshSeparatorSlotsCount > 0 && submeshSeparatorSlots.Contains(slot))) {
addSubmeshArgumentsTemp.Add(
new LastState.AddSubmeshArguments(lastMaterial, submeshStartSlotIndex, i, submeshTriangleCount, submeshFirstVertex, false)
);
=======
#else
Material material = (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject;
#endif
if ((lastMaterial != material && lastMaterial != null) || submeshSeparatorSlots.Contains(slot)) {
AddSubmesh(lastMaterial, submeshStartSlotIndex, i, submeshTriangleCount, submeshFirstVertex, false);
>>>>>>>
#else
Material material = (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject;
#endif
if ((lastMaterial != null && lastMaterial.GetInstanceID() != material.GetInstanceID()) ||
(submeshSeparatorSlotsCount > 0 && submeshSeparatorSlots.Contains(slot))) {
addSubmeshArgumentsTemp.Add(
new LastState.AddSubmeshArguments(lastMaterial, submeshStartSlotIndex, i, submeshTriangleCount, submeshFirstVertex, false)
);
<<<<<<<
// Set materials.
if (submeshMaterials.Count == sharedMaterials.Length)
submeshMaterials.CopyTo(sharedMaterials);
else
sharedMaterials = submeshMaterials.ToArray();
meshRenderer.sharedMaterials = sharedMaterials;
}
=======
// Set materials.
if (submeshMaterials.Count == sharedMaterials.Length)
submeshMaterials.CopyTo(sharedMaterials);
else
sharedMaterials = submeshMaterials.ToArray();
meshRenderer.sharedMaterials = sharedMaterials;
>>>>>>>
// Set materials.
if (submeshMaterials.Count == sharedMaterials.Length)
submeshMaterials.CopyTo(sharedMaterials);
else
sharedMaterials = submeshMaterials.ToArray();
meshRenderer.sharedMaterials = sharedMaterials;
}
<<<<<<<
=======
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
>>>>>>>
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
<<<<<<<
=======
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
>>>>>>>
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
<<<<<<<
} else {
SkinnedMeshAttachment skinnedMeshAttachment = attachment as SkinnedMeshAttachment;
if (skinnedMeshAttachment != null) {
int meshVertexCount = skinnedMeshAttachment.uvs.Length;
if (tempVertices.Length < meshVertexCount)
this.tempVertices = tempVertices = new float[meshVertexCount];
skinnedMeshAttachment.ComputeWorldVertices(slot, tempVertices);
color.a = slot.data.additiveBlending ? (byte) 0 : (byte)(a * slot.a * skinnedMeshAttachment.a);
color.r = (byte)(r * slot.r * skinnedMeshAttachment.r * color.a);
color.g = (byte)(g * slot.g * skinnedMeshAttachment.g * color.a);
color.b = (byte)(b * slot.b * skinnedMeshAttachment.b * color.a);
float[] meshUVs = skinnedMeshAttachment.uvs;
float z = i * zSpacing;
for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) {
vertices[vertexIndex].x = tempVertices[ii];
vertices[vertexIndex].y = tempVertices[ii + 1];
vertices[vertexIndex].z = z;
colors[vertexIndex] = color;
uvs[vertexIndex].x = meshUVs[ii];
uvs[vertexIndex].y = meshUVs[ii + 1];
if (tempVertices[ii] < meshBoundsMin.x)
meshBoundsMin.x = tempVertices[ii];
else if (tempVertices[ii] > meshBoundsMax.x)
meshBoundsMax.x = tempVertices[ii];
if (tempVertices[ii + 1]< meshBoundsMin.y)
meshBoundsMin.y = tempVertices[ii + 1];
else if (tempVertices[ii + 1] > meshBoundsMax.y)
meshBoundsMax.y = tempVertices[ii + 1];
}
=======
} else if (attachment is SkinnedMeshAttachment) {
SkinnedMeshAttachment meshAttachment = (SkinnedMeshAttachment)attachment;
int meshVertexCount = meshAttachment.uvs.Length;
if (tempVertices.Length < meshVertexCount)
this.tempVertices = tempVertices = new float[meshVertexCount];
meshAttachment.ComputeWorldVertices(slot, tempVertices);
color.a = (byte)(a * slot.a * meshAttachment.a);
color.r = (byte)(r * slot.r * meshAttachment.r * color.a);
color.g = (byte)(g * slot.g * meshAttachment.g * color.a);
color.b = (byte)(b * slot.b * meshAttachment.b * color.a);
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
float[] meshUVs = meshAttachment.uvs;
float z = i * zSpacing;
for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) {
vertices[vertexIndex] = new Vector3(tempVertices[ii], tempVertices[ii + 1], z);
colors[vertexIndex] = color;
uvs[vertexIndex] = new Vector2(meshUVs[ii], meshUVs[ii + 1]);
>>>>>>>
} else {
SkinnedMeshAttachment skinnedMeshAttachment = attachment as SkinnedMeshAttachment;
if (skinnedMeshAttachment != null) {
int meshVertexCount = skinnedMeshAttachment.uvs.Length;
if (tempVertices.Length < meshVertexCount)
this.tempVertices = tempVertices = new float[meshVertexCount];
skinnedMeshAttachment.ComputeWorldVertices(slot, tempVertices);
color.a = (byte)(a * slot.a * skinnedMeshAttachment.a);
color.r = (byte)(r * slot.r * skinnedMeshAttachment.r * color.a);
color.g = (byte)(g * slot.g * skinnedMeshAttachment.g * color.a);
color.b = (byte)(b * slot.b * skinnedMeshAttachment.b * color.a);
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
float[] meshUVs = skinnedMeshAttachment.uvs;
float z = i * zSpacing;
for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) {
vertices[vertexIndex].x = tempVertices[ii];
vertices[vertexIndex].y = tempVertices[ii + 1];
vertices[vertexIndex].z = z;
colors[vertexIndex] = color;
uvs[vertexIndex].x = meshUVs[ii];
uvs[vertexIndex].y = meshUVs[ii + 1];
if (tempVertices[ii] < meshBoundsMin.x)
meshBoundsMin.x = tempVertices[ii];
else if (tempVertices[ii] > meshBoundsMax.x)
meshBoundsMax.x = tempVertices[ii];
if (tempVertices[ii + 1]< meshBoundsMin.y)
meshBoundsMin.y = tempVertices[ii + 1];
else if (tempVertices[ii + 1] > meshBoundsMax.y)
meshBoundsMax.y = tempVertices[ii + 1];
}
<<<<<<<
// Update previous state
ExposedList<int> attachmentsTriangleCountCurrentMesh;
ExposedList<bool> attachmentsFlipStateCurrentMesh;
ExposedList<LastState.AddSubmeshArguments> addSubmeshArgumentsCurrentMesh;
if (useMesh1) {
attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh1;
addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh1;
attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh1;
lastState.immutableTrianglesMesh1 = immutableTriangles;
} else {
attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh2;
addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh2;
attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh2;
lastState.immutableTrianglesMesh2 = immutableTriangles;
}
attachmentsTriangleCountCurrentMesh.GrowIfNeeded(attachmentsTriangleCountTemp.Capacity);
attachmentsTriangleCountCurrentMesh.Count = attachmentsTriangleCountTemp.Count;
attachmentsTriangleCountTemp.CopyTo(attachmentsTriangleCountCurrentMesh.Items, 0);
attachmentsFlipStateCurrentMesh.GrowIfNeeded(attachmentsFlipStateTemp.Capacity);
attachmentsFlipStateCurrentMesh.Count = attachmentsFlipStateTemp.Count;
attachmentsFlipStateTemp.CopyTo(attachmentsFlipStateCurrentMesh.Items, 0);
addSubmeshArgumentsCurrentMesh.GrowIfNeeded(addSubmeshArgumentsTemp.Count);
addSubmeshArgumentsCurrentMesh.Count = addSubmeshArgumentsTemp.Count;
addSubmeshArgumentsTemp.CopyTo(addSubmeshArgumentsCurrentMesh.Items);
=======
if (submeshRenderers.Length > 0) {
foreach (var submeshRenderer in submeshRenderers) {
if (submeshRenderer.submeshIndex < sharedMaterials.Length)
submeshRenderer.SetMesh(meshRenderer, useMesh1 ? mesh1 : mesh2, sharedMaterials[submeshRenderer.submeshIndex]);
else
submeshRenderer.GetComponent<Renderer>().enabled = false;
}
}
>>>>>>>
// Update previous state
ExposedList<int> attachmentsTriangleCountCurrentMesh;
ExposedList<bool> attachmentsFlipStateCurrentMesh;
ExposedList<LastState.AddSubmeshArguments> addSubmeshArgumentsCurrentMesh;
if (useMesh1) {
attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh1;
addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh1;
attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh1;
lastState.immutableTrianglesMesh1 = immutableTriangles;
} else {
attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh2;
addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh2;
attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh2;
lastState.immutableTrianglesMesh2 = immutableTriangles;
}
attachmentsTriangleCountCurrentMesh.GrowIfNeeded(attachmentsTriangleCountTemp.Capacity);
attachmentsTriangleCountCurrentMesh.Count = attachmentsTriangleCountTemp.Count;
attachmentsTriangleCountTemp.CopyTo(attachmentsTriangleCountCurrentMesh.Items, 0);
attachmentsFlipStateCurrentMesh.GrowIfNeeded(attachmentsFlipStateTemp.Capacity);
attachmentsFlipStateCurrentMesh.Count = attachmentsFlipStateTemp.Count;
attachmentsFlipStateTemp.CopyTo(attachmentsFlipStateCurrentMesh.Items, 0);
addSubmeshArgumentsCurrentMesh.GrowIfNeeded(addSubmeshArgumentsTemp.Count);
addSubmeshArgumentsCurrentMesh.Count = addSubmeshArgumentsTemp.Count;
addSubmeshArgumentsTemp.CopyTo(addSubmeshArgumentsCurrentMesh.Items);
if (submeshRenderers.Length > 0) {
for (int i = 0; i < submeshRenderers.Length; i++) {
SkeletonUtilitySubmeshRenderer submeshRenderer = submeshRenderers[i];
if (submeshRenderer.submeshIndex < sharedMaterials.Length) {
submeshRenderer.SetMesh(meshRenderer, useMesh1 ? mesh1 : mesh2, sharedMaterials[submeshRenderer.submeshIndex]);
} else {
submeshRenderer.GetComponent<Renderer>().enabled = false;
}
}
}
<<<<<<<
private void AddSubmesh (Material material, int startSlot, int endSlot, int triangleCount, int firstVertex, bool lastSubmesh, ExposedList<bool> flipStates) {
=======
private void AddSubmesh (Material material, int startSlot, int endSlot, int triangleCount, int firstVertex, bool lastSubmesh) {
>>>>>>>
private void AddSubmesh (Material material, int startSlot, int endSlot, int triangleCount, int firstVertex, bool lastSubmesh, ExposedList<bool> flipStates) { |
<<<<<<<
// Clear existing panels
while (LeftWheelsPanel.Controls.Count > 0)
LeftWheelsPanel.Controls[0].Dispose();
while (RightWheelsPanel.Controls.Count > 0)
RightWheelsPanel.Controls[0].Dispose();
Dictionary<string, RigidNode_Base> availableNodes = new Dictionary<string, RigidNode_Base>(); // TODO: Rename this to availableNodes after a different merge
wheelSlots = new Dictionary<string, WheelSlotPanel>();
// Find all nodes that can be wheels
if (WizardData.Instance.driveTrain != WizardData.WizardDriveTrain.SWERVE)
{
foreach (RigidNode_Base node in Utilities.GUI.SkeletonBase.ListAllNodes())
{
if (node.GetSkeletalJoint() != null && node.GetSkeletalJoint().GetJointType() == SkeletalJointType.ROTATIONAL)
{
string readableName = node.ModelFileName.Replace('_', ' ').Replace(".bxda", "");
readableName = readableName.Substring(0, 1).ToUpperInvariant() + readableName.Substring(1); // Capitalize first character
availableNodes.Add(readableName, node);
}
}
}
else
=======
Dictionary<string, int> duplicatePartNames = new Dictionary<string, int>();
foreach (RigidNode_Base node in Utilities.GUI.SkeletonBase.ListAllNodes())
>>>>>>>
// Clear existing panels
while (LeftWheelsPanel.Controls.Count > 0)
LeftWheelsPanel.Controls[0].Dispose();
while (RightWheelsPanel.Controls.Count > 0)
RightWheelsPanel.Controls[0].Dispose();
Dictionary<string, RigidNode_Base> availableNodes = new Dictionary<string, RigidNode_Base>(); // TODO: Rename this to availableNodes after a different merge
wheelSlots = new Dictionary<string, WheelSlotPanel>();
// Find all nodes that can be wheels
Dictionary<string, int> duplicatePartNames = new Dictionary<string, int>();
foreach (RigidNode_Base node in Utilities.GUI.SkeletonBase.ListAllNodes())
<<<<<<<
string nodeName = (string)e.Data.GetData(DataFormats.StringFormat, true);
SetWheelSide(nodeName, WheelSide.RIGHT);
=======
if (wantedPanel.name.Equals(toFind))// checks if this panel is the one we want
{
foreach (WheelSlotPanel wheel in placementPanel.Controls)// iterates over the existing wheel nodes to find if a node is below the cursor to add the wheel into that pos
{
if ((wheel.PointToScreen(Point.Empty).Y > System.Windows.Forms.Control.MousePosition.Y)) // checks if the node is above or below the cursor
{
if (wantedPanel.Equals(wheel))// if the place where the panel should be put is the panel
{
return;// quit
}
foreach (WheelSlotPanel toRemove in placementPanel.Controls)// goes over the existing controll to find the one we want to remove
{
if (toRemove.name.Equals(toFind))// checks if its the panel we want
{
placementPanel.Controls.Remove(toRemove);// removes the pane
break;// ends the loop
}
}
placementList.Remove(wantedPanel);// removes the panel from the internal list
Control[] tempControls = new Control[placementPanel.Controls.Count - placementPanel.Controls.IndexOf(wheel)]; // makes a temp array for the controls below the cursor
List<WheelSlotPanel> tempSlots = new List<WheelSlotPanel>();// ^^
int pos = 0;// tracks the position of the temp array
for (int i = placementPanel.Controls.IndexOf(wheel); i < placementPanel.Controls.Count;)// iterates over the controls until there are only the controls above the cursor still exiting
{
tempControls[pos] = placementPanel.Controls[i];// copies the existing controls into a temp array
tempSlots.Add(placementList[i]);// ^^^
pos++;// increase pos for the next loop thru
placementPanel.Controls.RemoveAt(i); // removes the control form the actual array so we can add the control into the right place
placementList.RemoveAt(i);// ^^
}
placementList.Add(wantedPanel);// adds a new panel
placementPanel.Controls.Add(wantedPanel);// ^^
placementPanel.Controls.AddRange(tempControls);// add the temp controls back into the array
placementList.AddRange(tempSlots);// ^^
return; // quites the method
}
}
//this just adds the panel at the bottom
foreach (WheelSlotPanel toRemove in placementPanel.Controls) // goes over the panels in this group
{
if (toRemove.name.Equals(toFind))// checks if its the panel we want
{
placementPanel.Controls.Remove(toRemove);// removes the panel from the group
break;
}
}
placementList.Remove(wantedPanel); // removes the panel
placementList.Add(wantedPanel);// adds the panel back in
placementPanel.Controls.Add(wantedPanel);// ^^
return; // quites the method
}
>>>>>>>
string nodeName = (string)e.Data.GetData(DataFormats.StringFormat, true);
SetWheelSide(nodeName, WheelSide.RIGHT);
<<<<<<<
SetWheelSide(name, WheelSide.UNASSIGNED);
=======
foreach (Object wheel in LeftWheelsPanel.Controls)// goes over all the objects in the panel
{
if (wheel.GetType().Equals(typeof(WheelSlotPanel)))// confirms that the object is atucally a wheel panel, needed because there are things other than wheel panes in the panel
{
if (((WheelSlotPanel)wheel).name.Equals(s))// sees if this is the panel the remove event came from
{
LeftWheelsPanel.Controls.Remove(((WheelSlotPanel)wheel));// removes the pane from the panel
leftSlots.Remove(((WheelSlotPanel)wheel));// ^^
}
}
}
foreach (Object wheel in RightWheelsPanel.Controls)// goes over all the objects in the panel, second foreach needed because we need to look in both the left and right panel for the pane and there's no good way to search the panel ahead of time
{
if (wheel.GetType().Equals(typeof(WheelSlotPanel)))// confirms that the object is atucally a wheel panel, needed because there are things other than wheel panes in the panel
{
if (((WheelSlotPanel)wheel).name.Equals(s))// sees if this is the panel the remove event came from
{
RightWheelsPanel.Controls.Remove(((WheelSlotPanel)wheel));// removes the pane from the panel
rightSlots.Remove(((WheelSlotPanel)wheel));// ^^
}
}
}
NodeListBox.Items.Add(s);// adds the node back into the nodelist
object[] list;// makes a temporary array so we can sort the array
NodeListBox.Items.CopyTo(list = new object[NodeListBox.Items.Count], 0);// copies the nodes into the array
ArrayList a = new ArrayList();// makes a new arraylist so we can sort super easily
a.AddRange(list);// add the list to the arraylist
a.Sort();//sort the array
NodeListBox.Items.Clear();// clear the node list so we can readd the ordered list
foreach(object sortedItem in a)// goes over all the sorted values
{
NodeListBox.Items.Add(sortedItem);// add the ordered nodes back to the list
}
OnSetEndEarly(false);
return "";// needed because c# gets real ticked if this isn't here
>>>>>>>
SetWheelSide(name, WheelSide.UNASSIGNED); |
<<<<<<<
this.Text = "Save Robot";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SaveRobotForm_FormClosing);
this.MainLayout.ResumeLayout(false);
this.MainLayout.PerformLayout();
this.WindowControlLayout.ResumeLayout(false);
=======
this.Text = "Export Robot";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.windowControlPanel.ResumeLayout(false);
>>>>>>>
this.Text = "Export Robot";
this.MainLayout.ResumeLayout(false);
this.MainLayout.PerformLayout();
this.WindowControlLayout.ResumeLayout(false); |
<<<<<<<
private MotorController frontLeft, frontRight, backLeft, backRight;
private MotorController arm;
=======
private Entity testBody;
private MotorAssemblyManager motorManager;
private MotorAssembly frontLeft, frontRight, backLeft, backRight, arm;
>>>>>>>
private Entity testBody;
private MotorAssemblyManager motorManager;
private MotorAssembly frontLeft, frontRight, backLeft, backRight, arm;
<<<<<<<
Entity testBody = EnvironmentManager.AddEntity();
=======
testBody = EnvironmentManager.AddEntity();
>>>>>>>
testBody = EnvironmentManager.AddEntity();
<<<<<<<
//Entity jointTest = EnvironmentManager.AddEntity();
//Mesh m = new Mesh();
//Bundle b = new Bundle();
//b.Components.Add(selectable);
//Transform t = new Transform();
//t.Position = new Vector3D(10, 10, 10); //joint anchor position
//b.Components.Add(t);
//b.Components.Add(cube(m)); //replace the cube function with your mesh creation
//jointTest.AddBundle(b);
////when done
//jointTest.RemoveEntity();
=======
InputManager.AssignDigitalInput("move_arm_up", new Digital("t"));
InputManager.AssignDigitalInput("move_arm_down", new Digital("y"));
foreach (var i in EnvironmentManager.GetComponentsWhere<Rigidbody>(_ => true))
{
i.AngularDrag = 0;
}
>>>>>>>
InputManager.AssignDigitalInput("move_arm_up", new Digital("t"));
InputManager.AssignDigitalInput("move_arm_down", new Digital("y"));
foreach (var i in EnvironmentManager.GetComponentsWhere<Rigidbody>(_ => true))
{
i.AngularDrag = 0;
}
//Entity jointTest = EnvironmentManager.AddEntity();
//Mesh m = new Mesh();
//Bundle b = new Bundle();
//b.Components.Add(selectable);
//Transform t = new Transform();
//t.Position = new Vector3D(10, 10, 10); //joint anchor position
//b.Components.Add(t);
//b.Components.Add(cube(m)); //replace the cube function with your mesh creation
//jointTest.AddBundle(b);
////when done
//jointTest.RemoveEntity(); |
<<<<<<<
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.showRangeOfPagesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
=======
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
>>>>>>>
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.showRangeOfPagesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pdfViewer1 = new PdfiumViewer.PdfViewer();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
<<<<<<<
this.rotateCurrentPageToolStripMenuItem,
this.toolStripMenuItem5,
this.showRangeOfPagesToolStripMenuItem});
=======
this.rotateCurrentPageToolStripMenuItem,
this.toolStripSeparator7,
this.informationToolStripMenuItem});
>>>>>>>
this.rotateCurrentPageToolStripMenuItem,
this.toolStripSeparator7,
this.informationToolStripMenuItem,
this.toolStripMenuItem5,
this.showRangeOfPagesToolStripMenuItem});
<<<<<<<
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(241, 6);
//
// showRangeOfPagesToolStripMenuItem
//
this.showRangeOfPagesToolStripMenuItem.Name = "showRangeOfPagesToolStripMenuItem";
this.showRangeOfPagesToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.showRangeOfPagesToolStripMenuItem.Text = "Show range of pages";
this.showRangeOfPagesToolStripMenuItem.Click += new System.EventHandler(this.showRangeOfPagesToolStripMenuItem_Click);
//
=======
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(241, 6);
//
>>>>>>>
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(241, 6);
//
// showRangeOfPagesToolStripMenuItem
//
this.showRangeOfPagesToolStripMenuItem.Name = "showRangeOfPagesToolStripMenuItem";
this.showRangeOfPagesToolStripMenuItem.Size = new System.Drawing.Size(244, 22);
this.showRangeOfPagesToolStripMenuItem.Text = "Show range of pages";
this.showRangeOfPagesToolStripMenuItem.Click += new System.EventHandler(this.showRangeOfPagesToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(241, 6);
//
<<<<<<<
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripLabel toolStripLabel3;
private System.Windows.Forms.ToolStripTextBox _search;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripStatusLabel _pageToolStripLabel;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2;
private System.Windows.Forms.ToolStripStatusLabel _coordinatesToolStripLabel;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem showRangeOfPagesToolStripMenuItem;
=======
private System.Windows.Forms.ToolStripMenuItem informationToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
>>>>>>>
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripLabel toolStripLabel3;
private System.Windows.Forms.ToolStripTextBox _search;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripStatusLabel _pageToolStripLabel;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2;
private System.Windows.Forms.ToolStripStatusLabel _coordinatesToolStripLabel;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem showRangeOfPagesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem informationToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; |
<<<<<<<
private List<Sprite> _cleanupSpriteList = new List<Sprite>();
private SizeF _viewportSize;
=======
private List<CluwneSprite> _cleanupSpriteList = new List<CluwneSprite>();
private List<ITile> _visibleTiles;
>>>>>>>
private List<CluwneSprite> _cleanupSpriteList = new List<CluwneSprite>();
private SizeF _viewportSize;
<<<<<<<
=======
/// <summary>
/// Center point of the current render window.
/// </summary>
private Vector2 WindowOrigin
{
get { return ClientWindowData.Singleton.ScreenOrigin; }
}
>>>>>>>
<<<<<<<
_realScreenWidthTiles = (float)Gorgon.CurrentClippingViewport.Width / MapManager.TileSize;
_realScreenHeightTiles = (float)Gorgon.CurrentClippingViewport.Height / MapManager.TileSize;
=======
_realScreenWidthTiles = (float) CluwneLib.Screen.Size.X/MapManager.GetTileSpacing();
_realScreenHeightTiles = (float) CluwneLib.Screen.Size.Y/MapManager.GetTileSpacing();
>>>>>>>
_realScreenWidthTiles = (float)CluwneLib.Screen.Size.X / MapManager.TileSize;
_realScreenHeightTiles = (float)CluwneLib.Screen.Size.Y / MapManager.TileSize;
<<<<<<<
MousePosWorld = ClientWindowData.Singleton.ScreenToWorld(MousePosScreen);
=======
MousePosWorld = new Vector2(MousePosScreen.X + WindowOrigin.X, MousePosScreen.Y + WindowOrigin.Y);
>>>>>>>
MousePosWorld = ClientWindowData.Singleton.ScreenToWorld(MousePosScreen);
<<<<<<<
RenderLightMap(lights);
CalculateSceneBatches(vp);
=======
//RenderLightMap(lights);
CalculateSceneBatches(ClientWindowData.Singleton.ViewPort);
>>>>>>>
//RenderLightMap(lights);
CalculateSceneBatches(vp);
<<<<<<<
Gorgon.CurrentClippingViewport = new Viewport(0, 0, Gorgon.CurrentClippingViewport.Width,
Gorgon.CurrentClippingViewport.Height);
ClientWindowData.Singleton.ScreenViewportSize =
new SizeF(Gorgon.CurrentClippingViewport.Width, Gorgon.CurrentClippingViewport.Height);
=======
//CluwneLib.CurrentClippingViewport = new Viewport(0, 0,CluwneLib.Screen.Size.X, CluwneLib.Screen.Size.Y);
ClientWindowData.Singleton.UpdateViewPort(
PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
>>>>>>>
ClientWindowData.Singleton.ScreenViewportSize =
new SizeF(CluwneLib.Screen.Size.X, CluwneLib.Screen.Size.Y);
<<<<<<<
float distanceToPrev = (MousePosScreen - new Vector2D(e.Position.X, e.Position.Y)).Length;
MousePosScreen = new Vector2D(e.Position.X, e.Position.Y);
MousePosWorld = ClientWindowData.Singleton.ScreenToWorld(MousePosScreen);
=======
float distanceToPrev = (MousePosScreen - new Vector2(e.X, e.Y)).Length;
MousePosScreen = new Vector2(e.X, e.Y);
MousePosWorld = new Vector2(e.X + WindowOrigin.X, e.Y + WindowOrigin.Y);
>>>>>>>
float distanceToPrev = (MousePosScreen - new Vector2(e.X, e.Y)).Length;
MousePosScreen = new Vector2(e.X, e.Y);
MousePosWorld = ClientWindowData.Singleton.ScreenToWorld(MousePosScreen);
<<<<<<<
area.LightPosition = new Vector2D(area.LightPosition.X,
t.Y +
MapManager.TileSize + 1);
=======
area.LightPosition = new Vector2(area.LightPosition.X,
t.Position.Y +
MapManager.GetTileSpacing() + 1);
>>>>>>>
area.LightPosition = new Vector2(area.LightPosition.X,
t.Y +
MapManager.TileSize + 1);
<<<<<<<
area.LightPosition = new Vector2D(area.LightPosition.X,
t.Y +
MapManager.TileSize + 1);
=======
area.LightPosition = new Vector2(area.LightPosition.X,
MapManager.GetAllTilesAt(l.Position).FirstOrDefault().Position.Y +
MapManager.GetTileSpacing() + 1);
>>>>>>>
area.LightPosition = new Vector2(area.LightPosition.X,
t.Y +
MapManager.TileSize + 1);
<<<<<<<
Vector2D pos = area.ToRelativePosition(new Vector2D(t.X, t.Y));
t.Tile.TileDef.RenderPos(pos.X, pos.Y, MapManager.TileSize, (int)area.LightAreaSize.X);
=======
Vector2 pos = area.ToRelativePosition(t.Position);
t.RenderPos(pos.X, pos.Y, MapManager.GetTileSpacing(), (int)area.LightAreaSize.X);
>>>>>>>
Vector2 pos = area.ToRelativePosition(new Vector2(t.X, t.Y));
t.Tile.TileDef.RenderPos(pos.X, pos.Y, MapManager.TileSize, (int)area.LightAreaSize.X);
<<<<<<<
=======
//t.RenderGas(WindowOrigin.X, WindowOrigin.Y, tilespacing, _gasBatch);
>>>>>>> |
<<<<<<<
var ownerPos = Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position;
Vector2D renderPos = ClientWindowData.Singleton.WorldToScreen(ownerPos);
=======
Vector2 renderPos =
ClientWindowData.WorldToScreen(
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
>>>>>>>
var ownerPos = Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position;
Vector2 renderPos = ClientWindowData.Singleton.WorldToScreen(ownerPos); |
<<<<<<<
using GorgonLibrary;
using Lidgren.Network;
using System.Collections.Generic;
=======
using Lidgren.Network;
>>>>>>>
using Lidgren.Network;
using System.Collections.Generic;
<<<<<<<
event TileChangedEventHandler TileChanged;
=======
event TileChangeEvent OnTileChanged;
int GetTileSpacing();
int GetWallThickness();
void Shutdown();
bool IsSolidTile(Vector2 pos);
void HandleNetworkMessage(NetIncomingMessage message);
void HandleAtmosDisplayUpdate(NetIncomingMessage message);
>>>>>>>
event TileChangedEventHandler TileChanged;
<<<<<<<
int TileSize { get; }
=======
ITile GetWallAt(Vector2 pos);
ITile GetFloorAt(Vector2 pos);
ITile[] GetAllTilesAt(Vector2 pos);
>>>>>>>
int TileSize { get; } |
<<<<<<<
CluwneLib.TileSize = MapManager.TileSize;
=======
>>>>>>>
CluwneLib.TileSize = MapManager.TileSize;
<<<<<<<
=======
>>>>>>>
<<<<<<<
//Debug.DebugRendertarget(playerOcclusionTarget);
=======
>>>>>>>
//Debug.DebugRendertarget(playerOcclusionTarget); |
<<<<<<<
=======
using System.Collections;
using System;
using System.Collections.Generic;
>>>>>>>
using System;
using System.Collections.Generic;
<<<<<<<
public ProductSearchController(ICategoryService categoryService, IProductOptionManager productOptionManager, IProductService productService)
{
=======
public ProductSearchController(ICategoryService categoryService, IProductOptionManager productOptionManager, IProductService productService, IProductSearchService productSearchService)
{
>>>>>>>
public ProductSearchController(ICategoryService categoryService, IProductOptionManager productOptionManager, IProductService productService, IProductSearchService productSearchService)
{
<<<<<<<
_productService = productService;
=======
_productService = productService;
_productSearchService = productSearchService;
>>>>>>>
_productService = productService;
_productSearchService = productSearchService; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.