text:
Q: Error when using Firebase CLI in Cloud Build I get the following error when I run "cloud-build-local --dryrun=false ." on my local machine:

Firebase Management API has not been used in project 32555940559
before or it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/firebase.googleapis.com/overview?project=32555940559
then retry. If you enabled this API recently, wait a few minutes for
the action to propagate to our systems and retry.

The project number listed is not the number of any of my projects. I Googled this number and it seems like more users get errors with this project number in it. I already checked the following:

*

*The account that I am signed in with has owner permissions for the project

*"gcloud config list" show that the correct project and account are active

*The project is listed in my .firebase.rc file

Any help on this is appreciated!

A: cloud-build-local is the command used to build a image locally.
The Cloud Build local environment, as well as all other GCP local environments, are outside of your Google Cloud environment, hence the project-id you are seeing here references the gcloud project number. This means that gcloud will unable to use the login credentials for your respective project and will not automatically authenticate with the Cloud Build service account needed for the Cloud Build gcloud commands.
In this case you would need to utilize gcloud auth application-default login. This will provide new user credentials for use with Application Default Credentials so as to authorize you to utilize the needed service accounts for local Cloud Build development.


text:
Q: Testing Material Design Angular components with jasmine Edit2: Even more specific, using something like Material Button works fine. The Side Nav does not work well with the setup below, however.
Edit: I did more testing and found this is specifically related to Angular Material, as these errors don't occur without it. I'm still unsure how to fix it.
I'm trying to set up some basic tests for a new component, but I keep running into error after error. Specifically, after adding @angular/material to the project. The current error is:
Error: Found the synthetic listener @transform.start. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.

Which feels like a red herring to me.
Here is the spec:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { RouterTestingModule } from '@angular/router/testing';
import { MatSidenavModule } from '@angular/material/sidenav';

import { AngularNavigationComponent } from './angular-navigation.component';

describe('AngularNavigationComponent', () => {
    let component: AngularNavigationComponent;
    let fixture: ComponentFixture<AngularNavigationComponent>;

    beforeEach(
        async(() => {
            TestBed.configureTestingModule({
                declarations: [AngularNavigationComponent],
                imports: [RouterTestingModule, MatSidenavModule]
            }).compileComponents();
        })
    );

    beforeEach(() => {
        fixture = TestBed.createComponent(AngularNavigationComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

And here is the component
import { Component, OnInit } from '@angular/core';
import { MatSidenavModule } from '@angular/material/sidenav';
import { RouterLink } from '@angular/router';

@Component({
    selector: 'mysupercustomcat-navigation',
    templateUrl: './angular-navigation.component.html',
    styleUrls: ['./angular-navigation.component.scss']
})
export class AngularNavigationComponent implements OnInit {
    constructor() {}

    ngOnInit() {}
}

Can anyone tell me what I'm doing wrong, and also perhaps explain declarations vs. imports in the Testbed configuration area?
Edit: This is a hybrid app if that matters

A: I've added two key sections to avoid errors like this:
import { NO_ERRORS_SCHEMA } from '@angular/core';

is added at the top of the page and:
schemas: [NO_ERRORS_SCHEMA],

is added at the same level as declarations.
What does this do? This tells angular not to error on unknown elements or attributes. Now this works FOR THIS USE CASE because I am not super interested in integration testing. I believe that might cause problems in this case.
I am interested in unit testing, and ignoring template attributes is fine with me. Adding this lets me get to that level.
This answer is as complete as I could get it for the moment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Report on individual password expiration intervals in Sybase ASE 12.5 I want to run a report to make sure the password of every user is set to expire every 30 days, but the expiration interval doesn't seem to be stored in syslogins?

A: you can get report with following proc:
use sybsystemprocs
go
----------------------------------------------------------------------------
print 'sp__helpexpire'
----------------------------------------------------------------------------
if exists (select 1 from sysobjects where  type = "P" and  name = "sp__helpexpire")
        drop proc sp__helpexpire
go
create procedure sp__helpexpire
as
begin
  set nocount on
  declare @swexpire int
  select @swexpire=value from master.dbo.sysconfigures
    where name = 'systemwide password expiration'
  print "Serverwide password expire: %1!" ,@swexpire
  print ""
  print "Logins:"
  print "=============================================================="
  select l.name login , case a.int_value
      when null then @swexpire
      else a.int_value end "expire in days"
    from master.dbo.syslogins l , master.dbo.sysattributes a
    where l.suid *= a.object
      and a.object_type='PS'
      and a.attribute=0
      and object_cinfo='login'
  print ""
  print "Roles:"
  print "=============================================================="
  select r.name "role name", case a.int_value
      when null then @swexpire
      else a.int_value end "expire in days"
    from master.dbo.syssrvroles r , master.dbo.sysattributes a
    where r.srid *= a.object
      and a.object_type='PS'
      and a.attribute=0
      and object_cinfo='role'
end
go

it is always a good idea to check source code of those system procedures (stored in sybsystemprocs database) which manipulate with records you are looking for (in this case it is sp_addlogin, sp_modifylogin)

A: You can use sp_configure to set all users password expiration date
sp_configure "systemwide password expiration", 30
go

will set all users passwords to expire after 30 days. Not sure if this value can be read for a report though. The default is 0.

A: try
exec sp_displaylogin
to get the perms for the settings for an individual user, logged in as that user.


text:
Q: @Autowired bean in jar is giving null pointer exception In my project I am using a utility jar and in utility we have beans autowired.
When I am calling the method of jar it is giving null pointer exception at the place where autowired bean is used.
I tried to add package of jar in component scan of my project but still it is coming null.
below is the class from the jar file in which I a getting error

@Controller
public class UtilityController{

@Autowired
UtilityService utilityService;

public String getEmployeeDetails(String name){

Sting output = utilityService.getDetails(name);
--
--
}

getEmployeeDetails method is the one which I am trying to call from my code and utilityService is coming as null. I have the source code of jar and it is working fine when I am running it separately.

A: For Spring to create the beans you need to annotate the class with @Component, @Service or other annotations. Now in your case the class which you are trying to annotate is in utility jar. You don't have control over that code so you cannot annotate those classes with some spring annotation.
Another way would be to create you class then create the object of that class from utility jar in your own class and then autowire your class.


text:
Q: Doing math inside of pgfplotsset I am declaring an environment to help with drawing binomial distributions.  One of the natural parameters to give to such a function is "n", the number of trials.  My plotting function, however, needs to plot 0 .. n-1 samples.  I am finding that I am unable to do the "-1" within a pgfplotsset.  Can anyone help me do this?  MWE:
\documentclass{minimal}

\usepackage{pgfplots}

\newenvironment{BinomDist}[1]{%
  \pgfplotsset{DistAxis/.style={%
      samples at={0,...,#1} % Want this to say ``#1-1'' or equiv.
    }
  }
}{}

\begin{document}

\begin{BinomDist}{8}
  \begin{tikzpicture}
    \begin{axis}[DistAxis]
      \addplot [draw=black] {x};
    \end{axis}
  \end{tikzpicture}
\end{BinomDist}

\end{document}

A: This is very simple: samples at={0,...,\the\numexpr#1-1}.
\documentclass{article}
\usepackage{pgfplots}
%\pgfplotsset{compat=1.16} %<-consider using this
\newenvironment{BinomDist}[1]{%
  \pgfplotsset{DistAxis/.style={%
      samples at={0,...,\the\numexpr#1-1}
    }
  }
}{}

\begin{document}

\begin{BinomDist}{8}
  \begin{tikzpicture}
    \begin{axis}[DistAxis]
      \addplot [draw=black] {x};
    \end{axis}
  \end{tikzpicture}
\end{BinomDist}

\end{document}

BTW, please consider not to use the minimal class, and to indicate the version.
For more complicated cases you might want to use code with \pgfmathtruncatemacro.
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16} %<-consider using this
\newenvironment{BinomDist}[1]{%
  \pgfplotsset{DistAxis/.code={%
    \pgfmathtruncatemacro{\iMax}{pow(2,#1-1)}%
     \pgfplotsset{samples at={0,...,\iMax}}%
    }
  }
}{}

\begin{document}

\begin{BinomDist}{8}
  \begin{tikzpicture}
    \begin{axis}[DistAxis]
      \addplot [draw=black] {x};
    \end{axis}
  \end{tikzpicture}
\end{BinomDist}
\end{document}


text:
Q: Refresh Jframe on data change I made a class that extends jframe.
I have a border layout for the jframe and some components and a jpanel with absolute layout to hold some buttons and a jcombobox. The combo box holds some values from a table. And the table takes the values from a mysql query. I delete or add some records through the buttons and then I update the table.
All works great except the combo box that doesn't refresh the values. In order to work I have to close the jframe and open it again. I read many articles and tutorials about repaint etc... but nothing seems to work in my case. The action listener is also the same class that extends the jframe.
Any way to do it ?
Please keep it simple as I am new to java programing.
Thank you!

A: Did you hear about SwingUtilities.invokeLater(new Runnable()) or java.awt.EventQueue.invokeLater(new Runnable()) ?
Reading this thread could be useful: Concurrency in Swing
Sample code snippet that you can add to your main method:
java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        JFrame frame = new JFrame();
        frame.setVisible(true);
                ...
    }
});


text:
Q: puppet agent run backup of cron files Looks like I was having wrong entry in root crontab and when I ran puppet agent it got overwritten.
Error: Could not prefetch cron provider 'crontab': Could not parse line "====" at root:10

Is there any way to recover those cron entries which was there before I run puppet agent?


text:
Q: Google API php client: send etag I'm using the latest Google PHP Client library. How can I send the etag with this library?
I've already tried something like this:
$opt_params = array(
'etag' => 'F9iA7pnxqNgrkOutjQAa9F2k8HY/mOihMVEDLCvdSVCzwDmYHpSV');

$response = $youtube->channels->listChannels('snippet', array('id' => $channel_id), $opt_params);

Thanks!

A: The Google API PHP Client does not have native support for etags. That said, you can still alter the curl request and apply an etag as a header.
Unfortunately Google_Http_REST throws an exception when it receives a 304 Not Modified header so you'll need to handle those seperately in a catch-block.
This is the resulting PHP-code (note, this is for version 1 of the Google API PHP Client):
class EmptyResponse { }

$DEVELOPER_KEY = '';

$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);

$youtube = new Google_Service_YouTube($client);

// Do some logic, catch some resources
// ..

// Set the "If-None-Match" header for the etag
// This assumes the Google API is using CURL
$client->getIo()->setOptions(array(
    CURLOPT_HTTPHEADER => array('If-None-Match: "4FSIjSQU83ZJMYAO0IqRYMvZX98/OPaxOhv3eeKc9owSnDQugGfL8ss"'),
));

try {
  $response = $youtube->playlists->listPlaylists('snippet', array(
      'id' => 'PLOIvOnfHWjIkiz6fd5KYUXJY6ZpHRqPfW',
  ));
}
catch (Google_Service_Exception $e) {
  if (304 == $e->getCode()) {
      // If the error code is 304 (Not Modified) return an empty response
      $response = new EmptyResponse;
  }
  else {
      // The request was unsuccesful
      $response = null;
  }
}

// After the request set the headers back to default
$client->getIo()->setOptions(array(
    CURLOPT_HTTPHEADER => array(),
));

var_dump($response);

// Catch some more resources
// ...

A: This post is a little long (if not too long). If you just need the code scroll down and skip my discussions. Please proceed as you wish.
Background
I don't know if somebody has figured out a solution for this one. Coded Monkey's answer is a start. The problem is that the solution he presented assumes that the API makes request using only a developer key/api key and not an oauth access key. If you will try his code using an developer key you will get the following:

Error calling GET
  https://www.googleapis.com/youtube/v3/liveBroadcasts?part=id%2Csnippet%2Cstatus&mine=true&maxResults=50&key={developer key here}:
  (401) Login Required

A developer key is not enough to retrieve a user's youtube data and a developer key does not grant access to any account information. That includes youtube data. To access youtube data, one must use an oauth access key (read here: api keys)
Notice that the developer key becomes part of the query string. On the other hand when you use an oauth key, the key becomes a request header:

Authorization: Bearer {oauth key here}

However if you try to use an oauth key you will still get the same error as above. This is quite frustrating. And I guess that is why Coded Monkey's answer did not get an upvote. To understand why, one must understand how the google client send requests.
How the Google PHP client works
My explanation on how the google client work behind the scene is not complete and is only based on what I learned from my experience in figuring out how to solve this problem.
The google client, which I'll call $client, uses a Google_IO_Abstract class instance, I'll call $io, to send requests. One can get the current $io instance and change it using the $client->setIo() and $client->getIo() methods. Google_IO_Abstract is an abstract class. One of its concrete subclass available in the PHP Google API lib is Google_IO_Curl. As its name suggests the class uses curl.
From this point forward I shall assume that $io is a Google_IO_Curl instance. The following (from Code Mokey's solution):
$client->getIo()->setOptions(array(
    CURLOPT_HTTPHEADER => array('If-None-Match: "4FSIjSQU83ZJMYAO0IqRYMvZX98/OPaxOhv3eeKc9owSnDQugGfL8ss"'),
));

will add an If-None-Match HTTP header to curl's header option. The actual adding of header happens only when $io->executeRequest($request) is called. $request is the request $client needs to send.
Setting curl's header is done via curl_setopt($curl, CURLOPT_HTTPHEADER, $headers), where $curl is a curl instance and $headers is an array of headers.
If you will read executeRequestimplementation. You will see that most parts are for setting curl's options. One important part is the gathering of http headers from $requestinto an array called $curlHeaders as shown below (this is from Google_IO_Curl source code). The Authorization header is also added here.
    $requestHeaders = $request->getRequestHeaders();
    if ($requestHeaders && is_array($requestHeaders)) {
      $curlHeaders = array();
      foreach ($requestHeaders as $k => $v) {
        $curlHeaders[] = "$k: $v";
      }
      curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
    }

Notice that after gathering the headers, curl_setopt() is called to set curl's header options. Now comes the problem, after these lines of code comes the part where additional options are set. Options that are set using the setOptions() method, which means there will be another call for curl_setopt($curl, CURLOPT_HTTPHEADER, $headers) but this time $headers only contain the If-None-Match header. This second call will replace all previous headers. Voila! The Authorization header is gone. I am not sure if somebody has reported this yet. I am not sure if this is intentional. But this is really frustrating for beginners like me.
Anyway, I came up with a quick solution.
My Solution
I will stop my discussion here and instead give you the code (Google_IO_Curl_Mod.php):
<?php
/**
 * Wrapper class for Google_IO_Curl.
 *
 * This class fixes issues involving request headers added using setOptions()
 *
 * @author Russel Villacarlos<cvsurussel_AT_gmail.com>
 */

if (!class_exists('Google_Client')) {
  require_once 'Google/autoload.php';
}

class Google_IO_Curl_Mod extends Google_IO_Curl
{

  //Google_IO_Curl instance
  private $io;

  //Array for additional headers added using setOptions()
  private $headers;

  public function __construct(Google_IO_Curl $io)
  {
      $this->io = $io;
      $this->headers=[];
  }

  /**
   * Execute an HTTP Request
   *
   * @param Google_Http_Request $request the http request to be executed
   * @return array containing response headers, body, and http code
   * @throws Google_IO_Exception on curl or IO error
   */
  public function executeRequest(Google_Http_Request $request)
  {
      foreach ($this->headers as $value) {
          if(is_string($value) && strpos($value,":")!==false){
            $header = split(":\s*",$value);

            $request->setRequestHeaders(array($header[0]=>$header[1]));
          }
      }
      $result = $this->io->executeRequest($request);
      return $result;
  }

  /**
   * Set options that update the transport implementation's behavior.
   * @param $options
   */
  public function setOptions($options)
  {
      if($options){
          if(array_key_exists(CURLOPT_HTTPHEADER, $options)){
              $this->headers= array_merge($this->headers, $options[CURLOPT_HTTPHEADER]);
              unset($options[CURLOPT_HTTPHEADER]);
          }
          $this->io->setOptions($options);
      }
  }

  /**
   * Set the maximum request time in seconds.
   * @param $timeout in seconds
   */
  public function setTimeout($timeout)
  {
    $this->io->setTimeout($timeout);
  }

  /**
   * Get the maximum request time in seconds.
   * @return timeout in seconds
   */
  public function getTimeout()
  {
    return $this->io->getTimeout();
  }

  /**
   * Test for the presence of a cURL header processing bug
   *
   * {@inheritDoc}
   *
   * @return boolean
   */
  protected function needsQuirk()
  {
    return $this->io->needsQuirk();
  }
}

To use this just do the following:
$client = new Google_Client();
//codes for setting the oauth credential appears here
$io = new Google_IO_Curl_Mod(new Google_IO_Curl($client));
$client->setIo($io);
$client->getIo()->setOptions(array(
                    CURLOPT_HTTPHEADER =>
                           array('If-None-Match: "NO6QTeg0-3ShswIeqLchQ_mzWJs/wtg8du-olFPZ73k6UW7Jk5JcwpQ"'),
                   ));
//codes for calling youtube api or any google api goes here

Take note that the pair of double quotes is part of the etag.

A: If you check the documentation for channels.list you will notice that etag is not one of the optional parameters.
So you cant send etag to list channels via the api its not a limitation of the client library.


text:
Q: ASP.NET Core Binding to a dictionary In ASP.NET Core, can you bind dictionary values?
I saw in this related question  in a more recent answer (not the one marked correct) it states:

In ASP.NET MVC 4, the default model binder will bind dictionaries
using the typical dictionary indexer syntax property[key].

Is this also true for ASP.NET Core MVC (and/or Razor Pages)?

A: Yes it's also true for ASP.NET Core MVC (and/or Razor Pages).
You can see the following is a simple demo in asp.net core.
Class:
 public class Command
{
    [Key]
    public string ID { get; set; }
    public string Name { get; set; }
    public Dictionary<string, string> Values { get; set; }
}

Action:
 [HttpPost]
    public IActionResult Test(Command command)
    {
        return View();
    }

View:
@model Command
<form asp-action="Test">
    <input type="text" name="Id" />
    <input type="text" name="Name" />
    <input type="hidden" name="Values[0].Key" value="Apple" />
    <input type="text" name="Values[0].Value" />
    //....
    <input type="submit" value="Click" />
</form>

Result:


text:
Q: static NSString generates compilation warnings In a simple NSObject subclass that conforms to NSCoding protocol, I declare some static NSString in my header file :
static NSString *MYCodingKey = @"myPropertyName";
...

I wonder why Xcode is generating so many warnings about the fact I declare but don't use it. I understand the warning since the subclass is imported in many files and I don't employ the key for something in each. But so, does it mean that my key is in some way 'redefined' each time I import the header ? Doesn't the #import statement prevent the header from being included multiple times ? I surely don't have warning saying I've declared it multiple times.
I'm just ignoring these warnings at the time, but I would be glad to read a bit more on that.
Thank you.

A: Well the warning is because you have a variable declared but you're not using it. Essentially you're just wasting space in the programs data section with things you're never going to use. Some compilers will optimize it and actually remove it if the symbol is not used (not sure if gcc with objc flag does so).


text:
Q: Hibernate delete many to many lazy collection My Entity classes are:
@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private Long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_creation", nullable = false)
    private Date dtCreation;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_maj", nullable = false)
    private Date dtMaj;

    // bi-directional many-to-one
    @OneToMany(mappedBy = "quality", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<RQulityUser> RQualityUser;

@Entity
public class RQualityUser implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_creation", nullable = false)
    private Date dtCreation;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_maj", nullable = false)
    private Date dtMaj;

    // bi-directional many-to-one association to Questionnaire
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fk_user", updatable = false, nullable = false)
    private User user;

    // bi-directional many-to-one association to QualitePersonne
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cd_quality_user", updatable = false, nullable = false)
    private Quality quality;

When I get a user and I try to clear the list of RQualityUser i dosen't work :
 User user = em.getByid(11);
 user.getRQualityUserList().clear();

Hibernate doesn't delete the record in the relation table ?

A: "Lazy loading" means that an entity will be loaded only when you actually accesses the entity for the first time.
When you do
user.getRQualityUserList() // Still contains nothing.

So you are clearing empty list and afterwards when you will use this will call data from DB.

A: If you do this
User user = em.getByid(11);
user.getRQualityUserList().clear();

With an opened persistent context and inside a transaction Hibernate should delete records.
If you don't have a transaction you should use it.
If you do clear() with a closed persistent context you should update user to delete records.


text:
Q: DNS Inconsistency with Google Domain I am dealing with some weird inconsistency issues with the dns to my subdomain, and was hoping someone would be able to shed some light!
I have a domain purchased through Google Domains and have a need to use the main domain, and a single subdomain for my api service. With Route 53, i have 2 hosted zones, one for the main, and one for the subdomain, each providing the 4 NS configs, and two aliases back to my Elastic Beanstalk nodes for the www & non www calls.
For my main domain, using WhatsMyDomain, the propagation is pretty much worldwide at all times, but when it comes to my subdomain, it is intermittent and changes throughout the day, where it was working in one location earlier on, it will then stop working.
In Google Domains, i have all 8 NS configurations set in my DNS settings.
I feel like im missing just one piece of something, just can't figure it out

A: Thanks to Michael - sqlbot for his return question, never even thought about just trying it by adding an alias to the subdomain in the original Hosted Zone! In the docs on AWS, they do provide info on having 2 different zones, which i think thats what i stumbled across when i first started, but i believe there is a bit more setup involved in that route!
Just made the switch, gonna see if this solves the issue!


text:
Q: aspnetcore and applicationinsights.tracelistener Is it possible to use application insights trace logging/search when using aspnetcore and/or any .net core app?
I was able to add the applicationinsights.aspnetcore nuget but it doesn't seem that has capabilities for trace logging.
It seems the tracelistener nuget package requires full .net. How are people doing trace logging/search on dotnetcore code?

A: The Application Insights ASP.NET Core nuget adds the ability to automatically track requests and exceptions in your web app.
However, you can use the Application Insights core telemetry API to send custom telemetry, such as traces or custom events.
See the core telemetry API documentation on how to do it - specifically you need to use the TrackTrace method of the TelemetryClient class.
Hope this helps,
Asaf


text:
Q: Is there a notion of virtual time in Apache Flink tests like there is in Reactor and RxJava In RxJava and Reactor there is this notion of virtual time to tests operators that are dependent of time. I cant figure out how to do this in Flink. For example I have put together the following example where I would like to play around with late arriving events to understand how they are handled. However im not able to understand how such a test would look? Is there a way to combine Flink and Reactor to make the tests better?
public class PlayWithFlink {

    public static void main(String[] args) throws Exception {

        final OutputTag<MyEvent> lateOutputTag = new OutputTag<MyEvent>("late-data"){};

        // TODO understand how BoundedOutOfOrderness is related to allowedLateness
        BoundedOutOfOrdernessTimestampExtractor<MyEvent> eventTimeFunction = new BoundedOutOfOrdernessTimestampExtractor<MyEvent>(Time.seconds(10)) {
            @Override
            public long extractTimestamp(MyEvent element) {
                return element.getEventTime();
            }
        };

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        DataStream<MyEvent> events = env.fromCollection(MyEvent.examples())
                .assignTimestampsAndWatermarks(eventTimeFunction);

        AggregateFunction<MyEvent, MyAggregate, MyAggregate> aggregateFn = new AggregateFunction<MyEvent, MyAggregate, MyAggregate>() {
            @Override
            public MyAggregate createAccumulator() {
                return new MyAggregate();
            }

            @Override
            public MyAggregate add(MyEvent myEvent, MyAggregate myAggregate) {
                if (myEvent.getTracingId().equals("trace1")) {
                    myAggregate.getTrace1().add(myEvent);
                    return myAggregate;
                }
                myAggregate.getTrace2().add(myEvent);
                return myAggregate;
            }

            @Override
            public MyAggregate getResult(MyAggregate myAggregate) {
                return myAggregate;
            }

            @Override
            public MyAggregate merge(MyAggregate myAggregate, MyAggregate acc1) {
                acc1.getTrace1().addAll(myAggregate.getTrace1());
                acc1.getTrace2().addAll(myAggregate.getTrace2());
                return acc1;
            }
        };

        KeySelector<MyEvent, String> keyFn = new KeySelector<MyEvent, String>() {
            @Override
            public String getKey(MyEvent myEvent) throws Exception {
                return myEvent.getTracingId();
            }
        };

        SingleOutputStreamOperator<MyAggregate> result = events
                .keyBy(keyFn)
                .window(EventTimeSessionWindows.withGap(Time.seconds(10)))
                .allowedLateness(Time.seconds(20))
                .sideOutputLateData(lateOutputTag)
                .aggregate(aggregateFn);

        DataStream lateStream = result.getSideOutput(lateOutputTag);

        result.print("SessionData");

        lateStream.print("LateData");

        env.execute();
    }
}

class MyEvent {
    private final String tracingId;
    private final Integer count;
    private final long eventTime;

    public MyEvent(String tracingId, Integer count, long eventTime) {
        this.tracingId = tracingId;
        this.count = count;
        this.eventTime = eventTime;
    }

    public String getTracingId() {
        return tracingId;
    }

    public Integer getCount() {
        return count;
    }

    public long getEventTime() {
        return eventTime;
    }

    public static List<MyEvent> examples() {
        long now = System.currentTimeMillis();
        MyEvent e1 = new MyEvent("trace1", 1, now);
        MyEvent e2 = new MyEvent("trace2", 1, now);
        MyEvent e3 = new MyEvent("trace2", 1, now - 1000);
        MyEvent e4 = new MyEvent("trace1", 1, now - 200);
        MyEvent e5 = new MyEvent("trace1", 1, now - 50000);
        return Arrays.asList(e1,e2,e3,e4, e5);
    }

    @Override
    public String toString() {
        return "MyEvent{" +
                "tracingId='" + tracingId + '\'' +
                ", count=" + count +
                ", eventTime=" + eventTime +
                '}';
    }
}

class MyAggregate {
    private final List<MyEvent> trace1 = new ArrayList<>();
    private final List<MyEvent> trace2 = new ArrayList<>();

    public List<MyEvent> getTrace1() {
        return trace1;
    }

    public List<MyEvent> getTrace2() {
        return trace2;
    }

    @Override
    public String toString() {
        return "MyAggregate{" +
                "trace1=" + trace1 +
                ", trace2=" + trace2 +
                '}';
    }
}

The output of running this is:
SessionData:1> MyAggregate{trace1=[], trace2=[MyEvent{tracingId='trace2', count=1, eventTime=1551034666081}, MyEvent{tracingId='trace2', count=1, eventTime=1551034665081}]}
SessionData:3> MyAggregate{trace1=[MyEvent{tracingId='trace1', count=1, eventTime=1551034166081}], trace2=[]}
SessionData:3> MyAggregate{trace1=[MyEvent{tracingId='trace1', count=1, eventTime=1551034666081}, MyEvent{tracingId='trace1', count=1, eventTime=1551034665881}], trace2=[]}

However I would expect to see the lateStream trigger for the e5 event that should be 50seconds before the first event triggers.

A: If you modify your watermark assigner to be like this
AssignerWithPunctuatedWatermarks eventTimeFunction = new AssignerWithPunctuatedWatermarks<MyEvent>() {
    long maxTs = 0;

    @Override
    public long extractTimestamp(MyEvent myEvent, long l) {
        long ts = myEvent.getEventTime();
        if (ts > maxTs) {
            maxTs = ts;
        }
        return ts;
    }

    @Override
    public Watermark checkAndGetNextWatermark(MyEvent event, long extractedTimestamp) {
        return new Watermark(maxTs - 10000);
    }
};

then you will get the results you expect. I'm not recommending this -- just using it to illustrate what's going on.
What's happening here is that a BoundedOutOfOrdernessTimestampExtractor is a periodic watermark generator that will only insert a watermark into the stream every 200 msec (by default). Because your job completes long before then, the only watermark your job is experiencing is the one the Flink injects at the end of every finite stream (with value MAX_WATERMARK). Lateness is relative to watermarks, and the event that you expected to be late is managing to arrive before that watermark.
By switching to punctuated watermarks you can force watermarking to occur more often, or more precisely at specific points in the stream. This is generally unnecessary (and too frequent watermarking causes overhead), but is helpful when you want to have strong control over the sequencing of watermarks.
As for how to write tests, you might take a look at the test harnesses used in Flink's own tests, or at flink-spector.
Update:
The time interval associated with the BoundedOutOfOrdernessTimestampExtractor is a specification of how out-of-order the stream is expected to be. Events that arrive within this bound are not considered late, and event time timers won't fire until this delay has elapsed, thereby giving time for out-of-order events to arrive. allowedLateness only applies to the window API, and describes for how long past the normal window firing time the framework keeps window state so that events can still be added to a window and cause late firings. After this additional interval, window state is cleared and subsequent events are sent to the side output (if configured).

So when you use BoundedOutOfOrdernessTimestampExtractor<MyEvent>(Time.seconds(10)) you are not saying "wait 10 seconds after every event in case earlier events might still arrive". But you are saying that your events should be at most 10 seconds out of order. So if you are processing a live, real-time event stream, this means you will wait for at most 10 seconds in case earlier events arrive. (And if you are processing historic data, then you may be able to process 10 seconds of data in 1 second, or not -- knowing you will wait for n seconds of event time to pass says nothing about how long it will actually take.)
For more on this topic, see Event Time and Watermarks.


text:
Q: How to insert data to xml from a database using java? I'm learning by myself android Java (I'm finishing university and what contributes to this project is Java, PHP and MYSql) and have a question. How does it work to insert data from a database into de XML code from my app? Like, in HTML, you can use JS and PHP to insert and alter the value of an element but how is it done in android? I'm thinking I have to get the data from the database, parse it to XML and then asign it to the element I need it to be in, right? Or am I totally wrong?

A:
How does it work to insert data from a database into de XML code from my app?

You don't. You can't (or at least shouldn't) edit the XML files directly. On the other hand, you can use the View API to add views dynamically to the UI that the user sees on the screen. In fact, RecyclerView is made for just this purpose.

Like, in HTML, you can use JS and PHP to insert and alter the value of an element but how is it done in android?

Just to clarify what you mean here, JS allows you to add elements to the DOM that is rendered in the browser. It does not allow you to edit the original HTML code that is loaded from the server. In the same way, you cannot edit the XML code in your Android app while it is running. Instead, you add Views to the view hierarchy as the app runs.

I'm thinking I have to get the data from the database, parse it to XML and then asign it to the element I need it to be in, right?

Just to be clear, while your app is running, you don't use XML at all. Instead, you create View objects in Java or Kotlin and add them to the view hierarchy. You should start by learning about RecyclerView which in most cases will do what you need.


text:
Q: What does spite mean in "spite of despondence" in the poem Endymion by John Keats? The poem Endymion by John Keats reads:

A thing of beauty is a joy for ever:
  Its loveliness increases; it will never
  Pass into nothingness; but still will keep
  A bower quiet for us, and a sleep
  Full of sweet dreams, and health, and quiet breathing.
  Therefore, on every morrow, are we wreathing
  A flowery band to bind us to the earth,
Spite of despondence, of the inhuman dearth
  Of noble natures, of the gloomy days,
  Of all the unhealthy and o'er-darkened ways
  Made for our searching: yes, in spite of all,
  Some shape of beauty moves away the pall
  From our dark spirits. Such the sun, the moon,
  Trees old, and young, sprouting a shady boon
  For simple sheep; and such are daffodils
  With the green world they live in; and clear rills
  That for themselves a cooling covert make
  'Gainst the hot season; the mid-forest brake,
  Rich with a sprinkling of fair musk-rose blooms:
  And such too is the grandeur of the dooms
  We have imagined for the mighty dead;
  All lovely tales that we have heard or read:
  An endless fountain of immortal drink,
  Pouring unto us from the heaven's brink.

I believe it is short for "in spite of", as is later supported by the line " yes, in spite of all ". I am convinced of it.
But my teacher says spite here means 'specks'. Another source says it stands for 'malice'. I asked my teacher how would he explain the  'yes' afterwards. But he could not give a satisfactory answer.

A: The strongest argument for reading "Spite of despondence" as "In spite of despondence" is, as the poster points out, the follow-up usage of "in spite of" within the same sentence three lines later. Here again is the whole sentence:

Therefore, on every morrow, are we wreathing
A flowery band to bind us to the earth,
Spite of despondence, of the inhuman dearth
Of noble natures, of the gloomy days,
Of all the unhealthy and o'er-darkened ways
Made for our searching: yes, in spite of all,
Some shape of beauty moves away the pall
From our dark spirits.

Keats lists four things that might discourage a person from feeling bound to the earth through a love a beauty: (1) despondence; (2) a dearth of noble natures; (3) gloomy days; (4) unhealthy and darkened obstructions. But at both ends of this list he identifies things in opposition to those discouragements—first, the act of creating beauty ("wreathing a flowery band"), and second, the experience of feeling the force of beauty sweep away the cloud of gloom. Both positive things act contrarily and counter to the negative forces—which is to say, both act in spite of them.
I checked a number of books that quote this passage of Endymion, and most of them don't provide any commentary on the line in question. This, I think, is because most of them have no question that "Spite of despondence" means "In spite of despondence." I did find three texts, however, that venture a restatement or gloss on the original wording. From Milton Goldberg, The Poetics of Romanticism: Toward a Reading of John Keats (1969) [combined snippets]:

Mind and heart must interact to sprout a soul. Emulating the sweet sonnet, fettered in spite of loveliness, we must wreathe a flowery band to bind us to the earth—in spite of despondence or the dearth of noble natures:

If by dull rhymes our English must be chain'd,
And, like Andromeda, the Sonnet sweet
Fetter'd, in spite of pained loveliness;
Let us find out, if we must be constrain'd,

From Origins, volume 24 (1995) [combined snippets]:

He goes on to ask, in his classic poem, Are we creating some beauty each day ... in spite of despondence or the dearth of noble natures?

And from Keki Daruwalla, Poetry Magic 7 (2005), a collection of poetry designed for "the young":

Spite of despondence, of the inhuman dearth

[Explanatory note:] SPITE OF DESPONDENCE: in spite of being gloomy

This is not to say that Keats only uses spite to mean "in spite of." Michael Becker, Robert Dilligan & Todd Bender, A Concordance to the Poems of John Keats (2016) notes two other occurrences of spite in Endymion—in Book 3, line 615:

"Young lover, I must weep—such hellish spite
With dry cheek who can tell?

and in Book 3, line 650:

I saw grow up from the horizon's brink
A gallant vessel: soon she seem'd to sink
Away from me again, as though her course
Had resum'd in spite of hindering force—

The "hellish spite" is unmistakably maliciousness, and the later "in spite of" clearly functions in the sense of "notwithstanding."
In books about Endymion, the "Spite of despondence" line seems uncontroversial. The few texts that address it at all interpret it as meaning "In spite of despondence," but most don't comment on it at all. The first law of poetry is that nothing is certain, so people who interpret the line differently are exercising their muse-given right to do so. But I think that the poster's reading of the line is the most straightforward and coherent of the various readings that are possible.

A: Spite of despondence is no different from "Sorrow of loss" or "Joy of discovery"
OED Spite:

A strong feeling of (†contempt,) hatred or ill-will; intense grudge or desire to injure; rancorous or envious malice.

"Of" can be glossed as "from; originating in"
Thus:
Therefore, on every morrow, are we wreathing
A flowery band to bind us to the earth,
Spite of despondence, of the inhuman dearth
Of noble natures, of the gloomy days,
Of all the unhealthy and o'er-darkened ways
Made for our searching: yes, in spite of all,
Some shape of beauty moves away the pall
From our dark spirits.
Rough translation:
Therefore every day we are making a wreath
In order to keep us tied to the earth (to prevent us from developing "spiritual")
Spite, which comes from/originates in despondence, [spite] , which comes from the cruel lack
Of noble natures, [spite,] which comes from the depressing days
which comes from all the vices that are
created for our experimentation: yes, in spite of all,
Some shape of beauty moves away the clouds
From our depression.
† now obsolete

A: "Spite" could mean 'in spite' and this makes sense in the context of the line. It maybe that Keats shortened this because of the requirements of metre. In the following, the number after the line indicates the number of syllables in the line:

Therefore, on every morrow, we are wreathing (11)

A flowery band to bind us to the earth (11)

Spite of despondance, the inhuman dearth (10)

Of noble natures, of the gloomy days (10)

Of all the unhealthy and o'er darkened ways (11)

Made for our searching: yes, in spite of all (11)

As one can see there is a regular syllable count here, in pairs.
It can also mean 'malice' as "Malice of despondance" is meaningful and this tone is emphasised by the the lines completion, "the inhuman dearth" and this register and rhythm of tone is continued in "gloomy days" and "unhealthy and o'er darkened ways".
'Speck' makes no meaningful sense whatsover. Perhaps you misheard?


text:
Q: Issue - Integrating angualrjs with socket.io I am using socket.io and angularjs for showing the real time data in my project.
socket.io is working fine  without angularjs.
controller.js
   var realTime = angular.module('realTime',[]);
   realTime.controller('realTime', function($scope) { });
   realTime.factory('socket', function($rootScope) { });

   realTime.controller('realTime', function($scope,socket) {
    //socket is undefined
      socket.on('realTimeData', function (result) {
          $scope.realTimeCount = 2;
      });

    });

Above code is in the controller.js, Socket.io is emitting the realTimeData event data to client side at regular interval.  Problem is in client side.
Problem
socket is undefined inside the `realTime.controller` function.

Note:  Added the socket.io script in html file
<script src="/socket.io/socket.io.js"></script>

Any help or suggestion will be greatful.

A: When you define your socket factory resource (realTime.factory('socket', function($rootScope) { });) you leave it empty. Your socket methods (on, emit etc.) should be in there for it to work properly.
So try this instead:
realTime.factory('socket', function($rootScope) {
  var socket = io.connect();
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      });
    }
  };
});

It's explained in great detail here.


text:
Q: With Primefaces fileUpload component, is there an event fired when the user clicks "Cancel"? I'm using Primefaces 3.0.RC1 and on a form I have a <p:fileUpload mode="advanced" auto="true"> component. This has a fileUploadListener that is writing a copy of the temp file to disk.
The issue is (when uploading a file everything runs fine) that if while the file is being written to disk the user clicks the "Cancel" button, the file may already be partially written to the disk, but I need to be able to delete it at that point. Is there an event fired when the user clicks cancel?
EDIT: To clarify, the cancel button is still visible (and clickable) while the file upload event handler is executing. The issue is only if the user clicks cancel at this point. Clicking cancel while the file is still being uploaded to the server is fine.

A: I recommend you to set up a dedicated temporary directory to receive file uploaded thanks to the uploadDirectory parameter of FileUploadFilter in your web.xml:
<filter>
  <filter-name>PrimeFaces FileUpload Filter</filter-name>
  <filter-class>
    org.primefaces.webapp.filter.FileUploadFilter
  </filter-class>
  <init-param>
    <param-name>uploadDirectory</param-name>
    <param-value>/var/tmp/primefaces-upload</param-value>
  </init-param>
</filter>

I guess your code already move fully uploaded files to its definite location.
I propose you configure a regular job (with Quartz for instance) to remove any file older than more than one hour (or a configurable timeout) from the upload directory.


text:
Q: Backbone.js not performing document.write at the correct time? I have a backbone.js CMS of sorts, that accepts html and then renders it in the browser.  The following is the template file (in .hamlc) that renders the backbone page object.
%h1.text= @page.get('title')
.text.page-content!= @page.get('content')

This works fine, until I have a

This widget uses document.write (which you can see if you look at the source).  First, when I load the page it doesn't show anything (I've tested the widget in an html file by itself and it displays their normal god-awful ).  When I inspect the element, it looks like the script tag was removed.
However, when I test with the following:

It runs.  Still nothing in the inspector though.
Finally, testing with the following:

It also runs.  However, it completely destroys the page content and just shows 'test'.
According to this article about using document.write for widgets, it says it can't be run after the page load.  I'm assuming that's what's happening here is that document.write is being run after page load and destroying all the content, given that's the technique backbone.js uses (appending/replacing elements in the DOM once the page is loaded).
How can I make my Backbone.js CMS accept script tags with document.write widgets without either not showing anything or destroying the entire page?

A: I cannot reproduce it, the template renders as it should:
$ coffee
coffee> hc = require './src/hamlc'
{ compile: [Function],
  template: [Function],
  __express: [Function] }
coffee> template = hc.compile ".text.page-content!= @content"
[Function]
coffee> template(content: 'Hello ')
'
Hello
'

and the script tag is persisted. Do you have the latest version installed?

A: If I understand correctly, you're trying to include the script tag for the widget inside a template, which means it's being inserted after the initial DOM is ready. That won't work for the reasons you mentioned; when the script executes, it will replace everything in the DOM.
You need to load the script before the initial DOM is complete, that is either in  or at the beginning of . That in turn means that you have to include the script tag in your initial HTML as delivered by the server rather than trying to dynamically generate it client-side.

A: You're calling document.write after the page has been loaded, so it'll overwrite the whole page. You could try putting the script tag in an iframe, or monkey patch document.write to behave differently after the page has been loaded. See the top answer on this question:
Dynamically added JavaScript overwrite the html page view (not the code)


text:
Q: Converting String to Secret Key I want to transform a String value to secret KEY DES:
String sb="fffe7a50" //Example of DES key
byte []b=sb.getBytes();  //string to bytes
SecretKey key2 = new SecretKeySpec(b, 0, b.length, "DES");

however the output is completly different :
javax.crypto.spec.SecretKeySpec@183a2

i know that the numbers after the "@" are supposed to be the DES key , but why are the results different ? how can i fix it ?

A: You've got a few issues here:

*

*sb.getBytes() does not do what you think it does. What you are expecting is a byte array containing { 0xff, 0xfe, 0x7a, 0x50 }. What you are getting is a byte array containing { 0x46, 0x46, 0x46, 0x45, 0x37, 0x61, 0x35, 0x30 } (assuming you're using UTF-8).
Your choices here would be to either initialise the byte array manually, like so:
byte[] b = new byte[]{ (byte) 0xff, (byte) 0xfe, (byte) 0x7a, (byte) 0x50 };

Or to parse the string correctly. I'm not sure exactly how you'd go about that, but it should be doable (and there will likely be an open-source library to do it for you).

*The output javax.crypto.spec.SecretKeySpec@183a2 is not writing out the value of the key. All you're seeing is the toString output of the SecretKeySpec, which follows the format <fully-qualified-class-name>@<hashcode> (see here for details on the toString() method), so the numbers you're seeing, 183a2, are just the hashcode of the SecretKeySpec object, which must not be the key - that would very insecure. To see the value of the key it's holding, you'd need to call the SecretKeySpec#getEncoded() method.
Note that just calling System.out.println(byteArray) will not display the content of the byte array - it will just display the class name and hashcode again. You'll need to either iterate through the array and print out the elements one-by-one, or use another tool to compare the two arrays.


text:
Q: Spring Framework Connection Pool Properties There seems to be plenty of examples like Configuring a Tomcat Connection Pool in Spring Boot that show how to create and initialize a connection pool.
I have a problem though. I can't seem to properly associate my connection pool properties to the actual connection pool!
Some specifics about versions I'm using:
pom.xml values:
        <parent>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-parent</artifactId>
           <version>2.7.6</version>
        </parent>

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
            <version>9.0.69</version>
        </dependency>

application.properties entries (the following are test values to prove a point):
spring.datasource.tomcat.initial-size=1
spring.datasource.tomcat.max-wait=30000
spring.datasource.tomcat.max-active=1
spring.datasource.tomcat.max-idle=1
spring.datasource.tomcat.min-idle=1
spring.datasource.tomcat.default-auto-commit=false

I create my DataSource as follows:
    @Primary
    @Bean
    public DataSource fcstmgrdbDateSource() throws Exception {

        DataSource ss =  DataSourceBuilder
            .create()
            .type(org.apache.tomcat.jdbc.pool.DataSource.class)
            .username(username)
            .password(password)
            .url("jdbc:sqlserver://" + dbServername + ":" + dbPortNumber + ";databaseName=" + dbDatabasename + ";encrypt=true;authentication=ActiveDirectoryPassword")
            .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
            .build();

        return ss;
    }

When I run the code in the debugger, and inspect the "ss" object, I don't see the connectionpool properties I've set in my properties file.
Inspector Window
I have some Java driver code that quickly asks for a hundred connections and they're delivered in record time. This driver is simply testing whether I'm using the application.property settings or not.
I expected the driver code to shudder along granting one connection at a time. I also expected to see my testing property values in the Inspector window. What I saw was what looked like default values for the connection pool.
Here's a workaround that I found that works...
    if (ss instanceof DataSourceProxy) {
        DataSourceProxy dsp = (DataSourceProxy) ss;
        dsp.setInitialSize(Integer.parseInt(environment.getProperty("fcstmgrdb.datasource.tomcat.initial-size")));
        dsp.setMaxWait(Integer.parseInt(environment.getProperty("fcstmgrdb.datasource.tomcat.max-wait")));
        dsp.setMaxActive(Integer.parseInt(environment.getProperty("fcstmgrdb.datasource.tomcat.max-active")));
        dsp.setMaxIdle(Integer.parseInt(environment.getProperty("fcstmgrdb.datasource.tomcat.max-idle")));
        dsp.setMinIdle(Integer.parseInt(environment.getProperty("fcstmgrdb.datasource.tomcat.min-idle")));
        dsp.setValidationQuery(environment.getProperty("fcstmgrdb.datasource.tomcat.validationQuery"));
        dsp.setValidationQueryTimeout(Integer.parseInt(environment.getProperty("fcstmgrdb.datasource.tomcat.validationQueryTimeout")));
    }


text:
Q: D3: the exit().remove() not working on changing the dropdown value? I have two similar bar charts on a single webpage and a dropdown having month to change the bar chart according to the value of month. I have only one csv file containing all the values. Now. I am trying to change the bar chart dataset according to the value of dropdown but the bar chart is changing the dataset value but the function exit().remove() is not working properly, the charts gets appended on each other.
My code is as follow:
 function updateLegend(dataset)
{

var tip1=d3.tip()
        .attr("class","tooltip")
        .offset([-10,0])
        .html(function(d){
        return "Application Name : "+d.AppName+"
  Support Cost : "+d.Supportcost+"";
        });

 var tip2=d3.tip()
        .attr("class","tooltip")
        .offset([-10,0])
        .html(function(d){
        return "Application Name : "+d.AppName+"
  Support Hours : "+d.Supporthrs+"";
        });
   x.domain(dataset.map(function(d){return d.AppID;}));
   y0.domain([0,d3.max(dataset,function(d){return d.Supportcost;})]);

 chart1.append("g")
     .attr("class","x axis")
     .attr("transform","translate(0,"+height+")")
     .call(xAxis)
     .selectAll("text")
     .style("text-anchor","end")
     .attr("dx","-0.8em")
     .attr("dy","-.5em")
     .attr("transform","rotate(-90)");

     chart1.call(tip1);
  bars1=chart1.selectAll(".bar").data(dataset);

  bars1.enter()
     .append("rect")
    .attr("class","bar1")
    .attr("x",function(d){return x(d.AppID);})
    .attr("y",function(d){return y0(d.Supportcost);})
    .attr("width",x.rangeBand())
       .attr("height",function(d,i,j) { return height - y0(d.Supportcost);       })
       .on("mouseover",tip1.show)
       .on("mouseout",tip1.hide);

  x.domain(dataset.map(function(d){return d.AppID;}));
  y0.domain([0,d3.max(dataset,function(d){return d.Supporthrs;})]);

 chart2.call(tip2);
 bars2=chart2.selectAll(".bar").data(dataset);

 bars2.enter()
      .append("rect")
    .attr("class","bar2")
    .attr("x",function(d){return x(d.AppID);})
    .attr("y",function(d){return y0(d.Supporthrs);})
    .attr("width",x.rangeBand())
       .attr("height",function(d,i,j) { return height - y0(d.Supporthrs); })
         .on("mouseover",tip2.show)
       .on("mouseout",tip2.hide);

  bars1.exit().remove();
  bars2.exit().remove();
  }

My Full source code is as follows:-
http://plnkr.co/edit/ibu4H5u5lzuxTFYIqSaF
The bar chart appends like this:
Thanks

A: There's 2 problems:

*

*You selectAll against a class (".bar") which you then don't use as the class for the appended elements (you use "bar1"), so it will never find any .bar instances to exit.

*Once that's fixed you need a data function that identifies each data point in your set uniquely - I've went for appid and month and year - otherwise you will then never get any new elements entrying after the first month selected. They will sit in the update selection which you don't use here (which is the selection with neither .exit() or .enter() added as a qualifier)
Do the below for bars1 and then similar for bars2 (using .bar2 as the class):
bars1=chart1.selectAll(".bar1").data(dataset, function(d) {
      return d.AppID+d.Month+d.Year;
    });

    bars1.enter()
         .append("rect")
        .attr("class","bar1")
// your code continues...


text:
Q: Asynchronous : Why is form post redirecting? Objectives :

*

*Post a form

*Upload a file to AWS S3

*Show a valid message on HTML page.

Using Node JS, HTML.
The page keeps on waiting from server.
From the server, it seems like all functions have finished running.
Would you share any experience of this problem / any way of debbuging it?
HTML :
<form method="POST" action="/submit_form/">
    <input type="hidden" id="avatar_url" name="avatar_url" value="/public/default.png" />
    <input type="text" name="username" placeholder="Username" />

    <input type="text" name="full_name" placeholder="Full name" />

    <input id="form_input" type="submit" value="Update profile" />
</form>

My Form functions :
(function(){
    document.getElementById("form_input").onclick = init_upload;
})();

function init_upload(){
   var file = dataURItoBlob(document.getElementById('preview').src);
   if(file == null){
      alert("No file selected.");
      return;
  }
   get_signed_request(file);
}

function get_signed_request(file){
 var xhr = new XMLHttpRequest();
 var file_name = "an-image-name";
 xhr.open("GET", "/sign_s3?file_name="+file_name+"&file_type="+file.type);

xhr.onreadystatechange = function(){
  if(xhr.readyState === 4){
    if(xhr.status === 200){
        var response = JSON.parse(xhr.responseText);
        upload_file(file, response.signed_request, response.url);
        console.log("xhr status 200 : file : ", file);
        console.log("xhr status 200 : response.signed_request : ", response.signed_request);
        console.log("xhr status 200 : response.url : ", response.url);
    }
    else{
        alert("Could not get signed URL.");
    }
}
};
  xhr.send();
}

And the posts managing codes :
app.post('/submit_form', function(req, res){
  //something to be done
  console.log("submit form .....")
});

 app.get('/sign_s3', function(req, res){
 aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});
var s3 = new aws.S3();
var s3_params = {
  Bucket: S3_BUCKET_CREATION,
  Key: req.query.file_name,
  Expires: 60,
  ContentType: req.query.file_type,
  ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function(err, data){
if(err){
    console.log("/sign S3 : error");
    console.log(err);
}
else{
    var return_data = {
        signed_request: data,
        url: 'https://'+S3_BUCKET_CREATION+'.s3.amazonaws.com/'+req.query.file_name
    };
    res.write(JSON.stringify(return_data));
    console.log("/sign S3 : end");
    res.end("200");
   }
  });
});

A: You need to send a response using res.status(200).end(); Otherwise, your client keeps waiting for a response from the server that will never arrive.


text:
Q: C#: most readable string concatenation. best practice
Possible Duplicate:
How should I concatenate strings?

There are several ways to concat strings in everyday tasks when performance is not important.

*

*result = a + ":" + b

*result = string.Concat(a, ":", c)

*result = string.Format("{0}:{1}", a, b);

*StringBuilder approach

*... ?

what do you prefer and why if efficiency doesn't matter but you want to keep the code most readable for your taste?

A: It depends on the use. When you just want to concat two strings, using a + b is just much more readable than string.Format("{0}{1}", a, b). However, it is getting more complex, I prefer using string.Format. Compare this:
string x = string.Format("-{0}- ({1})", a, b);

against:
string x = "-" + a + "- (" + b + ")";

I think that in most cases it is very easy to spot the most readable way to do things. In the cases where it is debatable which one is more readable, just pick one, because your boss isn't paying for these pointless discussions ;-)

A: string.Format for me, but in practice I use whichever is fit for purpose, taking into account performance and readability.
If it was two variables I'd use.
string.Concat(str1, str2);
If it contained a constant or something that requires formatting then.
string.Format("{0} + {1} = {2}", x, y, x + y);
Or for something like an SQL query
string SqlQuery = "SELECT col1, col2, col3, col4" +
                  "FROM table t " +
                  "WHERE col1 = 1";

And string builder when performance matters.

A: String.Format(...) is slowest.
For simple concatenations which don't take place in a loop, use String.Concat(...) or the + operator, which translate to the same under the hood, afaik. What is more readable is very subjective.
Using a StringBuilder for simple concatenations is over-the-top for simple concatenations as well and has most likely too much overhead. I'd only use it in a loop.

A: For something like this (which I'm guessing is being sent to the UI), I would definitely prefer String.Format.  It allows the string to be internationalized easy; you can grep for calls to String.Format and replace them with your translating format.

A: My personal preference is:
I find the + approach the most readable and only use Format() or a StringBuilder if there is a good reason (i18n, performance etc) for it. I (almost) never use Concat.
I think I find the + approach easier to read than Format() simply because I don't have to skip ahead to the end to see what variables are put into in the {} place-holders. And if the place-holders aren't in numeric order, it gets even harder to read imo.
But I guess for larger projects it makes sense to simply enforce using Format by a style guide just in case the code might be (re-)used in a project requiring i18n later on.

A: *

*string.Format
for few concats. for more I use

*StringBuilder approach
even if performance is not important. there is a team agreement I have to follow

A: I prefer String.Format for small strings, and StringBuilder for larger ones.  My main reason is readability.  It's a lot more readable to me to use String.Format (or StringBuilder.AppendFormat()), but I have to admit that that is just personal preference.
For really big text generation, you might want to consider using the new (VS2010) T4 Preprocessed Templates - they are really nice.
Also, if you're ever in VB.NET, I like the XML literal technique Kathleen Dollard talked about in episode 152 of hanselminutes.

A: Prefer to use:
String.Concat for simple concatenations like String.Concat("foo", bar);
String.Format for complex formatting like String.Format("{1}", url, text);
StringBuilder for massive concatenations like:
var sb = new StringBuilder();
sb.AppendLine("function fooBar() {");
sp.AppendLine(String.Join(Environment.NewLine, blah));
sp.AppendLine("}");
page.RegisterClientScript(page.GetType(), sb.ToString());

Prefer to avoid "foo" + "bar" (as well as if (foo == "bar"). And especially String.Format("{0}{1}", foo, bar) and
throw new Exception("This code was" +
    "written by developer with" +
    "13\" monitor");


text:
Q: Jackson Feature ACCEPT_SINGLE_VALUE_AS_ARRAY would not work with annotation I want to be able to call my api with POST content
{
  "property1" : "value1",
  "property2" : "value2"
}

OR
[{
  "property1" : "value1",
  "property2" : "value2"
}]

For this I annotated the java class with
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)

public class MyClass {

    private String porperty1;
    private String property2;

    public MyClass() {
        super();
        // TODO Auto-generated constructor stub
    }

    public MyClass(String porperty1, String property2) {
        super();
        this.porperty1 = porperty1;
        this.property2 = property2;
    }

    public String getPorperty1() {
        return porperty1;
    }

    public void setPorperty1(String porperty1) {
        this.porperty1 = porperty1;
    }

    public String getProperty2() {
        return property2;
    }

    public void setProperty2(String property2) {
        this.property2 = property2;
    }

}

Inside the servlet I have an api like this
Response myAPI(Collection<MyClass> reqs, @Context HttpServletResponse httpResponse, @Context SecurityContext securityContext) {

}

But I keep getting Internal server error 500 with the 1st request type.
I have tried with updating the jackson=annotations version from 2.6.0 to 2.7.0, but it doesn't seem to be working in any.
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.7.0</version>
</dependency>

Note: I have other jackson dependencies in my POM e.g. jackson-databind and jackson-core, which are still pointing to 2.6.4 (and jackson-dataformat-xml pointing to 2.6.3).  I could not update the versions of these. Would that have any issues considering I am trying jackson-annotations with higher versions?

A: You will need to use that annotation on actual property, not the POJO that contains property.


text:
Q: Eclipse plugin to find the error on Double Click the file I need the help in console view of eclipse. When i build my project all my errors and warnings are displayed in console window and if i need to find the place where it showing those errors i need have to go into that file and find those information. I feel its much iritating to find when errors are huge. So is there any plugin available that take us to that location of errors on double click. Thanks in Advance

A: You have to left click on the warning or error once, to make sure that the Eclipse Problems view has focus.  Then, you double click on the warning or error description, and the cursor will take you to the warning or error in your code.


text:
Q: Characterizing strong connectedness
Prove a directed graph $G$ is strongly connected iff each nonempty subset $U\subset V$ has at least one edge going from it to $U^c$.

I started trying to construct this path with a bunch of choices and recursions but I feel I'm really missing the point and that a proof should be two lines in each direction. What should I be doing?

A: If $G$ is is strongly connected then any proper subset $U\subseteq V$ is not a connected component, and so there must exist an edge from $U$ to $U^c$.
Conversely, build the directed graph $G'$ in which the vertices are the connected components of $G$ and there is an edge from $c_1$ to $c_2$ if and only if there is an edge from a vertex of component $c_1$ to a vertex of component $c_2$ in $G$. Note that $G'$ must be a directed acyclic graph. Therefore there most be a vertex in $G'$ with out-degree $0$, let $c$ be the vertex with out-degree $0$.
Notice that if $c$ is not all of $G$ then the subset $c\subseteq V$ has no edges from $c$ to its complement, we conclude that if $G$ satisfies that for every proper subset $U\subseteq V$ there is an edge from $U$ to $U^c$ then $G$ is strongly connected.


text:
Q: VueJS change a table's row in a loop individually I'm struggling to wrap my head around the logic behind this:
I'm using VueJS to show some records from a database in a table, and to show it dinamically, so filtering, pagination etc, also, I want that when I click on a row, it acts like a clicked button and change its background-color, then it should "slide up" to show the row's complete content (so like a complete reactive UI), but let's focus on the background-color change:  The content is in the table, Vue loads everything it got from my endpoint and shows it, I made the class .selected, and edited the v-for loop on the tbody binding the selected class to a selected variable, then on click firing up a function to change the variable true\false value.
The problem is, if I click a row every row's color change because they all share the same class name and triggering it on one one triggers it for every row.
Since I didn't share any code yet, here's the tbody in all its glory, I won't type the Vue instance cause it's pretty simple : one variable in data (selected = false), and one function in methods (isSelected).

          @{{ post.id }}
          @{{ post.PID }}
          @{{ post.title }}
          @{{ post.slug }}
          @{{ post.content.substr(0,50) }}
          @{{ post.status }}
          @{{ post.likes_count }}
          @{{ post.comments_count }}
          @{{ post.publish_date }}

How do I approach this? I was thinking about making the class name dynamic so it's selected-N where N is the row's index, but it doesn't seem like the right solution.
How would you do it? How do you handle multiple looped data editing using VueJS? Cause after this one, I want everything in that table to be responding to the user's actions (changing color like a button so you know which row is selected, sliding up\down for showing informations and\or more options etc..).
Edit :
Following Husam's suggestion:
I've changed the v-for part

I've checked with some alerts, and the key is correctly passed to the selected function, which is this :
selected: function (key) {
        this.posts[key].selected = !this.posts[key].selected;

      } // end function

Also when I get the objects from the api call I create the selected property,
which effectively toggled in the correct object when I click the row, the problem is, the color doesn't change, so the class binding :class="{ selectedRow: post.selected }" is not toggling the class when I click, is post.selected the correct data to give? (selectedRow class in already created and changed the background color)
Adding more infos in case anybody else ends up here :
As suggested in the comments, adding this.$forceUpdate() to my selected(key) function fixes the problem :
selected: function (key) {
        this.$forceUpdate();
        this.posts[key].selected = !this.posts[key].selected;
      } // end function

So what'd the issue here?


text:
Q: Does having a companion onboard give away your position? The Serenity is regularly involved in activities of dubious legality, and is often on the run from either the authorities or powerful criminals and mobsters.
In the meanwhile, Inara, a companion, travels with them, communicates regularly with her guild, asks them information on potential clients on the planets they visit and arranges trades with them.
So it seems to me that someone powerful enough (or connected enough, or with enough hacking abilities) could infer the position of the spaceship by monitoring her activity. Isn't this a problem? Why does no one worries about the fact that their "ambassador" might make their position known to their enemies?

A: Until the events of the film, the crew of the cargo ship Serenity aren't really trying to hide from anyone in particular. They regularly submit to custom inspection, register their presence on the Cortex and bid for cargo shuttling work (even including Alliance work on one occasion). All of this suggests that they have no major problem with people knowing their location.
Under the surface, obviously they're supplementing their incomes through smuggling, bank robbery and various nefarious activities but the trick is that they need to look legitimate. Having a registered companion on board gives them an excuse to travel to places and planets that would frown on the arrival of a jobbing cargo ship.

Inara: Yes, because I can bring something that your surveyor or any of the other fish you might have on line can't.  A certain respectability.
Mal: Respectability?
Inara: And based on what little I've seen of your "operation," I suspect that's something you could use.
Mal: Fine.  Let me ask you this:  if you're so respectable, why are you even here?  I mean, I've heard tell of fancy ladies such as yourself shipping out with big luxury liners, and the like.  But a registered companion on a boat like this?  What are you running from?


text:
Q: Laplace transform of $\frac{d^{n}}{d t^{n}} \delta(t)$ What is the Laplace transform of $$f(t)=\frac{d^{n}}{d t^{n}} \delta(t)$$, where $\delta(t)$ is the Dirac-Delta distribution.
I am really not sure, but i am expecting that by using the formula:
$$\mathcal{L}\left\{f^{(n)}\right\}=s^{n} \mathcal{L}\{f\}-s^{n-1} f(0)-s^{n-2} f^{\prime}(0)-s^{n-3} f^{\prime \prime}(0)-\ldots-f^{(n-1)}(0)$$, we have
$$\mathcal{L}\left(\frac{d^{n}}{d t^{n}} \delta(t)\right)=s^n(1)-0-0-0...-0=s^n$$
But Mathematically how to prove formally that all the derivatives are zeros?


text:
Q: Property not found on object of type error with method declaration in Objective C Have a weird error on method declaration and call...
MyObject.h --- declarations. has been trimmed down
#import <Foundation/Foundation.h>

@interface MyObject : NSObject

- (void) useFlattenHTML;
- (NSString *) flattenHTML:(NSString *) inHtml;
- (NSString *) justAStringMethod;

@end

And method defined and called like this...
MyObject.m --- method declaration and usage. Trimmed down
#import "MyObject.h"

@implementation MyObject
- (NSString *) flattenHTML:(NSString *) inHtml {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:inHtml];
while ([theScanner isAtEnd] == NO) {
    [theScanner scanUpToString:@"<" intoString:NULL] ;
    [theScanner scanUpToString:@">" intoString:&text] ;
    inHtml = [inHtml stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
}
//
inHtml = [inHtml stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return inHtml;
}

- (NSString *) justAStringMethod
{
    // Some calls.
}

- (void) useFlattenHTML
{
    NSString* resultStr = [self.flattenHTML @"Some html tagged string"];
    NSString* anotherStr = [self.justAStringMethod];
}

@end

I get
 Property 'flattenHTML' not found on object of type 'MyObject *'

A: Maybe because you're using the dot notation in a case where it doesn't make much sense :
in useFlattenHTML method, self.flattenHTML is the same as [self flattenHTML], which doesn't exist, as you only have [self flattenHTML:someString].
On top of that, dot notation is possible, but you should keep it for fields declared as @property only


text:
Q: Dependency Injection in jersey 2.17 I have a resource class
@Path("/rest")
public class DemoResourceController {
    @Inject
    DemoService demoService;

    @Path("/get/demo")
    @GET
    @Produces(APPLICATION_JSON)
    public Response getDemoLists() {
        List<String> demoList=demoService.getDemoList();
        return  Response.ok(demoList).build();
    }

I tried the answers in the post
  Dependency injection with Jersey 2.0
if i use
compile group: "org.glassfish.jersey.ext.cdi" , name: "jersey-cdi1x" , version: "2.17"
compile group: "org.glassfish.jersey.ext.cdi" ,name: "jersey-weld2-se" , version: "2.17"

On launching the server i get
org.jboss.weld.exceptions.IllegalArgumentException: WELD-001408:
Unsatisfied dependencies for type demoService with qualifiers @Default
[BackedAnnotatedField] @Inject  DemoResourceController.demoService at injection point

If i remove the above dependencies then i get
javax.servlet.ServletException: A MultiException has 3 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no
   object available for injection at SystemInjecteeImpl(requiredType=DemoService,parent=DemoResourceController,qualifiers={},position=- 1,optional=false,self=false,unqualified=null,1952079126)**
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of DemoResourceController errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on package.DemoResourceController

org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:421)

The resourceconfig class is
public class ApplicationConfig extends ResourceConfig {

  public ApplicationConfig() {
    register(new ApplicationBinder());
    packages(..name of packages..);
  }

The binder class is
public class ApplicationBinder extends AbstractBinder{
  @Override
  protected void configure() {
      bind(DemoService.class).to(DemoServiceImpl.class);
  }
 }

I use tomcat in embedded mode and add init parameters
Context ctx = tomcat.addContext("/", new File("web-app").getAbsolutePath());
Wrapper wrapper = ctx.createWrapper();
wrapper.addInitParameter("javax.ws.rs.Application","xx.xx.ApplicationConfig");

How do i inject the service in the controller?
Is injection the preferred way to unit test it (when the service implementation,say demoServiceImpl is calling another service say,XService) and unit tests should not depend on Xservice and hence demoServiceImpl
How would i inject a mock of the service into the controller from the test?

A: In your second attempt (without the cdi dependencies; using HK2) your binding is incorrect. It should be
bind(Implementation).to(Contract)
// - i.e.
bind(DemoServiceImpl.class).to(DemoService.class);

You have it the other way around.
As far as testing, if you have the test in same package (in the test area of the project) you should be able to assign the service, as it's package private. Though personally, I've gotten into the habit of constructor injection. Another thing you can do is use Jersey Test Framework. You can see an complete example here, where a mock service is injected


text:
Q: How to find 2d angles for 3d vectors? I have three vectors in 3d that originate at a point. If I look at them along a line perpendicular to a plane that intersects two of them, how do I find the angles between those two vectors and the third one?
Clarification because this is frickin difficult to explain:

I'll also accept a way to find how much of the longest line is on either side of the shorter line, because that's ultimately what I need.

A: Hi the dot product (1) is a great way to do that
here is a random video
it seems I need to develop here a bit further sorry about the links I just wanna help^^
lets $\vec{OA}=\vec{A},\vec{OB}=\vec{B},\vec{OC}=\vec{C}$ be three vectors in 3D.
In the special case where $\vec{A}$ is perpendicular to $\vec{B}$ you can project $\vec{C}$ into the plane define by the two vectors $\vec{A}$ and $\vec{B}$ as the following sum
"the projection of $\vec{C}$ on $\vec{A}$" + "the projection of $\vec{C}$ on $\vec{B}$"
so $\vec{C_{proj}} =(\frac{\vec{C}\cdotp\vec{A}}{\vec{A}\cdotp\vec{A}}\vec{A}+\frac{\vec{C}\cdotp\vec{B}}{\vec{B}\cdotp\vec{B}}\vec{B}) $
next you can find the angle between $\vec{C_{proj}}$ and $\vec{A}$ with the formule from the dot product:
$\theta=\arccos (\frac{\vec{C_{proj}}\cdotp\vec{A}}{\|\vec{C_{proj}}\|\|\vec{A}\|})$
EDITED for the case where $\vec{A}$ is not perpendicular to $\vec{B}$
the general case: $\vec{C_{proj}} = \vec{C}-\frac{\vec{C}\cdotp(\vec{A}\times\vec{B})}{(\vec{A}\times\vec{B})\cdotp(\vec{A}\times\vec{B})}(\vec{A}\times\vec{B})$
note:
$(\vec{A}\times\vec{B})$ is call the cross product of $\vec{A}$ and $\vec{B}$
$(\vec{A}\cdotp\vec{B})$ is call the dot product of $\vec{A}$ and $\vec{B}$
ps: don't forget there is always two possibles answers for the angle between two vectors $\theta$ and $(360-\theta)$ and think about rad or degrees
ANOTHER SOLUTION:
using @amd resoning you can find another formula for your end goal:
Let $\vec{N}=(\vec{A}\times\vec{B})\times\vec{C}$
then $\frac{\vec{A}\cdotp\vec{N}}{\vec{A}\cdotp\vec{N}+\vec{B}\cdotp\vec{N}}\|\vec{A}-\vec{B}\|$ and $\frac{\vec{B}\cdotp\vec{N}}{\vec{A}\cdotp\vec{N}+\vec{B}\cdotp\vec{N}}\|\vec{A}-\vec{B}\|$ are how much of the longest line is on either side of the shorter line.
you can interpret "the direction of $\vec{C_{proj}}$" as "the vertical black vector", $\vec{N}$ as X , the fraction in front as the ratio between one of the rectangle(green or red) divide by both combine while $\|\vec{A}-\vec{B}\|$ is the lenght of the "longest line" as you call it.
cheers

A: $cos\phi = \frac{\vec v \bullet \vec u}{|\vec v|*|\vec u|}$
You also might need to project the vectors on the same plane, and than use the formulare, if you are referring to the vectors having a "2D angle" as having a certain angle when projected onto a shared plane.

A: I'm glad that you mentioned the problem that you're ultimately trying to solve because that can be worked out directly from the three vectors without resorting to computing angles or projections. Essentially, you need to find the intersection point of the line through points $A$ and $B$ with the line defined by the projection of the third vector $C$ onto the plane $P$ spanned by $A$ and $B$. This is equivalent to computing the intersection of the line $AB$ (the extension of the longer diagonal in your illustration) with the plane perpendicular to $P$ that contains $C$.
So, let $N = (A\times B)\times C$. $A\times B$ is perpendicular to the plane $P$, and $N$ is perpendicular to both this and $C$, so it is normal to the plane with which we want to intersect the line. Every point on this plane satisfies the equation $N\cdot X=0$. Expressing the line $AB$ as $Q(t) = (1-t)A+tB$, we then solve $$N\cdot Q(t) = N\cdot\left((1-t)A+tB\right) = 0,$$ so $$t = {N\cdot A\over N\cdot A-N\cdot B}.\tag1$$ As long as the projection of $C$ lies between $A$ and $B$ as you've pictured, the denominator won't vanish.
Now, this parameterization has the property that $t$ is equal to ${\lvert QA\rvert\over\lvert BA\rvert}$, so it gives you the proportion of the segment $AB$ that lies on the "$A$ side" of the intersection. If you want the actual distance, you need only multiply $t$ by the distance between $A$ and $B$.
This result makes geometric sense: For any point $X$, $N\cdot X$ is proportional to its distance from the plane defined by $N$; the sign tells you which side of the plane the point is on. So, formula (1) says that the distance to the intersection along the segment $AB$ is in proportion to the perpendicular distances to $P$, which can be demonstrated with similar triangles.


text:
Q: How to fix a Static Library? I'm trying to learn how to debug static libraries and I am trying to fix JsonCpp in particular.
What project settings can I use to see exactly what's being linked in the output window in Visual Studio?
==================================================================================
Here are the errors that I am getting:
Error   1   error LNK2005: "public: __thiscall std::_Lockit::~_Lockit(void)" (??1_Lockit@std@@QAE@XZ) already defined in libcpmtd.lib(xlock.obj)    msvcprtd.lib

Error   2   error LNK2005: "public: __thiscall std::_Lockit::_Lockit(int)" (??0_Lockit@std@@QAE@H@Z) already defined in libcpmtd.lib(xlock.obj) msvcprtd.lib

Error   3   error LNK2005: "void __cdecl std::_Debug_message(wchar_t const *,wchar_t const *,unsigned int)" (?_Debug_message@std@@YAXPB_W0I@Z) already defined in libcpmtd.lib(stdthrow.obj)    msvcprtd.lib

Error   4   error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)" (??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) already defined in Core.obj msvcprtd.lib

Error   5   error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(char const *)" (??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@PBD@Z) already defined in Core.obj   msvcprtd.lib

Error   6   error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z) already defined in Core.obj msvcprtd.lib

Error   7   error LNK2005: "public: char const * __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::c_str(void)const " (?c_str@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEPBDXZ) already defined in Core.obj    msvcprtd.lib

Error   8   error LNK2005: "public: void __thiscall std::_Container_base_secure::_Orphan_all(void)const " (?_Orphan_all@_Container_base_secure@std@@QBEXXZ) already defined in Core.obj msvcprtd.lib

Error   9   error LNK2005: "public: __thiscall std::_Container_base_secure::~_Container_base_secure(void)" (??1_Container_base_secure@std@@QAE@XZ) already defined in Core.obj  msvcprtd.lib

Error   10  error LNK2005: "public: __thiscall std::_Container_base_secure::_Container_base_secure(void)" (??0_Container_base_secure@std@@QAE@XZ) already defined in Core.obj   msvcprtd.lib

Error   11  error LNK2005: "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::operator=(char const *)" (??4?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV01@PBD@Z) already defined in libcpmtd.lib(locale0.obj)  msvcprtd.lib

Error   12  error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(unsigned int,char)" (??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ID@Z) already defined in Serialization.obj  msvcprtd.lib

Error   13  error LNK2005: "public: unsigned int __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::size(void)const " (?size@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEIXZ) already defined in Core.obj    msvcprtd.lib

Error   14  error LNK2005: "public: void __thiscall std::basic_ios<char,struct std::char_traits<char> >::setstate(int,bool)" (?setstate@?$basic_ios@DU?$char_traits@D@std@@@std@@QAEXH_N@Z) already defined in Serialization.obj    msvcprtd.lib

Error   15  error LNK2005: "public: static bool __cdecl std::char_traits<char>::eq_int_type(int const &,int const &)" (?eq_int_type@?$char_traits@D@std@@SA_NABH0@Z) already defined in Serialization.obj   msvcprtd.lib

Error   16  error LNK2005: "public: static int __cdecl std::char_traits<char>::eof(void)" (?eof@?$char_traits@D@std@@SAHXZ) already defined in Serialization.obj    msvcprtd.lib

Error   17  error LNK2005: "public: static unsigned int __cdecl std::char_traits<char>::length(char const *)" (?length@?$char_traits@D@std@@SAIPBD@Z) already defined in Core.obj   msvcprtd.lib

Error   18  error LNK2005: _malloc already defined in LIBCMTD.lib(dbgmalloc.obj)    MSVCRTD.lib

Error   19  error LNK2005: _free already defined in LIBCMTD.lib(dbgfree.obj)    MSVCRTD.lib

Error   20  error LNK2005: "public: virtual __thiscall std::exception::~exception(void)" (??1exception@std@@UAE@XZ) already defined in LIBCMTD.lib(stdexcpt.obj)    MSVCRTD.lib

Error   21  error LNK2005: "public: __thiscall std::exception::exception(void)" (??0exception@std@@QAE@XZ) already defined in LIBCMTD.lib(stdexcpt.obj) MSVCRTD.lib

Error   22  error LNK2005: "public: __thiscall std::exception::exception(class std::exception const &)" (??0exception@std@@QAE@ABV01@@Z) already defined in LIBCMTD.lib(stdexcpt.obj)   MSVCRTD.lib

Error   23  error LNK2005: _strchr already defined in LIBCMTD.lib(strchr.obj)   MSVCRTD.lib

Error   24  error LNK2005: __invalid_parameter already defined in LIBCMTD.lib(invarg.obj)   MSVCRTD.lib

Error   25  error LNK2005: __CrtDbgReportW already defined in LIBCMTD.lib(dbgrptw.obj)
MSVCRTD.lib

Error   26  error LNK2005: "public: __thiscall std::exception::exception(char const * const &)" (??0exception@std@@QAE@ABQBD@Z) already defined in LIBCMTD.lib(stdexcpt.obj)    MSVCRTD.lib

Error   27  error LNK2005: _memmove_s already defined in LIBCMTD.lib(memmove_s.obj) MSVCRTD.lib

Error   28  error LNK2005: _sprintf already defined in LIBCMTD.lib(sprintf.obj) MSVCRTD.lib

Error   29  error LNK2005: _sprintf_s already defined in LIBCMTD.lib(sprintf.obj)   MSVCRTD.lib

Error   30  error LNK2005: _strpbrk already defined in LIBCMTD.lib(strpbrk.obj) MSVCRTD.lib

Error   31  error LNK2005: "private: __thiscall type_info::type_info(class type_info const &)" (??0type_info@@AAE@ABV0@@Z) already defined in LIBCMTD.lib(typinfo.obj)  MSVCRTD.lib

Error   32  error LNK2005: "private: class type_info & __thiscall type_info::operator=(class type_info const &)" (??4type_info@@AAEAAV0@ABV0@@Z) already defined in LIBCMTD.lib(typinfo.obj)    MSVCRTD.lib

Warning 33  warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; use /NODEFAULTLIB:library   Afterfuture Game Engine

Error   34  fatal error LNK1169: one or more multiply defined symbols found C:\Users\Blake\Desktop\Afterfuture\Afterfuture Game Engine\Debug\Afterfuture Game Engine.exe

A: The problem is that you are linking together two different versions of the same library. If a library is statically-linked to the debug, single-threaded version of the standard C-library, an application using that library cannot dynamically-link to the release, multi-threaded version of the same runtime library.
Otherwise, you wind up with, for example, two different memory allocators and mayhem if memory is allocated from one but returned to the other. So even if the linker allowed you to do this, the application couldn't safely interoperate with the library anyway -- so what would be the point?
Suppose the library is already statically linked to the multithreaded version of the standard C library and the application dynamically links to the single threaded version. What happens if the library calls delete on an object that was allocated by the application and the library's allocator has to free an object despite never having allocated one?!
There is simply no way to make this work reliably. Either statically-link everything to the exact same static library or dynamically-link everything. (This is basically the reason dynamic-linking is preferred. Otherwise, you have to link all libraries and the application at the same time or be very careful.) Consider yourself lucky the symbols collided and you got a warning.