text:
Q: SpringBoot Web application - Could not resolve view with name 'index' I have been using Spring cloud for building my cloud based distributed application. All my micro services are working fine, however when i started moving my web application, which is a HTML/Angular based project, i am facing few issues.
Below are my configurations and remember this is a springboot web application that i am trying to build -
Pom dependencies (compiled as both war or jar) -
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

Main class -
@SpringBootApplication
@EnableDiscoveryClient
@EnableWebMvc
@ComponentScan
@EnableAutoConfiguration

public class CloudUIApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(CloudUIApplication.class);
    }

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

Controller -
@Controller
public class HomeController {

    @RequestMapping("/home")
    public String welcome() {
        return "index";
    }

    @RequestMapping("/")
    public String foo(Map<String, Object> model) {
        throw new RuntimeException("Foo");
    }
}

application.yml -
spring:
    mvc:
        view:
            prefix: /WEB-INF/views/
            suffix: .html

I have created a src/main/webapp/WEB-INF folder with sub folder named views with file name index.html
Below is the error i am hitting -
javax.servlet.ServletException: Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet'
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1237) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105) ~[spring-boot-actuator-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:107) ~[spring-boot-actuator-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_91]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.4.jar:8.5.4]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_91]

Any suggestions please, will be really helpful.
AJ


text:
Q: laravel: Inserting into database the selected image(s) from a form In Laravel, I have a form which has a gallery, I want to put the selected images by user after submit in database to retrieve it later.
<form action="{{ action('', $product->id) }}">

foreach($images as $image) {

cover }}">

{{ $image->code }}

}

<button type="submit">SUBMIT</button>
</form>

I have a many to many relation table names "image_product" with relation of images and products tables.
I think to send data by ajax/jquery but is it possible to send it directly from laravel and then get data from images_product table by Ajax/jquery?

A: You only submit an empty form, because no form method is used. Wrap a checkbox around each image with value of the image in base64. After submitting decide inside your Controller to store the submitted data in the relating model and access it later via unique id. With your relations it should work if your Models are coded correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculate proportion of positives values by group With this dataframe:
table <- "
    trt rep ss  d1  d4  d5  d6  d7
    1   1   1   0   0   0   0   0
    1   1   2   0   0   0   0   0
    1   1   3   0   0   1   2   2
    1   2   1   0   0   1   3   6
    1   2   2   0   1   1   2   4
    1   2   3   0   0   0   1   1
    1   3   1   0   0   0   0   0
    1   3   2   0   0   0   0   0
    1   3   3   0   1   1   1   1
    2   1   1   0   0   0   0   0
    2   1   2   0   0   0   1   1
    2   1   3   0   0   0   1   1
    2   2   1   0   0   0   0   0
    2   2   2   0   0   0   0   0
    2   2   3   0   0   0   0   1
    2   3   1   0   0   0   0   0
    2   3   2   0   0   0   1   3
    2   3   3   .   .   .   .   .
    "
d <- read.table(text=table, header = TRUE, check.names = F, na.strings = ".")

I'd like to obtain a dataframe with the proportion of positives values by trt for every day (d1,d4,..., d7) such as this table:
# trt    d1    d4     d5    d6    d7
# 1    0.00  0.22   0.44  0.56  0.56
# 2    0.00  0.00   0.00  0.38  0.50

A: Thanks to @A.Webb, here's a way in base R:
aggregate(d[,4:8]>0~d$trt, FUN = mean)

#   d$trt d1        d4        d5        d6        d7
# 1     1  0 0.2222222 0.4444444 0.5555556 0.5555556
# 2     2  0 0.0000000 0.0000000 0.3750000 0.5000000

Here was my original idea:
rowsum(+(d[-(1:3)] > 0), d$trt, na.rm=TRUE) /
  rowsum(+!is.na(d[-(1:3)]), d$trt, na.rm=TRUE)

The + is there because rowsum only works with numbers, and not with logicals.

A: Using data.table, something like this:
library(data.table)
d <- data.table(d)
d[,lapply(.SD,function(x) sum(x>0,na.rm=T)/sum(!is.na(x))),
  .SDcols=grep("^d",names(d),val=T),
   by=trt]

   trt d1        d4        d5        d6        d7
1:   1  0 0.2222222 0.4444444 0.5555556 0.5555556
2:   2  0 0.0000000 0.0000000 0.3750000 0.5000000

A: We can use dplyr
library(dplyr)
d %>%
  group_by(trt) %>%
  summarise_each( funs(round(mean(.>0, na.rm=TRUE),2)), d1:d7)
#   trt    d1    d4    d5    d6    d7
#  (int) (dbl) (dbl) (dbl) (dbl) (dbl)
#1     1     0  0.22  0.44  0.56  0.56
#2     2     0  0.00  0.00  0.38  0.50


text:
Q: How to reset the length of the control of scaleLine in OpenLayers? I want to change the style of the control of the ScaleLine,but I have no idea where to change it,anybody can give me some advice?
map.addControl(new OpenLayers.Control.ScaleLine());

A: Please check out following links
http://dev.openlayers.org/addins/scalebar/trunk/examples/scalebar.html
http://dev.openlayers.org/addins/scalebar/trunk/examples/scalebar-custom.html
will be helpful for you.


text:
Q: Magento 2. How do i put out of stock products to the end in catalog search result collection? I tried to do it via layer collection :

$collection->getSelect()->order('is_salable DESC');

It works for catalog, but does not sort the result in search .

A: I found the solution in this layer plugin:
public function afterGetProductCollection(
    \Magento\Catalog\Model\Layer $subject,
    $result
)
{
    $collection = $result;
    if(!$this->_added) {
        if($this->isCatalogSearchCollection() && $collection && $this->useSelect()) {

            $collection->getSelect()->joinLeft(
                ['stock_item_table' => $collection->getResource()->getTable('cataloginventory_stock_item')],
                "e.entity_id = stock_item_table.product_id",
                ['is_in_stock']
            );
            $collection->getSelect()->order('is_in_stock DESC');
            $orders = $collection->getSelect()->getPart(\Zend_Db_Select::ORDER);
            array_unshift($orders, array_pop($orders));
            $collection->getSelect()->setPart(\Zend_Db_Select::ORDER, $orders);
            $this->_added = true;
        }else{
            $collection->getSelect()->order('is_salable DESC');
            $this->_added = true;
        }
    }
    $result = $collection;
    return $result;
}

And i also added a class variable that comes up as false when class init, then after order is has been placed to avoid circle select and order method call:
 protected $_added = false;


text:
Q: newRawData.forEach is not a function in ui-grid I search for this error but not able to fix it.Am new to angular.Dont know exactly whats going wrong.
Html:

Angular code:
$scope.gridOptionsTrips = {};
        $scope.gridDataSourceTrips = [];
        var ROW_HEIGHT = 30;
      //  to show data on Grid
        $scope.gridOptionsTrips = {
            enableRowSelection: true,
            enableRowHeaderSelection: true,
            enableSorting: true,
            multiSelect: false,
            rowHeight: ROW_HEIGHT,
            virtualizationThreshold: 10,
            fastWatch: false,
            enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
            data: 'gridDataSourceTrips',
            appScopeProvider: $scope,
            showColumnMenu: true,
            enableSelectAll: false,
            noUnselect: true,
            enableCellSelection: true,
            rowTemplate: '

'
        };

 $scope.onTripsGridRowClick = function (row) {
            $scope.gridApi.selection.selectRow(row.entity);
        };

        $scope.gridColDefsTrips = function () {
            var idTemplate = '

';
            var sTemplate = '

';
            var speedTemplate = '

';
            var directionTemplate = '

';
            var timeTemplate = '

';
            var kmCounterTemplate = '

';
            var driverNameTemplate = '

';
            return [
                  { name: "CARDRIVER", displayName: "CARDRIVER", field: 'UserId', cellTemplate: idTemplate, enableColumnMenu: false, headerCellFilter: 'translate', width: 150, showInColumnFilter: true },
                  { name: 'STARTEND', displayName: 'STARTEND', field: 'Departure.DateTime', cellTemplate: idTemplate, width: 70, enableColumnMenu: false, headerCellFilter: 'translate', showInColumnFilter: true },
                  { name: 'STARTEND', displayName: 'STARTEND', field: 'Destination.DateTime',cellTemplate: idTemplate, enableColumnMenu: false, headerCellFilter: 'translate', width: 80, showInColumnFilter: true },
                  { name: 'TRIPLENGTH', displayName: 'TRIPLENGTH', field: 'Distance', cellTemplate: idTemplate, enableColumnMenu: false, headerCellFilter: 'translate', width: 150, showInColumnFilter: true }
            ];
        };
        $scope.gridDataSourceTrips = tripsDetailsService.GetAllTripsByWeek('2014-01-10', '2014-01-14', 1, 20);
        $scope.gridOptionsTrips.columnDefs = $scope.gridColDefsTrips();


text:
Q: Making Chart render for negative value efficiently This thread is a continuation of below:
Trying to make dynamic D3 Chart with Bar and Difference line/value
I was trying to test the chart using negative values (i.e -ve) but it is not working properly. I made some changes in the yAxis scale Domain by passing dynamic min value instead of static "0" value.
At "0" there should be a dotted line and the -ve value should display down of that and +ve (positive values) values start from "0" and height till its value.
Please help me to solve the issue.
Below is the Code:

var barData = [{
    "Time": "2019",
    "Value": 5388
  },
  {
    "Time": "2020",
    "Value": 6453
  },
  {
    "Time": "2021",
    "Value": -4345
  },
  {
    "Time": "2022",
    "Value": 7345
  },
  {
    "Time": "2023",
    "Value": 8345
  },
  {
    "Time": "2024",
    "Value": 5345
  },
  {
    "Time": "2025",
    "Value": 6345
  },
  {
    "Time": "2026",
    "Value": 3345
  }
];

const container = d3.select('#graph');
const divWidth = parseInt(container.style('width'));
const divHeight = parseInt(container.style('height'));

// Consider this width and Height are dynamic for div "graphID" because I am trying to responsive design
const margin = {
  top: 30,
  right: 50,
  bottom: 50,
  left: 50
};
const width = divWidth - margin.left - margin.right;
const height = divHeight - margin.top - margin.bottom;

//To add svg in the visualization node i.e Dome node
const svg = container.append("svg")
  .attr("width", divWidth)
  .attr("height", divHeight)
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);

//To add tooltip for bar
var tooltip = d3.select("body").append("div").attr("class", "toolTip");

const defs = svg.append("defs");

const marker = defs.append("marker")
  .attr("id", "arrowhead")
  .attr("markerWidth", "10")
  .attr("markerHeight", "7")
  .attr("refX", "0")
  .attr("refY", "3.5")
  .attr("orient", "auto")

const polygon = marker.append("polygon")
  .attr("fill", "gray")
  .attr("points", "0 0, 10 3.5, 0 7")

const xScale = d3.scaleBand()
  .domain(barData.map(d => d.Time))
  .range([0, width + margin.right]);

const xAxis = d3.axisBottom(xScale);

//Adding g attribute to svg for x axis
svg.append('g')
  .attr("transform", `translate(0,${height})`)
  .call(xAxis);

const yAxisMax = barData.reduce((max, item) => Math.max(max, item.Value), 0) * 1.5;

const yAxisMin = barData.reduce((min, item) => Math.min(min, item.Value), 0) * 1.5;

const yScale = d3.scaleLinear()
  .domain([yAxisMin, yAxisMax])
  .range([height, 0]);

const yAxis = d3.axisLeft(yScale).ticks(4);

svg.append('g')
  .call(yAxis);

const bars = svg.selectAll('g.bar')
  .data(barData)
  .enter()
  .append('g')
  .classed('bar', true)
  .attr('transform', d => `translate(${xScale(d.Time) + xScale.bandwidth() / 2}, 0)`);
/*
const staticColor =   "steelblue",
highlightColor = "orange";

var sheet = document.createElement('style')
sheet.innerHTML = ".bar {fill: "+staticColor+"} .highlight {fill:"+highlightColor+"}";
document.body.appendChild(sheet);
*/
bars.append('rect')
  .attr('x', -20)
  .attr('width', 40)
  .attr('y', d => yScale(d.Value))
  .attr('height', d => height - yScale(d.Value))
  .attr('fill', 'blue')
  //.attr("class", "bar")
  .on("mousemove", onMouseOver)
  .on("mouseout", onMouseOut);

function onMouseOver(d, i) {
  tooltip
    .style("left", d3.event.pageX - 50 + "px")
    .style("top", d3.event.pageY - 70 + "px")
    .style("display", "inline-block")
    .html("Year: " + (d.Time) + "
" + "Value: " + (d.Value));
  d3.select(this).attr('fill', "#eec42d");
  //d3.select(this).attr('class', 'highlight');
  //this.setState({ fillColour: 'green' });

}

function onMouseOut(d, i) {
  tooltip.style("display", "none");
  d3.select(this).attr('fill', "blue");
  //d3.select(this).attr('class', 'bar');
  //this.setState({ fillColour: 'blue' });
}

bars.append('text')
  .text(d => d.Value)
  .attr('text-anchor', 'middle')
  .attr('y', d => yScale(d.Value))
  .attr('dy', -5);

bars.filter((d, i) => i < barData.length - 1)
  .append('path')
  .attr('d', (d, i) => `M 5,${yScale(d.Value) - 20} V ${Math.min(yScale(d.Value), yScale(barData[i + 1].Value)) - 60} H ${xScale.bandwidth() - 5} V ${yScale(barData[i + 1].Value) - 25}`)
  .style('stroke', 'gray')
  .style('fill', 'none')
  .attr('marker-end', 'url(#arrowhead)')

bars.filter((d, i) => i < barData.length - 1)
  .append('rect')
  .attr('x', 15)
  .attr('y', (d, i) => Math.min(yScale(d.Value), yScale(barData[i + 1].Value)) - 70)
  .attr('width', xScale.bandwidth() - 30)
  .attr('height', 20)
  .attr('rx', 10)
  .style('fill', 'white')
  .style('stroke', 'gray');

bars.filter((d, i) => i < barData.length - 1)
  .append('text')
  .text((d, i) => `${barData[i + 1].Value > d.Value ? '+' : ''}${Math.round((barData[i + 1].Value / d.Value * 100) - 100)}%`)
  .attr('x', xScale.bandwidth() / 2)
  .attr('y', (d, i) => Math.min(yScale(d.Value), yScale(barData[i + 1].Value)) - 56)
  .attr('text-anchor', 'middle')
  .style('fill', 'black');
#graph {
  width: 600px;
  height: 500px;
}

text {
  font-size: 12px;
  font-family: "Ubuntu";
}

.toolTip {
  position: absolute;
  display: none;
  min-width: 80px;
  height: auto;
  background: none repeat scroll 0 0 #ffffff;
  border: 1px solid #6F257F;
  padding: 5px;
  text-align: left;
}

A: Try this:

const barData = [{
"Time": "2019",
"Value": 5388
  },
  {
"Time": "2020",
"Value": 6453
  },
  {
"Time": "2021",
"Value": -4345
  },
  {
"Time": "2022",
"Value": 7345
  },
  {
"Time": "2023",
"Value": 8345
  },
  {
"Time": "2024",
"Value": 5345
  },
  {
"Time": "2025",
"Value": 6345
  },
  {
"Time": "2026",
"Value": 3345
  }
];

const container = d3.select('#graph');
const divWidth = parseInt(container.style('width'));
const divHeight = parseInt(container.style('height'));

// Consider this width and Height are dynamic for div "graphID" because I am trying to responsive design
const margin = {
  top: 50,
  right: 50,
  bottom: 50,
  left: 50
};
const width = divWidth - margin.left - margin.right;
const height = divHeight - margin.top - margin.bottom;

//To add svg in the visualization node i.e Dome node
const svg = container.append("svg")
  .attr("width", divWidth)
  .attr("height", divHeight)
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);

//To add tooltip for bar
const tooltip = d3.select("body").append("div").attr("class", "toolTip");

const defs = svg.append("defs");

const marker = defs.append("marker")
  .attr("id", "arrowhead")
  .attr("markerWidth", "10")
  .attr("markerHeight", "7")
  .attr("refX", "0")
  .attr("refY", "3.5")
  .attr("orient", "auto")

const polygon = marker.append("polygon")
  .attr("fill", "gray")
  .attr("points", "0 0, 10 3.5, 0 7")

const xScale = d3.scaleBand()
  .domain(barData.map(d => d.Time))
  .range([0, width + margin.right]);

const xAxis = d3.axisBottom(xScale)

//Adding g attribute to svg for x axis
const yAxisMax = barData.reduce((max, item) => Math.max(max, item.Value), 0) * 1.5;

const yAxisMin = barData.reduce((min, item) => Math.min(min, item.Value), 0) * 1.5;

const yAxisRange = Math.max(yAxisMax, Math.abs(yAxisMin));

const yScale = d3.scaleLinear()
  .domain([-yAxisRange, yAxisRange])
  .range([height, 0]);

const yAxis = d3.axisLeft(yScale).ticks(4);

svg.append('g')
  .call(yAxis);

const bars = svg.selectAll('g.bar')
  .data(barData)
  .enter()
  .append('g')
  .classed('bar', true)
  .attr('transform', d => `translate(${xScale(d.Time) + xScale.bandwidth() / 2}, 0)`);

bars.append('rect')
  .attr('x', -20)
  .attr('width', 40)
  .attr('y', d => Math.min(yScale(d.Value), height/2))
  .attr('height', d => d.Value > 0 ?
(height/2 - yScale(d.Value)) :
(yScale(d.Value) - height/2)
  )
  .attr('fill', 'blue')
  .on("mousemove", onMouseOver)
  .on("mouseout", onMouseOut);

function onMouseOver(d, i) {
  tooltip
.style("left", d3.event.pageX - 50 + "px")
.style("top", d3.event.pageY - 70 + "px")
.style("display", "inline-block")
.html("Year: " + (d.Time) + "
" + "Value: " + (d.Value));
  d3.select(this).attr('fill', "#eec42d");
}

function onMouseOut(d, i) {
  tooltip.style("display", "none");
  d3.select(this).attr('fill', "blue");
}

bars.append('text')
  .text(d => d.Value)
  .attr('text-anchor', 'middle')
  .attr('alignment-baseline', d => d.Value > 0 ? 'baseline' : 'hanging')
  .attr('y', d => yScale(d.Value))
  .attr('dy', d => d.Value > 0 ? -5 : 5);

bars.filter((d, i) => i < barData.length - 1)
  .append('path')
  .attr('d', (d, i) => `M 5,${Math.min(yScale(d.Value) - 20, height/2)} V ${Math.min(yScale(d.Value), yScale(barData[i + 1].Value)) - 60} H ${xScale.bandwidth() - 5} V ${Math.min(yScale(barData[i + 1].Value) - 25, height/2 - 10)}`)
  .style('stroke', 'gray')
  .style('fill', 'none')
  .attr('marker-end', 'url(#arrowhead)')

bars.filter((d, i) => i < barData.length - 1)
  .append('rect')
  .attr('x', 15)
  .attr('y', (d, i) => Math.min(yScale(d.Value), yScale(barData[i + 1].Value)) - 70)
  .attr('width', xScale.bandwidth() - 30)
  .attr('height', 20)
  .attr('rx', 10)
  .style('fill', 'white')
  .style('stroke', 'gray');

bars.filter((d, i) => i < barData.length - 1)
  .append('text')
  .text((d, i) => `${barData[i + 1].Value > d.Value ? '+' : ''}${Math.round((barData[i + 1].Value / d.Value * 100) - 100)}%`)
  .attr('x', xScale.bandwidth() / 2)
  .attr('y', (d, i) => Math.min(yScale(d.Value), yScale(barData[i + 1].Value)) - 56)
  .attr('text-anchor', 'middle')
  .style('fill', 'black');

const xAxisG = svg.append('g')
  .attr("transform", `translate(0,${height/2})`)
  .call(xAxis);

xAxisG.selectAll('.tick').each(function() {
  const tick = d3.select(this);
  const text = tick.select('text').text();
  const data = barData.find(d => d.Time === text);
  if (data.Value < 0) {
tick.select('text').style('fill', 'white');
tick.select('line').style('stroke', 'white');
  }
})
#graph {
  width: 700px;
  height: 500px;
}

text {
  font-size: 12px;
  font-family: "Ubuntu";
}

.toolTip {
  position: absolute;
  display: none;
  min-width: 80px;
  height: auto;
  background: none repeat scroll 0 0 #ffffff;
  border: 1px solid #6F257F;
  padding: 5px;
  text-align: left;
}


text:
Q: Any clever ways of handling the context in a web app? In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application.
Thus myapp.war gets deployed to http://example.com/myapp.
The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider the root of your application to be "/myapp".
The Servlet API and JSP have facilities to help manage this. For example, if, in a servlet, you do: response.sendRedirect("/mypage.jsp"), the container will prepend the context and create the url: http://example.com/myapp/mypage.jsp".
However, you can't do that with, say, the IMG tag in HTML. If you do  you will likely get a 404, because what you really wanted was "/myapp/myimage.gif".
Many frameworks have JSP tags that are context aware as well, and there are different ways of making correct URLs within JSP (none particularly elegantly).
It's a nitty problem for coders to jump in an out of when to use an "App Relative" url, vs an absolute url.
Finally, there's the issue of Javascript code that needs to create URLs on the fly, and embedded URLs within CSS (for background images and the like).
I'm curious what techniques others use to mitigate and work around this issue. Many simply punt and hard code it, either to server root or to whatever context they happen to be using. I already know that answer, that's not what I'm looking for.
What do you do?

A: For HTML pages, I just set the HTML <base> tag. Every relative link (i.e. not starting with scheme or /) will become relative to it. There is no clean way to grab it immediately by  HttpServletRequest, so we need little help of JSTL here.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri">${req.requestURI}</c:set>

<!DOCTYPE html>

    <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
    <link rel="stylesheet" href="css/default.css">

    link

This has in turn however a caveat: anchors (the #identifier URL's) will become relative to the base path as well. If you have any of them, you would like to make it relative to the request URL (URI) instead. So, change like
jump

to
jump

In JS, you can just access the <base> element from the DOM whenever you'd like to convert a relative URL to an absolute URL.
var base = document.getElementsByTagName("base")[0].href;

Or if you do jQuery
var base = $("base").attr("href");

In CSS, the image URLs are relative to the URL of the stylesheet itself. So, just drop the images in some folder relative to the stylesheet itself. E.g.
/css/style.css
/css/images/foo.png

and reference them as follows
background-image: url('images/foo.png');

If you rather like to drop the images in some folder at same level as CSS folder
/css/style.css
/images/foo.png

then use ../ to go to the common parent folder
background-image: url('../images/foo.png');

See also:

*

*Is it recommended to use the <base> html tag?

A: I agree with tardate.
I have paid my attention at filters too and have found the solution in face of project UrlRewriteFilter.
The simple configuration like following:
<rule>
    <from>^.+/resources/(.*)$</from>
    <to>/resources/$1</to>
</rule>

helps to forward all requests for */resources path to /resources pass (including context path prefix). So I can simply put all my images and CSS files under resources folder and continue using relative URLs in my styles for background images and other cases.

A:
The Servlet API and JSP have
  facilities to help manage this. For
  example, if, in a servlet, you do:
  response.sendRedirect("/mypage.jsp"),
  the container will prepend the context
  and create the url:
  http://example.com/myapp/mypage.jsp".

Ah, maybe, maybe not - it depends on your container and the servlet spec!
From Servlet 2.3: New features exposed:

And finally, after a lengthy debate by
  a group of experts, Servlet API 2.3
  has clarified once and for all exactly
  what happens on a
  res.sendRedirect("/index.html") call
  for a servlet executing within a
  non-root context. The issue is that
  Servlet API 2.2 requires an incomplete
  path like "/index.html" to be
  translated by the servlet container
  into a complete path, but doesn't say
  how context paths are handled. If the
  servlet making the call is in a
  context at the path "/contextpath,"
  should the redirect URI translate
  relative to the container root
  (http://server:port/index.html) or the
  context root
  (http://server:port/contextpath/index.html)?
  For maximum portability, it's
  imperative to define the behavior;
  after lengthy debate, the experts
  chose to translate relative to the
  container root. For those who want
  context relative, you can prepend the
  output from  getContextPath() to your
  URI.

So no, with 2.3 your paths are not automatically translated to include the context path.

A: You can use JSTL for creating urls.
For example, <c:url value="/images/header.jpg" /> will prefix the context root.
With CSS, this usually isn't an issue for me.
I have a web root structure like this:
/css
/images
In the CSS file, you then just need to use relative URLs (../images/header.jpg) and it doesn't need to be aware of the context root.
As for JavaScript, what works for me is including some common JavaScript in the page header like this:

Then you can use the context root in all your scripts (or, you can define a function to build paths - may be a bit more flexible).
Obviously this all depends on your using JSPs and JSTL, but I use JSF with Facelets and the techniques involved are similar - the only real difference is getting the context root in a different way.

A: I've used helper classes to generate img tags etc. This helper class takes care of prefixing paths with the application's contextPath. (This works, but I don't really like it. If anyone has any better alternatives, please tell.)
For paths in css files etc. I use an Ant build script that uses a site.production.css for site.css in production environment and site.development.css in development encironment.
Alternatively I sometimes use an Ant script that replaces @token@ tokens with proper data for different environents. In this case @contextPAth@ token would be replaced with the correct context path.

A: One option is to use "flat" application structure and relative URLs whenever possible.
By "flat" I mean that there are no subdirectories under your application root, maybe just few directories for static content as "images/". All your JSP's, action URLs, servlets go directly under the root.
This doesn't completely solve your problem but simplifies it greatly.

A: Vilmantas said the right word here: relative URLs.
All you need to do in your IMG is to use

instead of

and it'll be relative to the app context (as the browser is interpreting the URL to go to)

A: Except for special cases, I'd recommend against using absolute URLs this way. Ever. Absolute URLs are good for when another webapp is pointing at something in your webapp. Internally -- when one resource is pointing at a second resource in the same context -- the resource should know where it lives, so it should be able to express a relative path to the second resource.
Of course, you'll write modular components, which don't know the resource that's including them. For example:
/myapp/user/email.jsp:
Email: ${user.email}

/myapp/browse/profile.jsp:
<jsp:include page="../user/email.jsp" />

/myapp/home.jsp:
<jsp:include page="../user/email.jsp" />

So, how does email.jsp know the relative path of sendmail.jsp? Clearly the link will break on either /myapp/browse/profile.jsp or it will break on /myapp/home.jsp . The answer is, keep all your URLs in the same flat filepath space. That is, every URL should have no slashes after /myapp/ .
This is pretty easy to accomplish, as long as you have some kind of mapping between URLs and the actual files that generate the content. (e.g. in Spring, use DispatcherServlet to map URLs to JSP files or to views.)
There are special cases. e.g. if you're writing a browser-side application in Javascript, then it gets harder to maintain a flat filepath space. In that case, or in other special cases, or just if you have a personal preference, it's not really a big deal to use <%= request.getContextPath() %> to create an absolute path.

A: You can use request.getContextPath() to build absolute URLs that aren't hard-coded to a specific context.  As an earlier answer indicated, for JavaScript you just set a variable at the top of your JSP (or preferably in a template) and prefix that as the context.
That doesn't work for CSS image replacement unless you want to dynamically generate a CSS file, which can cause other issues. But since you know where your CSS file is in relation to your images, you can get away with relative URLs.
For some reason, I've had trouble with IE handling relative URLs and had to fall back to using expressions with a JavaScript variable set to the context.  I just split my IE image replacements off into their own file and used IE macros to pull in the correct ones. It wasn't a big deal because I already had to do that to deal with transparent PNGs anyway.  It's not pretty, but it works.

A: I've used most of these techniques (save the XSLT architecture).
I think the crux (and consensus) of the problem is having a site with potentially multiple directories.
If your directory depth (for lack of a better term) is constant, then you can rely on relative urls in things like CSS.
Mind, the layout doesn't have to be completely flat, just consistent.
For example, we've done hierarchies like /css, /js, /common, /admin, /user. Putting appropriate pages and resources in the proper directories. Having a structure like this works very well with Container based authentication.
I've also mapped *.css and *.js to the JSP servlet, and made them dynamic so I can build them on the fly.
I was just hoping there was something else I may have missed.

A: I by no means claim that the following is an elegant issue. In fact, in hindsight, I wouldn't recommend this issue given the (most likely) performance hit.
Our web app's JSPs were strictly XML raw data. This raw data was then sent into an XSL (server-side) which applied the right CSS tags, and spit out the XHTML.
We had a single template.xsl which would be inherited by the multiple XSL files that we had for different components of the website. Our paths were all defined in an XSL file called paths.xml:
<?xml version="1.0" encoding="UTF-8"?>
<paths>
    <path name="account" parent="home">Account/</path>
    <path name="css">css/</path>
    <path name="home">servlet/</path>
    <path name="icons" parent="images">icons/</path>
    <path name="images">images/</path>
    <path name="js">js/</path>
</paths>

An internal link would be in the XML as follows:
<ilink name="link to icons" type="icons">link to icons</ilink>

This would get processed by our XSL:
<xsl:template match="ilink">
    <xsl:variable name="temp">
        <xsl:value-of select="$rootpath" />
        <xsl:call-template name="paths">
            <xsl:with-param name="path-name"><xsl:value-of select="@type" /></xsl:with-param>
        </xsl:call-template>
        <xsl:value-of select="@file" />
    </xsl:variable>
        <xsl:value-of select="." />
</xsl:template>

$rootPath was passed onto each file with ${applicationScope.contextPath} The idea behind us using XML instead of just hard-coding it in a JSP/Java file was we didn't want to have to recompile.
Again, the solution isn't a good one at all...but we did use it once!
Edit: Actually, the complexity in our issue arose because we weren't able to use JSPs for our entire view. Why wouldn't someone just use ${applicationScope.contextPath} to retrieve the context path? It worked fine for us then.

A: When creating a site from scratch, I side with @Will - aim for a consistent and predictable url structure so that you can stick with relative references.
But things can get really messy if you are updating a site that was originally built to work directly under the site root "/" (pretty common for simple JSP sites) to formal Java EE packaging (where context root will be some path under the root).
That can mean a lot of code changes.
If you want to avoid or postpone the code changes, but still ensure correct context root referencing, a technique I've tested is to use servlet filters. The filter can be dropped into an existing proejct without changing anything (except web.xml), and will remap any url references in the outbound HTML to the correct path, and also ensure redirects are correctly referenced.
An example site and usable code available here: EnforceContextRootFilter-1.0-src.zip
NB: the actual mapping rules are implemented as regex in the servlet class and provide a pretty general catch-all - but you may need to modify for particular circumstances.
btw, I forked a slightly different question to address migrating existing code base from "/" to a non-root context-path

A: I tend to write a property as part of my core JavaScript library within my. I don't think it's perfect but I think it's the best I've managed to achieve.
First off, I have a module that's part of my app core that is always available
(function (APP) {
  var ctx;
  APP.setContext = function (val) {
    // protect rogue JS from setting the context.
    if (ctx) {
      return;
    }
    val = val || val.trim();
    // Don't allow a double slash for a context.
    if (val.charAt(0) === '/' && val.charAt(1) === '/') {
      return;
    }
    // Context must both start and end in /.
    if (val.length === 0 || val === '/') {
      val = '/';
    } else {
      if (val.charAt(0) !== '/') {
        val = '/' + val;
      }
      if (val.slice(-1) !== '/') {
        val += '/';
      }
    }
    ctx = val;
  };
  APP.getContext = function () {
    return ctx || '/';
  };
  APP.getUrl = function (val) {
    if (val && val.length > 0) {
      return APP.getContext() + (val.charAt(0) === '/' ? val.substring(1) : val);
    }
    return APP.getContext();
  };
})(window.APP = window.APP || {});

I then use apache tiles with a common header that always contains the following:

Now that I've initialized the context I may use getUrl(path) from anywhere (js files or within jsp/html) which will return an absolute path for the given input string within the context.
Note that the following are both equivalent intentionally. getUrl will always return an absolute path as a relative path does not need you to know the context in the first place.
var path = APP.getUrl("/some/path");
var path2 = APP.getUrl("some/path");


text:
Q: What are the implied peak current ratings of GFCI's? Using GFCIs with transformer or other high-inrush current loads is problematic, because in some designs the differential transformer core can locally saturate and produce an invalid output in the sense winding, tripping the GFCI - without any ground leakage.
What are the standards/requirements applying to GFCIs (in various markets) in terms of maximum peak current they must handle without spurious tripping? I'd expect this peak rating to be higher than continuous rating.
Most GFCIs on the market do not specify such current in their spec sheets/datasheets, thus I presume that the actual requirement would be buried in a standard somewhere...
This question is about applications where a load may present, say, 10Arms continuous current, but have 10x+ higher inrush current (e.g. 100A or more). In practice, I've seen many GFCIs rated at 2x the continuous current (20A in this example) trip spuriously at 100A half-wave inrush. I would be surprised if this requirement wasn't addressed in the standardese, thus the question.


text:
Q: Refer tag function from js? I have this code in my jsp
    <script  type="text/javascript">

    function myJsFunction() {
       var queryString = new QueryString();
        queryString.add('initDate', document.getElementById('${id}').value);
    }

And it is working. I want document.getElementById('${id}').value to pass throught my tag lib and I add
 <%@ taglib prefix="my" uri="http://tags/my"%>

    <script  type="text/javascript">

    function myJsFunction() {
       var queryString = new QueryString();
        queryString.add('initDate', ${my:myTagFunc(document.getElementById('${id}').value)});
    }

But is slowing empty despite that document.getElementById('${id}').value returns a String. I can not understand why?

A: You are mixing two different codes. The key is to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is sent to the browser) and Javascript in the browser, after the browser receives the already generated response.
As commented by Satpal, you need AJAX.


text:
Q: GUI for Server Editions I'm developing a Photo sharing app so that I can seamlessly upload to my photos to my Home Computer even when I'm too much far from my Home.
For this purpose I'm planning to setup my own Home server using PostgreSQL and Glassfish because I only know C and Java.
The question is that is there any GUI available for Ubuntu 12.04 Server Edition so that I can easily manage these stuffs? I never used a server environment before.

A: Any desktop environment available for Ubuntu is available on the server edition of Ubuntu and can be installed as any other package with apt-get.
ubuntu-desktop will install the default Unity desktop, kde-desktop will install the Kubuntu KDE desktop, lubuntu-desktop will install the LXDE packages of the Lubuntu release and xfce-desktop the Xubuntu desktop environment.
Any of those will work for you, but there are other more "light" options. Please check the appropriate ubuntu wiki page for GUI setup in a server environment.

A: For this type of server, where you actually want a GUI, I'd recommend just using the desktop edition and then installing the services you need. It's the same system, so anything you can do with Ubuntu Server can also be done with Ubuntu Desktop and vice versa.


text:
Q: What does light purple mean in Chrome's console? What's the difference between light purple and purple?
Thanks.

background:
I was trying to extract all proto functions from Array Type.
const arrayProto = Array.prototype
const arrayMethods = Object.create(arrayProto)

arrayMethods returns Array {}
I found all methods are in proto (light purple) while none of them is counted.If I change arrayProto to a normal array like [1,2,3], I can get numbers by arrayMethods[i] since all the numbers are listed in proto.
My first thought is that light purple ones are ignored or somehow don't belong to  arrayMethods. However I cannot found any documents about this part of console.
Why and How to solve it?

A: In JavaScript, properties may be enumerable or not. Non-enumerable properties are ignored by a for-in loop or Object.keys(). All built-in methods are non-enumerable. (This is why for-in does not list all of the methods on Object.prototype for every object.)
It appears that Chrome uses the dark purple to indicate an enumerable property and light purple to indicate non-enumerable. They do not need to be inherited. Demo (screenshot from Chrome 73.0.3683.103):
Object.defineProperties({}, {
  foo: {enumerable: true, value: 1},
  bar: {enumerable: false, value: 2},
});

If you want to get the properties of an object including even unenumerable ones, you can use Object.getOwnPropertyNames(o). However, you will need to follow the prototype chain yourself if you want to find inherited properties.

A: Purple
its represent index of array or a key name of the Object
Light Purple
its represent the Object.prototype or Array.prototype
.You could perform the prototype function using that object or array


text:
Q: Get number from element and wrap with span I was hoping to indent a number, but the with html generated from my cms I can't seem to hook into the number and apply a style.

01. Header
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, anim odio hic autem
delectus qui labore rerum irure autem

I would like to wrap the number in a span. All of the content is the same. 02.[space]Title

01. Header
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, anim odio hic autem
delectus qui labore rerum irure autem

.indent{
    margin-left: -30px;
}

Here is what I have started but I can't seem to trim it to the first 3 characters including the empty space.
 $('.content b').each(function() {
var tmp = [],
    collecting = false;

$(this).contents().each(function() {
    if (this.nodeType === Node.TEXT_NODE && $.trim(this.nodeValue).length > 0) {
        if (collecting) {
            tmp.push(this);
            return false;
        }
        else {
            collecting = true;
        }
    }

    if (collecting) {
        tmp.push(this);
    }
});

$(tmp).wrapAll('');
});

http://jsfiddle.net/hGeuZ/

A: You can try this way
$('.content b').each(function () {
   var txtArr = $(this).text().split(' ');

    $(this).before(''+txtArr [0]+'')

    txtArr.shift()
    $(this).text(txtArr.join(' '))

});

Here is the demo, http://jsfiddle.net/hGeuZ/19/

A: This is not the most orthodox solution but it might suit your needs:
$('.content b').each(function () {
    var result = $(this).text().replace(/([0-9]+\.)/, '$1');
    $(this).html(result).find('.indent').remove().insertBefore(this);
});

http://jsfiddle.net/hGeuZ/10/

A: $("b").each(function() {
   var $title = $(this).html();
   var spaceIndex = $title.indexOf(" ");
   var num = $title.substring(0, spaceIndex+1);
   var text = $title.substring(spaceIndex+1, $title.length)
   console.log(num+text);
   num = ''+ num + '';
   $(this).html(num + text);

});

A: For this, one approach I'd suggest is:
$('.content b:first-child').replaceWith(
    function(i,h){
        return h.replace(/(\d+.\s)([\d\D]*)/g,'$1$2');
    });

JS Fiddle demo.
If CSS is an option:
.content {
    counter-increment: headerNumber;
}

.content b:first-child::before {
    content: counter(headerNumber, decimal-leading-zero);
    padding-right: 2em;
    color: #f90;
}

JS Fiddle demo.


text:
Q: Box divided by border Hey guys how can I make the border inside divide the box, but the gradient to be in the first one: http://i.stack.imgur.com/HhTHT.png
My code:https://jsfiddle.net/ivailo/1hx4axpt/1/
.parent2{
height:256px;
width: 202px;
border: 1px solid #E18728;
background: linear-gradient(to bottom, rgba(185,219,105,1) 44%,rgba(209,211,172,1) 80%);
border-radius:5px;
}

A: You could use a pseudo element, like ::before

.parent2 {
  height: 256px;
  width: 202px;
  border: 1px solid #E18728;
  background: rgba(209, 211, 172, 1);
  border-radius: 5px;
}
.parent2::before {
  content: '';
  display: block;
  height: 40px;
  border-bottom: 1px solid white;
  background: linear-gradient(to bottom, rgba(185, 219, 105, 1) 44%, rgba(209, 211, 172, 1) 80%);
  border-radius: 5px;
}

A: From your screenshot, the top of your box possess a border, in this case, create a child div and apply the gradient background to it. So for the html:

And for the CSS part :
.parent {
    height:256px;
    width: 202px;
    border: 1px solid #E18728;
    border-radius:5px;
  background-color: rgba(209,211,172,1);
}

.child {
  height:40px;
  background: linear-gradient(to bottom, rgba(185,219,105,1) 44%,rgba(209,211,172,1) 80%);
  border-radius:5px;
  border-bottom: 1px solid white;
}


text:
Q: How can density functional theory (DFT) be understood in many body perturbation theory (MBPT) language? Many body interacting fermions problems are formulated in the many body perturbation theory language using Feynman diagrams and imaginary time formalism. To the best of my knowledge the kinetic energy should be the energy of the non interacting system and any correction coming from the interaction would come as self energy corrections. In practical we rarely take the dispersion of the free electrons., it is in general a better to take the DFT dispersion. What is very confusing is that DFT already takes some of the interaction into account, so if i am to use the DFT dispersion in a many body perturbative theory, what should i take for the interaction ?
I understand how can DFT get the dispersion, and i understand how the dispersion is modified by the self energy in MBPT. What i don't understand, is what does it mean to mix both approaches.

A: Since some exchange and correlation is already included in the DFT Green's function, you need to subtract it — that is, to subtract the exchange-correlation potential from the self-energy:
$$
\begin{align}
G^{-1} &= G_0^{-1} - \Sigma \\
&= G_{DFT}^{-1} + V_{xc} - \Sigma
\end{align}
$$
Up to now, there is no advantage of using $G_{DFT}$, because you essentially go back to $G_0$. The advantage appears when you recall that the self-energy itself depends on the Green's function.
If you use some approximation based on skeleton diagrams, you need to perform self-consistent calculations, starting from a self-energy obtained from some initial Green's function. In this case, a good initial guess for $G$ (e. g., $G_{DFT}$) would speed up convergence. An example how this works within the $GW$ approximation can be found in [B. Holm and U. von Barth, "Fully self-consistent $GW$ self-energy of the electron gas"].
If you are not going to do self-consistent calculations of some skeleton diagrams and just want to construct a perturbation theory around $G_{DFT}$, you may simply substitute $G_0 = G_{DFT} + V_{xc}$ in the usual series in $G_0$ and $V$ — then both $V$ and $V_{xc}$ will be perturbations (though it does not look particularly useful).


text:
Q: cuda inline and noinline device functions According to the documentation, in devices of compute capability 1.x the compiler will inline __device__ functions by default, but for devices of compute capability 2.x and higher it will only do so if deemed appropriate by the compiler. When is it appropriate not to? There are also qualifiers such as __noinline__ and __forceinline__. In which cases is it better not to inline a __device__ function?

A: I've experienced it that if you force __device__ function call to be compiled inline, it can decreases runtime to half. Just in a recent one, I made a function call (which passed just 5 variables to function)  inline and kernel execution time decreased from 9.5ms to 4.5ms (almost half). And if you consider that you want to execute the same kernel hundred millions of times with total runtime of a week or more (like my case and many others that work on CFD or MD projects), increase in compile time is nothing important comparing to huge saving in runtime.
All in all, I think it worth to try inline function call impact on runtime especially for codes with very long runtimes.

A: The compiler heuristic for inlining presumably evaluates the potential performance benefit from inlining due to the elimination of function call overhead against other characteristics including compile time. Aggressive inlining can lead to very large code that cause very long compile times. From observing the code generated for many different kernels, the CUDA compiler seems to inline in the vast majority of cases. Note that in some cases, inlining is currently not possible, for example when the called function is in a different, separately compiled, compilation unit.
In my experience, the instances in which it makes sense to override the compiler's inlining heuristic are rare. I have used __noinline__ to limit code size and thus reduce excessive compile times. Use of __noinline__ has no predictable effect on register pressure that I am aware of. Inlining may allow more aggressive code movement such as load scheduling and this may increase register pressure, while not inlining may increase register pressure due to ABI restrictions on the use of registers. I have never found a case where use of __noinline__ improved performance, but of course such cases could exist, possibly due to instruction cache effects.


text:
Q: How to escape quotes when importing csv file in PostgreSQL / YugabyteDB Using YugabyteDB 2.5.3.1 (PostgreSQL 11.2).
I currently have this table:
create table bum2(id int, the_t text);

Looking to import this "a"bc" from a csv file into the text column.
Tried with this csv file:
6,""a""bc""

And:
\copy bum2 from data.csv WITH (FORMAT csv);

And getting:
yugabyte=# select * from bum2;
 id | the_t
----+-------
  6 | abc
(1 row)

A: You can use additional quotes to escape the quotes. The csv file below works:
6,"""a""bc"""

yugabyte=# \copy bum2 from data.csv WITH (FORMAT csv);
COPY 1
yugabyte=# select * from bum2;
 id | the_t
----+--------
  6 | "a"bc"
(1 row)


text:
Q: I'm getting error when I use conditional operation I've written a line using a conditional operator as shown below:
assign {RS2, RS1} = (!DisM || !DisX)? (RdEn==2'b00? (!DisI? {rs2, rs1} : 64'bz) : (RdEn==2'b01? (!switch? {rs2, Rn} : {Rn, rs1}) : {Rm, Rn}))) : 64'bz;

*

*RS2 & RS1 are 32 bit output wires.

*Rn & Rm are 32 bit inputs.

*rs1 & rs2 are 32 bit registers.

*RdEn is 2bit register.

*DisI and switch are one bit register.

The simulator (Icarus 0.9.7 or any) is showing there is a syntax error in the above line.
Here is my code which addresses the same problem:
module TEST(Rn, Rm, DisM, DisX, DisI, switch, RdEn, RS1, RS2);
input [31:0]Rn, Rm;
input DisM, DisX, DisI, switch;
input [1:0]RdEn;
output [31:0]RS1, RS2;

reg [31:0]rs1, rs2;

always@*
begin
    rs1 = Rn + 32'd7;
    rs2 = Rm - 32'd7;
end

assign {RS2, RS1} = (!DisM || !DisX)? (RdEn==2'b00? (!DisI? {rs2, rs1} : {64{1'bz}}) : (RdEn==2'b01? (!switch? {rs2, Rn} : {Rn, rs1}) : {Rm, Rn}))) : {64{1'bz}};

endmodule

A: The compiler interpreted the ? in RdEn==2'b00? as a 3rd bit instead of as the ternary operator.  Just add a space between b00 and ?.  Same for b01?.
? is a valid z_digit.  Refer to IEEE Std 1800-2012, section 5.7 Numbers.
Also, you had a mismatched number of parentheses (a good editor can show this):
assign {RS2, RS1} = (!DisM || !DisX)? (RdEn==2'b00 ? (!DisI? {rs2, rs1} : {64{1'bz}}) : (RdEn==2'b01 ? (!switch? {rs2, Rn} : {Rn, rs1}) : {Rm, Rn})) : {64{1'bz}};

It is also good practice to use {64{1'bz}} to make sure you get 64 bits of 1'bz.

A: Though you already got an accepted answer, I would highly recommend you re-code assignment. As is, it is hard to read and thereby hard to debug. At minimum add return lines and indent so the conditions are easy to visually pair. For example, the following is a copy of toolic's solution with added newlines and spaces. Notice how the RdEn==2'b00? issue cannot happen with this formatting style. Editors like emacs and vim have syntax plugins that can help with indent formatting.
assign {RS2, RS1} = (!DisM || !DisX)
  ? (RdEn==2'b00
    ? (!DisI ? {rs2, rs1} : {64{1'bz}})
    : (RdEn==2'b01
        ? (!switch ? {rs2, Rn} : {Rn, rs1})
        : {Rm, Rn}))
  : {64{1'bz}};

In practice I find the conditional operator ?: (w/o high-Z) usually makes explicit 2:1 muxs when synthesizing, which may not optimal for timing and area. I also find keeping tri-state assignments simple gives cleaner results.
The approach I usually recommend is to determine output enable and output data separate from the tri-state assignment. Synthesizers usually do better job with this approach than one long assign statement; at least from my experience. This approach is also good if you have a limited number tri-state drivers, which is common for FPGAs.
wire out_en = (!DisM || !DisX) && !(RdEn==2'b00 && !DisI);
reg [63:0] out_data;
always @* begin
  case(RdEn)
    2'b00 : out_data = {rs2, rs1};
    2'b01 : out_data = !switch ? {rs2, Rn} : {Rn, rs1});
    default : out_data = {Rm, Rn};
  endcase
end
assign {RS2, RS1} = out_en ? out_data : {64{1'bz}};

Occasionally parallel tri-state drivers with non-overlapping enable does better job at meeting some design criteria. This approach can reduce timing depending on the technology-node and architecture. There is usually an area hit and it could negatively impact the timing if there is to much loading.
assign {RS2, RS1} = ((!DisM || !DisX) && RdEn==2'b00 && !DisI)   ? {rs2, rs1} : {64{1'bz}};
assign {RS2, RS1} = ((!DisM || !DisX) && RdEn==2'b01 && !switch) ? {rs2,  Rn} : {64{1'bz}};
assign {RS2, RS1} = ((!DisM || !DisX) && RdEn==2'b01 &&  switch) ? { Rn, rs1} : {64{1'bz}};
assign {RS2, RS1} = ((!DisM || !DisX) && RdEn[1])                ? { Rm,  Rn} : {64{1'bz}};

Regardless of the approach used, make sure the enable control of the tri-state is glitch free. If the signal is not clean it can cause contention on the bus. Ideally the enable signal should be direct flop. A flopped enable signal is not always feasible in practice, so you need to keep an eye on it. You typically will not see potential glitches in RTL simulation. You synthesis report might have some insight if there is an issue.


text:
Q: Simulation in Google Chart by moving its Chart range slider after Some Seconds
I want to move a chart through using its chart range filter slider. i wan something like there is a play button on the screen .when i press play button then the range slider which is fixed some one or two minutes range are moving with specific interval of time. i will share my code with you. i want something like simulation.
   var chart = new google.visualization.ChartWrapper({
        chartType: 'LineChart',
        containerId: 'chart_div',
        options: {
            //title: 'Phase 1 -Tower 44',

            hAxis: {
                format: ' yyyy-MMM-dd  hh:mm',
                title: 'Time',
                textStyle: {
                    color: 'black',
                    fontSize: 10,
                    fontName: 'Arial',
                    bold: false,
                    italic: false
                },
                gridlines: { color: 'grey' },
                titleTextStyle: {
                    color: 'black',
                    fontSize: 10,
                    fontName: 'Arial',
                    bold: true,
                    italic: false
                }
            },

            vAxes: {
                0: {

                    viewWindowMode: 'explicit',
                    title: 'Line Current  (A)',
                    textStyle: { color: '#ED0A0A' },
                    titleTextStyle: {
                        color: 'ED0A0A'
                    },

                    viewWindow: {
                        min: 0,
                        max: 700

                    },
                    ticks: [0, 100, 200, 300, 400, 500, 600, 700],
                    gridlines: { color: 'transparent' }
                },
                1: {

                    title: 'Line Temperature  (°C)',
                    textStyle: { color: '#004BA5' },
                    gridlines: { color: 'grey' },
                    viewWindow: {
                        min: 0,
                        max: 500

                    },

                    ticks: [0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500],
                    titleTextStyle: {
                        color: '#004BA5'
                    }
                }
            },
            series: {
                0: { targetAxisIndex: 0 },
                1: { targetAxisIndex: 1 }

            },

            chartArea: {

                width: '85%',
                height: 500
            },

            //lineWidth: 3,
            //lineDashStyle: [1, 2, 2],
            'width': '85%',
            'height': 620,
            curveType: 'function',

            colors: ['#ED0A0A', '#004BA5', '#EDB80F'],
            legend: {
                position: 'none',

            },

            pointsVisible: true

        }
    });

then my control wrapper code is below
var control = new google.visualization.ControlWrapper({
        controlType: 'ChartRangeFilter',
        containerId: 'control_div',
        options: {

            filterColumnIndex: 0,

            ui: {
                chartOptions: {
                    height: 40,

                    chartArea: {
                        width: '90%',
                    },

                    'hAxis': { 'baselineColor': 'none', format: " hh:mm:ss" }

                    //      , 'gridlines': { 'color': 'none' }

                }
            }
        },

    });

and play button click event is something like this...
   $("#play").click(function () {

    setInterval(function () {

        var state = stateStatus.getState();

        control.setOption('ui.chartOptions.hAxis.viewWindow.min', state.range.start);
        control.setOption('ui.chartOptions.hAxis.viewWindow.max', state.range.end);

        control.setState(controll.getState());

        control.draw();

    }, 500);

A: see drawDateRange in the following working snippet...

google.charts.load('current', {
  callback: function () {
    drawChart();
    $(window).resize(drawChart);
  },
  packages: ['controls', 'corechart']
});

function drawChart() {
  var oneDay = (1000 * 60 * 60 * 24);
  var oneWeek = (oneDay * 7);
  var startDate = new Date(2017, 0, 1);
  var endDate = new Date();

  var data = new google.visualization.DataTable();
  data.addColumn('date', 'TimeStamp');
  data.addColumn('number', 'Value');
  for (var i = startDate.getTime(); i < endDate.getTime(); i = i + oneDay) {
    data.addRow([
      new Date(i),
      (2 * ((i - startDate.getTime()) / oneDay) + 8)  // y = 2x + 8
    ]);
  }

  var controlDate = new google.visualization.ControlWrapper({
    controlType: 'ChartRangeFilter',
    containerId: 'control-date',
    options: {
      filterColumnLabel: 'TimeStamp',
      ui: {
        chartOptions: {
          hAxis: {
            format: 'dd MMM yyyy'
          }
        }
      }
    }
  });

  function drawDateRange(rangeStart) {
    var drawAgain = true;
    var rangeEnd = new Date(rangeStart.getTime() + oneWeek);
    if (rangeEnd.getTime() > endDate.getTime()) {
      rangeEnd = endDate;
      drawAgain = false;
    }

    controlDate.setState({
      range: {
        start: rangeStart,
        end: rangeEnd
      }
    });
    controlDate.draw();

    if (drawAgain) {
      setTimeout(function () {
        drawDateRange(rangeEnd);
      }, 200);
    } else {
      setTimeout(function () {
        controlDate.setState({});
        controlDate.draw();
      }, 200);
    }
  }

  function drawTimeRange() {
    var state = controlDate.getState();
    controlTime.setState({
      range: {
        start: state.range.start,
        end: state.range.end
      }
    });
    controlTime.draw();
  }

  $("#play").click(function () {
    drawDateRange(startDate);
  });

  google.visualization.events.addListener(controlDate, 'ready', drawTimeRange);
  google.visualization.events.addListener(controlDate, 'statechange', drawTimeRange);

  var controlTime = new google.visualization.ControlWrapper({
    controlType: 'ChartRangeFilter',
    containerId: 'control-time',
    options: {
      filterColumnLabel: 'TimeStamp',
      ui: {
        chartOptions: {
          hAxis: {
            format: 'hh:mm:ss'
          }
        }
      }
    }
  });

  var chart = new google.visualization.ChartWrapper({
    chartType: 'LineChart',
    containerId: 'chart-line'
  });

  var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
  dash.bind([controlDate, controlTime], [chart]);
  dash.draw(data);
}

  <button id="play">Play</button>


text:
Q: How to make a variable accessible by all Swift files? Say I were to assign a variable in the app delegate. How could I access this variable in all my other view controllers/swift files without using segues?

A: UIApplication.sharedApplication().delegate gives access to the singleton application object, so:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let x = appDelegate.myVariable


text:
Q: n-p-n p-n-p and n-n-n heterostructure for LED I was studying LED Heterostructures and I found out that my book is always giving reference to p-p-n type heterostructure. So I looked up into another book in order to find other type of heterostructures like npn, pnp, nnp etc. but that book also contained same example. Is there any specific reason behind using ppn heterostructure for LED. Can't I use nnp, npn or ppp?
thanks for giving your precious time.

A: A common structure for LEDs the ppin-junction,
[p-layer][p electron blocking layer][i layer][n layer]

The p-layer, i-layer and n-layer is just your standard pin-junction structure. The p and n layers provide an electric field, which under forward bias will drive electron and hole towards i-layer where they can recombine radiatively. Normally the p and n layers will be made of a higher band gap material (e.g. AlGaAs) and form a barrier around the lower band gap i-layer (e.g. GaAs). This helps the i-layer act as a radiative recombination centre to improve efficiency.
However, it is possible for electrons and holes to pass over the i-region without recombining radiative, in LEDs this is loss mechanism. Electrons are much more mobile than holes (by about an order of magnitude), so if we can prevent electrons from escaping we should be able to improve the efficiency of the LED (i.e. the electrons are the rate limiting carrier type). This is the role of the second p-layer or electron blocking layer.
If the electron blocking layer has a wider band gap (so AlGaAs with a higher Al fraction than the n and p layers), and has more p-dopant, then it is possible to align the valence band with the p-layer (obviously there is a space charge at the hetero-interface where the bands are not flat). This gives a large barrier only in the conduction band which prevents electrons from crossing the junction (and escaping) but does not restrict the hole current flow, thus improving the device efficiency. So this is why ppn or ppin structures are used in practice. It's an optimisation.


text:
Q: How to dynamically cast numbers from firestore to long or double in Kotlin? I've noticed that I can explicitly define numbers as Longs in Kotlin when getting documents from Google's Firestore database, but reading the documentation here I see that it is a "64-bit double precision, IEEE 754." type, but according to Kotlin documentation that is a Double.
I've testing getting the numbers as Longs and Doubles and noticed that it will accept both and just automatically drop everything past the decimal point. This behavior seems to be the same as Double.toLong() in Kotlin.
Is there anyway to dynamically cast as the right number type without casting all values as doubles and then converting to long if the number in the decimal place is simply a 0?
EDIT: (providing minimum code as requested in a comment)
When number on Firestore console is 5
Log.d(TAG, "number: ${doc.getLong(MY_FIELD_NAME)}") //5
Log.d(TAG, "number: ${doc.getDouble(MY_FIELD_NAME)}") //5.0

When number on Firestore console is 5.5
Log.d(TAG, "number: ${doc.getLong(MY_FIELD_NAME)}") //5
Log.d(TAG, "number: ${doc.getDouble(MY_FIELD_NAME)}") //5.5

If it matters in my data scheme whether the number is 5 or 5.1, is the only safe way to cast as a double and just check the decimal point numbers or can the document conversion check at that time?

A: If you use getLong, which is obviously declared to return a long value, on a field that contains a floating point number, it's always going to truncate the decimal part of the number.  That's not Firestore, that's just the JVM default behavior.

If it matters in my data scheme whether the number is 5 or 5.1, is the only safe way to cast as a double and just check the decimal point numbers or can the document conversion check at that time?

If you want to find out the type of the value of a field, you should first access it as Any, which will give you the raw data as the SDK finds more appropriate:
val foo: Any? = doc.get("foo")

Then check to see what type it is dynamically and decide what to do with it:
if (foo is Long) {
    val long = foo
}
else if (foo is Double) {
    val double = foo
}


text:
Q: Is it bad practice to call a static method via an object? I found that calling the static method via object can be very convenient in some use case.
I'm wondering if this is is considered as a bad practice?
or if this feature will be removed in the future version of PHP?
class Foo
{
    public static function bar ()
    {
        echo 'hi';
    }
}

class SubFoo extends Foo
{
    public static function bar ()
    {
        echo 'hi subfoo';
    }
}

// The normal way to call a static method.
Foo::bar(); // => "hi"

// Call the static method via instance.
$foo = new Foo;
$foo::bar(); // => "hi"

// Here is the use case I found calling static method via instance is convenient.
function callbar(Foo $foo)
{
  // The type-hinting `Foo` can be any subclass of `Foo`
  // so I have to figure out the class name of `$foo` by calling `get_class`.
  $className = get_class($foo);
  $className::bar();

  // Instead of the above, I can just do `$foo::bar();`
}

callbar(new SubFoo); // => "hi subfoo"

A: As a general rule, using static methods is bad practice because:

*

*In fact, static methods or static variables are global variables

*static code makes can cause many troubles in testing

*static code makes high cohesion between parts of code

*static code makes hidden dependencies between parts of code

But, there are cases when using static code is justified. For example:

*

*Methods refer to a class and don't refer to objects

*Helpers or Util classes which don't have their states


text:
Q: Can PSU cause my PC to reboot? I'm having an issue with my PC: It is rebooting sometimes, and I am suspecting the PSU, so I want to confirm a few things. It is a new PC and the first issues started occuring roughly one month after purchase. Also they only occur after several hours of usage. And it seemed that completely shutting down powerline to the PC, and waiting few minutes, then putting it on again, seemed to relief the issue, but that might be just coincidence?
First off:

*

*Does the PSU capacity decrease over lifetime of the PSU?

*Does the PSU capacity temporarily decrease as it is active for a continious time?

My PC specs: Intel i7-3770, 16GB RAM, GTX 770, SSD, HDD. I think Asus Z77 motherboard.
As you can see it is pretty high-end, but I rechecked the PSU on the invoice yesterday and to my surprise I found a 30 euro PSU, namely the HKC V-550.
My system draws 480W of power from the powerline, if on full GPU & CPU stresstest. This is a heavily modified version of their base system, which did not include such a high-end GPU as the GTX770.
Also, as far as I know, a system shutdown (without! bluescreen) can only occur, if:

*

*PSU shuts down

*CPU shuts down

*Motherboard shuts down?

But to me it occurs to be logical that the PC would not reboot if the CPU or Motherboard had shutdown, yet with a PSU and a safety switch it might seem logical that it could reboot.
Also about the reboot: The PC "on"-LED in the front turns off once it reboots, and in my headset (that is connected through USB) I heard some kind of clicking sound once when it turns off, and once when it turns on. Might that be enough reason to believe that it is the PSU?
Also, the temperatures of my CPU and GPU, actually of my whole PC, are perfectly fine under load. The only real test I have not been able to do yet is Memtest86, but wouldn't that lead to a bluescreen under windows anyway? Instead of a reboot.
Well I hope someone is able to help me here.

A: It is possible that the power supply is faulty and causing the PC to shut down.
Your hypothesis that a system would reboot if there is a CPU or Motherboard fault is reasonable, although it is conceivable that it could cause a shutdown (particularly the motherboard).
If you need to leave the PC for a few minutes before a reboot will work, this is also a strong indicator of a PSU problem.
It does seem to me that that size power supply (unless its a very good one - unlikely at $30) might be on the low side.  The GPU has a TDP of 230 watts by itself, with the CPU having a TDP of 77 watts, so thats 305 watts excluding the motherboard and CPU - so your 480 watt figure sounds right.   I'd be inclined to believe the PSU might have been working too hard and is now not able to handle the load.

A: To answer your first two questions: Yes, and no.
I'd lean more towards a PSU myself, as that power supply that they? provided you is absolutely garbage as their 12V ratings are very low. When the 12V is overloaded it can cause the whole PC to reboot, and with a 770 you're definitely pushing the limit on it. If you're comfortable enough working inside the computer and you've got a video connector on-board your motherboard, try unplugging the GPU's PCI-E cables that lead to the power supply, move the video input to the on-board video connected to the motherboard and boot up your computer for a while. If it stays stable longer than "several hours", you've probably narrowed down your issue. You'll need to contact whoever sold you that thing and have them get you a power supply that isn't made from the junkyard scrap.

A: To those who feel like commenting on this answer or even downvoting, please make sure to read it in full and check out the links before you do so. Constructive criticism is by all means welcome, but I don't fancy fielding comments that are already covered by the answer itself. Thank you.
It seems like your current power supply is underrated for the load you are putting on it. As you found, the PSU can provide a maximum of 24 A on the single 12 V rail (288 W), while the GTX 770 supposedly (according to the OP's comment) needs 42 A at 12 V (504 W); @davidgo found a TDP of 230 W for the GPU itself, which goes well with figures published on Tom's Hardware saying about 250 W is needed. The graphics card drawing "just" 250 W would still leave very little margin for anything else on 12 V when the graphics card is working hard. Things that run on 12 V are usually those with motors: spinning-rust hard disks (clocking at about 10 W apiece when working, more on startup), fans, and (as you have found out) some high-powered electronics. To prevent worse problems, including short circuits, the power supply might very well be designed through either a current or thermal trip to shut down in case of an overload.
As this is a card you apparently have added yourself, you shouldn't expect the supplied PSU to be dimensioned to handle such a load. Keep in mind that the typical idle power consumption of a desktop computer is 60 W, and on the order of twice that might be a reasonable figure for a fairly typical computer (except the monitor) under load.
You should look for a power supply that is rated for the necessary load on the appropriate rails. Since you'd need to supply at least around 50 A on 12 V (600 W there alone) to guarantee enough power for the graphics card if it really draws 500 W, you'll be looking at power supplies at least in the 800 W and up range. If the graphics card draws on the order of 250 W, you might easily get away with a 500 W PSU. What is most important (more so than the total wattage rating) is to pay close attention to the rated amperages on the different rails and the requirements of your particular graphics card and through the motherboard the CPU (since those two by far will consume most of the power unless you have an insane number of other pieces of equipment in the computer) so you don't end up with another power supply that exhibits the same problem.

A:
Does the PSU capacity decrease over lifetime of the PSU?

*

*PSUs, like most modern appliances, broke with time. Cheap PSUs broke faster. But yours is a new one.

Does the PSU capacity temporarily decrease as it is active for a continious time?

*

*It depends on the load and the quality of the electronics.

PSU is one of the most important parts when you are building a rig, and yet it is often one of the most overlooked parts, along with the motherboard. PC vendors usually mount cheap PSUs to cut costs, even in medium to high end PCs. You need to decide whether you would want to keep going on for some time with a crappy PSU and replace it when it brokes, or buy a good one from the beginning that would work fine for your PC's lifespan. Being a high-end PC I would choose the latter, specially because a faulty PSU can fry your motherboard when it stops working normally.
I personally have bought a high end PC in the past, and I selected one of the best mobo's at the time, good GX card, best HDD, everything from reputable brands. But the vendor sold me a cheap $40 PSU. It wasn't the cheapest available though. Two years later it started failing randomly, causing boot loops. Turned out a capacitor has blown out. Replaced it with a decent PSU (Corsair) and everything is ok.
So my advice: go to the store where you bought the PC and have them diagnose the PSU. If it turns out to be faulty, try to replace it for a better one, and pay the difference. Spare no expense on it, expect to expend $100+ on a good one if it is brand new.


text:
Q: "At my earliest convenience" I'm quite used to using the phrase "at your earliest convenience" to express urgency but also polite sensitivity to others' schedules and deadlines. It means "Please do this as son as you can without dropping something else."
Lately I've heard more and more voice mail greetings and written notes that use the phrase "at my earliest convenience."  To me, this is rather rude, since it means "I'll do it when I feel like it."  More to the point, politeness requires minimizing the bother of a request on oneself while expressing appreciation for the bother of a request made on someone else.
Am I reading too much into this?  Is it polite to use "at my earliest convenience?"  It certainly sounds rude to me.

A: I too am surprised to hear prerecorded messages to the effect that a call will be returned "at our earliest convenience."  The originator of the message is confusing the two formal idioms "at your earliest convenience" and "as soon as possible."  The first is a polite way to request action from another person.  The second is an accommodating way to obligate yourself. Neither are to be taken literally.

A: At your convenience: is a common expression often  used  in business context meaning:

at a suitable time, at your leisure, in your own time, whenever you like, in your spare time, in a spare moment

At my convenience actually  stresses the fact that the you will do whatever you are asked to  whenever you may like or have spare time to do it, but whether it is 'rude' may also depend on personal opinion.
Ngram actually shows little usage of the expression.
I  think that a polite to neutral way to express  the same concept is:  as soon as possible, often written as (ASAP).

A: To me, "at my earliest convenience" is rude. Anyone using it should use "as soon as I can," "at my earliest opportunity," or similar phrase expressing urgency.
Of course, there is no way to inform people of any of this without being rude and picayune.

A: The phrase "at my earliest convenience" isn't inherently impolite.  It is, however, somewhat ambiguous, and may be used politely, indifferently, or rudely.  Here are two examples:
• Bill will ship your order as soon as possible, but must complete three other tasks before going to the stockroom; he writes: "I'll ship your order at my earliest convenience." (Polite.)
• Jane, offended by your request, puts your order at the very bottom of a giant pile of orders, then writes sarcastically: "I'll complete your order at my earliest convenience." (Impolite.)
A phrase that sometimes may be used instead is "When I'm good and ready".  It is less ambiguous, but like the other phrase may be used a variety of ways.  Jane, quite self-satisfied, might impolitely tell you, "I'll complete your order when I'm good and ready."  Other persons might tell you, matter-of-factly and indifferently,  "I'll do it when I'm good and ready", merely to inform you that their time is arranged to suit their own needs rather than yours, and you'll get no special consideration.

A: I've never seen this but the statement is left vague at the word "convenience" in my opinion. From a boss or a client, asking someone to do something as soon as it is convenient sounds as though they're expected to put it high on their priority list, above anything non essential or time insensitive. Coming from the person expected to do the favor, it is just as polite if they are putting "convenience" as high on their to-do list as we expect. For all we know, it could be just after "surf English.stackexchange for 3 hours" but before "take a 2 hour lunch".

A: Hold on folks!
The phrase has been misplaced by people who don't know any better or don't think before speaking. The phrase is quite at home in the context it was developed for. When leaving a voice mail or sending an email you may want a reply so you say, "please reply at your earliest convenience" or "I would appreciate an answer at your earliest convenience".
Telling a client or customer that you will reply when it's convenient to you is simply rude and not what the phrase was intended for... think people!