vendredi 1 mai 2020

python how to reflect line between 2 points off of line of angle x?

I have x,y and x1,y1 as 2 endpoints of a line, in this case basically the vector. in between them is a line from (0,0) of angle x. How do I model the reflection of the vector on the angled line?

As far as I know, I could just get the line as vectors parallel and perpendicular to the angled line, then negate the perpendicular one. Sadly, I don't know how to do this mathematically.

Best I have is convert it to angle and magnitude, subtract the angled line angle from it, then negate the y value and rotate it back, but this involves a lot of calculation.





How to invoke generic method with Action

I want this code to be called generic.

services.AddDbContext<ProductsDbContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
        sqlServerOptions =>
        {
            sqlServerOptions.MigrationsAssembly("Modules.Products");
        });
});

It's from entityframeworkcore. See the documentation here.

I created a class for getting the builder:

public static class DbContextExtensions
{
    public static Action<DbContextOptionsBuilder> GetDbContextOptionsBuilder(string connectionString, AssemblyName moduleName)
    {
        return options =>
        {
            options.UseSqlServer(connectionString,
                sqlServerOptions =>
                {
                    sqlServerOptions.MigrationsAssembly(moduleName.Name);
                });
        };
    }
}

And I created the following for invoke the method:

var moduleAssembly = Assembly.GetAssembly(manifest);
var moduleName = moduleAssembly.GetName();

// Get dbcontext like ProductsDbContext
var dbContext = moduleAssembly.GetTypes().Where(p => typeof(DbContext).IsAssignableFrom(p)).First();

// Get the correct extensionmethod with Action<DbContextOptionsBuilder>
MethodInfo addDbContextMethod = typeof(EntityFrameworkServiceCollectionExtensions)
    .GetMethod(nameof(EntityFrameworkServiceCollectionExtensions.AddDbContext),
        1,
        new Type[] { typeof(ServiceCollection), typeof(Action<DbContextOptionsBuilder>), typeof(ServiceLifetime), typeof(ServiceLifetime) });
MethodInfo generic = addDbContextMethod.MakeGenericMethod(dbContext);


// But how to pass the Action<DbContextOptionsBuilder> method?
// I tried the following but i'm lost...
var delegateType = typeof(Action<>).MakeGenericType(typeof(DbContextOptionsBuilder));
var methodInfo = typeof(DbContextExtensions).GetMethod(nameof(DbContextExtensions.GetDbContextOptionsBuilder));
var del = Delegate.CreateDelegate(delegateType, null, methodInfo);

// invoke subscribe method
generic.Invoke(services, new[] { del });

Any ideas? Thanks





TFS build failing when adding a .runsettings file

I'm trying to specify a runsettings file from VS to add some coverage rules.

Since I added it, one of the tests started to fail.

The test uses reflection to load a dependent assembly and enforce some validation on its classes.

String FluentMigratorFullName = "MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
var fluentMigratorAssemblyName = new AssemblyName(FluentMigratorFullName);
var fluentMigratorAssembly = Assembly.Load(fluentMigratorAssemblyName);

The error I get is:

System.IO.FileNotFoundException: Could not load file or assembly 'MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

This works fine locally.

I know there is a AssemblyResolution parameter, but the location would be different at each execution as it depends on the agent picking up the build.

This is my .runsettings

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <!-- Configurations that affect the Test Framework -->
  <RunConfiguration>

  </RunConfiguration>

  <!-- Configurations for data collectors -->
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
        <Configuration>
          <CodeCoverage>
            <ModulePaths>
              <Exclude>
                <ModulePath>.*MyModule.*</ModulePath>
              </Exclude>
            </ModulePaths>

            <!-- We recommend you do not change the following values: -->
            <UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
            <AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
            <CollectFromChildProcesses>True</CollectFromChildProcesses>
            <CollectAspDotNet>False</CollectAspDotNet>

          </CodeCoverage>
        </Configuration>
      </DataCollector>

    </DataCollectors>
  </DataCollectionRunSettings>

  <!-- Parameters used by tests at runtime -->
  <TestRunParameters>

  </TestRunParameters>

  <!-- Adapter Specific sections -->

  <!-- MSTest adapter -->
  <MSTest>
    <MapInconclusiveToFailed>false</MapInconclusiveToFailed>
    <CaptureTraceOutput>true\<CaptureTraceOutput>
  </MSTest>

</RunSettings>

What am I doing wrong?





Get Property that has max Character size from list of objects java

I have an List<Staff> where i will be getting those values from db. I need to find the max character size of a specific field which will be dynamic. For now im able to get the max size of firstName but its kind of hardcoded as shown below.

 public class Staff {

    private String firstName;
    private String lastName;
    private String surName;
    private String mailId;
}

List<String> fields = Arrays.asList("firstName", "lastName", "surName");
List<Staff> staffList = staffRepository.findAll();

fields.stream.map(field ->
Long maxLength = staffList.stream()
.map(Staff::getFirstName()) // i need to pass the field which will be dynamically changing
.mapToInt(String::length)
.max()).mapToLong(max -> max.orElse(0)).sum()




How to get `Type.GenericParameterPosition` for method parameter of class-generic type

It's easy to get the GenericParameterPosition for a parameter when its type is a generic type argument of the method:

public class MyClass {
    public void Foo<T>(T a) { }
}

// ...

Console.WriteLine("pos: " + typeof(MyClass)
    .GetMethod("Foo")
    .GetParameters()
    .Single()
    .ParameterType
    .GenericParameterPosition);

pos: 0

But how can we accomplish this for a parameter who's type is a generic type argument of the class?

public class MyClass<T> {
    public void Foo(T a) { }
}

// ...

Console.WriteLine("pos: " + typeof(MyClass<int>)
    .GetMethod("Foo")
    .GetParameters()
    .Single()
    .ParameterType
    .GenericParameterPosition);

InvalidOperationException: Method may only be called on a Type for which Type.IsGenericParameter is true.





Automaticly generate code to dynamicly cerate java objects

I have classes which are automatically created from a JSON schema. In my Example one of these classes is called AvroPropertie.

Declaring and initializing objects from this class looks like this:

AvroPropertie aPropertie = AvroPropertie.newBuilder()
                    .setName(properties.get("name").asText())
                    .setDate(properties.get("date").asText())
                    .build();

If the JSON schema differs the variables like name and date differ as well. There could be more, less or totally different ones. It's always only these setters and the build() method at the end.

Is there a way to generate this code automatically? Maybe reflection?

More context: Is the ApacheAvro Serializing and deserializing with code generation.

Ty!





How do I use a function on individual variables in a collection of objects

I'm looking for a way to apply a function to a collection of objects each with multiple variables of the same time such that I can apply the function to each of the objects in the collection and select which of the variables I want to apply it to. For example: take the class

point{
   int x;
   int y;
   int z;
}

Now let's say that I wish to apply the function "flatten" to a list of these points such that one of it's variables becomes 0.

Where flatten might be something like:

   flatten<variableName>(List<Point> points){
          foreach(var point in points){
             point.<variableName> = 0;
          }
   }

Does anybody know if this is possible with c#, maybe using some kind of reflection like structure? I know it can be done in Javascript and I was hoping to do this in c# as it would prevent a lot of duplicate code (note the real function I want to use this for is far larger and contains multiple sub functions).