text:
Q: How to fix preallocated matrix for parfor function in Matlab? I want to paralyze my forloop in Matlab.I use parfor function for that, but I get error because the way I used variable inside of the loop. would someone help me to fix that. I'm new in matlab.
Here is part of my try.
Here is part of problematic part:
CV_err=zeros(length(gamma), (Num_Tasks + 1));

parfor k=1:length(gamma)

#block of code

#
CV_err(k,1:Num_Tasks)= sum(In_Fold_Error)./size(In_Fold_Error,1);
CV_err(k,Lambda_location)= Lambda;
CV_err(k,(Num_Tasks +2))= sum(CV_err(k,1:Num_Tasks))/Num_Tasks;
end

Error: parfor loop can not run due to way   CV_err is used.
CV_err is indexed in different ways, potentially causing dependencies
Seems that valid indices are restricted in parfor .

A: While your variable is sliced, you only access the k-th row in the k-th iteration, the code analyser does not understand it. Give a little help to matlab, first put all data into a vector and then write all at once to the sliced variable.
CV_err=zeros(length(gamma), (Num_Tasks + 2));
parfor k=1:length(gamma)

%block of code

%
  temp=zeros(1,(Num_Tasks + 2));
  temp(1,1:Num_Tasks)= sum(In_Fold_Error)./size(In_Fold_Error,1);
  temp(1,Lambda_location)= Lambda;
  temp(1,(Num_Tasks +2))= sum(temp(1,1:Num_Tasks))/Num_Tasks;
  CV_err(k,:)=temp;
end

The limitation is explained in the documentation:

Form of Indexing. Within the list of indices for a sliced variable, one of these indices is of the form i, i+k, i-k, k+i, or k-i, where i is the loop variable and k is a constant or a simple (nonindexed) broadcast variable; and every other index is a scalar constant, a simple broadcast variable, a nested for-loop index, colon, or end.

Source

A: To fix pre-allocation, don't pre-allocate. You're just telling to MATLAB how it should split the work among workers; parfor doesn't like that.
The answer is: don't make loops change common variables, write your results separately, grow cell arrays instead of matrices, i.e.
    clear CV_err;

    parfor k=1:length(gamma)
            %// here your other code
            this_CV_err                  = zeros(Num_Tasks+2,1);
            this_CV_err(1:Num_Tasks)     = sum(In_Fold_Error)./size(In_Fold_Error,1);
            this_CV_err(Lambda_location) = Lambda;
            this_CV_err(Num_Tasks+2)     = mean(this_CV_err(1:Num_Tasks));
            CV_err{k} = this_CV_err;
    end;


text:
Q: matplotlib colorbar tick label formatting I am wondering how I can explicitly set the format of a colorbar object in matplotlib
Here is an example plotting script:
from matplotlib import pyplot
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from pylab import *
import numpy as np
import random

# ----------

plot_aspect = 1.2
plot_height = 10.0
plot_width = int(plot_height*plot_aspect)

# ----------

pyplot.figure(figsize=(plot_width, plot_height), dpi=100)
pyplot.subplots_adjust(left=0.10, right=1.00, top=0.90, bottom=0.06, hspace=0.30)
subplot1 = pyplot.subplot(111)

# ----------

cbar_max = 40.0
cbar_min = 20.0
cbar_step = 1.0
cbar_num_colors = 200
cbar_num_format = "%d"

# ----------
# make random dataset

dx, dy = 5.0, 5.0
y, x = np.mgrid[slice(-100.0, 100.0 + dy, dy),slice(-100.0, 100.0 + dx, dx)]

z = []
for i in x:
    z.append([])
    for j in y:
        z[-1].append(random.uniform(cbar_min,cbar_max))

# ----------
# make random dataset

levels = MaxNLocator(nbins=cbar_num_colors).tick_values(cbar_min, cbar_max)
cmap = pyplot.get_cmap('gist_ncar')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
pp = pyplot.contourf(x,y,z,levels=levels,cmap=cmap)
cbar = pyplot.colorbar(pp, orientation='vertical', ticks=np.arange(cbar_min, cbar_max+cbar_step, cbar_step), format=cbar_num_format)
cbar.ax.set_ylabel('Color Scale [unit]', fontsize = 16, weight="bold")

CS = pyplot.contour(x,y,z, alpha=0.5)

majorLocator1   = MultipleLocator(10)
majorFormatter1 = FormatStrFormatter('%d')
minorLocator1   = MultipleLocator(5)

subplot1.xaxis.set_major_locator(majorLocator1)
subplot1.xaxis.set_major_formatter(majorFormatter1)
subplot1.xaxis.set_minor_locator(minorLocator1)

pyplot.xticks(fontsize = 16)
pyplot.xlim(-100.0,100.0)

majorLocator2   = MultipleLocator(10)
majorFormatter2 = FormatStrFormatter('%d')
minorLocator2   = MultipleLocator(5)

subplot1.yaxis.set_major_locator(majorLocator2)
subplot1.yaxis.set_major_formatter(majorFormatter2)
subplot1.yaxis.set_minor_locator(minorLocator2)

pyplot.yticks(fontsize = 16)
pyplot.ylim(-100.0,100.0)

subplot1.xaxis.grid()
subplot1.yaxis.grid()
subplot1.axes.set_aspect('equal')

pyplot.suptitle('Main Title', fontsize = 24, weight="bold")

pyplot.xlabel('X [unit]', fontsize=16, weight="bold")
pyplot.ylabel('Y [unit]', fontsize=16, weight="bold")

pyplot.show()
pyplot.close()

which gives me output like this:

Currently the colorbar tick label formatting will use the format string provided  earlier: cbar_num_format = "%d", but I'd like to also set the font size and weight using:
cbar.ax.set_yticklabels(np.arange(cbar_min, cbar_max+cbar_step, cbar_step), fontsize=16, weight='bold')

...but when I do this, the previously applied formatter string seems to go away and the numbers are back in "%0.1f" format instead of the "%d" that I applied earlier:

How can I prevent this from happening or control the colorbar tick labeling in a better way?

A: A better solution is
from matplotlib.ticker import FuncFormatter

fmt = lambda x, pos: '{:.1%}'.format(x)
cbar = plt.colorbar(format=FuncFormatter(fmt))

A: One option is to just format the ticklabels manually.  There is probably a better way but this usually works for me.
cbar.ax.set_yticklabels(['{:.0f}'.format(x) for x in np.arange(cbar_min, cbar_max+cbar_step, cbar_step)], fontsize=16, weight='bold')

Edit:
If you don't want to figure out the ticks yourself you can use:
for l in cbar.ax.yaxis.get_ticklabels():
    l.set_weight("bold")
    l.set_fontsize(16)

You may need to call draw() if they are not properly updated. This can be reduced to a one liner with:
setp(cbar.ax.yaxis.get_ticklabels(), weight='bold', fontsize=16)

A: Here I format colorbar ticks as percentage.
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(0, 1, 20)
ys = xs ** 3
colors = xs ** 2
scatter = plt.scatter(xs, ys, c=colors)

cb = plt.colorbar(scatter)
cb.ax.set_yticklabels(["{:.1%}".format(i) for i in cb.get_ticks()]) # set ticks of your format

plt.show()

Also you could manually set tick positions.
ticks = np.linspace(0, 1, 5)
cb = plt.colorbar(scatter, ticks=ticks)
cb.ax.set_yticklabels(["{:.1%}".format(i) for i in ticks]) # set ticks of your format

For this example I used python 3.7, matplotlib 3.1.2.

A: Just changing it to
cbar.ax.set_yticklabels(np.arange(int(cbar_min), int(cbar_max+cbar_step), int(cbar_step)), fontsize=16, weight='bold')

does the trick !!!
i.e. just give int() to your np.arange() values inside cbar.ax.set_yticklabels

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using foreach and unset() to keep only a specific set of data in a php array I have an array that contains category numbers collected from a database. The array is not static and could change in length and content.
Based on the result of an if/else statement I need to drop everything from the array apart from one specific category and it's subcategories.
I thought this was what I needed, but I don't get any content at all if I use this.
foreach($this->data[$parent_id] as $key => $value) {
if(!in_array($key, 131)) {
    unset($this->data[$parent_id][$key]);
}
}

What I thought i was doing was getting all the array data, and if the array key isn't 131, drop it.

A: Right now, this is how your code reads:
/** For each, Array as $key => $value **/
foreach($this->data[$parent_id] as $key => $value) {
/** if needle $key is not found in Array 131,
       which in this case is never **/
    if(!in_array($key, 131)) {
        /** destroy array[key], or in this case, all the elements**/
        unset($this->data[$parent_id][$key]);
    }
}

So the above should give you back an empty array. Refer to php.net's in_array documentation to pass the appropriate parameters, in the appropriate order.
If all you are wanting to compare is the key of the current iteration of $this->data[$parent_id] with (e.g.) 131, then this is all you need:
/** For each, Array as $key => $value **/
foreach($this->data[$parent_id] as $key => $value) {
/** if the current $key of the array element is not equal to number 131 **/
    if($key != 131) {
        /** destroy the array element**/
        unset($this->data[$parent_id][$key]);
    }
}

PS: Updating my answer to reflect that, in this specific case, the loop logic above is equivalent to the following:
/**
 * If key 131 exists in data[$parent_id]
 *   assign an array with only thisArray[131] as an element,
 *   where thisArray is data[parent_id]
 **/
if(array_key_exists(131, $this->data[$parent_id]))
    $this->data[$parent_id] = [$this->data[$parent_id][131]];


text:
Q: How can I speed up a loop that queries a kd-tree? The following section of my code is taking ages to run (it's the only loop in the function, so it's the most likely culprit):
tree = KDTree(x_rest)
for i in range(len(x_lost)):
    _, idx = tree.query([x_lost[i]], k=int(np.sqrt(len(x_rest))), p=1)
    y_lost[i] = mode(y_rest[idx][0])[0][0]

Is there a way to speed this up? I have a few suggestions from Stack Overflow:

*

*This answer suggests using Cython. I'm not particularly familiar with it, but I'm not very against it either.

*This answer uses a multiprocessing Pool. I'm not sure how useful this will be: my current execution takes over 12h to run, and I'm hoping for at least a 5-10x speedup (though that may not be possible).

A: Here are a few notes about how you could speed this up:

*

*This code loops over x_rest, and calls tree.query() with one point
from x_rest at a time. However, query() supports querying multiple
points at once. The loop inside query() is implemented in Cython,
so I would expect it to be much faster than a loop written in
Python. If you call it like this, it will return an array of matches.

*The query() function supports a parameter called workers,
which if set to a value larger than one, runs your query in
parallel. Since workers is implemented using threads, it will likely be faster than a solution using multiprocessing.Pool, since it avoids pickling. See the documentation.

*The code above doesn't define the mode() function, but I'm assuming
it's scipy.stats.mode(). If that's the case, rather than calling mode() repeatedly, you can use the axis argument, which would let you take the mode of nearby points for multiple queries at once.


text:
Q: Oracle on Alpine linux I am trying to install OCI8 extension on my Alpine Linux Docker environment. Although there are several places saying it won't work, there are some which say it actually does. I have a 3.4 version and for corporate reasons it is staying like that for now.
I have done this within my Docker conf:
# Install Oracle Client and build OCI8 (Oracel Command Interface 8 - PHP extension)
USER root
ENV LD_LIBRARY_PATH=/usr/local/instantclient
ENV ORACLE_HOME=/usr/local/instantclient

RUN apk update && apk upgrade
RUN apk add musl-dev libaio autoconf && apk add --update make

## Unzip Instant Client v12
RUN pecl channel-update pecl.php.net
COPY instantclient_12_2.zip /var/www/html/instantclient_12_2.zip
RUN unzip -d /usr/local/ /var/www/html/instantclient_12_2.zip
RUN ln -s /usr/local/instantclient_12_2 /${ORACLE_HOME} && \
    ln -s /${ORACLE_HOME}/libclntsh.so.* /${ORACLE_HOME}/libclntsh.so && \
    ln -s /${ORACLE_HOME}/libocci.so.* /${ORACLE_HOME}/libocci.so && \
    ln -s /${ORACLE_HOME}/lib* /usr/lib && \
    ln -s /${ORACLE_HOME}/sqlplus /usr/bin/sqlplus &&\
    ln -s /usr/lib/libnsl.so.2.0.0  /usr/lib/libnsl.so.1

RUN apk add gcc; exit 0 # This has a history of failing sometimes

RUN echo "instantclient,/usr/local/instantclient" | pecl install oci8 &&\
    echo 'extension=oci8.so' > /usr/local/etc/php/conf.d/30-oci8.ini &&\
    rm -rf /tmp/*.zip /var/cache/apk/* /tmp/pear/

Now the build passes, and it looks okay, however when I do a php -v I am getting the following:

PHP Warning:  PHP Startup: Unable to load dynamic library
  '/usr/local/lib/php/extensions/no-debug-non-zts-20160303/oci8.so' -
  Error loading shared library libnsl.so.1: No such file or directory
  (needed by /usr/local/instantclient/libclntsh.so.12.1) in Unknown on
  line 0

PHP version is 7.1.12.
What I've tried is doing apk add libnsl but this returns me this error:

ERROR: unsatisfiable constraints:   so:libtirpc.so.3 (missing):

So I tried also adding apk add libtirpc-dev (the 'plain' libtirpc isn't available for my version or something), but that changed nothing.
Any clues?

A: I share my version of docker that I made to work with the latest version of alpine and instantclient basiclite. The size of the docker image is 124 mb.
I share my github where you can download it
Docker + alpine + Instantclient Basiclite
Or you can see below the content of the dockerfile
FROM alpine:latest
# Install Instantclient Basic Light Oracle and Dependencies
RUN apk --no-cache add libaio libnsl libc6-compat curl && \
cd /tmp && \
curl -o instantclient-basiclite.zip https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip -SL && \
unzip instantclient-basiclite.zip && \
mv instantclient*/ /usr/lib/instantclient && \
rm instantclient-basiclite.zip && \
ln -s /usr/lib/instantclient/libclntsh.so.19.1 /usr/lib/libclntsh.so && \
ln -s /usr/lib/instantclient/libocci.so.19.1 /usr/lib/libocci.so && \
ln -s /usr/lib/instantclient/libociicus.so /usr/lib/libociicus.so && \
ln -s /usr/lib/instantclient/libnnz19.so /usr/lib/libnnz19.so && \
ln -s /usr/lib/libnsl.so.2 /usr/lib/libnsl.so.1 && \
ln -s /lib/libc.so.6 /usr/lib/libresolv.so.2 && \
ln -s /lib64/ld-linux-x86-64.so.2 /usr/lib/ld-linux-x86-64.so.2

ENV ORACLE_BASE /usr/lib/instantclient
ENV LD_LIBRARY_PATH /usr/lib/instantclient
ENV TNS_ADMIN /usr/lib/instantclient
ENV ORACLE_HOME /usr/lib/instantclient

A: I might be late to answer this. I got the same problem of having a alpine base image and add oracle client to that. So i came up with this solution -
https://github.com/Shrinidhikulkarni7/OracleClient_Alpine
Here is the Dockerfile, but you would also need the shell script in it for it to work.
FROM alpine:latest

ENV LD_LIBRARY_PATH=/lib

RUN wget https://download.oracle.com/otn_software/linux/instantclient/193000/instantclient-basic-linux.x64-19.3.0.0.0dbru.zip && \
    unzip instantclient-basic-linux.x64-19.3.0.0.0dbru.zip && \
    cp -r instantclient_19_3/* /lib && \
    rm -rf instantclient-basic-linux.x64-19.3.0.0.0dbru.zip && \
    apk add libaio

ADD script.sh /root/script.sh

RUN /root/script.sh

Over here I'm directly downloading the oracle client inside image, setting the path, adding packages and finally using the shell script for creating symbolic link.

A: I'd recommend using an operating system supported by Oracle, thus avoiding the headache of hacking Alpine and the uncertainty that it won't fall over at a critical time.  And thus giving you some confidence your business won't be negatively impacted.  Try https://github.com/oracle/docker-images/tree/master/OracleInstantClient
Other comments

*

*Don't set ORACLE_HOME when using Instant Client.  That variable is
for full software installs.

*Use ldconfig to set the system library path, see
the Instant Client installation instructions e.g. here.

*Use Instant Client 19, which can connect to the same DB versions that 12.2 can. (19 is really the renamed terminal 12.2 release in the new versioning system)

*Using Oracle Linux Docker images has the advantage that it will download and install the 19 Instant Client without you having to manually do the download.

See this blog for info about the 'slim' Oracle Linux container it uses.

A: Here is the Dockerfile For Golang With ORACLE-CLIENT
FROM golang:alpine

RUN apk update

ENV CLIENT_FILENAME instantclient-basic-linux.x64-12.1.0.1.0.zip

WORKDIR /opt/oracle/lib

ADD https://github.com/bumpx/oracle-instantclient/raw/master/${CLIENT_FILENAME} .

RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories && \
apk add --update libaio libnsl && \
ln -s /usr/lib/libnsl.so.2 /usr/lib/libnsl.so.1

RUN LIBS="*/libociei.so */libons.so */libnnz12.so */libclntshcore.so.12.1 */libclntsh.so.12.1" && \
unzip ${CLIENT_FILENAME} ${LIBS} && \
for lib in ${LIBS}; do mv ${lib} /usr/lib; done && \
ln -s /usr/lib/libclntsh.so.12.1 /usr/lib/libclntsh.so && \
rm ${CLIENT_FILENAME}

RUN mkdir /app

ADD . /app

WORKDIR /app

RUN apk add git
RUN apk add libc-dev
RUN apk add gcc

RUN go mod tidy
RUN go build -o main .

CMD ["/app/main"]

A: I was just tackling a similar problem to this using the Godror Golang Driver for Oracle. I was  never able to solve this on using an Alpine image. The problem eventually came that libint.sh, would never fully install to be recognized by the system. Even changing the docker file to using the Glibc library.
How i eventually fixed the issue was to use the images from Oracle itself. The full version not the slim images that can be seen here:  https://github.com/oracle/docker-images/tree/master/OracleLinuxDevelopers
you then have to install golang and then your Instant client and Oracle dependencies if you need it.
FROM oraclelinux:7 as builder
RUN yum install -y oracle-golang-release-el7 && \
    yum install -y git && \
    yum install -y golang unzip

COPY . /app
RUN go version
WORKDIR /app
{Your Docker Specific Commands Here}

{Insert Build Specific Environment Variables here}
#Oracle Specific Environment Variables
{Insert Oracle Env Variables here}

WORKDIR /root/
#Install oracle dependencies
RUN yum install -y wget unzip libaio && \
    rm -rf /var/cache/yum
#install Oracle Instant Client
RUN wget https://download.oracle.com/otn_software/linux/instantclient/199000/instantclient-basic-linux.x64-19.9.0.0.0dbru.zip -O /tmp/instantclient.zip && \
    unzip /tmp/instantclient.zip -d /usr/lib/instantclient && \
    rm /tmp/instantclient.zip

#Install Oracle SDK
RUN wget https://download.oracle.com/otn_software/linux/instantclient/199000/instantclient-sdk-linux.x64-19.9.0.0.0dbru.zip -O /tmp/instantclient-sdk-linux.x64-19.9.0.0.0.zip && \
    unzip /tmp/instantclient-sdk-linux.x64-19.9.0.0.0.zip -d /usr/lib/ && \
    rm /tmp/instantclient-sdk-linux.x64-19.9.0.0.0.zip

#Install Oracle Tools through SQLPlus
RUN wget https://download.oracle.com/otn_software/linux/instantclient/199000/instantclient-sqlplus-linux.x64-19.9.0.0.0dbru.zip -O /tmp/instantclient-sqlplus-linux.x64-19.9.0.0.0.zip && \
    unzip /tmp/instantclient-sqlplus-linux.x64-19.9.0.0.0.zip -d /usr/lib/ && \
    rm /tmp/instantclient-sqlplus-linux.x64-19.9.0.0.0.zip

WORKDIR /app

COPY --from=builder /app/cmd/svr .
EXPOSE 8000

CMD ["./app"]

Again this is how i solved the problem for a Golang API. There may be others that solved the Alpine issue but i was never able to get it to work, even using older version of the Oracle Instant Client.

A: Try this Docker file. Start from the basic alpine linux image and add the required packages.
FROM alpine:3.13

WORKDIR /project

RUN wget https://download.oracle.com/otn_software/linux/instantclient/211000/instantclient-basiclite-linux.x64-21.1.0.0.0.zip -qO- | busybox  unzip -q - && \
    wget https://download.oracle.com/otn_software/linux/instantclient/211000/instantclient-sqlplus-linux.x64-21.1.0.0.0.zip -qO- | busybox  unzip -q - && \
    wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.33-r0/glibc-2.33-r0.apk -q

RUN apk add --allow-untrusted libaio glibc-2.33-r0.apk

RUN cd instantclient_21_1 && cp /usr/lib/libaio.so.1 /lib/libc.musl-x86_64.so.1 . && chmod +x sqlplus

ENV LD_LIBRARY_PATH=/project/instantclient_21_1


text:
Q: Can't bind to color since it isn't a known property of 'button' Error
Can't bind to color since it isn't a known property of 'button'.

Code
@Component({
    selector: "nav-next",
    template: `

        <button [color]="color" class="primary" [
        </button>

`
})

Expected Behaviour
This child directive enabled us in Angular2-RC4 to set colors dynamically from the parent component. Angular2-Final says this is no good. Any ideas?

A: After the debut of ngModule, you have to include your Directive into the ngModule declarations array before using it:
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, ColorDirective ],
  bootstrap: [ App ]
})
export class AppModule {}

And make sure your Directive selector is of property type too:
@Directive({
  selector: "[color]"
})

Here is the working example, if you change either one of the two things above, you'll get that error: http://plnkr.co/edit/ymUTyuMo9FsSORd9XI2H?p=preview

A: For any one else having this issue and the other answer didn't work, this worked for me.
Changing [color] to [style.color]

    <button [style.color]="color" class="primary" [
    </button>

A: I primarily used @Ruan suggestion, but it seems didn't work well. Although I've got rid of that annoying error messages, this also messed up with the button background color.
Solution for me was adding MatButtonModule to TestBed imports which were using that component.


text:
Q: Right Triangle calculations returning 0? I can't figure out what I am doing wrong here. I just wrote a similar code that worked fine. once I got a handle on how to use the scanner class. I am working on a program that takes the height and base of a right triangle and then calculates the perimeter, area, and hypotenuse. But it returns 0.0 for each method and I can't figure out if I am missing some sort of syntax or if I am just really messing up my calculations. Can someone just point me in the right direction of my mistake?
    public class RightTriangle {

    private double height;
    private double base;
    private final double hypotenuse = Math.sqrt(Math.pow(height, 2) + Math.pow(base, 2));

   public RightTriangle(double triHeight, double triBase)
   {
       triHeight = height;
       triBase = base;
   }

   public double getPerimeter()
   {
       double perimeter = height + base + hypotenuse;
       return perimeter;
   }

   public double getArea()
   {
       double area = (height + base) / 2;
       return area;
   }

   public double getHypotenuse()
   {
       return hypotenuse;
   }
}

Here is my main method:
    import java.util.Scanner;

    public class CalculateTriangle
{

    public static void main(String[] args)
    {
        Scanner triangleHeight = new Scanner(System.in);
        System.out.print("Enter Triangle Height: ");
        double height = triangleHeight.nextDouble();

        Scanner triangleBase = new Scanner(System.in);
        System.out.print("Enter Triangle Base: ");
        double base = triangleBase.nextDouble();

        RightTriangle newTriangle = new RightTriangle(height, base);

        newTriangle.getPerimeter();
        double perimeter = newTriangle.getPerimeter();

        newTriangle.getArea();
        double area = newTriangle.getArea();

        newTriangle.getHypotenuse();
        double hypotenuse = newTriangle.getHypotenuse();

        System.out.println(perimeter);
        System.out.println(area);
        System.out.println(hypotenuse);

    }
}

A: Your code:
public RightTriangle(double triHeight, double triBase)
{
   triHeight = height;
   triBase = base;
}

Should be:
public RightTriangle(double triHeight, double triBase)
{
   height = triHeight;
   base = triBase;
}

A: make this as your function-->
  private double hypotenuse;

 public double getHypotenuse()
   {
       hypotenuse = Math.sqrt(Math.pow(height, 2) + Math.pow(base, 2));
       return hypotenuse;
   }

because you are calculating the value of hypotenuse before you initialize height or base, that is why you are getting 0.
also your constructor should be-->
height=triHeight;
bas=triBase;

hope this helps.


text:
Q: Does a Node Docker container has to be started for Gulp us? I don't know if my question is stupid but, after hours crushing my brain on it, I prefer to ask you.
I'm trying to run NPM on a Docker container (windows).
I don't want a real "node server" ; I just use NPM to run utilities like gulp, webpack, browserify, vue.js...
So I added this in my ./docker-compose.yml file :
services:
  node:
    build: docker/node
    environment:
      - NODE_ENV=dev

Until here, everything sounds good in my head.
Now here is the content of my ./docker/node/Dockerfile :
# See https://github.com/nodejs/docker-node#dockerfile
FROM node:6

EXPOSE 8080

USER node

# set the working directory
RUN mkdir /home/node/app
WORKDIR /home/node/app

# delete existing modules and re-install dependencies
COPY package.json /home/node/app/package.json
RUN rm -rf node_modules
RUN npm install

# launch the app
# EDIT : I removed this line to solve the issue. See answer.
CMD  ["npm", "start"]

To create it, I just followed official tutorials.
And then, here is my ./docker/node/package.json file :
{
  "name": "custom-symfony-project",
  "version": "1.0.0",
  "dependencies": {
    "gulp": "^4.0.0"
  },
  "devDependencies": {
    "gulp": "^4.0.0"
  }
}

I also have 3 containers : PHP, MySQL and NGINX but they are independants and they all start correctly, so I don't thing they are the pain of the issue.
So I run my docker-compose build : everything works fine.
But when I run docker-compose start I got thing in my Node container logs :
npm ERR! missing script: start

I tried to add an empty server.js but the container doesn't start.
So my question is : do I really need to start something ? Do I need a server.js ? I don't what to put into it.
When I was using npm with Ubuntu, I've just never specified a start script..!
Thanks !

A: Containers are designed to run as long as the process they support is running and a container should run only one process. In your case, you are removing the CMD line, which is starting the process the container supports, so the container has nothing to do and just shuts down immediately.
You should think about your Docker container as a process, not a VM (virtual machine). A VM would have Node and other dependencies loaded and it would be ready to run commands any time you log into it, but a container spins up to run one command and then shut down.
It sounds like you want this container to spin up, run Gulp, then shut down. If that's the case you can use a CMD line like this (assuming you install gulp globally within the Dockerfile):
CMD ['gulp']

Or maybe you want it to spin up and watch for changes using gulp-watch? In that case, the CMD should be something like this:
CMD ['gulp', 'watch']

If you go with either option, note that Gulp will build the files within the container and not on your host filesystem unless you use a bind mount. A bind mount will allow your host filesystem to share a directory with the container and facilitate one or two-way updates to files.

A: Ok so I remove the CMD line into the Dockerfile but the container just stopped naturally.
So I added the tty: true option into the docker-compose.yml file in order to keep the container active even if nothing's currently running on it, and for the moment it seems to work :
node:
    build: docker/node
    environment:
      - NODE_ENV=dev
    container_name: symfony4-windock-node
    tty: true


text:
Q: Why $\frac{1}{f\left(D^{2}\right)} \sin a x=\frac{\sin a x}{f\left(-a^{2}\right)}$ gives the particular solution? Recently the topic of second order differential equations and their particular solutions is thought in our college , and they done some messy calculation and arrived at some complex formulas to Solve for particular solutions (they refer it as particular integral) , here is a example of one of those
$\frac{1}{f\left(D^{2}\right)} \sin a x=\frac{\sin a x}{f\left(-a^{2}\right)}$
But  I am familiar with the method which uses trial solutions to find particular solution
So it is very hard to comprehend that how the term ($\frac{1}{f\left(D^{2}\right)} \sin a x$) can refer to particular solution of a differential equation with sinusoidal forcing term
Someone plese help me to understand it

A: Set $D:=\frac{\mathrm d}{\mathrm dx}$
$D(\sin ax)=a\cos ax, D^2(\sin ax)=(-a^2)\sin ax$
It serves for notational convenience. Given an ODE with constant coefficients, $f(D)y=p(x)$ then a particular solution is denoted by $y_p=\frac 1{f(D)}p(x).$ Think of it as $\overbrace{\frac{\mathrm d f}{\mathrm dx}(x)=g(x)}^{Df(x)=g(x)}\implies \overbrace{f(x)=\int g(t)\,dt}^{f(x)=\frac 1{D} g(x)}.
$
Note that $D^{2r}(\sin ax)=(-a^2)^r\sin ax, r\ge 1$.
Suppose that the given ODE is:
$(D^{2r}+a_{2r-2}D^{2r-2}+...+a_2D^2)y=\sin ax\implies y=\frac 1{f(D^2)}\sin ax,\tag 1$
where  $f(D^2):=D^{2r}+a_{2r-2}D^{2r-2}+...+a_2D^2$.
Note that: $(D^{2r}+a_{2r-2}D^{2r-2}+...+a_2D^2)\sin ax=f(D^2)\sin ax=f(-a^2)\sin ax\tag 2$
Use $(2)$ in $(1)$ to get: $y=\frac 1{f(-a^2)}\sin ax,$ provided that $f(-a^2)\ne 0$.


text:
Q: DB2 Stored Procedure to (ALTER) RESTART the column with number I'm using SSIS packages to refresh my development tables with production data, using "Execute SQL Task" to run these queries:
alter table DEV.tablename alter column ID drop identity;
delete from DEV.tablename;
insert into DEV.tablename SELECT * FROM RESTORE.COVERAGE;
alter table DEV.tablename  alter column ID set generated always as identity;
alter table DEV.tablename  alter column ID restart with some_Integer_value;

I could not pass a number via parameters (some_Integer_value in above case) to passing parameter in execute SQL taskExecute SQL task(SSIS) so I had to use a stored procedure to run last ALTER table statement.
CREATE PROCEDURE set_auto_incrementSP (IN TABLENAM VARCHAR(50),IN TABLECOLUM VARCHAR(30),IN INC_NUM INT)
    RESULT SETS 1
    LANGUAGE SQL

P1: BEGIN

    DECLARE STATEMENT1 VARCHAR(50);
    DECLARE NAME VARCHAR(30);
    DECLARE TABLENAME VARCHAR(50);
    DECLARE TABLECOLUMN VARCHAR(30);
    DECLARE INC_NUMBER INTEGER DEFAULT 0;

    SET TABLENAME=TABLENAM;
    SET TABLECOLUMN=TABLECOLUM;
    SET INC_NUMBER=INC_NUM;
    -- Declare cursor

        SET STATEMENT1 = 'ALTER TABLE '||TABLENAME||' alter column '||TABLECOLUMN||' restart with'||INC_NUMBER||' ';

        PREPARE NAME FROM STATEMENT1;

        EXECUTE IMMEDIATE STATEMENT1;

The stored procedure has been deployed successfully but when executing the stored procedure, I see this error:

Run: DEV.SET_AUTO_INCREMENTSP(VARCHAR(50), VARCHAR(30), INTEGER)
  {? = call DEV.SET_AUTO_INCREMENTSP(?,?,?)}
  [SQL0104] Token  was not valid. Valid tokens: SET DROP RESTART.
  Run of routine failed.
   - Roll back completed successfully.

A: STATEMENT1 is 50 long, that's probably not enough, and you don't put any space between with and the number


text:
Q: How do I correctly create a mergesort function? This is for my computer science c++ data structures class.
For my assignment I have to create mergesort code for ascending and descending arrays.
My professor has me compile his test code along with my file code. The terminal will print out any errors in my coding logic.
This is the error that prints out in the terminal when I run my file:

   **** Testing mergesort ****

Testing simple two-element merge:
OK

Testing 20-element merge (10 and 10): OK

Testing 21-element merge: OK

Sorting empty sequence:OK

Sorting random vector of size 2:
{48, 77}
OK

Sorting random vector of size 3:
{48, 77, 64}
OK

Sorting random vector of size 4:
{48, 77, 64, 2}
OK

Sorting random vector of size 5:
{48, 77, 64, 2, 11}

FAILED: result is not sorted:
{11, 2, 48, 64, 77}

This is my code:
void merge(int *input, int size, int *output, bool output_asc) {
    if (output_asc == true) { //sort ascending
        int i = 0;
        int j = size - 1;
        int k = 0;
        while (i <= j) {
            if (input[i] <= input[j]) {
                output[k++] = input[i++];
            } else {
                output[k++] = input[j--];
            }
        }
    } else
    if (output_asc == false) { //sort descending
        int i = 0;
        int j = size - 1;
        int k = 0;
        while (i <= j) {
            if (input[i] <= input[j]) {
                output[k++] = input[j--];
            } else {
                output[k++] = input[i++];
            }
        }
    }
}

void mergesort(int *input, int size, int *output, bool output_asc) {
    int begin = 0;
    int end = size - 1;
    if (begin >= end) {
        return;
    }
    int mid = (begin + end) / 2;

    mergesort(input, mid - 1, output, output_asc);
    mergesort(input, end, output, output_asc);

    merge(input, size, output, output_asc);
}

int *mergesort(int *input, int size) {
    int *output = new int[size];
    mergesort(input, size, output, true);
    return output;
}

This is my professors test code:
/* test_mergesort()
Test mergesort on a variety of inputs.
*/
bool test_mergesort() {
    cout << "Sorting empty sequence:";
    vector<int> no_data;

    int *no_data_sorted = mergesort(no_data);
    // No data means nothing to check!
    delete[] no_data_sorted;
    cout << "OK\n";

    vector<int> sizes = { 2, 3, 4, 5, 7, 8, 15, 16, 19, 20, 50, 64, 100, 128 };

    for (int s : sizes) {

        // Test sorting a vector of random data
        vector<int> data = make_random_vector(s);

        cout << "Sorting random vector of size " << s << ":\n" << data << "\n";

        int *data_sorted = mergesort(data);
        if (!is_sorted(data_sorted, data.size())) {
            cout << "FAILED: result is not sorted:\n";

            cout << "{";
            for (int *i = data_sorted; i != data_sorted + data.size() - 1; ++i)
                cout << *i << ", ";
            cout << data_sorted[data.size() - 1] << "}\n";

            return false;
        } else
        if (!is_permutation(&data[0], data.size(), data_sorted)) {
            cout << "FAILED: result is not a permutation of the input sequence:\n";
            cout << "{";
            for (int *i = data_sorted; i != data_sorted + data.size() - 1; ++i)
                cout << *i << ", ";
            cout << data_sorted[data.size() - 1] << "}\n";

            return false;
        } else
            cout << "OK\n";
    }
    return true;
}

Any help will be appreciated, thank you.

A: Your mergesort looks stupidly complex.  Start with a simple inefficient version that is correct.
Then replace parts to make it more efficient.
std::vector<int> merge( std::vector<int> a, std::vector<int> b );

this is 20x easier to write.  Write it and test it.
Then write
std::vector<int> merge_sort( std::vector<int> in );

with a simple inefficient divide, recurse, then merge.
Test and confirm it works.
Now hook it up to your professors test code.  Inefficiently; copy the pointer and size to a vector, do the sort, then copy it back.  Confirm your professors tests pass.
If you really want the reverse feature, add it.  Add a bool to merge saying return its result backwards, and assume the right argument is backwards.
Next, write inefficient wrappers around merge that convert pointers to vectors and back.  It takes two pointers and two sizes, and assumes the right one is backwards, just like the vector version.
Test it on some data.  Be confident you got allocation right.
Write merge sort takes a std vector and calls those pointer-wrapped version of merge.  Test it with professors code.
Now you have a reliable pointer based merge test harness.
Take the outer merge sort, and make it take pointers as input and call pointer based merge.  Test with professors test harness.
Now take the inner merge function and replace it with one that uses pointers internally.
The basic idea is do it simple and correct first.  Then make it possible to replace a piece with something more efficient.  Test that your wrapping didn't break anything.  Thsn make that one piece faster.  And test again.
Writing single large complex optimized systems only works when the problem is trivial for you.

A: Your code is incorrect for multiple reasons:

*

*merge merges the halves of the input array in opposite directions. This does not work as both halves have been sorted in the same direction (increasing or decreasing) so the merge process should proceed from left to right from 0 to mid-1 and from mid to right.

*you always copy from input to output, so you do not merge the sorted halves, but the original halves.

*since you are expected to return a newly allocated array, you probably should not modify the argument array. You should allocate a temporary array for the sorted halves.

*supporting both ascending and descending order seems beyond the scope of your assignment.

Here is a modified version, using a less confusing convention for the upper index: using the index of the element after the last one.
void merge(int *array, int mid, int high, int *temp, bool output_asc) {
    int i = 0;
    int j = mid;
    int k = 0;
    if (output_asc) { //sort ascending
        while (i < mid) {
            if (j >= high || array[i] <= array[j]) {
                temp[k++] = array[i++];
            } else {
                temp[k++] = array[j++];
            }
        }
    } else { //sort descending
        while (i < mid) {
            if (j >= high || array[i] >= array[j]) {
                temp[k++] = array[i++];
            } else {
                temp[k++] = array[j++];
            }
        }
    }
    for (i = 0; i < k; i++)
        array[i] = temp[i];
}

void mergesort(int *array, int size, int *temp, bool output_asc) {
    if (size >= 2) {
        int mid = size / 2;
        mergesort(array, mid, temp, output_asc);
        mergesort(array + mid, size - mid, temp + mid, output_asc);
        merge(array, mid, size, temp, output_asc);
    }
}

int *mergesort(int *input, int size) {
    int *output = new int[size];
    int *temp = new int[size];
    for (int i = 0; i < size; i++)
        output[i] = input[i];
    mergesort(output, size, temp, true);
    delete[] temp;
    return output;
}


text:
Q: Adding node function to resolver attribute I am trying to define a custom Node.js function to a Sequelize query and I can't find the most efficient way to do it.
I want to add to the booksVersions a custom field that returns the value of a Node function. In this case I named the function translateTitle. What is the right way to implement it?
My resolver looks:
 function translateTitle(title) {
     //custom code
    return title_in_german;
 }

Query: {
        books: async (root, args, { models }) => {
            const options = {
                include: [
                    {
                        model: models.BooksVersions,
                        as: "booksVersions",
                        attributes: ["title",translateTitle("title")]
                    }
                ]
            }
            const Books = await models.Books.findAll(options);
            return {
                nodes: Books
            }
        },


text:
Q: leakage current of a 10uF MLCC compared with an aluminium decoupling capacitor I am trying to track down a ~10uA current leak in my circuit.
My PCB has this 10uF ceramic decoupling capacitor between 1.8V and GND.
I cannot see it's ESR value in the datasheet so I do not know what leakage current I should expect. I also cannot see a minimum voltage listed to check if it is suitable for 1.8V.
I am using a CurrentRanger, a multimeter and an oscilloscope to measure current. When I physically removed the capacitor, the current dropped 10uA.
The datasheet for the LIS3DH sensor that it is attached to, says it should be an aluminium capacitor.
What leakage current should I expect from this capacitor?
Any help is greatly appreciated.

A: I misread the question.  I had in mind that you wanted to replace an aluminum capacitor with an MLCC.
What you are considering is replacing an MLCC with an aluminum capacitor.
Don't.
The leakage of the aluminum capacitor is almost guaranteed to be higher.
ESR isn't what defines the leakage current.
ESR (equivalent series resistance) is like putting a resistor in series with an ideal capacitor, while leakage is like putting a resistor in parallel with an ideal capacitor.
The datasheet you linked gives an insulation resistance of 50 ohms F.  Take 50, divide by 10 microfarads (as farads) and that's the resistance of the insulation. That works out to 500000 ohms for your 10uF part.
At 1.8V, that's about 3.5 microamperes.
You need to find an MLCC with a higher insulation resistance.
The one I picked before for comparison says 100000 Mohm or 1000 ohms F, which ever is larger."  For a 10uF part, that'll be 100000 Mohm because the ohms F is smaller.  The leakage current is then far below 1uA.
You can reduce the leakage current by using a better MLCC.  Aluminum capacitors don't get much better.

Incorrect answer.  Leaving it here for the comparison of MLCC to aluminum capacitors.
Picking the datasheet for an aluminum capacitor at random, I find a maximum of 3 microamperes.  That's in the same ballpark as your 10 microamperes so it looks you have a reasonable measured value.
Picking a datasheet for a 10 microfarad MLCC capacitor at random, I don't find leakage directly given.  It does give a value for "insulating resistance," which I take to be related to leakage current.  At 100000 megaohm, the leakage will be lower than the aluminum part at any rated voltage.
The MLCC won't necessarily give you the same capacitance, though.  You may need to use a 20 uF or more rated part to guarantee the same capacitance at your operating voltage.  Ok, you are working at 1.8V, so the loss may be lower than usual.  You should still consider it, if only to look at the datasheet voltage derating curve and think "nah, doesn't matter."


text:
Q: Function of a random variable Here is a probability density function (PDF)
pdfq[q_] = C q^(4 n ν - 1) (1 - q)^(4 n μ - 1)

$$P_q(Q=q) = C q^{4 n\nu - 1} (1 - q)^{4 n \mu - 1}$$
I'd like to find the PDF of $l$ (noted $P_l(L=l)$), which is a function of $q$.
f[q_] = 2 q s

$$f(q)=2\cdot q\cdot s$$
What is the PDF of l?

Here is my try
I think $f(q)$ is an invertible, differentiable and continuously increasing function of $q$ and therefore:
$$P_l(L=l) = P_q(f^{-1}(l))\left|\frac{df^{-1}(l)}{dl}\right|$$
according to wiki, where $f^{-1}(..)$ is the inverse function of $f(..)$.
Calculating this with Mathematica gives:
In[1]:= pdfq[q_] =
 C E^(4 n s q ) q^(4 n ν - 1) (1 - q)^(4 n μ - 1)

Out[1]= C E^(4 n q s) (1 - q)^(-1 + 4 n μ) q^(-1 + 4 n ν)

In[2]:= f[q_] = 2 q s

Out[2]= 2 q s

In[3]:= Solve[l == f[q], q]

Out[3]= {{q -> l/(2 s)}}

In[4]:= finverse[l_] = l/(2 s)

Out[4]= l/(2 s)

In[5]:= Absdfinversedl[l] = Abs[Integrate[finverse[l], l]]

Out[5]= 1/4 Abs[l^2/s]

In[7]:= pdfl[l_] = pdfq[finverse[l]] Absdfinversedl[l]

Out[7]= 2^(-1 - 4 n ν) C E^(
 2 l n) (1 - l/(2 s))^(-1 + 4 n μ) (l/s)^(-1 + 4 n ν)
  Abs[l^2/s]

In[8]:= pdfl[0.5] /. C -> 1 /. n -> 1000 /. μ -> 0.02 /. ν ->
    0.05 /. s -> 0.1 // N

Out[8]= -1.554651720194871*10^527

But the result is obviously not correct as I get negative probability densities. What am I doing wrong? Does the problem have to do with my constant of integration $C$? Thanks a lot for your help.

A: First look into the documentation to see if your distribution is already defined.
If it is not, you can define your own distribution based on its PDF or CDF using ProbabilityDistribution.
dist=ProbabilityDistribution[ C q^(4 n Nu - 1) (1 - q)^(4 n Mu - 1), {q, 0, 1}, ...]

(This is incomplete, you need to define the ranges of the parameters)
Whatever ranges you variables and parameters are, you could test it by obtaining  Mean[dist] or PDF[dist,x] and checking that the there are no errors.
Now you have your original distribution, you want to transform it using  TransformedDistribution .
tDist = TransformedDistribution[2 q s, q \[Distributed] dist[Nu, Mu]]

Now the PDF of your new transformed distributions would be PDF[tDist,x]


text:
Q: How to understand the notion of a differential of a function In elementary calculus (and often in courses beyond) we are taught that a differential of a function, $df$ quantifies an infinitesimal change in that function. However, the notion of an infinitesimal is not well-defined and is nonsensical (I mean, one cannot define it in terms of a limit, and it seems nonsensical to have a number that is smaller than any other real number - this simply doesn't exist in standard analysis). Clearly the definition $$df=\lim_{\Delta x\rightarrow 0}\Delta f =f'(x)dx$$ makes no sense, since, in the case where $f(x)=x$ we have that $$ dx=\lim_{\Delta x\rightarrow 0}\Delta x =0.$$
All of this leaves me confused on how to interpret expressions such as $$df=f'(x)dx$$ Should it be seen simply as a definition, quantifying the first-order (linear) change in a function about a point $x$? i.e. a new function that is dependent both on $x$ and a finite change in $x$, $\Delta x$, $$df(x,\Delta x):=f'(x)\Delta x$$ then one can interpret $dx$ as $$dx:=dx(x,\Delta x)= \Delta x$$ such that $$\Delta f=f'(x)dx+\varepsilon =df +\varepsilon$$ (in which $\varepsilon$ quantifies the error between this linear change in $f$ and the actual change in $f$, with $\lim_{\Delta x\rightarrow 0}\varepsilon =0$).
I feel that there must be some sort of rigorous treatment of the notion of differentials since these kind of manipulations are used all the time, at least in physics?!
I've had some exposure to differential geometry in which one has differential forms, in particular $1-$forms which suggestively notationally "look like" differentials, for example $$\omega =df$$ but as I understand it these are defined as linear maps, members of a dual space to some vector space, $V$, which act on elements of $V$, mapping them to real numbers. Furthermore, the basis $1-$forms are suggestively written as what in elementary calculus one would interpret as an infinitesimal change in x, $dx$. But again, this is simply symbolic notation, since the basis $1-$forms simply span the dual space and are themselves linear maps which act on elements of $V$.
I've heard people say that differential forms make the notion of a differential of a function mathematically rigorous, however, in my mind I can't seem to reconcile how this is the case, since at best they specify the direction in which the differential change in a function occurs, via $$df(v)=v(f)$$ (since $v(f)$ is the directional derivative of a function $f$ along the vector $v$).
If someone could enlighten me on this subject I'd really appreciate it.

A: A differential is a $1$-form. At each point a $1$-form gives a linear functional in a tangent space, and the level sets of a linear functional are parallel affines subspaces. Now $df$ in $\mathbb R^3$  gives a sort of a ruling in each tangent. For a given $p$, the level sets of $df_p$ are what we can see if we zoom in on the level sets of $f$ in a neighborhood of $p$, like in the picture bellow.
$\hskip1in$
where on the left should be the level sets of $f$.

A: I think that the biggest problem comes from the subtlety of the notation.
First of all, there is a general formula for the derivative, and that is usually represented as $df\over dx$ or $f^\prime(x)$.
There is also the notion of a derivative at a point $x_0$, and that is represented as ${df \over dx}|_{x=x_0}$,  When you see the manipulation of differentials, it is usually in this context.  (And it is all the more confusing because, when differentials are used by themselves, there is never any mention of the $x_0$ that links $dy$ and $dx$.)
For instance, take $y \equiv f(x) = x^2$ and  $x_0 = 0$, and consider the discrete sequence $x_n = {1 \over 2^n}$.  (We see that $x_n \rightarrow 0.)  $
For the  $k$th term of this sequence, we can (exercise) make the finite difference $\Delta x_k = x_{k+1} - x_k = -{{1}\over {2^k}}$. Then (another exercise)  $\Delta y_k = -{3\over 4}\cdot {1\over{2^{2k}}}$.
We see that $\Delta y$ and $\Delta x$ both go to 0 as $k\rightarrow \infty$, but the above exercise shows that the speed of $\Delta y$ toward 0 is dictated by $\Delta x$.  So, it makes sense to split $dx$ and $dy$ apart, so long as we keep track of how they are related at the point at which $dy/dx$ is evaluated.
Hope that made sense--I kind of think that I might be rambling.

A: Differentials are not really the same as differential 1-forms, this is something that I think confuses a lot of people because the notation is the same despite them being fundamentally different mathematical objects. This can be seen best when looking at how $\iint dx\wedge dx =0\neq\iint dxdx$ despite $\iint dx\wedge dy = \iint dxdy$
Not thinking of differential 1-forms as differentials requires a new understanding of them. Differential forms are mathematical objects that fundamentally deal with space and geometry which is why a differential 1-form can be thought of as the level sets of a vector and a differential 2-form can be thought of as a signed area. All the differentials in the differential-forms are (The dx part in fdx) are bases of the co-vector space of differential forms.
Using this framework we can see that the exterior derivative of a function is just how much a change in the direction of one of its coordinates effects each basis in this co-vector space.
A quick example would be
$$f(x)=x
\\ \text{Then taking the exterior derivative}
\\ df=f_xdx=dx$$
All this is saying is that as you change the function f in the x-direction in the vector space f is defined in the dx basis in its co vector space changes by the same amount, which in this case is the classical single variable derivative of the function f.
So instead of thinking of differential 1-forms as being tiny changes in variables think about them as bases in a co-vector space that lives alongside the vector space in which a function is defined.


text:
Q: Using dynamically generated type for variable declaration and assignment Following this question, it is possible to create a type and an instance form it dynamically like this:
var type = typeof(AnimalContext<>).MakeGenericType(a.GetType());
var a_Context = Activator.CreateInstance(type);

Great.
However, what I want to do instead of creating an instance of a determined type with Activator.CreateInstance(type);is to use a dynamic created type to declare a variable, and assign an instance to my dynamically created type.
Kind of:
myDynamicallyCreatedType variableName = figuredTypeInstace;

But I cannot use the created type(var type = typeof(AnimalContext<>).MakeGenericType(a.GetType()); for declarations. Is that possible?
Edit:
Short scenario explanation where the need came up. I need to call a method that will be called from a "topManager", this topManager holds the respective instance of the types type1Manager and type2Manager that implement the same base interface IMyInterface method ImplementedMethod.
What I am trying to do, could be solved with ifs, like this:
private int HandleInstance(Type itemType, //other args) {
    if (itemType == Type.type1) {
       topManagerInstance.manager1Instance.ImplementedMethod(//args):
    }
    elseif (itemType == Type.type2) {
       topManagerInstance.manager2Instance.ImplementedMethod(//args):
    }
    ...not meaningful code
{

But, I was wondering if it could be solved handling types to avoid the ifs, like (caps used to spot the key of the question out, not to shout):
private int HandleInstance(Type itemType, //other args) {
    Type managerType = itemType == Type.type1 ? typeof(manager1Type) :
    typeof(manager2Type);
    Type[] managerTypeArray = { managerType, typeof(int) };
    var myDynamicallyCreatedType = typeof(IMyInterface<,>).MakeGenericType(managerTypeArray);

    //KEY OF THE QUESTION. THIS IS WHAT I AM ASKING FOR
    //assign created variable to dynamic created type to call respective method
    myDynamicallyCreatedType variableName = topManagerInstance.type1Manager;
    //base type. any type1ManagerType or type2ManagerType to be assigned, as
    //they inherit from the same IMyInterface<,>, and the type created is
    //generic
    variableName.ImplementedMethod(//args):
}

A: It seems like you're just looking to map an enum value to a function call in a specific implementation. One way to do that is to have a factory class that handles it with a Dictionary used as a map. For example:
Given a setup something like this:
// The enum you use for mapping
public enum Thing
{
    Foo,
    Bar
}

// The various implementations...
public interface ISomeInterface
{
    void SomeMethod();
}

public class Foo : ISomeInterface
{
    public void SomeMethod() => Console.WriteLine("Foo method!");
}

public class Bar : ISomeInterface
{
    public void SomeMethod() => Console.WriteLine("Bar method!");
}

Now you could have a factory that looks like this:
public class MyThingFactory
{
    private Dictionary<Thing, ISomeInterface> _registry;

    public MyThingFactory()
    {
        _registry = new Dictionary<Thing, ISomeInterface>
        {
            {Thing.Foo, new Foo()},
            {Thing.Bar, new Bar()},
        };
    }

    public void RunMethod(Thing thing)
    {
        if(!_registry.TryGetValue(thing, out var item))
        {
            throw new ArgumentOutOfRangeException(nameof(thing));
        }

        item.SomeMethod();
    }
}

And call it like this:
// You may want to make this static for performance reasons since you won't recreate
// the dictionary every time
var factory = new MyThingFactory();

factory.RunMethod(Thing.Foo);
factory.RunMethod(Thing.Bar);

//Output:
//Foo method!
//Bar method!


text:
Q: error building ndk for opencv nonfree modules I've been trying to build the opencv nonfree libraries for a while,
when calling the ndk-build function it aborts with this error

Android NDK: ERROR:jni/Android.mk:opencv_java: LOCAL_SRC_FILES points to a missing file
Android NDK: Check that /03-Projects//WorkSpace//OpenCV-2.4.11-android-sdk//OpenCV-android-sdk//sdk//native//jni//../libs/armeabi/libopencv_java.so exists or that its path is correct
C:/android-ndk-r11c/build//../build/core/prebuilt-library.mk:45: ***
Android NDK: Aborting.  Stop.

I've followed this tutorial:Tutorial - part 1: Using OpenCV Nonfree Module (SIFT, SURF) in Android NDK Projects
I've also tried the solution provided here by Kornel: Kornel's solution for building nonfree
Here's my files hierarchy:   app -> src -> main -> jni
and here's my Android.mk file
LOCAL_PATH  := $(call my-dir)
OPENCV_PATH := D:\\03-Projects\\WorkSpace\\OpenCV-2.4.11-android- sdk\\OpenCV-android-sdk\\sdk\\native\\jni

include $(CLEAR_VARS)
OPENCV_INSTALL_MODULES := on
OPENCV_CAMERA_MODULES  := off
include $(OPENCV_PATH)\\OpenCV.mk

LOCAL_C_INCLUDES :=             \
  $(LOCAL_PATH)             \
  $(OPENCV_PATH)/include

LOCAL_SRC_FILES :=              \
  nonfree_init.cpp          \
  sift.cpp                  \
  surf.cpp

LOCAL_MODULE := nonfree
LOCAL_CFLAGS := -Werror -O3 -ffast-math
LOCAL_LDLIBS := -llog -ldl

include $(BUILD_SHARED_LIBRARY)

I'm trying to build the ndk with APP_ABI set for both:

x86 armeabi-v7a

A: Problem Solved:
it turns out that I'm building the ndk project inside a folder under the "main" of an android studio project, which for some reasons wasn't working.
 I moved the folder into into another directory not belongs to any android project and problem was solved.
although I've faced some other different problems later, but all were also sloved, and I'll soon provide a step-by-step solution on how to build nonfree modules for newer versions of opencv than the mentioned in the tutorials above.


text:
Q: How to throw different errors in a Promise function? For testing I want that all code is coveraged and I want to reject different self written errors for each of the steps in this Promise function.
function convertToXML(b64DataPara) {

return new Promise(function(resolve, reject) {

    var b64Data = b64DataPara;

    if(b64Data === '' || b64Data === undefined){
        return reject(new Error(errorMessages.B64Undefined));
    }

    if(typeof b64Data === 'number'){
        return reject(new Error(errorMessages.StringNeededNotNumber));
    }

    // Decode base64 (convert ascii to binary)

    var strData = atob(b64Data);

    if (strData === undefined){
        return reject(new Error(errorMessages.invalidCharacterInB64));
    }

    // Convert binary string to character-number array
    var charData = strData.split('').map(function(x){return x.charCodeAt(0);});

    // Turn number array into byte-array
    var binData = new Uint8Array(charData);

    // Decompress data
    var data = pako.inflate(binData);

    // Convert gunzipped byteArray back to ascii string:
    var xmlData = String.fromCharCode.apply(null, new Uint16Array(data));

    resolve(xmlData);

})

I have two ideas:

*

*Wrap each step with an if / else

*Put all the code inside the Promise function in a try-catch and handle in the catch block all errors with if else and so on.

Both ideas seem not professional to me. So I am wondering whats the best / elegant way to do this. Or do you think all substeps should be inside its own Promise function?


text:
Q: Trying to change the style in "Select an Option" dropdown of Woocommerce checkout I am trying to change the "Select an option" text's style, of WooCommerce checkout page, in bolder because it is faded and I get an accessibility error when scanned with WAVE.
I have tried this CSS but nothing changes, could you indicate me where am I mistaking?
Select a category {
  color: #cccccc

}
span.select2-selection.select2-selection--single {
  color: #000000;
}
span.select2-selection__placeholder {
  font-family: Roboto;
  font-size: 16px;
  line-height: 18px;
  font-weight: 400;
  font-style: normal;
  color: #cccccc;
  background-color: #ffffff;
}

Or if there is an other CSS to do it?
The site is www.defkalionsa.gr

A: you can try the below css:
.select2-selection__placeholder {
    font-weight:bold; /* for your "bolder" request" */
    color:black; /* better than gray for accessibility */
}

if that does not work, you should clear browser cache, and check if other style declarations are taking precedence.
You can temporarily add "!important" to overwrite other declarations.
.select2-selection__placeholder {
    font-weight:bold!important;
    color:black!important;
}


text:
Q: createShareIntent with Picasso library I open images fullscreen from a productDetails activity. This new fullScreeActivity is working fine in the first try. Problem is happening when I press android native back button to return to productDetails and so try to open fullScreeActivity with the same image (just as if I´d like to see the image full again). The app crashes.
When I remove createShareIntent() and Picasso codes it works fine. So I suppose this is the cause of the problem. Is there a better way of doing this?
productDetails.java
ImageView arquivo;
private static final String TAG_ARQUIVO = "arquivo";
String imagem;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.no_image_available)
.showImageForEmptyUri(R.drawable.no_image_available)
.cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();

arquivo = (ImageView) findViewById(R.id.arquivo);

Intent i = getIntent();
imagem = i.getStringExtra(TAG_ARQUIVO);

ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imagem, arquivo, defaultOptions);

arquivo.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        Intent iFullImg = new Intent(getApplicationContext(), FullScreenActivity.class);
        iFullImg.putExtra(TAG_ARQUIVO, imagem);
        startActivity(iFullImg);

    }
});
}

fullScreenActivity.java
PhotoViewAttacher mAttacher;
private ShareActionProvider mShareActionProvider;
private static final String TAG_ARQUIVO = "arquivo";
String path;
File file;

ImageView fullImg;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_full_screen);

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.no_image_available)
.showImageForEmptyUri(R.drawable.no_image_available)
.cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

fullImg = (ImageView) findViewById(R.id.fullImage);

Intent i = getIntent();
path = i.getStringExtra(TAG_ARQUIVO);

ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(path, fullImg, defaultOptions);

mAttacher = new PhotoViewAttacher(fullImg);

Picasso.with(this).load(path).into(fullImg, new Callback(){
    @Override
    public void onError() {

    }

    @Override
    public void onSuccess() {
        createShareIntent();
    }
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.full_screen, menu);

  MenuItem item = menu.findItem(R.id.menu_item_share);
  mShareActionProvider = (ShareActionProvider) item.getActionProvider();

  return true;
}

private void createShareIntent() {

Uri bmpUri = getLocalBitmapUri(fullImg);

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
mShareActionProvider.setShareIntent(shareIntent);

}

public Uri getLocalBitmapUri(ImageView imageView) {

Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
   bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
   return null;
}

Uri bmpUri = null;
try {
    File file =  new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
    file.getParentFile().mkdirs();
    FileOutputStream out = new FileOutputStream(file);
    bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
    out.close();
    bmpUri = Uri.fromFile(file);
} catch (IOException e) {
    e.printStackTrace();
}
  return bmpUri;
}

Logcat:
07-31 05:22:01.395: E/AndroidRuntime(1019): FATAL EXCEPTION: main
07-31 05:22:01.395: E/AndroidRuntime(1019): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.habitodigital.handy/com.habitodigital.handy.FullScreenActivity}: java.lang.NullPointerException
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.os.Looper.loop(Looper.java:137)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.ActivityThread.main(ActivityThread.java:4745)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at java.lang.reflect.Method.invokeNative(Native Method)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at java.lang.reflect.Method.invoke(Method.java:511)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at dalvik.system.NativeStart.main(Native Method)
07-31 05:22:01.395: E/AndroidRuntime(1019): Caused by: java.lang.NullPointerException
07-31 05:22:01.395: E/AndroidRuntime(1019):     at com.habitodigital.handy.FullScreenActivity.createShareIntent(FullScreenActivity.java:99)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at com.habitodigital.handy.FullScreenActivity.access$0(FullScreenActivity.java:91)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at com.habitodigital.handy.FullScreenActivity$1.onSuccess(FullScreenActivity.java:74)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at com.squareup.picasso.RequestCreator.into(RequestCreator.java:514)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at com.habitodigital.handy.FullScreenActivity.onCreate(FullScreenActivity.java:66)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.Activity.performCreate(Activity.java:5008)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
07-31 05:22:01.395: E/AndroidRuntime(1019):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
07-31 05:22:01.395: E/AndroidRuntime(1019):     ... 11 more

A: After some modifications and simplifications that I did, the NPE was solved.
public class FullScreenActivity extends Activity {

PhotoViewAttacher mAttacher;
ShareActionProvider mShareActionProvider;
private static final String TAG_ARQUIVO = "arquivo";
String path;
File file;
Intent shareIntent;
ImageView fullImg;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_full_screen);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    fullImg = (ImageView) findViewById(R.id.fullImage);

    Intent i = getIntent();
    path = i.getStringExtra(TAG_ARQUIVO);

    Picasso.with(FullScreenActivity.this).load(path).into(fullImg);
    mAttacher = new PhotoViewAttacher(fullImg);

    Uri bmpUri = getLocalBitmapUri(fullImg);

    shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("image/*");
    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.full_screen, menu);

    MenuItem item = menu.findItem(R.id.menu_item_share);
    mShareActionProvider = (ShareActionProvider) item.getActionProvider();
    if (mShareActionProvider != null) {
        mShareActionProvider.setShareIntent(shareIntent);
    }
    return true;
}

public Uri getLocalBitmapUri(ImageView imageView) {

    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;
    if (drawable instanceof BitmapDrawable){
       bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
       return null;
    }

    Uri bmpUri = null;
    try {
        File file =  new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

Thanks for the attention.


text:
Q: Документирование кода метками Насколько хорошей практикой является документирование кода метками? В каких ситуациях стоит её использовать?
К примеру, если надо акцентировать внимание в алгоритме:
special_case:
if (cond) {
  ...
  return true;
}

usual_path:
return false;

Из плюсов:

*

*меньше символов;

*можно написать в начале строки перед кодом с более простым синтаксисом, чем /* */.

Из минусов:

*

*только короткие фразы;

*предупреждения компиляторов.

A: Довольно неожиданное предложение по использованию меток и как уже было упомянуто, такое действие будет порождать предупреждения компилятора со всеми вытекающими. Его придётся подавлять, чтобы не отвлекало внимание от других проблем, или вовсе не блокировало сборку при наличии опции "treat warning as an error". Но в таком случае этот тип предупреждений (пусть и редкий в наши дни) можно пропустить в другом коде, где "метки используются как метки, а не альтернатива комментариям".
Вообще, в современном C++ для указания на наиболее вероятную ветвь ветвления стоит использовать атрибуты [[likely]], [[unlikely]]. Атрибуты не только могут быть подспорьем документированию кода, но и дадут подсказку компилятору, чтобы сделать код более эффективным.
if (cond) [[unlikely]] {
  ...
  return true;
}

return false;


text:
Q: Spring boot entityManager не строит таблицы БД Application properties:

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/post
spring.datasource.sql-script-encoding=UTF-8
spring.datasource.username = *******
spring.datasource.password = *******

# JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)
spring.jpa.database-platform = org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto = create
spring.jpa.generate-ddl = true
spring.jpa.show-sql = false

@EnableAsync
@Configuration
@SpringBootApplication
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class AppConfig extends WebMvcConfigurerAdapter {
      private static final Logger log =
        LoggerFactory.getLogger(AppConfig.class);
        private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
           {"classpath:/static/",
            "classpath:/public/","classpath:/templates/"};

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {

           return (container -> {

           ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED,
           "/error/401/");
           ErrorPage error403Page = new ErrorPage(HttpStatus.FORBIDDEN,
           "/error/403/");
           ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND,
           "/error/404/");
           ErrorPage error500Page = new
           ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500/");
           ErrorPage registrationException = new
           ErrorPage(RegistrationException.class,
           "/error/registrationPageError/");

            container.addErrorPages(error401Page, error403Page, error404Page,
            error500Page);
            });
           }

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
      Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      connector.setScheme("http");
      connector.setSecure(false);
      connector.setPort(33950);
      connector.setRedirectPort(33443);

        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };

        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }

     @Bean
     public LocalContainerEntityManagerFactoryBean entityManagerFactory
     (DataSource dataSource,JpaVendorAdapter jpaVendorAdapter){

        LocalContainerEntityManagerFactoryBean entityManagerFactory
                        = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setDataSource(dataSource);
        entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
        entityManagerFactory.setPackagesToScan("ua.kiev.dobrobutZahyst");

        return entityManagerFactory;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }
    }

    @Bean
    public ShaPasswordEncoder getShaPasswordEncoder(){
        return new ShaPasswordEncoder();
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text","plain", Charset.forName("utf-8"))));
        converters.add(stringConverter);
    }

    @Bean
    public Gson gson(){
        final GsonBuilder gsonBuilder = new GsonBuilder();

        gsonBuilder.registerTypeAdapter(InputPost.class, new InputPostGsonConverter());
        gsonBuilder.registerTypeAdapter(OutputPost.class, new OutputPostGsonConverter());
        gsonBuilder.registerTypeAdapter(CorporationPost.class, new CorporationPostGsonConverter());
        gsonBuilder.registerTypeAdapter(File.class, new FileGsonConverter());
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();

        return gsonBuilder.create();
    }

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

При старте приложения построение таблиц пропускается и стартует приложение. Exception никакой не выскакивает. Подскажите, пожалуйста, что делать?


text:
Q: css image overlay on background image so i am trying to get an overlay to work on my website, i've been watching a tutorial, but now i have gotten to a point where i don't know what i'm doing wrong.

  <link rel="stylesheet" href="css/venues.css">

 Places we've played.

        Bar 42

        The Prince Albert

and the css is..
.alt-section{
  background-color: #e6e6e6;
  margin: 0 auto;
}

.alt-section h2{
  padding:50px;
  color: #e1c184;
  font-family: Spliffs;
  text-align: center;
  font-size: 35;
}

.alt-section a{
  font-family: sans-serif;
  padding:10px;
  font-size: 18px;
  text-decoration: none;
  color: #cd9732;
}

.alt-section a:hover{
  color: #e1c184;
}

.thumb-container{
  max-width: 960px;
  margin: 0px auto;
  padding-bottom: 100px;
  overflow: hidden;

}

.thumb-unit{
  display:block;
  width: 150px;
  float:left;
  position: relative;
  height: 150px;

  background-image: url(http://i.imgur.com/3VTqQ8M.jpg);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}

.thumb-overlay{
  position:absolute;
  top:100%;
  left:0px;
  right:0px;
  bottom:null;
  height:100%;
  background:rgba(205,151,50,0.5);

}

.thumb-overlay:hover{
  position:absolute;
  top:0%;
  left:0px;
  right:0px;
  bottom:null;
  background:rgba(205,151,50,0.5);
  transition: linear;
  transition-duration: 0.5s;

}

The youtube video has got me up to a point where they have completed it but i am still stuck on this. https://www.youtube.com/watch?v=ygvo1_kqVUg
So my actuall problem is to do with the size of a hitbox on an anchor tag i cant seem to increase the size so when i hover over it the overlay will pop up.
I have turned the overflow back to visible so you can see my problem, but when i scroll over the photo the overlay will not pop up its only when i hover over the writing will it then come up.

A:

#element-with-background-image {
    background-image:
        linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),
 url("https://s-media-cache-ak0.pinimg.com/564x/b9/ea/bd/b9eabd96be305e1ee9fe5b6ca3fea673.jpg");
}

#color-overlay {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   background-color: black;
   opacity: 0.6;

   ...


text:
Q: {"Message":"Authorization has been denied for this request."} In Umbraco 7.2.6 When I set site's Culture and Host names, I got the following Error Message in  Umbraco 7.2.6.
{"Message":"Authorization has been denied for this request."}
Please give a solution for this issue.

A: I hit this error myself.
My problem was having registered the webapi route manually like this in my OWIN startup.
// register default api route
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Apparently this will cause umbraco to behave the way described above.
My solution was to remove the owin registration and cave in and conform to the setup recommended by umbraco: https://our.umbraco.org/documentation/reference/routing/webapi/
And there by changing my api urls from
mysite.com/api/products/all

to
mysite.com/umbraco/api/products/all


text:
Q: How can I access values created from my sql in a seperate javascript file? Is json one of the options? I am new to node.js I have sql values created in my reports.js file. When I console.log them the correct info show up. I am trying to access these values in my reports.handlebars and save them in an array so I can use it with google charts. Please no php. Below is my reports.js file:
function get_reports(callback) {
  var sql = 'select created_by, count(id) as value from charts group by created_by';
  pool.query(sql, function(error, results, fields) {
    callback(results);
  });
}

router.get('/', (req, res, next) => {
  get_reports(function(data) {
    console.log(data);
    res.status(200).render('reports', {data: data});
  });
});

module.exports = router;

and here is part of my reports.handlebars:

var obj = JSON.parse(data);
    console.log(obj.value);

      function drawChart() {

        // Create the data table.
        var data2 = new google.visualization.DataTable();
            data2.addColumn('string', 'CreatedBy');
            data2.addColumn('number', 'Awards');
        for(var i=0; i < arr.length; i++){
            data2.addRows([arr[i], arr[i+1]]);
        }

I'm trying to access the values that are sent in my js file.


text:
Q: How should I maintain Intel microcode? I have installed ubuntu-drivers-common on my minimal Install of Ubuntu 16.04.
Should I run "ubuntu-drivers autoinstall" after any kernel update?
How should I maintain this package?

A: The intel-microcode package (which contains the microcode update data) will refresh the initramfs by itself when it is updated.  You don't have to do anything.
You will get the new microcode automatically the next time you reboot, as the microcode updated is (nowadays) only applied during boot, for several technical reasons.


text:
Q: How to recover data stored in file format? I had a ton of photos on my laptop I transferred from my phone. I tried to sort the photos as 'faceless pictures' and 'face pictures' by using python (openCV cascade classifier). I made two folders in my D: drive: 'Face pics' and 'Faceless pics'. But in the destination path in my code, I mistakenly wrote the wrong address. Since the destination folder didn't exist in the address I typed, I saw that my photos were saved in File format in the destination I previously inputted. I don't know what a 'File' format is and how to work with it. I have attached a picture to better explain my conundrum. I want to recover the photos, if possible. Any advice is appreciated.
Below is the code I used:
import numpy as np
import cv2
import os
from PIL import Image
import matplotlib.pyplot as plt
import shutil

source = 'D:\\User\\Pictures\\'
dest1 = 'D:\\User\\Faceless pics\\'
dest2 = 'D:\\User\\Face pictures\\' #Here, by mistake, I used 'D:\\User\\Face pics\\'. I should have used pictures instead of pics. The code did not make a new folder; instead it dumped all the data into a single file whose type is 'File' and not 'Text' or 'Folder'

sourcedirs = os.listdir(source)[:-3]

face_cascade = cv2.CascadeClassifier('C:\Anaconda\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')

for x in sourcedirs:
    for y in os.listdir(source + x):
        if y[-3:]=='JPG':
            style = Image.open(source + x + '\\' + y)
            style = np.asarray(style)
            plt.imshow(style)
            gray = cv2.cvtColor(style, cv2.COLOR_BGR2GRAY)
            faces = face_cascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(10, 10),
                flags = cv2.CASCADE_SCALE_IMAGE
            )
            if len(faces)>0:
                shutil.move(source + x + '\\' + y, dest2)
            else:
                shutil.move(source + x + '\\' + y, dest1)

The picture is the properties tab of the file from which I want to recover my data


text:
Q: I want to call the object in the data.json file I want to call the object in the data.json file

as an example in my getData.js:
var data = JSON.parse(data.json);
alert(data['name']);

How can I do that?

A: This is how you get a value from a JSON object, I used a dummy JSON object from jsonplaceholder https://jsonplaceholder.typicode.com/users

dummyData = [
{
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "Sincere@april.biz",
address: {
street: "Kulas Light",
suite: "Apt. 556",
city: "Gwenborough",
zipcode: "92998-3874",
geo: {
lat: "-37.3159",
lng: "81.1496"
}
},
phone: "1-770-736-8031 x56442",
website: "hildegard.org",
company: {
name: "Romaguera-Crona",
catchPhrase: "Multi-layered client-server neural-net",
bs: "harness real-time e-markets"
}
},
{
id: 2,
name: "Ervin Howell",
username: "Antonette",
email: "Shanna@melissa.tv",
address: {
street: "Victor Plains",
suite: "Suite 879",
city: "Wisokyburgh",
zipcode: "90566-7771",
geo: {
lat: "-43.9509",
lng: "-34.4618"
}
},
phone: "010-692-6593 x09125",
website: "anastasia.net",
company: {
name: "Deckow-Crist",
catchPhrase: "Proactive didactic contingency",
bs: "synergize scalable supply-chains"
}
},
{
id: 3,
name: "Clementine Bauch",
username: "Samantha",
email: "Nathan@yesenia.net",
address: {
street: "Douglas Extension",
suite: "Suite 847",
city: "McKenziehaven",
zipcode: "59590-4157",
geo: {
lat: "-68.6102",
lng: "-47.0653"
}
},
phone: "1-463-123-4447",
website: "ramiro.info",
company: {
name: "Romaguera-Jacobson",
catchPhrase: "Face to face bifurcated interface",
bs: "e-enable strategic applications"
}
},
{
id: 4,
name: "Patricia Lebsack",
username: "Karianne",
email: "Julianne.OConner@kory.org",
address: {
street: "Hoeger Mall",
suite: "Apt. 692",
city: "South Elvis",
zipcode: "53919-4257",
geo: {
lat: "29.4572",
lng: "-164.2990"
}
},
phone: "493-170-9623 x156",
website: "kale.biz",
company: {
name: "Robel-Corkery",
catchPhrase: "Multi-tiered zero tolerance productivity",
bs: "transition cutting-edge web services"
}
},
{
id: 5,
name: "Chelsey Dietrich",
username: "Kamren",
email: "Lucio_Hettinger@annie.ca",
address: {
street: "Skiles Walks",
suite: "Suite 351",
city: "Roscoeview",
zipcode: "33263",
geo: {
lat: "-31.8129",
lng: "62.5342"
}
},
phone: "(254)954-1289",
website: "demarco.info",
company: {
name: "Keebler LLC",
catchPhrase: "User-centric fault-tolerant solution",
bs: "revolutionize end-to-end systems"
}
},
{
id: 6,
name: "Mrs. Dennis Schulist",
username: "Leopoldo_Corkery",
email: "Karley_Dach@jasper.info",
address: {
street: "Norberto Crossing",
suite: "Apt. 950",
city: "South Christy",
zipcode: "23505-1337",
geo: {
lat: "-71.4197",
lng: "71.7478"
}
},
phone: "1-477-935-8478 x6430",
website: "ola.org",
company: {
name: "Considine-Lockman",
catchPhrase: "Synchronised bottom-line interface",
bs: "e-enable innovative applications"
}
},
{
id: 7,
name: "Kurtis Weissnat",
username: "Elwyn.Skiles",
email: "Telly.Hoeger@billy.biz",
address: {
street: "Rex Trail",
suite: "Suite 280",
city: "Howemouth",
zipcode: "58804-1099",
geo: {
lat: "24.8918",
lng: "21.8984"
}
},
phone: "210.067.6132",
website: "elvis.io",
company: {
name: "Johns Group",
catchPhrase: "Configurable multimedia task-force",
bs: "generate enterprise e-tailers"
}
},
{
id: 8,
name: "Nicholas Runolfsdottir V",
username: "Maxime_Nienow",
email: "Sherwood@rosamond.me",
address: {
street: "Ellsworth Summit",
suite: "Suite 729",
city: "Aliyaview",
zipcode: "45169",
geo: {
lat: "-14.3990",
lng: "-120.7677"
}
},
phone: "586.493.6943 x140",
website: "jacynthe.com",
company: {
name: "Abernathy Group",
catchPhrase: "Implemented secondary concept",
bs: "e-enable extensible e-tailers"
}
},
{
id: 9,
name: "Glenna Reichert",
username: "Delphine",
email: "Chaim_McDermott@dana.io",
address: {
street: "Dayna Park",
suite: "Suite 449",
city: "Bartholomebury",
zipcode: "76495-3109",
geo: {
lat: "24.6463",
lng: "-168.8889"
}
},
phone: "(775)976-6794 x41206",
website: "conrad.com",
company: {
name: "Yost and Sons",
catchPhrase: "Switchable contextually-based project",
bs: "aggregate real-time technologies"
}
},
{
id: 10,
name: "Clementina DuBuque",
username: "Moriah.Stanton",
email: "Rey.Padberg@karina.biz",
address: {
street: "Kattie Turnpike",
suite: "Suite 198",
city: "Lebsackbury",
zipcode: "31428-2261",
geo: {
lat: "-38.2386",
lng: "57.2232"
}
},
phone: "024-648-3804",
website: "ambrose.net",
company: {
name: "Hoeger LLC",
catchPhrase: "Centralized empowering task-force",
bs: "target end-to-end models"
}
}
]

console.log(dummyData[2].name); // Clementine Bauch

alert(dummyData[5].company.name) // Considine-Lockman

A: Nodejs
You need to require fs which is library help to work with files. Then read the file.

    var fs = require('fs');
    var obj;
    fs.readFile('data.json', 'utf8', function (err, data) {
     if (err) throw err;
     obj = JSON.parse(data);
     });

Using jQuery
http://api.jquery.com/jQuery.getJSON/
$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});


text:
Q: Qt android ndk - app crashes I've been recently trying to make some very simple app in Qt, and yesterday it used to work correctly on both Desktop and Android  (using android ndk, I know it's not good to make android apps in c++, but I just want to try).
Today, out of nowhere, application output says sth like this:
The only thing I've found was cleaning app's cache and data, restarting phone, rebuilding, none of these things worked

A: A Qt app has an array of used .so library names, somewhere in the resources.
On start-up, it loads all these .so libraries (via loadLibrary()).
The order in which the libraries are loaded is important: functions cannot
reference functions defined in libraries that have not yet been loaded. So implementing a circular dependency is tricky.
From the logs I see that
some function in libszachy_android_1.so (is it the right name? it's a bit strange) invokes srand() that has not yet been loaded; maybe, it is mentioned later in the load list, but loadLibrary() has no idea about the planned future.
Therefore, you get this.
If your code worked yesterday, you likely have made some changes. If you use version control, you likely can compare the today's and yesterday's versions and see the difference. Maybe, you have inserted a forward reference (in the load list sense). OTOH, sometimes both Eclipse and make cannot detect that the source has changed and make incorrect builds (I did observe this, but cannot reproduce). Did you try to uninstall the app from the phone? Did you try to remove all existing .so files in the build directories (rm *.so)?
Maybe, one of your .so modules is broken: sometimes an object is generated despite of errors and it may get used in subsequent builds (at least this is how I can explain the build glitches).
Maybe, you have no memory left on the device, and the .so could not be unpacked correctly.
I suggest examining the application directory with adb shell on a rooted device.
PS you posted a screenshot that is barely readable. Please replace it with the relevant portion of the adb logcat output (I hope you know how to use it; if not, the first thing to do is to learn adb logcat and adb shell).


text:
Q: capifony no such file or directory on cap deploy i've the following easy capifony script to copy the local project to my server:
set :application, "project"
set :domain,      "88.88.88.88"
set :deploy_to,   "/var/www/project"
set :app_path,    "app"
set :user,        "root"

set   :scm,              :git
set   :repository,       "file:///Users/berlin/vagrant-workspace/essen"
set   :deploy_via,       :capifony_copy_local
set   :use_composer,     true
set   :use_composer_tmp, false
set   :copy_vendors,     true

role  :web,           domain
role  :app,           domain, :primary => true

set   :use_sudo,      false
set   :keep_releases, 3

logger.level = Logger::MAX_LEVEL

This is my output for cap:deploy:setup:
  * 2014-10-06 21:55:38 executing `deploy:setup'
  * executing "mkdir -p /var/www/project /var/www/project/releases /var/www/project/shared"
    servers: ["88.88.88.88"]
    [88.88.88.88] executing command
    command finished in 119ms
  * executing "chmod g+w /var/www/project /var/www/project/releases /var/www/project/shared"
    servers: ["88.88.88.88"]
    [88.88.88.88] executing command
    command finished in 144ms

And then i can't deploy because of a missing folder. It looks like that the script doesn't create the folder inside releases.
cap deploy
  * 2014-10-06 21:55:59 executing `deploy'
  * 2014-10-06 21:55:59 executing `deploy:update'
 ** transaction: start
  * 2014-10-06 21:55:59 executing `deploy:update_code'
    triggering before callbacks for `deploy:update_code'
--> Updating code base with capifony_copy_local strategy
--> Using Copy Local Strategy
    executing locally: "git ls-remote file:///Users/berlin/vagrant-workspace/project HEAD"
    command finished in 12ms
  * getting (via checkout) revision a7ba07ac38fee4b5375c6d383886a906c1a551d5 to /var/folders/l6/ptd6l19s2vb98z6bbnb1k7b00000gq/T/20141006195559
    executing locally: git clone -q file:///Users/berlin/vagrant-workspace/project /var/folders/l6/ptd6l19s2vb98z6bbnb1k7b00000gq/T/20141006195559 && cd /var/folders/l6/ptd6l19s2vb98z6bbnb1k7b00000gq/T/20141006195559 && git checkout -q -b deploy a7ba07ac38fee4b5375c6d383886a906c1a551d5
    command finished in 72ms
  * 2014-10-06 21:55:59 executing `symfony:composer:install'
    triggering before callbacks for `symfony:composer:install'
  * 2014-10-06 21:55:59 executing `symfony:composer:copy_vendors'
--> Copying vendors from previous release
  * executing "vendorDir=/var/www/project/current/vendor; if [ -d $vendorDir ] || [ -h $vendorDir ]; then cp -a $vendorDir /var/www/project/releases/20141006195559; fi;"
    servers: ["88.88.88.88"]
    [88.88.88.88] executing command
    command finished in 103ms
  * 2014-10-06 21:56:00 executing `symfony:composer:get'
  * executing "if [ -e /var/www/project/releases/20141006195559/composer.phar ]; then echo 'true'; fi"
    servers: ["88.88.88.88"]
    [88.88.88.88] executing command
    command finished in 90ms
--> Downloading Composer
  * executing "sh -c 'cd /var/www/project/releases/20141006195559 && curl -s http://getcomposer.org/installer | php'"
    servers: ["88.88.88.88"]
    [88.88.88.88] executing command
*** [err :: 88.88.88.88] sh: line 0: cd: /var/www/project/releases/20141006195559: No such file or directory
    command finished in 106ms
*** [deploy:update_code] rolling back
  * executing "rm -rf /var/www/project/releases/20141006195559; true"
    servers: ["88.88.88.88"]
    [88.88.88.88] executing command
    command finished in 102ms
failed: "sh -c 'sh -c '\\''cd /var/www/project/releases/20141006195559 && curl -s http://getcomposer.org/installer | php'\\'''" on 88.88.88.88

I can't find any solution.
Does anybody have an idea for my problem? Thank you very much.

A: If someone will have the same problem. This is a working script for me:
set     :application,   "project"
set     :domain,      "88.88.88.88"
set     :deploy_to,     "/var/www/project"
set     :app_path,      "app"
set     :user,          "root"

set     :scm,           :git
set     :repository,    "file:///Users/berlin/vagrant-workspace/project"

set   :deploy_via,       :capifony_copy_local
set   :use_composer,     true
set   :use_composer_tmp, true

role  :web,           domain
role  :app,           domain, :primary => true

set   :use_sudo,      false
set   :keep_releases, 3

set :shared_files,      ["app/config/parameters.yml"]
set :shared_children,   [app_path + "/logs"]

#logger.level = Logger::MAX_LEVEL

after "deploy:finalize_update" do
  capifony_pretty_print "--> Set permissions for writable directories"
  run "chown -R www-data:www-data #{latest_release}/#{cache_path}"
  run "chown -R www-data:www-data #{latest_release}/#{log_path}"
  run "chmod -R 777 #{latest_release}/#{cache_path}"
  puts "✔"
end

I don't know exactly the difference, but this snippet works fine.


text:
Q: Another way of redirecting standard output of method call in Spring Boot I'm developing a Spring Boot application, which aims to receive code from users, compile, execute it and finally show users their code output. For that purpose I created a Component responsible for executing code and saving the output in a txt file (via PrintStream), which looks like that:
@Component
public class SimpleExecutor implements Executor {
    @Autowired
    private FileStorageService fileStorageService;

    public Path runClass(Class helloClass, String outputPath) throws Exception {
        helloClass.getConstructor().newInstance();
        Method method = helloClass.getMethod("main", String[].class);
        try {
            PrintStream fileStream = new PrintStream(outputPath);
            System.setOut(fileStream);
            String[] params = null;
            method.invoke(null, (Object) params);
            return Paths.get(outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.setOut(null);
        }
        return null;
    }
}

Above runClass method is called by another @Async method (so it is working in another thread than the application's). The problem is that changing System.out to my fileStream means storing Spring debug information as well (which of course isn't intended). For example, instead of simple "Hello world" I sometimes get:
2019-05-17 01:43:58.371 DEBUG 9720 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : POST "/code/upload", parameters={}
2019-05-17 01:43:58.372 DEBUG 9720 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.String> com.example.controllers.CompilerApiController.singleFileUpload(org.springframework.web.multipart.MultipartFile) throws java.io.UnsupportedEncodingException
2019-05-17 01:43:58.374 DEBUG 9720 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'text/plain', given [*/*] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-05-17 01:43:58.375 DEBUG 9720 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing ["Successfully uploaded file!"]
2019-05-17 01:43:58.376 DEBUG 9720 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2019-05-17 01:43:59.163 DEBUG 9720 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : POST "/code/upload", parameters={}
2019-05-17 01:43:59.165 DEBUG 9720 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.String> com.example.controllers.CompilerApiController.singleFileUpload(org.springframework.web.multipart.MultipartFile) throws java.io.UnsupportedEncodingException
2019-05-17 01:43:59.167 DEBUG 9720 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'text/plain', given [*/*] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-05-17 01:43:59.167 DEBUG 9720 --- [nio-8080-exec-4] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing ["Successfully uploaded file!"]
2019-05-17 01:43:59.168 DEBUG 9720 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2019-05-17 01:44:00.101 DEBUG 9720 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : POST "/code/upload", parameters={}
2019-05-17 01:44:00.101 DEBUG 9720 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.String> com.example.controllers.CompilerApiController.singleFileUpload(org.springframework.web.multipart.MultipartFile) throws java.io.UnsupportedEncodingException
2019-05-17 01:44:00.103 DEBUG 9720 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'text/plain', given [*/*] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-05-17 01:44:00.103 DEBUG 9720 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing ["Successfully uploaded file!"]
2019-05-17 01:44:00.104 DEBUG 9720 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
Hello world

Is there any other way I can redirect standard output of method.invoke call? That's the one that prints the stuff I would like to store.

A: Please try like this.
public Path runClass(Class helloClass, String outputPath) throws Exception {

........ other code

FileOutputStream f = new FileOutputStream("mySeparateLog.txt");
System.setOut(new PrintStream(f));

....... other code

}