问:
How to get ApplicationContext in main function - Spring boot
I want to combine two libraries - JavaFx and Spring Boot, thus I need to have an instance of ApplicationContext in my start() method in main class:

Main class:

```<code>@SpringBootApplication
public class JavaFXandSpringBootTestApplication extends Application{

    @Autowired
    ApplicationContext ctx;

    public static void main(String[] args) {
        SpringApplication.run(JavaFXandSpringBootTestApplication.class, args);
        launch();
    }

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/LogIn.fxml"));
        loader.setController(ctx.getBean(LogInController.class)); // HERE OCCURES ERROR
        Scene scene = new Scene((Parent)loader.load());
        stage.setScene(scene);
        stage.show();

    }

}
</code>```

Controller class:

```<code>@Component
public class LogInController {

}
</code>```

As I have read the documentary @SpringBootApplication enables auto detect of Components and under the hood is also annotating the class with @Configuration.
So now, why am i reciving a NullPointerException in commended line? It's because that ctx isn't injected properly, but why? What am i doing wrong?

答:
You can't inject the ApplicationContext (or anything else) into the Application instance on which start() is invoked: that instance of Application is created for you by JavaFX, not by Spring. Since it's not a spring-managed object, there is no mechanism for Spring to inject anything into it.

Move the call to SpringApplication.run() to the init() method, where you can simply assign the context directly. Also, imho a better way to let the controllers be Spring-managed is to tell the FXMLLoader to create controllers via Spring, which you can do with a controller factory. See Dependency Injection and JavaFX.

```<code>@SpringBootApplication
public class JavaFXandSpringBootTestApplication extends Application{

    private ApplicationContext ctx;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void init() {
        String[] args = getParameters().getRaw().toArray(new String[0]);
        ctx = SpringApplication.run(JavaFXandSpringBootTestApplication.class, args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/LogIn.fxml"));
        loader.setControllerFactory(ctx::getBean);
        // or, if you prefer,
        // loader.setController(ctx.getBean(LoginController.class));
        // though the controller factory approach lets you use `fx:controller` as usual.
        Scene scene = new Scene((Parent)loader.load());
        stage.setScene(scene);
        stage.show();

    }

}
</code>```

Body:
I want to combine two libraries - JavaFx and Spring Boot, thus I need to have an instance of ApplicationContext in my start() method in main class:

Main class:

@SpringBootApplication
public class JavaFXandSpringBootTestApplication extends Application{

    @Autowired
    ApplicationContext ctx;

    public static void main(String[] args) {
        SpringApplication.run(JavaFXandSpringBootTestApplication.class, args);
        launch();
    }

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/LogIn.fxml"));
        loader.setController(ctx.getBean(LogInController.class)); // HERE OCCURES ERROR
        Scene scene = new Scene((Parent)loader.load());
        stage.setScene(scene);
        stage.show();

    }

}

Controller class:

@Component
public class LogInController {

}

As I have read the documentary @SpringBootApplication enables auto detect of Components and under the hood is also annotating the class with @Configuration.
So now, why am i reciving a NullPointerException in commended line? It's because that ctx isn't injected properly, but why? What am i doing wrong?

Body:
You can't inject the ApplicationContext (or anything else) into the Application instance on which start() is invoked: that instance of Application is created for you by JavaFX, not by Spring. Since it's not a spring-managed object, there is no mechanism for Spring to inject anything into it.

Move the call to SpringApplication.run() to the init() method, where you can simply assign the context directly. Also, imho a better way to let the controllers be Spring-managed is to tell the FXMLLoader to create controllers via Spring, which you can do with a controller factory. See Dependency Injection and JavaFX.

@SpringBootApplication
public class JavaFXandSpringBootTestApplication extends Application{

    private ApplicationContext ctx;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void init() {
        String[] args = getParameters().getRaw().toArray(new String[0]);
        ctx = SpringApplication.run(JavaFXandSpringBootTestApplication.class, args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/LogIn.fxml"));
        loader.setControllerFactory(ctx::getBean);
        // or, if you prefer,
        // loader.setController(ctx.getBean(LoginController.class));
        // though the controller factory approach lets you use `fx:controller` as usual.
        Scene scene = new Scene((Parent)loader.load());
        stage.setScene(scene);
        stage.show();

    }

}


来源: stackexchange

问:
Create new php var which increments from previous var without changing the inital var in PHP
I need to take a variable of the current month (in this case output as the number "1") - and output it is the numbers "02" and "03". I'm trying to do this:

```<code><?php $current_month = "{current_time format="%m"}";
$next_month = "0".$current_month++;
$third_month = "0".$next_month++;
?>
</code>```

but this is changing the original variable, which I don't want to do. How do I accomplish this?

Thanks for the help.

答:
Just use + 1:

```<code><?php
$current_month = "{current_time format="%m"}";
$next_month = "0". ($current_month + 1);
$third_month = "0". ($next_month + 2); ?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to take a variable of the current month (in this case output as the number "1") - and output it is the numbers "02" and "03". I'm trying to do this:

<?php $current_month = "{current_time format="%m"}";
$next_month = "0".$current_month++;
$third_month = "0".$next_month++;
?>

but this is changing the original variable, which I don't want to do. How do I accomplish this?

Thanks for the help.

Body:
Just use + 1:

<?php
$current_month = "{current_time format="%m"}";
$next_month = "0". ($current_month + 1);
$third_month = "0". ($next_month + 2); ?>


问:
Animation in Angular 5 runs instantly
I create a trigger with two states and a transition between two states

When I click to make animation it runs instantly even when I enter 3000ms transition time

```<code><div class="divv" [@goals]='stateExression'>
  <mat-card class="example-card">
    <mat-card-header>
      <div mat-card-avatar class="example-header-image"></div>
      <mat-card-title>Shiba Inu</mat-card-title>
      <mat-card-subtitle>Dog Breed</mat-card-subtitle>
    </mat-card-header>
    <img mat-card-image src="https://material.angular.io/assets/img/examples/shiba2.jpg" alt="Photo of a Shiba Inu">
    <mat-card-content>
      <p>
        Hello
      </p>
    </mat-card-content>
    <mat-card-actions>
      <button mat-button (click)="anim()">LIKE</button>
      <button mat-button>SHARE</button>
    </mat-card-actions>
  </mat-card>
</div>
</code>```

state change function :

```<code>stateExression : string='inactive';

anim() {
  if(this.stateExression === 'inactive')
  this.stateExression ='expended';
  else
  this.stateExression = 'inactive';
}
</code>```

Animation trigger :

```<code>trigger('goals', [
    state('inactive', style({
      height: '300px'
  })),
    state('expended', style({
      height: '0px'
  })),
  transition ('inactive <=> expanded',animate('2000ms'))

  ])
]
</code>```

How to make transition runs slowly ?

答:
```<code>trigger('goals', [
    state('inactive', style({
      height: '300px'
  })),
    state('expended', style({
          ^^^^^^^^^^^
      height: '0px'
  })),
  transition ('inactive <=> expanded',animate('2000ms'))
                           ^^^^^^^^^^
  ])
]
</code>```

state names are different expanded vs expended

ContentLicense: CC BY-SA 3.0

Title: Animation in Angular 5 runs instantly

Body:
I create a trigger with two states and a transition between two states

When I click to make animation it runs instantly even when I enter 3000ms transition time

  <mat-card class="example-card">
    <mat-card-header>

      <mat-card-title>Shiba Inu</mat-card-title>
      <mat-card-subtitle>Dog Breed</mat-card-subtitle>
    </mat-card-header>

    <mat-card-content>

        Hello

    </mat-card-content>
    <mat-card-actions>
      <button mat-button (click)="anim()">LIKE</button>
      <button mat-button>SHARE</button>
    </mat-card-actions>
  </mat-card>

state change function :

stateExression : string='inactive';

anim() {
  if(this.stateExression === 'inactive')
  this.stateExression ='expended';
  else
  this.stateExression = 'inactive';
}

Animation trigger :

trigger('goals', [
    state('inactive', style({
      height: '300px'
  })),
    state('expended', style({
      height: '0px'
  })),
  transition ('inactive <=> expanded',animate('2000ms'))

  ])
]

How to make transition runs slowly ?

Body:
trigger('goals', [
    state('inactive', style({
      height: '300px'
  })),
    state('expended', style({
          ^^^^^^^^^^^
      height: '0px'
  })),
  transition ('inactive <=> expanded',animate('2000ms'))
                           ^^^^^^^^^^
  ])
]

state names are different expanded vs expended


问:
No parameterless constructor defined for this object in automapper

Question

I have the following value resolver:

```<code>public class StudentResolver : IValueResolver<Lesson, LessonResponse, UserResponse>
{
    private readonly ApplicationDbContext _dbContext;

    public StudentResolver(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public UserResponse Resolve(
        Lesson lesson,
        LessonResponse response,
        UserResponse member,
        ResolutionContext context)
    {
        var user = _dbContext.Users
            .Where(x => x.Id == lesson.StudentId)
            .FirstOrDefault();
        if (user == null)
            return null;
        var result = Mapper.Map<UserResponse>(user); // this line triggers a "no parameterless constructor", why?
        return result;
    }
}
</code>```

This resolver tries to fetch the Student attribute for this model:

```<code>public class LessonResponse
{
    public string Id { get; set; }

    public UserResponse Student { get; set; }
}
</code>```

But on the line:

```<code>var result = Mapper.Map<UserResponse>(user);
</code>```

I get:

{System.MissingMethodException: No parameterless constructor defined for this object.   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)   at System.Activator.CreateInstance(Type type, Boolean nonPublic)   at System.Activator.CreateInstance(Type type)   at AutoMapper.MappingOperationOptions`2.CreateInstanceT}

The only type in that expression that should be created is UserResponse which is defined as follows:

```<code>public class UserResponse
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Picture { get; set; }
    public string X { get; set; }

    public bool IsAdmin { get; set; }
    public bool IsClient { get; set; }
    public bool IsInstructor { get; set; }
}
</code>```

But it is constructible, so what am I doing wrong?

Extra

The mapping profile is the following:

```<code>public class MappingProfile : Profile
{
    public MappingProfile() {
        CreateMap<Lesson, LessonResponse>()
            .ForMember(
                dest => dest.Student,
                opts => opts.ResolveUsing<StudentResolver>());

    }
}
</code>```

And the mapping for the user is:

```<code>public class MappingProfile : Profile
{
    public MappingProfile() {
        CreateMap<ApplicationUser, UserResponse>()
            .ForMember(
                dest => dest.FullName,
                opts => opts.MapFrom(
                    origin => origin.FirstName + " " + origin.LastName))
            .ForMember(
                dest => dest.IsAdmin,
                opts => opts.ResolveUsing<IsAdminResolver>())
            .ForMember(
                dest => dest.IsInstructor,
                opts => opts.ResolveUsing<IsInstructorResolver>())
            .ForMember(
                dest => dest.IsClient,
                opts => opts.ResolveUsing<IsClientResolver>());
    }
}
</code>```

The boolean resolvers are all similar to:

```<code>public class IsAdminResolver : IValueResolver<ApplicationUser, UserResponse, bool>
{
    private readonly UserManager<ApplicationUser> _userManager;

    public IsAdminResolver(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public bool Resolve(ApplicationUser user, UserResponse response, bool member, ResolutionContext context)
    {
        return _userManager.IsInRoleAsync(user, "Admin").Result;
    }
}
</code>```

答: I had the same problem because of my inattention. I generated it with Visual Studio quick tip default constructor for the class inherited from Profile which was protected instead of public. I hope this will help somebody.

Body:
Question

I have the following value resolver:

public class StudentResolver : IValueResolver<Lesson, LessonResponse, UserResponse>
{
    private readonly ApplicationDbContext _dbContext;

    public StudentResolver(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public UserResponse Resolve(
        Lesson lesson,
        LessonResponse response,
        UserResponse member,
        ResolutionContext context)
    {
        var user = _dbContext.Users
            .Where(x => x.Id == lesson.StudentId)
            .FirstOrDefault();
        if (user == null)
            return null;
        var result = Mapper.Map<UserResponse>(user); // this line triggers a "no parameterless constructor", why?
        return result;
    }
}

This resolver tries to fetch the Student attribute for this model:

public class LessonResponse
{
    public string Id { get; set; }

    public UserResponse Student { get; set; }
}

But on the line:

var result = Mapper.Map<UserResponse>(user);

I get:

{System.MissingMethodException: No parameterless constructor defined for this object.   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)   at System.Activator.CreateInstance(Type type, Boolean nonPublic)   at System.Activator.CreateInstance(Type type)   at AutoMapper.MappingOperationOptions`2.CreateInstanceT}

The only type in that expression that should be created is UserResponse which is defined as follows:

public class UserResponse
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Picture { get; set; }
    public string X { get; set; }

    public bool IsAdmin { get; set; }
    public bool IsClient { get; set; }
    public bool IsInstructor { get; set; }
}

But it is constructible, so what am I doing wrong?

Extra

The mapping profile is the following:

public class MappingProfile : Profile
{
    public MappingProfile() {
        CreateMap<Lesson, LessonResponse>()
            .ForMember(
                dest => dest.Student,
                opts => opts.ResolveUsing<StudentResolver>());

    }
}

And the mapping for the user is:

public class MappingProfile : Profile
{
    public MappingProfile() {
        CreateMap<ApplicationUser, UserResponse>()
            .ForMember(
                dest => dest.FullName,
                opts => opts.MapFrom(
                    origin => origin.FirstName + " " + origin.LastName))
            .ForMember(
                dest => dest.IsAdmin,
                opts => opts.ResolveUsing<IsAdminResolver>())
            .ForMember(
                dest => dest.IsInstructor,
                opts => opts.ResolveUsing<IsInstructorResolver>())
            .ForMember(
                dest => dest.IsClient,
                opts => opts.ResolveUsing<IsClientResolver>());
    }
}

The boolean resolvers are all similar to:

public class IsAdminResolver : IValueResolver<ApplicationUser, UserResponse, bool>
{
    private readonly UserManager<ApplicationUser> _userManager;

    public IsAdminResolver(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public bool Resolve(ApplicationUser user, UserResponse response, bool member, ResolutionContext context)
    {
        return _userManager.IsInRoleAsync(user, "Admin").Result;
    }
}

ContentLicense: CC BY-SA 4.0


问:
Powerful algorithms too complex to implement
What are some algorithms of legitimate utility that are simply too complex to implement?

Let me be clear: I'm not looking for algorithms like the current asymptotic optimal matrix multiplication algorithm, which is reasonable to implement but has a constant that makes it useless in practice. I'm looking for algorithms that could plausibly have practical value, but are so difficult to code that they have never been implemented, only implemented in extremely artificial settings, or only implemented for remarkably special-purpose applications.

Also welcome are near-impossible-to-implement algorithms that have good asymptotics but would likely have poor real performance.

答: I'm not sure I know what you're asking, but standard NP Incomplete calculations are pretty difficult as far as I know, and they have real world value in many ways, for example computing the most efficient routes for data transmission, or cutting circuit boards, or routing power to power grids...the possibilities are legion.</p>


问:
Fix PIL.ImageDraw.Draw.line with wide lines
From the PIL Documentation:

PIL.ImageDraw.Draw.line(xy, fill=None, width=0)

Draws a line between the coordinates in the xy list.

Parameters:

xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or    numeric values like [x, y, x, y, ...].

fill – Color to use for the    line.

width – The line width, in pixels. Note that line joins are not    handled well, so wide polylines will not look good.

I'm looking for a fix for this issue. A good solution for me would be to have the line drawn by PIL.ImageDraw have rounded ends (capstyle in TKinter). Is there an equivalent in PIL.ImageDraw?

This is what I would like to obtain:

Minimal Working Example:

```<code>from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

MyDraw.line([100,100,150,200], width=40, fill=BLUE)
MyDraw.line([150,200,300,100], width=40, fill=BLUE)
MyDraw.line([300,100,500,300], width=40, fill=BLUE)

MyImage.show()
</code>```

Result from MWE:

答:
I have the same problem as you.  However, you can easily solve the problem by simply plotting a circle of the same diameter as the line widths at each vertex.  Below is your code, slightly modified, to fix the problem

```<code>from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
RED  = "#ff0000"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

# Note: Odd line widths work better for this algorithm,
# even though the effect might not be noticeable at larger line widths

LineWidth = 41

MyDraw.line([100,100,150,200], width=LineWidth, fill=BLUE)
MyDraw.line([150,200,300,100], width=LineWidth, fill=BLUE)
MyDraw.line([300,100,500,300], width=LineWidth, fill=BLUE)

Offset = (LineWidth-1)/2

# I have plotted the connecting circles in red, to show them better
# Even though they look smaller than they should be, they are not.
# Look at the diameter of the circle and the diameter of the lines -
# they are the same!

MyDraw.ellipse ((150-Offset,200-Offset,150+Offset,200+Offset), fill=RED)
MyDraw.ellipse ((300-Offset,100-Offset,300+Offset,100+Offset), fill=RED)

MyImage.show()
</code>```

Body:
From the PIL Documentation:

PIL.ImageDraw.Draw.line(xy, fill=None, width=0)

Draws a line between the coordinates in the xy list.

Parameters:

xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or    numeric values like [x, y, x, y, ...].

fill – Color to use for the    line.

width – The line width, in pixels. Note that line joins are not    handled well, so wide polylines will not look good.

I'm looking for a fix for this issue. A good solution for me would be to have the line drawn by PIL.ImageDraw have rounded ends (capstyle in TKinter). Is there an equivalent in PIL.ImageDraw?

This is what I would like to obtain:

Minimal Working Example:

from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

MyDraw.line([100,100,150,200], width=40, fill=BLUE)
MyDraw.line([150,200,300,100], width=40, fill=BLUE)
MyDraw.line([300,100,500,300], width=40, fill=BLUE)

MyImage.show()

Result from MWE:

Body:
I have the same problem as you.  However, you can easily solve the problem by simply plotting a circle of the same diameter as the line widths at each vertex.  Below is your code, slightly modified, to fix the problem

from PIL import Image, ImageDraw

WHITE = (255, 255, 255)
BLUE = "#0000ff"
RED  = "#ff0000"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)

# Note: Odd line widths work better for this algorithm,
# even though the effect might not be noticeable at larger line widths

LineWidth = 41

MyDraw.line([100,100,150,200], width=LineWidth, fill=BLUE)
MyDraw.line([150,200,300,100], width=LineWidth, fill=BLUE)
MyDraw.line([300,100,500,300], width=LineWidth, fill=BLUE)

Offset = (LineWidth-1)/2

# I have plotted the connecting circles in red, to show them better
# Even though they look smaller than they should be, they are not.
# Look at the diameter of the circle and the diameter of the lines -
# they are the same!

MyDraw.ellipse ((150-Offset,200-Offset,150+Offset,200+Offset), fill=RED)
MyDraw.ellipse ((300-Offset,100-Offset,300+Offset,100+Offset), fill=RED)

MyImage.show()


问:
How do I find the earliest date in PostgreSQL?
I am working with a Postgres table that has a field named first_contact_date where it is of type date.  I am using the the mm/dd/yyyy representation of a date.
My query works correctly as written but it orders literally by month.

```<code>SELECT first_contact_date
FROM schema.table
ORDER BY first_contact_date
</code>```

For example "10/3/2016" would go after "1/2/2017", even though in a date sense, it should be "1/2/2017" that goes after "10/3/2016".

I have looked at

How to find the earliest and latest date from a database, but its too vague and I am using an order by already.

SQL ordering by earliest date in group, but I am using a different format.

How do I return the record with the earliest date?, ditto with number 2

and

PostgreSQL query where date oldest, but this limits it to one year

How to I structure the query so that the earliest date from a calendar perspective is returned?

答:
You can extract interval starting from beginning of year and order by it:

```<code>SELECT first_contact_date-date_trunc('year',first_contact_date), first_contact_date
FROM schema.table
ORDER BY 1;
</code>```

Edit: Long years might not work properly as duration starting from begining of year might differ after February.

This is a bit dirty, but will work correctly also for long years:

```<code>    SELECT to_char(first_contact_date,'MM')::int*100+to_char(first_contact_date,'DD')::int datenum
FROM schema.table
ORDER BY 1;
</code>```

Body:
I am working with a Postgres table that has a field named first_contact_date where it is of type date.  I am using the the mm/dd/yyyy representation of a date.
My query works correctly as written but it orders literally by month.

SELECT first_contact_date
FROM schema.table
ORDER BY first_contact_date

For example "10/3/2016" would go after "1/2/2017", even though in a date sense, it should be "1/2/2017" that goes after "10/3/2016".

I have looked at

How to find the earliest and latest date from a database, but its too vague and I am using an order by already.

SQL ordering by earliest date in group, but I am using a different format.

How do I return the record with the earliest date?, ditto with number 2

and

PostgreSQL query where date oldest, but this limits it to one year

How to I structure the query so that the earliest date from a calendar perspective is returned?

Body:
You can extract interval starting from beginning of year and order by it:

SELECT first_contact_date-date_trunc('year',first_contact_date), first_contact_date
FROM schema.table
ORDER BY 1;

Edit: Long years might not work properly as duration starting from begining of year might differ after February.

This is a bit dirty, but will work correctly also for long years:

    SELECT to_char(first_contact_date,'MM')::int*100+to_char(first_contact_date,'DD')::int datenum
FROM schema.table
ORDER BY 1;


问:
glLookAt moves camera position when lookAt is moved - role of projection matrix?
Short version: I'm using a glLookAt view matrix with a perspective projection matrix, and I'm wondering why a change in the camLookAt vector (the point where I'm looking at) leads to a change in the camera's position.

Long version: I'm using the code described here for my own implementation of the well-known glLookAt function:

```<code>        var z = glm.normalize(camPosition - camLookAt);
        var y = up;
        var x = glm.normalize(glm.cross(y, z));
        y = glm.cross(z, x);
        var result = new mat4(1.0f);
        result[0, 0] = x.x;
        result[1, 0] = x.y;
        result[2, 0] = x.z;
        result[3, 0] = -Dot(x, camPosition);
        result[0, 1] = y.x;
        result[1, 1] = y.y;
        result[2, 1] = y.z;
        result[3, 1] = -Dot(y, camPosition);
        result[0, 2] = z.x;
        result[1, 2] = z.y;
        result[2, 2] = z.z;
        result[3, 2] = -Dot(z, camPosition);
        result[0, 3] = 0;
        result[1, 3] = 0;
        result[2, 3] = 0;
        result[3, 3] = 1.0f;
        return result;
</code>```

This seems to work nicely, except for one strange thing: When I leave the cam's position fixed, but change the camLookAt variable, it seems that the camera moves not just its angle, but also its position.

To demonstrate it, I have made an explicit calculation:

Take the world points (0, 0, 0) and (1, 0, 0).

Look at them from camPosition = (-3, 0, 0) and camLookAt = (0, 0, 0) with up = (0, 0, 1). So we're looking at the origin, in the direction of the positive x axis. This is the matrix I get:

```
     0, -1,  0,  0
     0,  0,  1,  0
    -1,  0,  0, -3
     0,  0,  0,  1
```

Since both points lie on the x axis, they should appear at the same spot on our camera. One dot should be exactly behind the other one. This works great, the first point gets mapped to (0, 0, -3) and the second one to (0, 0, -4).

Now change camLookAt to (0, 3, 0), i.e. rotate the camera by 45 degrees to the left. This is the matrix I get:

```
     0.71, -0.71,  0.00,  2.12
     0.00,  0.00,  1.00,  0.00
    -0.71, -0.71,  0.00, -2.12
     0.00,  0.00,  0.00,  1.00
```

Since we don't move the camera's position, the points should still be behind each other. However, this isn't the case, the two points get transformed to (2.1213, 0, -2.1213) and (2.8284, 0, -2.8284) respectively. So the (X,Y) components of the two transformed points do not match.

Now, up to this point we have used Euclidean transformations only, so there is no perspective yet. However, I'm using a perspective projection matrix like this

```<code>const float radians = (60.0f / 360.0f) * (float)Math.PI * 2.0f;
projectionMatrix = glm.perspective(radians, width / height, 0.01f, 1000f);
</code>```

Even after this projection matrix is applied, the two points don't land on the same (X, Y) coordinates, i.e. on the same pixel on screen.

What am I missing? Is that the intended behavior of glLookAt, or am I using / implementing it wrong?

EDIT: The projection matrix is applied in the vertex shader, simply like this:

```<code>void main(void) {
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
}
</code>```

EIDT 2: Here's a recording of my current scene, just as clarification. The only thing that's being changed with time is the camLookAt vector. The camera should stay at the same position, but somehow it seems to move:

EDIT 3: As recommended by @NicoSchertler, I just did all the calculations on the CPU. The viewMatrix multiplication is done above, and it results in (2.1213, 0, -2.1213) and (2.8284, 0, -2.8284) respectively. Now I apply the projection matrix (see above for how I'm getting the projection matrix):

```
    1.30,  .00,   .00,  .00
     .00, 1.73,   .00,  .00
     .00,  .00, -1.00, -.02
     .00,  .00, -1.00, 1.00
```

and I get the following vectors

```<code>(2.75, 0.00, 2.10, 3.12)
(3.67, 0.00, 2.81, 3.83)
</code>```

Then I divide them by their w value which yields

```<code>(0.88, 0.00, 0.67, 1.00)
(0.96, 0.00, 0.73, 1.00)
</code>```

So they clearly are not behind each other.

Is there a bug in the projection matrix?

答:
However, this isn't the case, (...) the (X,Y) components of the two transformed points do not match.

The two points having different x/y coordinates does not mean that they are not behind each other. Obviously, they have a different depth. The camera is located at the origin in this coordinate system. And if you calculate the direction from camera to the points (i.e. normalize(p - 0)), we get:

```<code>direction1 = {0.707107, 0, -0.707107}
direction2 = {0.707107, 0, -0.707107}
</code>```

So, the direction from the camera to the two points is the same, hence they are behind each other.

You haven't shown how you do the projection. But the points must project onto the same location. There is a little caveat with perspective projections, though. The projected point will have a w-component that is not 1. You need to divide the point by this w-component (perspective divide) to find the actual projected point. And then, the x/y coordinates should actually match.

Body:
Short version: I'm using a glLookAt view matrix with a perspective projection matrix, and I'm wondering why a change in the camLookAt vector (the point where I'm looking at) leads to a change in the camera's position.

Long version: I'm using the code described here for my own implementation of the well-known glLookAt function:

        var z = glm.normalize(camPosition - camLookAt);
        var y = up;
        var x = glm.normalize(glm.cross(y, z));
        y = glm.cross(z, x);
        var result = new mat4(1.0f);
        result[0, 0] = x.x;
        result[1, 0] = x.y;
        result[2, 0] = x.z;
        result[3, 0] = -Dot(x, camPosition);
        result[0, 1] = y.x;
        result[1, 1] = y.y;
        result[2, 1] = y.z;
        result[3, 1] = -Dot(y, camPosition);
        result[0, 2] = z.x;
        result[1, 2] = z.y;
        result[2, 2] = z.z;
        result[3, 2] = -Dot(z, camPosition);
        result[0, 3] = 0;
        result[1, 3] = 0;
        result[2, 3] = 0;
        result[3, 3] = 1.0f;
        return result;

This seems to work nicely, except for one strange thing: When I leave the cam's position fixed, but change the camLookAt variable, it seems that the camera moves not just its angle, but also its position.

To demonstrate it, I have made an explicit calculation:

Take the world points (0, 0, 0) and (1, 0, 0).

Look at them from camPosition = (-3, 0, 0) and camLookAt = (0, 0, 0) with up = (0, 0, 1). So we're looking at the origin, in the direction of the positive x axis. This is the matrix I get:

     0, -1,  0,  0
     0,  0,  1,  0
    -1,  0,  0, -3
     0,  0,  0,  1

Since both points lie on the x axis, they should appear at the same spot on our camera. One dot should be exactly behind the other one. This works great, the first point gets mapped to (0, 0, -3) and the second one to (0, 0, -4).

Now change camLookAt to (0, 3, 0), i.e. rotate the camera by 45 degrees to the left. This is the matrix I get:

     0.71, -0.71,  0.00,  2.12
     0.00,  0.00,  1.00,  0.00
    -0.71, -0.71,  0.00, -2.12
     0.00,  0.00,  0.00,  1.00

Since we don't move the camera's position, the points should still be behind each other. However, this isn't the case, the two points get transformed to (2.1213, 0, -2.1213) and (2.8284, 0, -2.8284) respectively. So the (X,Y) components of the two transformed points do not match.

Now, up to this point we have used Euclidean transformations only, so there is no perspective yet. However, I'm using a perspective projection matrix like this

const float radians = (60.0f / 360.0f) * (float)Math.PI * 2.0f;
projectionMatrix = glm.perspective(radians, width / height, 0.01f, 1000f);

Even after this projection matrix is applied, the two points don't land on the same (X, Y) coordinates, i.e. on the same pixel on screen.

What am I missing? Is that the intended behavior of glLookAt, or am I using / implementing it wrong?

EDIT: The projection matrix is applied in the vertex shader, simply like this:

void main(void) {
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
}

EIDT 2: Here's a recording of my current scene, just as clarification. The only thing that's being changed with time is the camLookAt vector. The camera should stay at the same position, but somehow it seems to move:

EDIT 3: As recommended by @NicoSchertler, I just did all the calculations on the CPU. The viewMatrix multiplication is done above, and it results in (2.1213, 0, -2.1213) and (2.8284, 0, -2.8284) respectively. Now I apply the projection matrix (see above for how I'm getting the projection matrix):

    1.30,  .00,   .00,  .00
     .00, 1.73,   .00,  .00
     .00,  .00, -1.00, -.02
     .00,  .00, -1.00, 1.00

and I get the following vectors

(2.75, 0.00, 2.10, 3.12)
(3.67, 0.00, 2.81, 3.83)

Then I divide them by their w value which yields

(0.88, 0.00, 0.67, 1.00)
(0.96, 0.00, 0.73, 1.00)

So they clearly are not behind each other.

Is there a bug in the projection matrix?

Body:
However, this isn't the case, (...) the (X,Y) components of the two transformed points do not match.

The two points having different x/y coordinates does not mean that they are not behind each other. Obviously, they have a different depth. The camera is located at the origin in this coordinate system. And if you calculate the direction from camera to the points (i.e. normalize(p - 0)), we get:

direction1 = {0.707107, 0, -0.707107}
direction2 = {0.707107, 0, -0.707107}

So, the direction from the camera to the two points is the same, hence they are behind each other.

You haven't shown how you do the projection. But the points must project onto the same location. There is a little caveat with perspective projections, though. The projected point will have a w-component that is not 1. You need to divide the point by this w-component (perspective divide) to find the actual projected point. And then, the x/y coordinates should actually match.


问:
Read source file from and XML file
I have a process that is receiving files that come in pairs. One is a ctr file and the other is the data file. The ctr and data file will always have the same name except different extensions. E.g. dfghj.ctl and dfghj.dat

The problem I have is that I receive multiple of these pairs at the same time. The only way to tell which is which is to look into the ctl file. This tells me if the the .dat file related to it is either the report.jsonl file or the delta.jsonl file.

An example of a .ctl is:

```<code><DTSControl>
<Version>1.0</Version>
<AddressType>DTS</AddressType>
<MessageType>Data</MessageType>
<From_DTS>x26OT075</From_DTS>
<To_DTS>x26OT075</To_DTS>
<Subject>ECDS Submission</Subject>
<LocalId>TEST-delta.jsonl</LocalId>
<WorkflowId>SUS_CDS</WorkflowId>
<Encrypted>N</Encrypted>
<Compress>Y</Compress>
</DTSControl>
</code>```

The bit I need to get to is the LocalId which tells me what type of file the .dat is and therefore which table I need I need to load it to. Once I know which file is which, I then need to pass the associated .dat file name to a variable to populate the source connection.

The only thing I can think of is a script task to load a ctl file, isolate the LocalId and if it is like *-report.jsonl then strip the last three characters of the file and replace ctl with dat and pass that string to the variable but I've no idea how to get to LocalId as I don't work with c#.

Is anyone able to give a pointer as to how to get there? It may not always be the eighth line so I would prefer to tell it to go LocalID which won't change.

Thanks in advance

答:
Here a solution using Regex:</p>

```<code>//var input=File.ReadAllText("someFile.ctl");
var input=@"<DTSControl>
<Version>1.0</Version>
<AddressType>DTS</AddressType>
<MessageType>Data</MessageType>
<From_DTS>x26OT075</From_DTS>
<To_DTS>x26OT075</To_DTS>
<Subject>ECDS Submission</Subject>
<LocalId>TEST-delta.jsonl</LocalId>
<WorkflowId>SUS_CDS</WorkflowId>
<Encrypted>N</Encrypted>
<Compress>Y</Compress>
</DTSControl>";
Regex reg = new Regex(@".*<LocalId>(.*?)</LocalId>.*");
// Check, if it exists in the string
if(reg.IsMatch(input)){
    // Get all the Matches (here: 1)
    var mtch=reg.Matches(input);
    // collect the good stuff from the capture group
    Console.WriteLine(mtch[0].Groups[1].Value);
}
</code>```

Title: Read source file from and XML file

Body:
I have a process that is receiving files that come in pairs. One is a ctr file and the other is the data file. The ctr and data file will always have the same name except different extensions. E.g. dfghj.ctl and dfghj.dat

The problem I have is that I receive multiple of these pairs at the same time. The only way to tell which is which is to look into the ctl file. This tells me if the the .dat file related to it is either the report.jsonl file or the delta.jsonl file.

An example of a .ctl is:

<DTSControl>
<Version>1.0</Version>
<AddressType>DTS</AddressType>
<MessageType>Data</MessageType>
<From_DTS>x26OT075</From_DTS>
<To_DTS>x26OT075</To_DTS>
<Subject>ECDS Submission</Subject>
<LocalId>TEST-delta.jsonl</LocalId>
<WorkflowId>SUS_CDS</WorkflowId>
<Encrypted>N</Encrypted>
<Compress>Y</Compress>
</DTSControl>

The bit I need to get to is the LocalId which tells me what type of file the .dat is and therefore which table I need I need to load it to. Once I know which file is which, I then need to pass the associated .dat file name to a variable to populate the source connection.

The only thing I can think of is a script task to load a ctl file, isolate the LocalId and if it is like *-report.jsonl then strip the last three characters of the file and replace ctl with dat and pass that string to the variable but I've no idea how to get to LocalId as I don't work with c#.

Is anyone able to give a pointer as to how to get there? It may not always be the eighth line so I would prefer to tell it to go LocalID which won't change.

Thanks in advance

Body:
Here a solution using Regex:

//var input=File.ReadAllText("someFile.ctl");
var input=@"<DTSControl>
<Version>1.0</Version>
<AddressType>DTS</AddressType>
<MessageType>Data</MessageType>
<From_DTS>x26OT075</From_DTS>
<To_DTS>x26OT075</To_DTS>
<Subject>ECDS Submission</Subject>
<LocalId>TEST-delta.jsonl</LocalId>
<WorkflowId>SUS_CDS</WorkflowId>
<Encrypted>N</Encrypted>
<Compress>Y</Compress>
</DTSControl>";
Regex reg = new Regex(@".*<LocalId>(.*?)</LocalId>.*");
// Check, if it exists in the string
if(reg.IsMatch(input)){
    // Get all the Matches (here: 1)
    var mtch=reg.Matches(input);
    // collect the good stuff from the capture group
    Console.WriteLine(mtch[0].Groups[1].Value);
}


问:
Macros support in tooling
https://www.reddit.com/r/Kotlin/comments/7hoytl/kotlin_team_ama_ask_us_anything/dqt56nv/

Traditional macros are very hard to support well in the tooling

In Java we already have Lombok @Data what generate methods, almost the same as macros.
https://projectlombok.org/features/Data

Why macros are hard to support in tooling?

答:
Tooling can mean many different things, right from the low level of the binary code which implements macro transformations, up to the high level of the IDE where you are implementing or using your macro, which is what abreslav is mentioning. Since macros can change the meaning of the code they encompass, you start having problems like deciding which kind of source code you want to show to the user.

Imagine having a macro which prefixes all the properties with a string, uppercasing naturally the original variable during concatenation of the identifier:

```<code>someclass {
    prefix("longPrefix") {
        val a: String = ""
    }

    fun bar() {
        println("Look at $longPrefixA")
    }
}
</code>```

Imagining that this compiled and worked, you have difficult to answer design decisions, because you are displaying the original source before the macro transformation… but wouldn't it be useful to also see the code after? Also, part of the source code depends on the macro being run, which in turn means that the IDE has to actually compile and run your code while you are typing to validate that the reference to $longPrefixA is valid. In a way, you would need a compilation time debugger for the compiler/IDE just like you have your usual debugger for the runtime, if you are writing the macro in first place.

There are even more troubles when you think about control flow macros and such where the compilation abstract syntax tree is modified in non obvious ways, which is also one of the reasons macros get bad reputation for hiding the program (though I argue that comes mainly from our C textual preprocessor biased history). Even when you look at other programming languages with built in macro support, their tooling tends to be lackluster, in a way perpetuating the meme.

Title: Macros support in tooling

Body:
Tooling can mean many different things, right from the low level of the binary code which implements macro transformations, up to the high level of the IDE where you are implementing or using your macro, which is what abreslav is mentioning. Since macros can change the meaning of the code they encompass, you start having problems like deciding which kind of source code you want to show to the user.

Imagine having a macro which prefixes all the properties with a string, uppercasing naturally the original variable during concatenation of the identifier:

someclass {
    prefix("longPrefix") {
        val a: String = ""
    }

    fun bar() {
        println("Look at $longPrefixA")
    }
}

Imagining that this compiled and worked, you have difficult to answer design decisions, because you are displaying the original source before the macro transformation… but wouldn't it be useful to also see the code after? Also, part of the source code depends on the macro being run, which in turn means that the IDE has to actually compile and run your code while you are typing to validate that the reference to $longPrefixA is valid. In a way, you would need a compilation time debugger for the compiler/IDE just like you have your usual debugger for the runtime, if you are writing the macro in first place.

There are even more troubles when you think about control flow macros and such where the compilation abstract syntax tree is modified in non obvious ways, which is also one of the reasons macros get bad reputation for hiding the program (though I argue that comes mainly from our C textual preprocessor biased history). Even when you look at other programming languages with built in macro support, their tooling tends to be lackluster, in a way perpetuating the meme.


问:
Define MYSQL query according to values sent from another page
I am trying to set a MYSQL query based on the presence (or absence) of values sent across from a parent page via the URL. The variables are the following:

```<code>        $startdate = $_GET["selectstartdate"];
        $enddate = $_GET["selectenddate"];
        $ensemble = $_GET["selectensemble"];
        $venue = $_GET["selectvenue"];
        $city = $_GET["selectcity"];
</code>```

The first two will ALWAYS be non-NULL, but the remaining three have a default value of NULL, which may or may not be redefined on the parent page. So, what I need to do is to restructure my SQL query, according to which of these variables I receive.

IF only the first two variables are sent (and all others are NULL), then the following query is correct:

```<code>        $sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map
                FROM Concert, Ensemble, Venue
                WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
                AND Concert.date BETWEEN '$startdate' AND '$enddate'";
</code>```

However, if for example $ensemble is not NULL, then I would need an extra line added to my query:

```<code>                AND Ensemble.short_name='$ensemble';
</code>```

Similarly, if $venue is not NULL, then I would need:

```<code>                AND Venue.name='$venue';
</code>```

...and, of course, if $city is not NULL, then I would need:

```<code>                AND Venue.city='$city';
</code>```

I am really what the best way to go about this is. Many thanks in advance for your help!

答:
Here is your answer to manage your where conditions in simpler way:</p>

```<code><?php
// note that this mysqli_real_escape_string will prevent sql injection and $con is your connection variable
$startdate = mysqli_real_escape_string($con, $_GET["selectstartdate"]);
$enddate = mysqli_real_escape_string($con, $_GET["selectenddate"]);
$ensemble = mysqli_real_escape_string($con, $_GET["selectensemble"]);
$venue = mysqli_real_escape_string($con, $_GET["selectvenue"]);
$city = mysqli_real_escape_string($con, $_GET["selectcity"]);

$sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map
        FROM Concert, Ensemble, Venue
        WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
        AND Concert.date BETWEEN '$startdate' AND '$enddate'";
$where_clause = ["Concert.ensemble_id = Ensemble.id", "Concert.venue_id = Venue.id", "Concert.date BETWEEN '$startdate' AND '$enddate'"];

if(!empty($ensemble)) {
    $where_clause[] = "Ensemble.short_name='$ensemble'";
}

if(!empty($venue)) {
    $where_clause[] = "Venue.name='$venue'";
}

if(!empty($city)) {
    $where_clause[] = "Venue.city='$city'";
}

$sql .= " WHERE " . implode(" AND ", $where_clause);
</code>```

Body:
I am trying to set a MYSQL query based on the presence (or absence) of values sent across from a parent page via the URL. The variables are the following:

        $startdate = $_GET["selectstartdate"];
        $enddate = $_GET["selectenddate"];
        $ensemble = $_GET["selectensemble"];
        $venue = $_GET["selectvenue"];
        $city = $_GET["selectcity"];

The first two will ALWAYS be non-NULL, but the remaining three have a default value of NULL, which may or may not be redefined on the parent page. So, what I need to do is to restructure my SQL query, according to which of these variables I receive.

IF only the first two variables are sent (and all others are NULL), then the following query is correct:

        $sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map
                FROM Concert, Ensemble, Venue
                WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
                AND Concert.date BETWEEN '$startdate' AND '$enddate'";

However, if for example $ensemble is not NULL, then I would need an extra line added to my query:

                AND Ensemble.short_name='$ensemble';

Similarly, if $venue is not NULL, then I would need:

                AND Venue.name='$venue';

...and, of course, if $city is not NULL, then I would need:

                AND Venue.city='$city';

I am really what the best way to go about this is. Many thanks in advance for your help!

Body:
Here is your answer to manage your where conditions in simpler way:

<?php
// note that this mysqli_real_escape_string will prevent sql injection and $con is your connection variable
$startdate = mysqli_real_escape_string($con, $_GET["selectstartdate"]);
$enddate = mysqli_real_escape_string($con, $_GET["selectenddate"]);
$ensemble = mysqli_real_escape_string($con, $_GET["selectensemble"]);
$venue = mysqli_real_escape_string($con, $_GET["selectvenue"]);
$city = mysqli_real_escape_string($con, $_GET["selectcity"]);

$sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map
        FROM Concert, Ensemble, Venue
        WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
        AND Concert.date BETWEEN '$startdate' AND '$enddate'";
$where_clause = ["Concert.ensemble_id = Ensemble.id", "Concert.venue_id = Venue.id", "Concert.date BETWEEN '$startdate' AND '$enddate'"];

if(!empty($ensemble)) {
    $where_clause[] = "Ensemble.short_name='$ensemble'";
}

if(!empty($venue)) {
    $where_clause[] = "Venue.name='$venue'";
}

if(!empty($city)) {
    $where_clause[] = "Venue.city='$city'";
}

$sql .= " WHERE " . implode(" AND ", $where_clause);


问:
Gradle fails at task transformClassesAndResourcesWithSyncLibJarsForDebug
Gradle build fails after my AS updated to 3.1 Canary 5. Below is the error I am getting: I don't have any clue what is the problem.</p>

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':ceeutil:transformClassesAndResourcesWithSyncLibJarsForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipCachedTaskExecuter.execute(SkipCachedTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ResolveBuildCacheKeyExecuter.execute(ResolveBuildCacheKeyExecuter.java:61)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Type def recipe not found: file collection
    at com.android.build.gradle.internal.transforms.LibraryAarJarsTransform.transform(LibraryAarJarsTransform.java:95)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:221)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:217)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:212)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 34 more
</code>```

答:
I got the root cause of this bug. But don't know what is the proper solution yet.

The bug was caused by the gradle plugin for Canary 5.

```<code>classpath 'com.android.tools.build:gradle:3.1.0-alpha05'
</code>```

As it was working fine in Canary 4, so I reverted this as below

```<code>classpath 'com.android.tools.build:gradle:3.1.0-alpha04'
</code>```

Now everything started working fine. Though this is a workaround, I have to go with this as I don't have a proper fix yet. It is clearly a bug from gradle plugin.

The only problem now is, since the AS is Canary 5 and plugin is alpha4, everytime I run my app, AS asks to update the plugin.

Please let me know if you have any proper solution to this.

Body:
Gradle build fails after my AS updated to 3.1 Canary 5. Below is the error I am getting: I don't have any clue what is the problem.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':ceeutil:transformClassesAndResourcesWithSyncLibJarsForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipCachedTaskExecuter.execute(SkipCachedTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ResolveBuildCacheKeyExecuter.execute(ResolveBuildCacheKeyExecuter.java:61)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Type def recipe not found: file collection
    at com.android.build.gradle.internal.transforms.LibraryAarJarsTransform.transform(LibraryAarJarsTransform.java:95)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:221)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:217)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:212)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 34 more

Body:
I got the root cause of this bug. But don't know what is the proper solution yet.

The bug was caused by the gradle plugin for Canary 5.

classpath 'com.android.tools.build:gradle:3.1.0-alpha05'

As it was working fine in Canary 4, so I reverted this as below

classpath 'com.android.tools.build:gradle:3.1.0-alpha04'

Now everything started working fine. Though this is a workaround, I have to go with this as I don't have a proper fix yet. It is clearly a bug from gradle plugin.

The only problem now is, since the AS is Canary 5 and plugin is alpha4, everytime I run my app, AS asks to update the plugin.

Please let me know if you have any proper solution to this.


问:
Wpf DataGrid Right "Gutter" IsSelected Trigger
In a Wpf DataGrid, each row has a blank area that grows to fill the remaining space. I imagine this area is more appropriately called a "gutter", but I actually don't know the proper terminology for it. I like having this, but I noticed a problem with it. If I click on the blank area, it does not seem to process the IsSelected trigger that I have set on the Row. However, the IsMouseOver trigger is fired. Very strange. Here is a picture demonstrating the area that I have mentioned:

And here is the segment of Xaml that I think will be required to fix this. If more is needed, just tell me and I will post it.

```<code><!--  Style and template for the DataGridRow.  -->
    <Style x:Key="VoidwalkerDataGridRowStyle" TargetType="{x:Type DataGridRow}">
        <Setter Property="SnapsToDevicePixels" Value="true" />
        <Setter Property="Validation.ErrorTemplate" Value="{x:Null}" />
        <Setter Property="ValidationErrorTemplate">
            <Setter.Value>
                <ControlTemplate>
                    <TextBlock
                        Margin="2,0,0,0"
                        VerticalAlignment="Center"
                        Foreground="Red"
                        Text="!" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridRow}">
                    <Border
                        x:Name="DGR_Border"
                        Background="{DynamicResource VoidwalkerContextBrush}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        SnapsToDevicePixels="True">
                        <SelectiveScrollingGrid>
                            <SelectiveScrollingGrid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                            </SelectiveScrollingGrid.ColumnDefinitions>
                            <SelectiveScrollingGrid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="Auto" />
                            </SelectiveScrollingGrid.RowDefinitions>
                            <DataGridCellsPresenter
                                Grid.Column="1"
                                ItemsPanel="{TemplateBinding ItemsPanel}"
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                            <DataGridDetailsPresenter
                                Grid.Row="1"
                                Grid.Column="1"
                                SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding AreRowDetailsFrozen, ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical}, Converter={x:Static DataGrid.RowDetailsScrollingConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                                Visibility="{TemplateBinding DetailsVisibility}" />
                            <DataGridRowHeader
                                Grid.Row="0"
                                Grid.RowSpan="2"
                                Grid.Column="0"
                                SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
                                Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Row}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
                        </SelectiveScrollingGrid>

                    </Border>
                    <ControlTemplate.Triggers>
                        <!--
                            Alternation Coloration Triggers
                        -->
                        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                            <Setter Property="Foreground" Value="{DynamicResource VoidwalkerForegroundBrush}" />
                            <Setter TargetName="DGR_Border" Property="Background" Value="{DynamicResource VoidwalkerContextBrush}" />
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                            <Setter Property="Foreground" Value="{DynamicResource VoidwalkerForegroundBrush}" />
                            <Setter TargetName="DGR_Border" Property="Background" Value="{DynamicResource VoidwalkerControlBrush}" />
                        </Trigger>
                        <!--
                            Is Selected Triggers
                        -->
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="DGR_Border" Property="BorderBrush" Value="{DynamicResource VoidwalkerBorderBrush}" />
                            <Setter TargetName="DGR_Border" Property="Background" Value="{DynamicResource VoidwalkerBorderBrush}" />
                        </Trigger>

                        <!--
                            Is Mouse Over Triggers
                        -->
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="DGR_Border" Property="BorderBrush" Value="{DynamicResource VoidwalkerBorderBrush}" />
                            <Setter TargetName="DGR_Border" Property="Background" Value="{DynamicResource VoidwalkerBorderBrush}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Just to clarify my question even further:

When I click on the "Gutter" area in the picture, my IsSelected trigger is not fired. If I click on any cell to the left of it, that row will be selected. The strange thing is that my other IsMouseOver trigger is still fired when mousing over the gutter area. Is there a way that I can emulate the IsSelected behavior on the gutter area for the row it is on?

答:
It's only the actual cells that are selectable. You can easily make the "gutter" selectable by simply adding another blank column to your DataGrid:

```<code><DataGrid.Columns>
    ...
    <DataGridTemplateColumn Width="*" />
</DataGrid.Columns>
</code>```

Or make the last existing column stretch horizontally by setting its Width to *.

Body:
In a Wpf DataGrid, each row has a blank area that grows to fill the remaining space. I imagine this area is more appropriately called a "gutter", but I actually don't know the proper terminology for it. I like having this, but I noticed a problem with it. If I click on the blank area, it does not seem to process the IsSelected trigger that I have set on the Row. However, the IsMouseOver trigger is fired. Very strange. Here is a picture demonstrating the area that I have mentioned:

And here is the segment of Xaml that I think will be required to fix this. If more is needed, just tell me and I will post it.

Just to clarify my question even further:

When I click on the "Gutter" area in the picture, my IsSelected trigger is not fired. If I click on any cell to the left of it, that row will be selected. The strange thing is that my other IsMouseOver trigger is still fired when mousing over the gutter area. Is there a way that I can emulate the IsSelected behavior on the gutter area for the row it is on?

Body:
It's only the actual cells that are selectable. You can easily make the "gutter" selectable by simply adding another blank column to your DataGrid:

<DataGrid.Columns>
    ...
    <DataGridTemplateColumn Width="*" />
</DataGrid.Columns>

Or make the last existing column stretch horizontally by setting its Width to *.


问:
LoadError: cannot load such file -- selenium/webdriver/phantomjs
I have this code in my Cucumber Hooks file to run the ghost driver it was working until yesterday I start seeing the error message:

```<code>Before do
  Selenium::WebDriver::PhantomJS.path = 'C:\phantomjs-2.1.1-windows\bin\phantomjs.exe'
  @browser = Watir::Browser.start "https://www.google.com",  :phantomjs
  @browser.window.maximize
end
</code>```

Error message:

```<code>LoadError: cannot load such file -- selenium/webdriver/phantomjs
</code>```

答:
Yes, we've removed support for PhantomJS as of Selenium 3.8.
The PhantomJS project is no longer being maintained. If you actually do need headless, please investigate either the Chrome or Firefox headless options.</p>

Body:
I have this code in my Cucumber Hooks file to run the ghost driver it was working until yesterday I start seeing the error message:

Before do
  Selenium::WebDriver::PhantomJS.path = 'C:\phantomjs-2.1.1-windows\bin\phantomjs.exe'
  @browser = Watir::Browser.start "https://www.google.com",  :phantomjs
  @browser.window.maximize
end

Error message:

LoadError: cannot load such file -- selenium/webdriver/phantomjs


问:
Windows Phone 7 download pure HTML as string?
I have been trying to get a clear answer on how to download a page's HTML as a string for months, but have made zero progress. I can mess with all of the parsing myself, and I'll be able to figure out where it needs to fit into the application as I mess around with it. I would be very very grateful if someone could give me a clear code block to download a page's HTML as a string from a given url.</p>

答:
Here's a project I posted that demonstrated two ways of downloading html as a string and the relative merits of each.

WebClient, HttpWebRequest and the UI Thread on Windows Phone 7

HttpWebRequest gives you a nice UI performance benefit for a little extra work.


答:
Try xml linq :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {

        static void Main(string[] args)
        {
            string xml =
               "<DTSControl>" +
                    "<Version>1.0</Version>" +
                    "<AddressType>DTS</AddressType>" +
                    "<MessageType>Data</MessageType>" +
                    "<From_DTS>x26OT075</From_DTS>" +
                    "<To_DTS>x26OT075</To_DTS>" +
                    "<Subject>ECDS Submission</Subject>" +
                    "<LocalId>TEST-delta.jsonl</LocalId>" +
                    "<WorkflowId>SUS_CDS</WorkflowId>" +
                    "<Encrypted>N</Encrypted>" +
                    "<Compress>Y</Compress>" +
               "</DTSControl>";

            XDocument doc = XDocument.Parse(xml);

            string localId = (string)doc.Descendants("LocalId").FirstOrDefault();
        }
    }

}
</code>```

Title: Read source file from and XML file

Body:
Try xml linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {

        static void Main(string[] args)
        {
            string xml =
               "<DTSControl>" +
                    "<Version>1.0</Version>" +
                    "<AddressType>DTS</AddressType>" +
                    "<MessageType>Data</MessageType>" +
                    "<From_DTS>x26OT075</From_DTS>" +
                    "<To_DTS>x26OT075</To_DTS>" +
                    "<Subject>ECDS Submission</Subject>" +
                    "<LocalId>TEST-delta.jsonl</LocalId>" +
                    "<WorkflowId>SUS_CDS</WorkflowId>" +
                    "<Encrypted>N</Encrypted>" +
                    "<Compress>Y</Compress>" +
               "</DTSControl>";

            XDocument doc = XDocument.Parse(xml);

            string localId = (string)doc.Descendants("LocalId").FirstOrDefault();
        }
    }

}


问:
Android ViewGroup crash: Attempt to read from field 'int android.view.View.mViewFlags' on a null object reference
We have found several cases for this kind of crashes reported by backend logging monitoring. It seems the crashes do not tie to particular UX failure. And from the reports, there is no sign of how our own classes being involved(no sign of any of our classes names). Here is an example of typical crashes:

```<code>java.lang.NullPointerException: Attempt to read from field 'int android.view.View.mViewFlags' on a null object reference
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3357)
at android.view.View.updateDisplayListIfDirty(View.java:14288)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:273)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:279)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:318)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2561)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2377)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2007)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1086)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6453)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:846)
at android.view.Choreographer.doCallbacks(Choreographer.java:647)
at android.view.Choreographer.doFrame(Choreographer.java:601)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:829)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:927)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:713)
</code>```

Does anyone know whether there is related bug logged against Android code?

答:
Override dispatchDraw method and put in it a try/catch block, like this:</p>

```<code>public void dispatchDraw(Canvas c)
    {
        try
        {
            super.dispatchDraw(c);
            return;

        }
        catch(Exception exception)
        {
            return;
        }
    }
</code>```

Body:
We have found several cases for this kind of crashes reported by backend logging monitoring. It seems the crashes do not tie to particular UX failure. And from the reports, there is no sign of how our own classes being involved(no sign of any of our classes names). Here is an example of typical crashes:

java.lang.NullPointerException: Attempt to read from field 'int android.view.View.mViewFlags' on a null object reference
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3357)
at android.view.View.updateDisplayListIfDirty(View.java:14288)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:273)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:279)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:318)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2561)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2377)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2007)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1086)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6453)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:846)
at android.view.Choreographer.doCallbacks(Choreographer.java:647)
at android.view.Choreographer.doFrame(Choreographer.java:601)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:829)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:927)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:713)

Does anyone know whether there is related bug logged against Android code?

Body:
Override dispatchDraw method and put in it a try/catch block, like this:

public void dispatchDraw(Canvas c)
    {
        try
        {
            super.dispatchDraw(c);
            return;

        }
        catch(Exception exception)
        {
            return;
        }
    }


问:
bigger than and lesser than javascript
I am trying to make a simple function that validates an ID.
the ID is supposed to be longer either 2 or 3 letters, so bigger than or equal to 2 and lesser than or equal to 3, heres what im using atm:</p>

```<code>else if (pasientID.length < 2)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er ikke lang nok.";
}

else if(pasientID.length > 3)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er for lang.";
}
</code>```

答:
You can get id property by getAttribute and check length it

function checkLength(button){
console.log(button.getAttribute("id"))
let len = button.getAttribute("id").length;
if (len<2){
console.log("too short")
}
if (len>3)
console.log("too long")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" id="twoooo" onclick="checkLength(this)" value="button" /></code>```

Title: bigger than and lesser than javascript

Body:
I am trying to make a simple function that validates an ID.
the ID is supposed to be longer either 2 or 3 letters, so bigger than or equal to 2 and lesser than or equal to 3, heres what im using atm:

else if (pasientID.length < 2)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er ikke lang nok.";
}

else if(pasientID.length > 3)
{
 lovligPasientID=false;
 feilmelding="Pasient ID'en er for lang.";
}

Body:
You can get id property by getAttribute and check length it

function checkLength(button){
console.log(button.getAttribute("id"))
let len = button.getAttribute("id").length;
if (len<2){
console.log("too short")
}
if (len>3)
console.log("too long")
}

<input type="button" id="twoooo" onclick="checkLength(this)" value="button" />


问:
Tomcat console output in Eclipse: where is my System.out.print() output, how to debug?
In Eclipse's console I can only see the tomcat server start logs, but then nothing else, none of the system.out.print() from my application are displayed, which makes it difficult to debug.

What settings can I change in Eclipse to get my system.out.print() out put back in the console?

答: It's not the right practice but you could switch to System.err.println() as a switch instead to capture values in console. The right approach will be to use loggers (like log4j) as pointed in comments.</p>


问:
Is there a way to make Spring Thymeleaf process a string template?
I would like to write something like :

```<code>    @Autowired
    private SpringTemplateEngine engine;
....
  // Thymeleaf Context
  WebContext thymeleafContext = new WebContext(request, response, request.getServletContext(), locale);

    // cached html of a thymeleaf template file
    String cachedHtml=....

    // process the cached html
  String html=engine.process(cachedHtml, thymeleafContext);
</code>```

By default, the [process] method can't do that. I can understand from the docs that I need a special Template Resolver :

In order to execute templates, the process(String, IContext) method will be used:
final String result = templateEngine.process("mytemplate", ctx);
The "mytemplate" String argument is the template name, and it will relate to the physical/logical location of the template itself in a way configured at the template resolver/s.

Does anyone know how to solve my problem ?

The goal is to cache the Thymeleaf templates (files) in strings and then process theses strings rather than the files.

答:
Yep StringTemplateResolver is the way to go.</p>

```<code>public class ReportTemplateEngine {

    private static TemplateEngine instance;

    private ReportTemplateEngine() {}

    public static TemplateEngine getInstance() {
        if(instance == null){
            synchronized (ReportTemplateEngine.class) {
                if(instance == null) {
                    instance = new TemplateEngine();
                    StringTemplateResolver templateResolver = new StringTemplateResolver();
                    templateResolver.setTemplateMode(TemplateMode.HTML);
                    instance.setTemplateResolver(templateResolver);
                }
            }
        }
        return instance;
    }
}
</code>```

Body:
I would like to write something like :

    @Autowired
    private SpringTemplateEngine engine;
....
  // Thymeleaf Context
  WebContext thymeleafContext = new WebContext(request, response, request.getServletContext(), locale);

    // cached html of a thymeleaf template file
    String cachedHtml=....

    // process the cached html
  String html=engine.process(cachedHtml, thymeleafContext);

By default, the [process] method can't do that. I can understand from the docs that I need a special Template Resolver :

In order to execute templates, the process(String, IContext) method will be used:
final String result = templateEngine.process("mytemplate", ctx);
The "mytemplate" String argument is the template name, and it will relate to the physical/logical location of the template itself in a way configured at the template resolver/s.

Does anyone know how to solve my problem ?

The goal is to cache the Thymeleaf templates (files) in strings and then process theses strings rather than the files.

Body:
Yep StringTemplateResolver is the way to go.

public class ReportTemplateEngine {

    private static TemplateEngine instance;

    private ReportTemplateEngine() {}

    public static TemplateEngine getInstance() {
        if(instance == null){
            synchronized (ReportTemplateEngine.class) {
                if(instance == null) {
                    instance = new TemplateEngine();
                    StringTemplateResolver templateResolver = new StringTemplateResolver();
                    templateResolver.setTemplateMode(TemplateMode.HTML);
                    instance.setTemplateResolver(templateResolver);
                }
            }
        }
        return instance;
    }
}


问:
How to hide elements on css
I would like to hide the "Promotions" element of this panel. Could anyone help me with the code needed to do so?

https://prntscr.com/hku99v

Thank you in advance

答:
You should really post code here. But anyway adding this to your CSS should work:

```<code>#wp_dp_member_promoted_listings {
    display: none;
}
</code>```

Title: How to hide elements on css

Body:
You should really post code here. But anyway adding this to your CSS should work:

#wp_dp_member_promoted_listings {
    display: none;
}


问:
How to access settings from `.env` inside the `index.php`
I’m creating a deployment configuration for Laravel project.
On my hosting public/ folder must be moved to another place.
Obviously, since that, I need to change path to the autoload.php and app.php in index.php.

However, I’d like to add and use a parameter which would tell where these files reside. Something like this:

```<code>require __DIR__ . '/../' . env('DEP_EXT_FOLDER') . 'vendor/autoload.php';
</code>```

I think, the most proper place for such a parameter is .env file.
However, I’ve got an error:

```<code>Call to undefined function env()
</code>```

答:
You can't use the env() function before loading the autoloader.

if you absolutely want to use your .env file, you will have to use native php preg_match() for finding your key and using the value after that :)

Body:
I’m creating a deployment configuration for Laravel project.
On my hosting public/ folder must be moved to another place.
Obviously, since that, I need to change path to the autoload.php and app.php in index.php.

However, I’d like to add and use a parameter which would tell where these files reside. Something like this:

require __DIR__ . '/../' . env('DEP_EXT_FOLDER') . 'vendor/autoload.php';

I think, the most proper place for such a parameter is .env file.
However, I’ve got an error:

Call to undefined function env()


问:
Is it possible to create a call tracking app on iOS?
From all I have read here, creating a call tracking app on iOS seems impossible. However, after some investigation, I have found a couple of workarounds and would like to know if they are legal and would work at all.

So, at least, I will need one of these features:

access call log history. I've read that's impossible, but also I know that on many devices where iCloud backup is turned on, call history data is saved there, so using some API, for example, this, I can access it. Am I right?

receive notifications when the call is ended. I've read this is possible only in foreground, therefore makes no sense. But following this question, I see that you can initiate calls from the application, which allows at least to track outgoing calls.

Would this be enough or I am wasting time?

答:
Unless you're running on a jailbroken device, the answer is no because there is no publicly available API that provides access to the call list and that is a good thing from a privacy point of view.

A quick search shows that CallKit is for integrating VOIP into the call list, so again the answer is no, CallKit will not be of any use to you.

The notifications are there so that your app can respond properly to calls that take place while it is active.