text:
Q: Migrating RAID6 array from HP SmartArray P600 to LSI MegaRAID SAS 8888ELP My customer has an external RAID6 array (8x 1TB in HP MSA60 enclosure) attached to HP SmartArray P600 controller. They have now decided to replace the server and the new one comes with LSI MegaRAID SAS 8888ELP. The HW supplier insists the migration is as simple as pulling the eSATA cable from P600 and inserting it into LSI but I'm not convinced. Unfortunately I have nowhere to test, and will have to do the exercise on the production array :(
So the question in brief - is it possible to import the HP SmartArray P600-created RAID6 array to LSI MegaRAID 8888ELP?

A: No, this is not possible... HP Smart Array controllers and LSI have completely different on-disk RAID metadata formats.
This will not work.
The cable connecting the Smart Array P600 to the Storageworks MSA60 enclosure is not eSATA either. It's going to be a SFF-8470->SFF-8088 4-lane SAS cable.
So, what problem are you trying to solve? You have a new server. Obviously it's not an HP server, so the expectation that you'd be able to just reattach the external storage is wrong. However, you can use a modern HP Smart Array controller in your new server to connect to the external storage. HP Smart Array P800, P411, P212 or P812 RAID controllers would all work for this purpose.
But since you're also working with a new server, do you have an option to use the new server's resources to allow you to copy the data from the old setup to the new? HP MSA60 storage enclosures are very much outdated now. I'd expect that your new server hardware can accommodate larger disks or a more appropriate external storage setup. You only seem to need 6TB of usable space, so it would definitely be safer to copy data rather than risk compatibility issues in retaining your old gear.
Edit:
For a ProLiant DL380 G6 specifically, you'll want to go with a Smart Array P812 controller or a P212 with additional cache and battery. Both can be found used/cheap. Firmware updates are going to be very important to ensure everything is updated to the right revisions. Download the HP Service Pack for ProLiant to bring firmware to the proper revision levels after you've connected everything. Take backups before you try this, if possible.


text:
Q: Introduce page break for columns of horizontal table I have a horizontal table for which columns are rendered dynamically from model data in an MVC razor view. The sample code is here:

        @foreach (var employee in Model.Employees)
        {

              @employee.Name
              @employee.Age

        }

When more than 5 employees are rendered as columns, I need the columns to break into next page when printing to an A4 size paper. How can I achieve this using css/less?

A: To have the page break purely using CSS, you could use the :nth-child() selector to select, lets say every 5 employees.
Try using something like:
span:nth-child(5) {padding-bottom:10px;}

You easily change the five to represent how many span increments you want to use, and the padding-bottom to change how big you want that space to be.
If you are using spans althroughout your page you could also just put that inside of a parent div and restrict it to just the employee data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: basic diferences between root and real_root boot arg I notice that we have set root=, but deeper there are real_root too.
Also why the real_root is rarely used?
I mean why it more common to use root rather the real_root?

A: If you are using the initial ram disk (initrd) or the initial ram fs (initramfs), then the bootloader will load both kernel and the initial ram disk/fs, then the kernel will manage the initial ram disk/fs to mount a temporary root fs into the memory.
Once the necessary drivers and modules are available then the initial ram disk/fs will need real_root parameter (passed by the grub to the kernel) to load the real root fs partition from a block device or over the network (via nfsroot grub parameter) then switch to it.
So in case your are not using the initial ram disk/fs, than means that all the necessary drivers and modules are compiled within the kernel then real_root will have no impact since no initial ram disk/fs is needed to finalize the boot sequence.


text:
Q: Enable _metadata files in Spark 2.1.0 It seems that saving empty Parquet files is broken in Spark 2.1.0 as it is not possible to read them in again (due to faulty schema inference)
I found that since Spark 2.0 writing the _metadata file is disabled by default when writing parquet files. But I cannot find the configuration setting to put this back on.
I tried the following:
spark_session = SparkSession.builder \
                        .master(url) \
                        .appName(name) \
                        .config('spark.hadoop.parquet.enable.summary-metadata', 'true') \
                        .getOrCreate()

and quite some different combination as without spark.hadoop for example.
The code I am trying to run in PySpark:
spark_session = session.get_session()
sc = spark_session.sparkContext

df = spark_session.createDataFrame(sc.emptyRDD(), schema)

df.write.mode('overwrite').parquet(path, compression='none')

# this works
df = spark_session.read.schema(schema).parquet(path)

# This throws an error
df = spark_session.read.parquet(path)

A: It is a problem with the behavior of sc.emptyRDD(). You can find more information on https://github.com/apache/spark/pull/12855 why exactly this behavior occurs.
The current solution is to do the following: df = spark_session.createDataFrame(sc.emptyRDD(), schema).repartition(1) and still have the config settings mentioned in the question asked.


text:
Q: R extract data from pdf Here is the data
http://drdpat.bih.nic.in/Downloads/Rice-Varieties-1996-2012.pdf
It is a pdf. If you open the pdf, you will on page 2, there is a table that I need to extract and store it in a dataframe. I followed this link to do this
https://ropensci.org/blog/2016/03/01/pdftools-and-jeroen
library(pdftools)
text <- pdf_text("data.pdf")
dat<-text[2] # this reads the second page

After this, no matter what I try it does not convert it into a tabular format. I
tried this:
dat1 <- matrix(dat, byrow = TRUE,nrow = 12, ncol = 8) # it didn't work

Tried to use the scan function
dat.s <- scan(dat, what = "character", sep = " ", skip = 2) # no use

Can anyone help me with this? Also I am only looking to achieve this in R
Thanks

A: The structure of the tables in the PDF is a bit messed up: some columns overlap with each other and the tabulizer algorithm does not extract them correctly.
I was only able to extract the first 6 columns from page 2; the last 2 columns (Salient Features, "Recommended for cultivation") remain problematic...
library(tabulizer)
library(dplyr)

out1 <- extract_tables("Rice-Varieties-1996-2012.pdf", pages=2)[[1]]

## With a moderate amount of hacking,
## the following columns are correctly extracted:
## 1. Sl. No.
## 4. Year of Notification
## 5. Duration (in days)
## 6. Eco-System

sel <- gsub(" ","",out1[ ,c(1,4,5,6)])

## To extract Parentage column, you can use the `area` parameter:
## I figured out the values by trial and error
out2 <- extract_tables("Rice-Varieties-1996-2012.pdf", guess=FALSE,
                       pages=2,
                       area=list(c(80,120,2000,420) ) )[[1]]
sel <- cbind(sel,out2[1:nrow(sel),1])

## The header is contained in the first 3 rows of `sel`
## which can be aggregated by `paste0`
print(sel)
head <- aggregate(sel[1:3, ], by=list(rep(1,3)), paste0, collapse="") %>%
    select(-Group.1)

## The body is a bit harder, because each record might be split across
## a variable number of rows, depending on the entries.
## I have used non-empty records for column 1 (Sl.No.)
## to identify the breakpoints where to split sel into row blocks
## pertaining to the same record.
body <- sel[-(1:3), ]
brks <- body[ ,1]!=""
ibrk <- c((1:nrow(body))[brks], nrow(body)+1)
ll <- unlist(sapply(1:(length(ibrk)-1), function(k) rep(ibrk[k],ibrk[k+1]-ibrk[k])))

stopifnot(length(ll)==nrow(body))

body <- data.frame(body, stringsAsFactors=FALSE)
colnames(body) <- head

tab <- aggregate(body, by=list(ll), paste0, collapse="") %>%
    select(-Group.1)

print(tab)

## Using the same trick as above with brks and ibrk,
## one is able to extract column "Name of variety"
## (again, I found the values of area by trial and error).
out3 <- extract_tables("Rice-Varieties-1996-2012.pdf", guess=FALSE,
                       pages=2,
                       area=list(c(80,20,2000,130) ) )[[1]]
sel3 <- gsub(" ","",out3)
head3 <- aggregate(sel3[1:2, ], by=list(rep(1,2)), paste0, collapse="") %>%
    select(-Group.1)
body3 <- sel3[-(1:2), ]
brks3 <- body3[ ,1]!=""
ibrk3 <- c((1:nrow(body3))[brks3], nrow(body3)+1)
ll3 <- unlist(sapply(1:(length(ibrk3)-1), function(k) rep(ibrk3[k],ibrk3[k+1]-ibrk3[k])))

stopifnot(length(ll3)==nrow(body3))
body3 <- data.frame(body3, stringsAsFactors=FALSE)
colnames(body3) <- head3

tab3 <- aggregate(body3, by=list(ll3), paste0, collapse="") %>%
    select(-Group.1)

print(tab3)

## I have not managed to find a value of `area` which correctly splits
## the last two columns *and* allows to identify the rows in each record...

tab <- tab %>% left_join(tab3)


text:
Q: ajax php post with sessions wont give results I am trying to get pre set session variables through ajax and display in my modal. its like a cart. But when i try to get them there is no result at all when i read the ajax result from chrome inspect network or the modal. below is my code. what am i doing wrong here?
<script>
    $("#cart-button").click(function(){
        $.ajax({
            url: "includes/cart-read.php",
            success: function(data){

                  console.log(data);
                  alert(data);
                $('#modal-body').empty().append(''+data+'');
            }
        });
    });
</script>

and in cart-read.php
if(isset($_SESSION['dices'])){
    foreach ($_SESSION['dices'] as $dice){

        $msg = $dice;

        echo json_encode($msg);

    }
}

session dices is an array with simple numbers. such as 4, 5, 6.

A: Make sure you have the following things in your code

*

*Check if you have added session_start(); below after

*Try putting an else case to your session check,

*Try using an array to store and display the results.
<?php
session_start();
$result = array();
$msg = array();
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){

    array_push($msg,$dice);
    }

    if(sizeof($msg) > 0)
    {
        $result['status'] = true;
        $result['message'] = $msg;
    }
    else
    {
        $result['status'] = false;
        $result['message'] = 'No values';
    }
}
else
{
$result['status'] = false;
$result['message'] = 'Session not set';
}

  echo json_encode($result);
?>


text:
Q: Python socket.recv(8192) is hanging despite epoll I'm quite sure I'm the problem here, but I can't separate myself to understand what I've done wrong.
I'm using epoll to check if there's data in the pipe from clients.
If there is, retrieve it and just put it in a placeholder and if the data is len(0) or less, disconnect.
But for whatever reason, .recv(8192) becomes a blocking call holding up the code for 5 solid seconds. Which is coincidentally the same amount I'm using as as sleep on my thread in the client application for the first thread.
Server side:
import sys
from select import epoll, EPOLLIN, EPOLLHUP
from socket import *
from time import time

socks = {}
polly = epoll()

sock = socket()
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(('', 1337))
sock.listen(4)
mainFid = sock.fileno()

polly.register(mainFid, EPOLLIN)

while 1:
    for fid, eid in polly.poll(0.25):
        #print('New event:', fid, eid)
        if fid == mainFid:
            ns, na = sock.accept()
            polly.register(ns.fileno())
            print(time(), na,'connected', ns.fileno())
            socks[ns.fileno()] = {'sock' : ns, 'addr' : na}
        elif fid in socks:
            print(time(), 'Client is sending data!')
            data = socks[fid]['sock'].recv(8192)
            print(time(), 'Data recieved successfully.')
            if len(data) <= 0: socks[fid]['sock'].close()

Client side:
from socket import *
from time import sleep, time
from threading import *

class aClient(Thread):
    def __init__(self, delay=5):
        Thread.__init__(self)
        self.s = socket()
        self.delay = delay
        print(time(), 'Connecting.')
        self.s.connect(('127.0.0.1', 1337))
        self.start()

    def run(self):
        print(time(), 'Sending data.')
        self.s.send(b'Get me data!')
        print(time(), 'Data has been sent.')
        sleep(self.delay)
        self.s.close()

aClient()
sleep(2)
aClient(10)

I can't for the love of it all understand why recv() becomes a blocking call, there's obviously(?) data in the pipe..
For starters, this makes the code useless in terms of speed, but also clients will received "Connection refused" because I'm not picking them up quickly enough because I send way to much time in recv().
Using python -m trace --trace test_socket.py it also shows that it gets stuck on:
test_socket.py(27):                     data = socks[fid]['sock'].recv(8192)

Whenever the client disconnects the recv() releases, that's the correlation between the clients sleep.
And this is normally not how it's supposed to happen.
I've tested on two different machines including not using 127.0.0.1 as the source and destination. Same thing there. And searching for a solution just returns my own solutions on SO threads


text:
Q: Drawing a Tinted QPixmap using QPainter I have a single-color transparent PNG loaded with a QPixmap, I want to draw this pixmap multiple times using different colors (e.g. once green, another yellow, etc). These QPixmaps are rendered through QPainter in the paintEvent function of a QWidget.

A: you can convert the pixmap into qimage and paint your own color .
1- Use QImage::fill(DesiredColor)
2- QPaintDevice  supports QImage so use QPainter painter(&qImage); // 8 bit will not support in paint event .
then recreate QPixmap with image using QPixmap::fromImage(qImage);


text:
Q: Enable Console.log Output To Webpack When Using HMR I am using Webpack's HMR.
When I run webpack from the Terminal, I get all of Weback's own output, but any of my own logging within the application is only written to the browser console and not to webpack's output in the Terminal (I am using LogLevel, but the same is true of a console.log()) . Is is possible to pipe console output to Webpack so that it is displayed in the Terminal?


text:
Q: How to replace Php7 install from dotdeb with php7 from Stretch I used PHP7 from the dotdeb packages for my install of Debian 8 Jessie. Now, I want to upgrade to Debian 9 Stretch (which has php7) and I want my Php7 package to be from Stretch and no more from dotdeb.
Is it possible, or should I keep php from dotdeb?
(Note: I don't want to uninstall php and reinstall it because I don't want to lose my configurations...)

A: You can change the php7 from dotdeb to the stretch package, but to avoid any conflicts it will be best to uninstalling and then reinstalling php.
Which can be achieved by:
apt-get remove php7.0

followed by removing the repository for dotdeb from sources.list (see this stackexchange answer) then update apt and install php7 again:
apt-get update
apt-get install php7.0

(package name is PHP7.0)


text:
Q: How to speed up code to solve bit deletion puzzle [This is related to Minimum set cover ]
I would like to solve the following puzzle by computer for small size of n.  Consider all 2^n binary vectors of length n. For each one you delete exactly n/3 of the bits, leaving a binary vector length 2n/3 (assume n is an integer multiple of 3).   The goal is to choose the bits you delete so as to minimize the number of different binary vectors of length 2n/3 that remain at the end.
For example, for n = 3 the optimal answer is 2 different vectors 11 and 00. For n = 6 it is 4, for n = 9 it is 6 and for n = 12 it is 10.
I had previously attempted to solve this problem as a minimum set cover problem of the following sort.   All the lists contain only 1s and 0s.
I say that a list A covers a list B if you can make B from A by inserting exactly x symbols.
Consider all 2^n lists of 1s and 0s of length n and set x = n/3.   I would like to compute a minimal set of lists of length 2n/3 that covers them all.  David Eisenstat provided code that converted this minimal set cover problem into a Mixed Integer Programming Problem that could be fed into CPLEX (or http://scip.zib.de/ which is open source).
from collections import defaultdict
from itertools import product, combinations

def all_fill(source, num):
    output_len = (len(source) + num)
    for where in combinations(range(output_len), len(source)):
        poss = ([[0, 1]] * output_len)
        for (w, s) in zip(where, source):
            poss[w] = [s]
        for tup in product(*poss):
            (yield tup)

def variable_name(seq):
    return ('x' + ''.join((str(s) for s in seq)))
n = 12
shortn = ((2 * n) // 3)
x = (n // 3)
all_seqs = list(product([0, 1], repeat=shortn))
hit_sets = defaultdict(set)
for seq in all_seqs:
    for fill in all_fill(seq, x):
        hit_sets[fill].add(seq)
print('Minimize')
print(' + '.join((variable_name(seq) for seq in all_seqs)))
print('Subject To')
for (fill, seqs) in hit_sets.items():
    print(' + '.join((variable_name(seq) for seq in seqs)), '>=', 1)
print('Binary')
for seq in all_seqs:
    print(variable_name(seq))
print('End')

The problem is that if you set n=15 then the instance it outputs is too large for any solver I can find.  Is there a more efficient way of solving this problem so I can solve n=15 or even n = 18?

A: This doesn't solve your problem (well, not quickly enough), but you're not getting many ideas and someone else may find something useful to build on here.
It's a short pure Python 3 program, using backtracking search with some greedy ordering heuristics.  It solves the N = 3, 6, and 9 instances very quickly.  It finds a cover of size 10 for N=12 quickly too, but will apparently take a much longer time to exhaust the search space (I'm out of time for this, and it's still running).  For N=15, the initialization time is already slow.
Bitstrings are represented by plain N-bit integers here, so consume little storage.  That's to ease recoding in a faster language.  It does make heavy use of sets of integers, but no other "advanced" data structures.
Hope this helps someone!  But it's clear that the combinatorial explosion of possibilities as N increases ensures that nothing will be "fast enough" without digging deeper into the mathematics of the problem.
def dump(cover):
    for s in sorted(cover):
        print("    {:0{width}b}".format(s, width=I))

def new_best(cover):
    global best_cover, best_size
    assert len(cover) < best_size
    best_size = len(cover)
    best_cover = cover.copy()
    print("N =", N, "new best cover, size", best_size)
    dump(best_cover)

def initialize(N, X, I):
    from itertools import combinations
    # Map a "wide" (length N) bitstring to the set of all
    # "narrow" (length I) bitstrings that generate it.
    w2n = [set() for _ in range(2**N)]
    # Map a narrow bitstring to all the wide bitstrings
    # it generates.
    n2w = [set() for _ in range(2**I)]
    for wide, wset in enumerate(w2n):
        for t in combinations(range(N), X):
            narrow = wide
            for i in reversed(t):  # largest i to smallest
                hi, lo = divmod(narrow, 1 << i)
                narrow = ((hi >> 1) << i) | lo
            wset.add(narrow)
            n2w[narrow].add(wide)
    return w2n, n2w

def solve(needed, cover):
    if len(cover) >= best_size:
        return
    if not needed:
        new_best(cover)
        return
    # Find something needed with minimal generating set.
    _, winner = min((len(w2n[g]), g) for g in needed)
    # And order its generators by how much reduction they make
    # to `needed`.
    for g in sorted(w2n[winner],
                    key=lambda g: len(needed & n2w[g]),
                    reverse=True):
        cover.add(g)
        solve(needed - n2w[g], cover)
        cover.remove(g)

N = 9  # CHANGE THIS TO WHAT YOU WANT

assert N % 3 == 0
X = N // 3 # number of bits to exclude
I = N - X  # number of bits to include

print("initializing")
w2n, n2w = initialize(N, X, I)
best_cover = None
best_size = 2**I + 1  # "infinity"
print("solving")
solve(set(range(2**N)), set())

Example output for N=9:
initializing
solving
N = 9 new best cover, size 6
    000000
    000111
    001100
    110011
    111000
    111111

Followup
For N=12 this eventually finished, confirming that the minimal covering set contains 10 elements (which it found very soon at the start).  I didn't time it, but it took at least 5 hours.
Why's that?  Because it's close to brain-dead ;-)  A completely naive search would try all subsets of the 256 8-bit short strings.  There are 2**256 such subsets, about 1.2e77 - it wouldn't finish in the expected lifetime of the universe ;-)
The ordering gimmicks here first detect that the "all 0" and "all 1" short strings must be in any covering set, so pick them.  That leaves us looking at "only" the 254 remaining short strings.  Then the greedy "pick an element that covers the most" strategy very quickly finds a covering set with 11 total elements, and shortly thereafter a covering with 10 elements.  That happens to be optimal, but it takes a long time to exhaust all other possibilities.
At this point, any attempt at a covering set that reaches 10 elements is aborted (it can't possibly be smaller than 10 elements then!).  If that were done wholly naively too, it would need to try adding (to the "all 0" and "all 1" strings) all 8-element subsets of the 254 remaining, and 254-choose-8 is about 3.8e14.  Very much smaller than 1.2e77 - but still way too large to be practical.  It's an interesting exercise to understand how the code manages to do so much better than that.  Hint:  it has a lot to do with the data in this problem.
Industrial-strength solvers are incomparably more sophisticated and complex.  I was pleasantly surprised at how well this simple little program did on the smaller problem instances!  It got lucky.
But for N=15 this simple approach is hopeless.  It quickly finds a cover with 18 elements, but makes no more visible progress for at least hours.  Internally, it's still working with needed sets containing hundreds (even thousands) of elements, which makes the body of solve() quite expensive.  It still has 2**10 - 2 = 1022 short strings to consider, and 1022-choose-16 is about 6e34.  I don't expect it would visibly help even if this code were sped by a factor of a million.
It was fun to try, though :-)
And a small rewrite
This version runs at least 6 times faster on a full N=12 run, simply by cutting off futile searches one level earlier.  Also speeds initialization, and cuts memory use by changing the 2**N w2n sets into lists (no set operations are used on those).  It's still hopeless for N=15, though :-(
def dump(cover):
    for s in sorted(cover):
        print("    {:0{width}b}".format(s, width=I))

def new_best(cover):
    global best_cover, best_size
    assert len(cover) < best_size
    best_size = len(cover)
    best_cover = cover.copy()
    print("N =", N, "new best cover, size", best_size)
    dump(best_cover)

def initialize(N, X, I):
    from itertools import combinations
    # Map a "wide" (length N) bitstring to the set of all
    # "narrow" (length I) bitstrings that generate it.
    w2n = [set() for _ in range(2**N)]
    # Map a narrow bitstring to all the wide bitstrings
    # it generates.
    n2w = [set() for _ in range(2**I)]
    # mask[i] is a string of i 1-bits
    mask = [2**i - 1 for i in range(N)]
    for t in combinations(range(N), X):
        t = t[::-1]  # largest i to smallest
        for wide, wset in enumerate(w2n):
            narrow = wide
            for i in t:  # delete bit 2**i
                narrow = ((narrow >> (i+1)) << i) | (narrow & mask[i])
            wset.add(narrow)
            n2w[narrow].add(wide)
    # release some space
    for i, s in enumerate(w2n):
        w2n[i] = list(s)
    return w2n, n2w

def solve(needed, cover):
    if not needed:
        if len(cover) < best_size:
            new_best(cover)
        return
    if len(cover) >= best_size - 1:
        # can't possibly be extended to a cover < best_size
        return
    # Find something needed with minimal generating set.
    _, winner = min((len(w2n[g]), g) for g in needed)
    # And order its generators by how much reduction they make
    # to `needed`.
    for g in sorted(w2n[winner],
                    key=lambda g: len(needed & n2w[g]),
                    reverse=True):
        cover.add(g)
        solve(needed - n2w[g], cover)
        cover.remove(g)

N = 9  # CHANGE THIS TO WHAT YOU WANT

assert N % 3 == 0
X = N // 3 # number of bits to exclude
I = N - X  # number of bits to include

print("initializing")
w2n, n2w = initialize(N, X, I)

best_cover = None
best_size = 2**I + 1  # "infinity"
print("solving")
solve(set(range(2**N)), set())

print("best for N =", N, "has size", best_size)
dump(best_cover)

A: First consider if you have 6 bits. You can throw away 2 bits. Therefore, any pattern balance of 6-0, 5-1 or 4-2 can be converted to 0000 or 1111. In the case a 3-3 zero-one balance any pattern can be converted to one of four cases: 1000, 0001, 0111, or 1110. Therefore, one possible minimum set for 6 bits is:
0000
0001
0111
1110
1000
1111

Now consider 9 bits with 3 thrown away. You have the following set of 14 master patterns:
000000
100000
000001
010000
000010
110000
000011
001111
111100
101111
111101
011111
111110
111111

In other words, each pattern set has ones/zeros in the center, with every permutation of n/3-1 bits on each end. For example, if you have 24 bits then you will have 17 bits in the center and 7 bits on the ends. Since 2^7 = 128 you will have 4 x 128 - 2 = 510 possible patterns.
To find correct deletions there are various algorithms. One method is to find the edit distance between the current bit set and each master pattern. The pattern with the minimum edit distance is the one to convert to. This method uses dynamic programming. Another method would be to do a tree search through the patterns using a set of rules to find the matching pattern.


text:
Q: Position element according to body instead of the relative parent I have a div with position relative and two children using it and both have position absolute. And I need them. But I want to make another child inside the relative div and give it the position absolute. But now the problem is that I want some part of it to appear outside of the element. So how can I do it in CSS? Thanks in advance.
Reference to what I need is: Example of what I need, check the search icon. How it is placed. I want that kind of thing.
div {
   //Parent div
    position:relative;
}
div {
   //Child div
    position:absolute;
}
div {
   //Child div
    position:absolute;
   //This is an emoji
   //But I want this to appear half outside of the parent div,
   //i.e. on the border of the parent div
}

A: in the given example, section is the parent div  which is relative and rest 2 child, or you can have as many as you want, all are absolute, and image is out on border as you requested

* {margin: 0; padding: 0; box-sizing: border-box;}
img {max-width: 30px;}
section {border:15px solid #ccc; border-radius: 20px; height: 100px; position: relative;}
.child {position: absolute;}
.child1 {top: 50%; left: 50%; transform: translate(-50%,-50%);}
.childEmoji {top: 0; left:0; transform: translate(-50%,-50%);}

Child 1

A: Use vw or vh in your positioning. If you use for example: 50% it will get the width of the parent and then divide it by 2. If you use vw(width of page) or vh(height of page) it takes the width and height of the whole page. Should work for you. Remember your positioning is important as well.


text:
Q: How to define the audit score assertions for Lighthouse tests in Azure DevOps I have the Lighthouse checks configured for some critical links on my website.
How can I integrate these checks with my build pipeline, so that it stops if any of my checks fail?

A: Once the Lighthouse checks are configured in Azure DevOps for the agreed URLs, run the Lighthouse tasks 10 - 20 times to have a good idea of the median values you should expect. Ideally, run checks for every environment you have individually, not just for the Production one.
When you have some reference values you can start setting the audit score assertions in the  "Audit score assertions" field for your Lighthouse task. Any audit score generated by Lighthouse is between 0 and 1, so that you can specify the audit score assertions that can make your pipeline fail based on the audit scores: = 1, >0, <1 etc.
For instance, to make sure that a page has the successful HTTP status code, you should expect http-status-code = 1. Specify one assertion per line. More audit metrics of Lighthouse 5.6.0 can be found here.


text:
Q: Hive results differs from MySql result. Join query on Hive returns unexpected result or OK results I have a join query (that joins 4 table) on mysql returns 2 rows while on Hive returns OK results. So I checked table individually on hive and mysql side.
Records on each table on both side matches but the results with JOIN query differs. It is not the case for the other JOIN query.
I have checked the directory for all the tables which look fine.
The OK results comes specially when there is no records on either of table or no directory available for table. But that is not the case.
Is the OK results on hive an issue.
Below is the part of the result:
Stage-Stage-6: Map: 2  Reduce: 1   Cumulative CPU: 22.22 sec   MAPRFS Read: 0 MAPRFS Write: 0 SUCCESS
Stage-Stage-7: Map: 2  Reduce: 1   Cumulative CPU: 24.94 sec   MAPRFS Read: 0 MAPRFS Write: 0 SUCCESS
Stage-Stage-8: Map: 2  Reduce: 1   Cumulative CPU: 22.25 sec   MAPRFS Read: 0 MAPRFS Write: 0 SUCCESS
Total MapReduce CPU Time Spent: 2 minutes 36 seconds 110 msec
OK
Time taken: 411.225 seconds
hive>

A: Yes.
Based on the reported behavior, we can deduce that there is a difference between what's implemented on MySQL, and what's implemented on Apache Hive.
As far as whether the difference is due to a difference in the JOIN behavior, there's not enough information given here to determine why the query against MySQL and the query against Hive would be returning different results.


text:
Q: document ready after dom manipulation I'm doing an application with Phonegap and I'm using a self-built slide transition to change the pages.
It works like this:
Every page is a div with 100% height and width, so if I change the Page, I set the next div right to the currently active and slide both to the left side.
Now to the Problem: the sliding works fine, but it's executed before the content of the right div is completely loaded. So the right div slides in empty, and only after a few hundred miliseconds the content will appear.
I tried it with document.ready, but as I've read this event is only executed the first time the DOM is loaded.
Does anybody know how I can wait for the DOM to be completely rendered again after I've manipulated the DOM with Javascript?

A: In your case, you can pick one element in the content of the next div and keep checking it with $(...).length. If the value is > 0, the DOM is loaded and you can change the page.
You may want to try this function:
Function.prototype.deferUntil = function(condition, timeLimit) {
    var ret = condition();

    if (ret) {
        this(ret);
        return null;
    }

    var self = this, interval = null, time = ( + new Date());
    interval = setInterval(function() {
        ret = condition();
        if (!ret) {
            if (timeLimit && (new Date() - time) >= timeLimit) {
                // Nothing
            } else {
                return;
            }
        }
        interval && clearInterval(interval);
        self(ret);
    }, 20);

    return interval;
};

Usage:
(function() {
    console.log('Next page loaded');
}).deferUntil(function() {
    return $('#nextDiv').length > 0;
}, 3000);

The above example will check the div that has id="nextDiv" in every 20ms (not longer than 3 seconds). When the div is loaded, it will show 'Next page loaded' in the console.
You can try on this fiddle

A: There is a DOMNodeInserted event that is supposed to work like document.ready but for individual DOM nodes. But it is deprecated and has lots of issues. StackOverflow users found a good alternative to it that works quite well in all mobile browsers: Alternative to DOMNodeInserted

A: Here is a function that will trigger a callback once all images matching a jquery selector have finished loading
Js Fiddle Sample
//css
input {width: 420px;}

//html

    <input type="text" value="http://goo.gl/31Vs" id="img1">

<input type="text" value="http://wall.alafoto.com/wp-content/uploads/2010/11/Fractal-Art-Wallpapers-09.jpg" id="img2">

<input type="text" value="http://pepinemom.p.e.pic.centerblog.net/ssg8hv4s.jpg" id="img3">

<input type="button" value="Load images" name="loadImages" id="btn">

//javascript

//Call a function after matching images have finished loading
function imagesLoadedEvent(selector, callback) {
    var This = this;
    this.images = $(selector);
    this.nrImagesToLoad = this.images.length;
    this.nrImagesLoaded = 0;

    //check if images have already been cached and loaded
    $.each(this.images, function (key, img) {
        if (img.complete) {
            This.nrImagesLoaded++;
        }
        if (This.nrImagesToLoad == This.nrImagesLoaded) {
            callback(This.images);
        }
    });

    this.images.load(function (evt) {
        This.nrImagesLoaded++;
        if (This.nrImagesToLoad == This.nrImagesLoaded) {
            callback(This.images);
        }
    });
}

$("#btn").click(function () {
    var c = $("#container"), evt;
    c.empty();
    c.append("");
    c.append("");
    c.append("");
    evt = new imagesLoadedEvent("img", allImagesLoaded);
});

function allImagesLoaded(imgs) {
    //this is called when all images are loaded
    $("#message").text("All images loaded");
    setTimeout(function() {$("#message").text("");}, 2000);
}

A: You could use jQuery ajax to load the content, and on success run a function with the slide.
$("#page1").load('page2.html', function() {
    //do your custom animation here
});

Althoug I'm not completely sure how you're loading the content. Is it static (Already there but just not visible?) Or is it loaded with ajax?
EDIT: You could just do a small .delay() or setTimeout with a few millisec, and then animate the sliding.

A: I had a similar problem making a masonry site responsive. I use window.onload which waits for all elements to complete loading before initialising masonry.js. I also placed the window.onload inside .onchange function and it fired everytime the viewport resized.
I am sure applying similar principles will solve your problem.

A: try once
$(window).bind('load',function(){
//code
});

A: Maybe you can set an event on your div.
myDiv.onafterupdate = myHandler;

function myHandler() {
   // Do here what you want to do with the updated Div.
}

Does this help you?

A: In jquery you could use $() just after your DOM manipulation code.
$(function(){
//code that needs to be executed when DOM is ready, after manipulation
});

$() calls a function that either registers a DOM-ready callback (if a function is passed to it) or returns elements from the DOM (if a selector string or element is passed to it)
You can find more here
difference between $ and $() in jQuery
http://api.jquery.com/ready/


text:
Q: Magento Custom Order Attribute I am trying to add a custom attribute field to the sales_flat_order table in the database for Magento 1.8+.  Do I need to create a New Admin theme?
<?php
$installer = $this;
$installer->startSetup();

$installer->addAttribute("order", "my_custom_input_field", array("type"=>"varchar"));
$installer->addAttribute("quote", "my_custom_input_field", array("type"=>"varchar"));
$installer->endSetup();

A: Try this:
$installer->addAttribute(Mage_Sales_Model_Order::ENTITY, 'THIS_IS_THE_CODE', array(
    'group'         => 'General',
    'type'          => 'varchar',
    'default'       => '0',
    'input'         => 'text',
    'label'         => 'My pretty pretty label',
    'source'        => '',
    'visible'       => true,
    'required'      => false,
    'visible_on_front' => false,
    'user_defined'  =>  false
));

$installer->addAttribute(Mage_Sales_Model_Quote::ENTITY, 'THIS_IS_THE_CODE', array(
    'group'         => 'General',
    'type'          => 'varchar',
    'default'       => '0',
    'input'         => 'text',
    'label'         => 'My pretty pretty label',
    'source'        => '',
    'visible'       => true,
    'required'      => false,
    'visible_on_front' => false,
    'user_defined'  =>  false
));


text:
Q: Why is String.Contains case-insensitive in this query? I'm working my way through this ASP MVC tutorial. This page of the tutorial deals with writing a simple "search" page. The controller contains this method:
public ActionResult SearchIndex(string searchString)
{
     var movies = from m in db.Movies
                  select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    return View(movies);
}

According to MSDN, String.Contains is case-sensitive. But when I navigate to [website url]/Movies/SearchIndex?searchString=mel, it returns a movie with the title Melancholia as a result. If I inspect the controller method in the debugger, searchString is mel (in lower case) as expected.
Why does String.Contains match this title case-insensitively?

A: When using Linq to entities the query is done by the SQL Server. Your Lambda expression is translated to an SQL query, so whether or not it is case sensitive depends on the server configuration.
If you'd like to change your SQL Server collation and make it case sensitive, please see this page:
http://blog.sqlauthority.com/2007/04/30/case-sensitive-sql-query-search/


text:
Q: Bypass nginx cache if user is authenticated Django I'm implementing nginx as a reverse proxy for a Django project. I'm now trying implement nginx's cache config below:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:5m max_size=1g inactive=60m;
proxy_temp_path /var/cache/nginx/tmp;

server {
  ...

  location / {
     proxy_pass http://127.0.0.1:8000;
     proxy_set_header Host $host;
     proxy_set_header X-Forwarded-Host $server_name;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';

     # cache
     proxy_cache my_cache;
     proxy_cache_min_uses 1;
     proxy_cache_valid 200 302 10m;
     proxy_cache_valid 404 1m;
     proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
     proxy_cache_use_stale error timeout invalid_header http_500 http_502 http_503 http_504;
     proxy_cache_lock on;

     proxy_hide_header "Set-Cookie";

     add_header X-Proxy-Cache $upstream_cache_status;
  }
}

All works great, however I'd like it so that authenticated users are able to bypass the cache, as otherwise when they update the site content, they won't see the changes, only the cached content until it expires.
What would be the best way to approach this?
Any help would be much appreciated.
Thanks

A: Add a middleware to set cookie (eg cachedisable) in response if user is autheticated else remove that cookie. So that you can put $cookie_ cachedisable in nginx conf
location / {
    proxy_cache_bypass $cookie_cachedisable $arg_nocache;
    ...
}

Whenever you want bypass cache do requests like
http://www.example.com/?nocache=true #or if cookie `cachedisable` is present

For more info https://www.nginx.com/blog/nginx-caching-guide/?utm_source=nginx-caching-guide&utm_medium=blog#caching-guide-faq-hole-punch


text:
Q: "sudo yum install nginx" throws "Cannot retrieve repository metadata (repomd.xml) for repository" Here's what I get when I type it in via the command line:
[prompt]$ sudo yum install nginx
Loaded plugins: priorities, security, update-motd, upgrade-helper
http://nginx.org/packages/rhel/latest/x86_64/repodata/repomd.xml: [Errno 14] PYCURL ERROR 22 - "The requested URL returned error: 404 Not Found"
Trying other mirror.
Error: Cannot retrieve repository metadata (repomd.xml) for repository: nginx. Please verify its path and try again

I tried creating a /etc/yum.repos.d/nginx.repo file as described here but got the same thing. Any ideas?
I'm running "Amazon Linux AMI release 2012.09".

A: I also caught that problem, try this:
vim /etc/yum.repos.d/nginx.repo

Change the repo site:
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1

So: http://nginx.org/packages/centos/6/$basearch/
Please read the instructions completely:

Due to differences between how CentOS, RHEL, and Scientific Linux populate the
     $releasever variable, it is necessary to manually replace $releasever with either
     "5" (for 5.x) or "6" (for 6.x), depending upon your OS version.

See also: https://serverfault.com/questions/531045/nginx-repomd-xml-404-not-found


text:
Q: Convert Rows to Columns - SQL Server I have below table in SQL Server 2014.

ColumnName	RowOrdinal	Value

EmpName	0	John

EmpTitle	0	Engineer

EmpCity	0	Chicago

EmpName	1	Matt

EmpTitle	1	Analyst

EmpCity	1	Boston

Basically I need to convert rows to columns (maybe using PIVOT), so my output should be as follow:

RowOrdinal	EmpName	EmpTitle	EmpCity

0	John	Engineer	Chicago

1	Matt	Analyst	Boston

Please provide, if possible, SQL to achieve this. Thanks.

A: Simple PIVOT will do the job for you
SELECT RowOrdinal,
       [EmpName],
       [EmpTitle],
       [EmpCity]
FROM   yourtable
       PIVOT (Max(Value)
             FOR columnname IN([EmpName],
                               [EmpTitle],
                               [EmpCity]))pv

or use Conditional Aggregate
SELECT RowOrdinal,
       EmpName=Max(CASE WHEN ColumnName = 'EmpName' THEN Value END),
       EmpTitle=Max(CASE WHEN ColumnName = 'EmpTitle' THEN Value END),
       EmpCity=Max(CASE WHEN ColumnName = 'EmpCity' THEN Value END),
FROM   yourtable
GROUP  BY RowOrdinal


text:
Q: How do we convert a (confusion matrix) decimal output to % with 2 decimal points when using the plot function the matrix is plotted either with a % with many decimal places
or not as a % but with set decimal places
how can I do both at once

*

*a % with a set decimal place

disp = ConfusionMatrixDisplay(confusion_matrix = cm) # Use ConfusionMatrixDisplay to visualize 'cm'
disp.plot(values_format='%')

A: Try
disp.plot(values_format='.2%')


text:
Q: Can't set video mode for SDL screen on embedded device I've been hacking away on an ARM based device (Freescale i.MX27 ADS) with a built-in screen for the past few days. The device is running a modified, minimal GNU/Linux system, with no window management or graphical server. By default, the device is only supposed to run the one application that came with it.
I've never done any graphical programming before, so this is a learning experience for me. I tried writing a simple SDL program to run on the device, which would read a bitmap, and display the image on the embedded device's screen.
The problem I'm having is that no matter what resolution, depth, or flags I try, the video mode always fails to apply, and I get nothing.
I know my code isn't the problem, but I'm going to post it anyway.
#include "SDL/SDL.h"

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#define SCREEN_DEPTH 24

int main(int argc, char *argv[])
{
    SDL_Surface *screen;

    if(!SDL_Init(SDL_INIT_VIDEO))
    {
            printf("Unable to initialize SDL.\n");
            return 1;
    }

    // It always fails right here
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DEPTH, SDL_SWSURFACE);
    if(screen == NULL)
    {
            printf("Unable to set video mode.\n");
            return 1;
    }

    SDL_Surface* image;
    SDL_Surface* temp;

    temp = SDL_LoadBMP("hello.bmp");
    if(temp == NULL)
    {
            printf("Unable to load bitmap.\n");
            return 1;
    }

    image = SDL_DisplayFormat(temp);
    SDL_FreeSurface(temp);

    SDL_Rect src, dest;

    src.x = 0;
    src.y = 0;
    src.w = image->w;
    src.h = image->h;

    dest.x = 100;
    dest.y = 100;
    dest.w = image->w;
    dest.h = image->h;

    SDL_BlitSurface(image, &src, screen, &dest);

    printf("Program finished.\n\n");

    return 0;
}

From what I can tell, the application that's supposed to run on this device uses Qtopia. Again, I'm new to graphics programming, so I have no idea how one should control graphical output in an embedded environment like this.
Any ideas?

A: My code was hiding the fact that the problem was with initializing SDL, not setting the video mode. SDL wasn't initializing because my embedded system has no X server, and no mouse. After setting SDL_NOMOUSE, the problem was resolved.


text:
Q: Correct Way to Use "Hashtable"? I am new to Hashtables, and am trying to understand how they fully work. I need to determine if a string occurs in a large file that contains around 100,000 strings, each on their own line. I have been told that a HashTable would be much more efficient than a LinkedList or ArrayList to runtime being O(n) for both.
I have looked into the HashTable Class in Java, but do not understand how exactly I would enter in every string from the file due to the "put" method needing a key, as well as the object.
I imagine I could use a Scanner to run through every string in my file, but how would I enter them into a Hashtable, and how would the contains() method be utilized in a HashTable?

A: To me, this sounds like a Usecase of HashSet. Check that out!
You put only values in, which are stored in a distinct way (no doubled values). You can then just call the contains method, to check wether your String is inside the Set.

A: You could just put the strings in to a HashSet.
Set yourStrings = new HashSet<String>();

for (String line : yourFile) {
    yourStrings.add(line);
}

Then to check if a particular string is present:
if (yourStrings.contains("Hi!")) {
    // It's present
}
else {
    // It's not present
}

A: Hashtable is pretty old, and has been superseded by HashMap.  There's also HashSet.  Both use a hash table, but they have different purposes.  A HashMap is used when you want to associate some sort of value with each key; for example, you could use it to look up somebody's name and get their phone number.  A HashSet, however, just stores the keys without any values.  You'd use that just to add names to the set, and then later check to see if the name is in the set.
As Luiggi mentioned in the comments, HashMap and HashSet are just specific implementations of Map and Set; those implementations use hash tables, but other implementations of those classes are available.  You'll need to use HashMap and HashSet when constructing the table, but you should usually declare your variables simply as Map and Set, because that way you could replace the HashMap or HashSet with some other class that implements the same methods.  That way you're not tied to a specific implementation.

A: You need a HashSet to store each line of your file.
*You would probably need a HashMap only if you were interested in the number of occurrences of each String in the file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class MyFileUtils {

//this can be omitted, just added to increase speed
//when requiring multiple searches in the same file, to avoid recalculations.
//Use it only if you need to search in one file ONLY
private static Set<String> stringLines = null;

/*
 * Get a HashSet of all the (distinct) lines in a file
 */
public static Set<String> getStringLinesFromFile (String filePath) {
    //this can be omitted, just added to support fast multiple calls of this function
    if (stringLines != null) return stringLines;

    Set<String> stringLines = new HashSet<String>();

    Scanner scanner = null;
    try {
        scanner = new Scanner(new File(filePath));
        while (scanner.hasNextLine())
            stringLines.add(scanner.nextLine());
    } catch (FileNotFoundException e) {
        System.out.println("File does not exist");
    } finally {
        if(scanner != null)
            scanner.close();
    }
    //as the first line, this can be omitted, just added to support fast multiple calls of this function
    MyFileUtils.stringLines = stringLines;

    return stringLines;
}

/*
 * Call this method to search for a stringLine in a file
 */
public static boolean checkIfStringExistsInFile(String filePath, String aStringLine) {
    return getStringLinesFromFile(filePath).contains(aStringLine);
}

//Test
public static void main (String args[]) {
    System.out.println(checkIfStringExistsInFile("test.txt", "Hello World"));
}

}


text:
Q: viewController lifecycle Apple's documentation says "When a segue is triggered, it causes a new view controller to be instantiated and transitioned onscreen." Some behavior I'm seeing has me questioning if the VC is actually destroyed and recreated each time the view is seque'd to.
In my application each time I seque to a particular view I note that the  the following viewController function is called (which is consistent with the VC being recreated each time it is sequed to):
- (id)initWithCoder:(NSCoder *)aDecoder

Note, this viewController is also a datasource for it's collectionView and has a property:
@property (strong, nonatomic) NSMutableArray *messages;

And every time initWithCoder is called I alloc and init a messages array and assign it to the above pointer.
When I navigate back to another view and then seque back again I'm seeing strangeness that has me thinking that the VC might be being re-used.  Or alternately if the first instance wasn't destroyed and can still receive notifications.
The first thing that is strange is that in viewDidLoad if I call addObserver:self for a particular notification which I want this VC to handle then the second time I seque into this VC I will get two notifications sent to the VC's notification handler for every notification sent.  This is consistent with the VC being reused otherwise why would the handler get called twice?
But going against this re-use scenario is that initWithCoder is in-fact being called the second time the View is loaded.
Since I don't want 2 or more notifications generated for every notification post, I use a static boolean to guarantee that addObserver is only called once.  I.e. addObserver is only called the first time viewDidLoad is called, and not subsequent times.
viewDidLoad and notification handler access the messages array.  On the second seque, viewDidLoad seems to access a newly alloc/init'd messages array but when the notification handler accesses messages it seems to be the previous messages array from the previous time the VC was loaded.
Any ideas?

A: Make sure you are unregistering yourself as an observer on those specific keys once the view is being dismissed.  You might have old method still being performed because they were never unregistered.


text:
Q: Unknown Menu Bar Item that won't go away I just started noticing this menacing and unknown icon in my menu bar. It's a red exclamation mark in a blue circle with a green arrow. Here's an image:

If I click it, whether I press Cmd or not while clicking, nothing happens. Any ideas?

A: I had the same problem and found out that the application displaying the icon is Mobile Partner. It is trying to communicate that there is and update for the device. After multiple reboots I was able to click it and get the update process started.

A: Have a look in Activity Monitor for any strange apps. Also try right clicking on it. slhck's advice (looking at the login items in the user accounts pref pane) is also good.


text:
Q: javascript not reading value of input -Uncaught TypeError: Cannot read property 'value' of null been trying a while and for some reason not able to get the value of each input
the error im getting is app.js:9 Uncaught TypeError: Cannot read property 'value' of null
    at getProtein (app.js:9)
    at app.js:26
my html

        <form>

            Age
            <input type="number" class="form-control age" id="age" value="25">

            Height
            <input type="number" class="form-control" id="height" placeholder="Inches" value="167">

            Weight
            <input type="number" class="form-control" id="weight" placeholder="lbs" value="255">

              <input type="radio" name="options" id="male"  >Male

              <input type="radio" name="options" id="female">Female

        </form>

          <button class="btn btn-secondary dropdown-toggle"
          type="button" id="dropdownMenu1" data-toggle="dropdown"
          aria-haspopup="true" aria-expanded="false">
          Activity Level
        </button>

          Basic Metabolic Rate
          Sedentry
          Lightly Active (Exercise 1-3 Times a Week)
          Moderatly Active (Exercise 3-5 Times a Week)
          Very Active (Exercise 6-7 Times a Week)
          Extra Active (Very Hard Exercise/Physical Job)

    <button class="btn btn-lg"type="button" name="calculate" onclick="getProtein()" id="calculate">Calculate</button>

      0

my script

function getProtein() {

  const age = document.getElementById('age').value;
  const height = document.getElementById('height').value;
  const weight = document.getElementById('weight').value;

  let result = 0;

  if(document.getElementById('male').checked) {
    return result = 66.47 +  (13.75 * weight) + (5.0 * height - (6.75 * age));
  }else if (document.getElementById('female')) {
    return result = 66.47 +  (13.75 * weight) + (5.0 * height - (6.75 * age));
  }

  document.getElementById('totalProtein').innerHTML = Math.round( result );

}

document.getElementById('calculate').onClick = getProtein();

it seems to have a problem with the .value, .checked and .innterHTML.
can anyone shine some light on this?

A: You might call the getProtein function too early, so your input-field are not yet ready to be queried, with this line:
document.getElementById('calculate').onClick = getProtein();

You can rewrite this line:
document.getElementById('calculate').onClick = getProtein;

or remove it because you already assigned the getProtein function to your calculate element:
<button class="btn btn-lg"type="button" name="calculate" onclick="getProtein()" id="calculate">Calculate</button>

Hope this helps.


text:
Q: Unable to query new table from asp.net core web application using EF 1.0 I have developed a new asp.net Core web application using Visual Studio 2015. I am at the point where I am adding user customization options by adding additional tables to my local database. However I have been unable to add whatever EF needs to query a new table correctly. I get the following error when attempting to query the table..
Applying existing migrations for ApplicationDbContext may resolve this issue
There are migrations for ApplicationDbContext that have not been applied to the database
•00000000000000_CreateIdentitySchema
Apply Migrations
In Visual Studio, you can use the Package Manager Console to apply pending migrations to the database:
PM> Update-Database
Alternatively, you can apply pending migrations from a command prompt at your project directory:

dotnet ef database update

My table is a simple table with a few varchar or nvarchar columns.  The model looks something like...
namespace MyNamespace.ColorSchemes
{
    public class ColorSchemesViewModel
    {
    [Required]
    public string Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string bc { get; set; }

}

Table looks something like this in SQL Server...
CREATE TABLE [dbo].[ColorSchemes](
    [Id] [nvarchar](50) NOT NULL,
    [Name] [varchar](32) NOT NULL,
    [bc] [nchar](7) NOT NULL
)

I have added the table to the application context like such...
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<ColorSchemesViewModel> Colors { get; set; }

I have also used as separate class similarly like..
    public DbSet<ColorSchemes> Colors { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

    // Customize the ASP.NET Identity model and override the defaults if needed.
    // For example, you can rename the ASP.NET Identity table names and more.
    // Add your customizations after calling base.OnModelCreating(builder);
}

}
I have added the context to a controller like this...
    private ApplicationDbContext _context;
    public MyController(IMemoryCache memoryCache, ILoggerFactory loggerFactory, ApplicationDbContext context)
    {
        _memoryCache = memoryCache;
        _logger = loggerFactory.CreateLogger<ChordMVCController>();
        _context = context;

    }

I have tried to query the table in my controller like this...
        var colorSchemes = (from c in _context.Colors
                            select c).ToList();

I have attempted to use the Package Manager to per instructions from the error...
PM> Update-Database

I always get this error...
System.Data.SqlClient.SqlException: There is already an object named 'AspNetRoles' in the database.

This doesn't make sense since this table is already in the database and the EF definition. How do I get my table added properly to the EF migrations so I can query it?

A: I was able to solve this myself...
I created a different context rather than trying to embed the dbset in the default ApplicationDbContext and also removed the onModelCreating method.
public class ColorSchemeDbContext : DbContext
{
    public ColorSchemeDbContext(DbContextOptions<ColorSchemeDbContext> options) : base(options)
    {
    }
    public DbSet<ColorScheme> ColorSchemes { get; set; }
}

Replaced the ApplicationDBContext with the new context in my controller class...
    private readonly ColorSchemeDbContext _context;
    public MyController(IMemoryCache memoryCache, ILoggerFactory loggerFactory, ColorSchemeDbContext context)
    {
        _memoryCache = memoryCache;
        _logger = loggerFactory.CreateLogger<ChordMVCController>();
        _context = context;

    }

After that the query worked. I spent a lot of time attempting to use the EF migrations to create the tables from a class syntax. Nothing seemed to work. I was creating a new .NET CORE web application in VS 2015 with the template and using user authentication which creates the AspNetRoles tables in SqlLite once you do an update-database. It is very confusing how to add additional tables using a code first approach after that. A lot more documentation is needed regarding EF migrations with respect to managing projects over time. I see the benefits of having all of your database updates maintained from your VS project but it is not easy to understand.


text:
Q: Why mongoose Model object returned got a _id property, but id works as well in Typescript? I  was using Typescript to get an object
const query = Workflow.where({ _id: id });
const workflow = await query.findOne().exec();
console.log(workflow); // <-- (1) this console.log()
console.log(workflow.id); // <-- (2) this console.log()
return workflow;

Then I got:
{
  _id: 608e7fb7ee267e23fff1da65,
  title: 'WorkFlow 14',
  description: 'Este es un nuevo workflow',
  date: 2021-05-02T10:32:23.423Z,
  __v: 0
}
608e7fb7ee267e23fff1da65

As you note I got _id as property in first console.log but the when I console.log workflow.id I get the result.
My Schema
import mongoose from 'mongoose';

const WorkflowSchema = new mongoose.Schema({
  title: { type: String, required: true },
  description: { type: String, required: false },
  date: { type: Date, default: Date.now },
});

export default mongoose.model('Workflow', WorkflowSchema);

This happens only with id property.
Why did it works? I expected an Error or an undefined at least.

A: id is string version of _id and this getter exists on all documents by default.
More info here.

A: This is a feature of Mongoose. So it is not happening because you are using TypeScript, it would also happen if you did it in JavaScript.

Mongoose assigns each of your schemas an id virtual getter by default
which returns the document's _id field cast to a string, or in the
case of ObjectIds, its hexString.


text:
Q: Exe running in C # windows service I am writing with c # windows service. Tickers in this manner when it is working without a problem.
bool processIsRunning(string process)
{
    return (System.Diagnostics.Process.GetProcessesByName(process).Length != 0);
}
if (!processIsRunning("notepad"))
{
    Process.Start("notepad.exe");
}

When the codes are not working this way.
StreamReader read = new StreamReader(Environment.GetEnvironmentVariable("appdata") + "\\path.txt");
string path = oku.ReadLine();
string processname = Path.GetFileName("notepad");
if (processIsRunning(processname) == false)
{
    System.Diagnostics.Process.Start(path);
}

I'm getting the name of the program and the program path from registry.

A: Your question doesn't make a lot of sense, but there are some possible problems if the code you have posted is your entire relevant code.
Your StreamReader is called read, yet you are trying to read from a stream called oku?
Also, you haven't shown that you actually close your StreamReader, you would be better of using ausing` block to make sure that your Stream is properly closed and disposed of.
using (StreamReader read = new StreamReader(Environment.GetEnvironmentVariable("appdata") + "\\path.txt"))
{
    string path = read.ReadLine();
    string processname = Path.GetFileName("notepad");
    if (processIsRunning(processname) == false)
    {
        System.Diagnostics.Process.Start(path);
    }
}


text:
Q: Can you have
*s without them being under a
* or
*? I have a navigation that I am using a list for. I have it in a
, but that is messing up my UI because it has weird automatic margins. I tried without the
 and they seem to work. Would this work across all browsers? Is this legal? Anybody else done this before?

A: It's not valid HTML to use
 outside an ol, ul, or menu element. It's much better to assign a class to the ul element:

And then use CSS to remove the margin and padding:
.nav {
    margin: 0;
    padding: 0;
}

A: It's probably working in browsers because browsers are too forgiving, but that's not valid says the validator:

Document type does not allow element "li" here; missing one of "ul", "ol", "menu", "dir" start-tag

Well, you can remove customize margins in CSS. That's your only solution. Generally, you can remove it on all
 tags in the documents by:
ul {
    margin: 0;
    padding: 0;
}

In case you're wondering what padding is, see it here.

A: You can, and almost all browsers will recognize it, but it's not good, semantic HTML, and won't validate.
Try removing the margin and padding for the ul in your stylesheet:
#the-specific-ul { margin: 0; padding: 0; }

A: This might not answer your question directly, but I'm wondering if you use a CSS reset?
I have found since I started using them, I don't encounter those sort of issues any more.
http://developer.yahoo.com/yui/3/cssreset/
Also, another thing to consider is that your nav doesn't have to be in
's (necessarily). Why not make them just links in a

Hope this helps!

A: The UL and LI combination are one of the most liberally interpreted elements in all of HTML. Meaning they tend to look wildly different depending on which browser you use. As others suggest, reset the margins and paddings to 0. But you should be doing this anyway in a reset stylesheet, so that you catch the other elements that display differently across browsers.


text:
Q: Many "Emulator unknown emulator - xxxx [null]"s are redundantly shown in android studio this is more of a benign bug in android studio. Whenever I wake my computer from sleep or hibernate the connection between the emulator and android studio is not proper and I have to restart the emulator and try again, so as a result of that (I think) all the dead emulators are always shown in the listing when trying to run the app.
And FYI I don't usually restart/shutdown my computer (once in 10 days or so). I was just wondering if there was a way to fix this bug without having to restart the computer.

Screenshot of problem
Thanks in advance!

A: I am having the same issue using Windows 10 hibernate.
Try terminating the adb.exe process in the task manager. Sometimes you will find two or more adb.exe processes, kill them all. Then close all running emulators (if any) and disconnect all physical devices.
You don't have to restart android studio or eclipse.
After dong this, all unknown/null emulators should be gone (at least in my case).

A: Did you open multiple android studio and use the terminal in android studio?
you can close all android studio, and restart them. the unknown emulator will be gone


text:
Q: Stubbing .sample in Ruby - Rails project using Il8n gem I am working on a description generator feature that will look at an objects attributes and populate a description by pulling strings from various locales (in multiple languages) that are already setup.
I have the following code
module Rooms
  class DescriptionGenerator
  attr_reader :room, :locale

  def initialize(room, locale="en")
    @room = room
    @locale = locale
  end

  private

  def t(key, options={})
    I18n.t("rooms.description_generator.#{key}", options.merge({ locale: locale }))
  end

  def wifi
    t("wifi", room_type: room.room_type.type).values.sample if room.wifi
  end

I then have the following test:
describe "#wifi" do
  let!(:room_with_wifi) { create(:room, :visible, wifi: true) }
  let!(:room) { create(:room) }

  #This one is failing
  it "returns wifi sentence if room has wifi" do
    sentence = I18n.t('rooms.description_generator.wifi', room_type: room_with_wifi.room_type.type).values.sample
    expect(Rooms::DescriptionGenerator.new(room_with_wifi,"en").send(:wifi)).to eq (sentence)
  end

  it "returns nil if room does not have wifi" do
    expect(Rooms::DescriptionGenerator.new(room,"en").send(:wifi)).to eq nil
  end
end

My question is "What is the best way to test this given the use of sample?"
My original solution (which I am pretty sure is not recommended) was to add:
class DescriptionGenerator
  def sample(arr)
    if Rails.env.test?
      arr.values.first
    else
      arr.sample.values
    end
  end
end

This 'enforced' that RSpec would take the first option from my locales set out like this:
three_positive_reviews:
  a: "This is not so great"
  b: "This %{string_for_interpolation} is great."
  c: "This is bad"

This was all passing until I added a string to be interpolated into the first (a) that was being used in the test and realised that in i18n gem does not support interpolation within an array (Interpolation in I18n array).
So I refactored to:
def t(key, options={})
  value = I18n.t("rooms.description_generator.#{key}")
  key = "#{key}.#{sample(value.keys)}" if value.is_a?(Hash)
  I18n.t("rooms.description_generator.#{key}", options.merge({ locale: locale }))
end

def sample(keys)
  if Rails.env.test?
    keys.first
  else
    keys.sample
  end
end

This now passes my test suite - however having looked at this in some detail wanted to ask for more optimal solutions & also how I more appropriately test (perhaps by stubbing sample??) without the line
if Rails.env.test?

A: I would do the following (I didn't run the code, thought):
let(:room) { create(:room) }
let(:locale) { 'en' }
let(:generator) { Rooms::DescriptionGenerator.new(room, locale) }

describe '#wifi' do
  let(:wifi_sentences) do
    I18n.t('rooms.description_generator.wifi', locale: locale)).values
  end

  context 'when the room has wifi' do
    it 'returns wifi sentence' do
      expect(generator.send(:wifi)).to be_in(wifi_sentences)
    end
  end

  context 'when the room has no wifi' do
    before do
      allow(room).to receive(:wifi).and_return(false) # or nil, don't know
    end

    it 'returns nil' do
      expect(generator.send(:wifi)).to be(nil)
    end
  end
end

Hope this helps :)

A: Thanks Victor for your answer - extremely helpful to refactor my tests. I wanted to post up my final solution which takes your advice into account with a few tweaks in case it's useful for others.
let(:room) { create(:room) }
let(:locale) { 'en' }
let(:generator) { Rooms::DescriptionGenerator.new(room, locale) }

describe "#laundry" do
  it "returns wifi sentence if room has wifi" do
    sentence = "This apartment is equipped with laundry facilities."
    room.laundry = true
    expect(generator.send(:laundry)).to eq(sentence)
  end

  it "returns nil if room is not have laundry" do
    expect(generator.send(:laundry)).to eq nil
  end
end

This works for a simple one option locale:
  laundry: "This %{room_type} is equipped with laundry facilities."

However due to the fact that Rails i18n cannot interpolate strings within an array (i.e. when there are multiple key-value pairs offered up) I stubbed sample.
context "translations with multiple options that require interpolation" do
  before do
    allow(generator).to receive(:sample) { |keys| keys.first }
  end

  describe "#three_positive_reviews" do

   context 'when the room has 3 positive reviews' do
     before do
       3.times do
         create(:feedback, :non_external, :positive, room: room)
       end
     end

    it "returns three_positive_reviews sentence" do
      sentence = "This apartment is highly reviewed"
      expect(generator.send(:three_positive_reviews)).to eq(sentence)
    end
  end

  context 'when the room does not have 3 positive reviews' do
    it "returns nil" do
      expect(generator.send(:three_positive_reviews)).to eq nil
    end
  end

and was then able to recfactor my sample method in my code to:
def sample(keys)
  keys.sample
end

This seems like a cleaner solution to me than my original posted in the question.


text:
Q: Draw a pandas plot like "Americans are more confident than Britons that they could beat any animal in a fight" by YouGov I'd like to plot a graph like this tweet:

Does anyone know how to create a graph like this in matplotlib/seaborn?
I tried making a similar graph using matplotlib, but am having difficulties.


text:
Q: Choice of server for local Django webapp? I've put together a Django app that was intended to run on Pythonanywhere. However, I soon found out that Pythonanywhere's free plan blocks the remote sites which I intend to interact with, so I decided running the app on a local machine would be good enough for my purposes.
Now, I know that Django's development server isn't meant to be run in a production setting. So, what server daemon do I run on the aging Windows workstation the app's probably gonna be deployed to? Apache, lighttpd, Cherokee? Something else?
My first priority here is conserving system resources as much as I can; I'm probably also going to use Python's built-in sqlite3 instead of MySQL.

A: Personally I deploy Django with fcgi and Nginx. Nginx offers various strategies to conserve system resources; its use as reverse proxy is well documented and widely used.
The question/answer pair here might help you clear some initial questions about the various components when deploying Django.

A: Sorry to hear you can't use PythonAnywhere's free version :-(
I'll second the usage of nginx; it's what we use as the front-end for PA.  However, we use uwsgi for the backend.  It works really well for us and is very easy to configure.


text:
Q: OpenLayers 3: putting an image (or logo/legend) on the map I'm relatively new to OpenLayers. How to insert a simple image (or logo/legend) on the map?
From this example, http://jsfiddle.net/expedio/od5eLpb9/
Is it possible to overlay the legend (that in this case is a simple image) on the map?

A: Just put the
...
 in
 like below:

    Load a QGIS-Server-WMS-Layer to OpenLayer3

Legend:

and add the styling as:

    #legende{
position: absolute;
z-index: 100000;
}

Now you further set the size and position of lengends in CSS only. All the Best


text:
Q: Does a r.e. language as a r.e. set assume some encoding from the set of all words to the set of natural numbers? https://en.wikipedia.org/wiki/Recursively_enumerable_set says

A subset S of the set of natural numbers is called recursive enumerable, if there is a partial recursive function whose domain is exactly S.

A recursive enumerable language is a recursive enumerable subset of a formal language.

*

*Does "A recursive enumerable language is a recursive enumerable subset of a formal language" mean "A recursive enumerable language is a recursive enumerable subset of $\Sigma^*$" instead?

*Does the second sentence for a recursive enumerable language assume some encoding from the set of all words over an alphabet to the set of all natural numbers? What is some classic encoding?
Similar questions about that https://en.wikipedia.org/wiki/Recursive_set says:

A subset S of the set of natural numbers is called recursive if there exists a total recursive function whose domain is exactly S.

A recursive language is a recursive subset of a formal language.

Thanks.

A: We have many equivalent options here, analogously to how there are many equivalent formulations of computability in the first place; and just as in that situation, the equivalences between all reasonable notions let us be pretty blithe about the details.
The two main points to have in mind are the following:

*

*We can define "recursively enumerable subset of $\Sigma^*$" for any finite language $\Sigma$ directly: as the set of strings in $\Sigma$ accepted by some Turing machine with alphabet some superset of $\Sigma^*$. This doesn't involve any coding and is totally unambiguous; however, it really only works for finite $\Sigma$s.

*Alternatively, given a finite language $\Sigma$ we can consider for each $f:\Sigma^*\rightarrow\mathbb{N}$ the notion of computability gotten by saying that $X\subseteq\Sigma^*$ is recursively enumerable via $f$ if $f[X]:=\{f(x): x\in X\}$ is an r.e. subset of $\mathbb{N}$. Note that of course this will depend on the choice of $f$. On the plus side, this generalizes quite a lot and is a useful abstraction down the road.
It turns out that any "natural" choice of $f$ will result in the first version of r.e.-ness, and moreover such an $f$ is easy to whip up. For a generally applicable example, fix some numbering $\{\sigma_1,...,\sigma_k\}$ of $\Sigma$ and consider the map $\sigma_{i_1}\sigma_{i_2}...\sigma_{i_n}\mapsto p_1^{i_1}p_2^{i_2}...p_n^{i_n}$ where $p_j$ denotes the $j$th prime; for a particularly nice example in the case where $\Sigma=\{0,1\}$, just send $x\in\{0,1\}^*$ to the natural number with binary expansion $1x$ (so e.g. "$010$" goes to $1010_2=10$). So we tend to ignore the details here.


text:
Q: Debugging dynamically added javascript files I have a web application which dynamically adds javascript files based on what the user chooses as options using ajax in real time to avoid refreshing the screen.
I am now trying to debug these dynamically added javascript files and have tried both Google Chrome's developer tools and Firebug's pluggin for Firefox, and have noticed that the dynamically added javascript "files" do not appear, so I can't select them to add breakpoints etc.
So, is there a solution for this, i.e. debugging dynamically added javascript files?

A: You can add the debugger; statement in your dynamic scripts where you want to set the breakpoint. This will make chrome stop on it like a regular breakpoint if the execution thread reaches the statement while the developper tools UI is opened.
You can also start your script with that, so your script appears in the debugger, and you can after that manually set a breakpoint where you want.

A: Check out sourceURL which is a way to indicate to the DevTools that should treat eval'd strings as real files. It does exactly what you're looking for.
At the end of the string to be evaled, leave comment of this form:
//# sourceURL=app/js/myapp.js

From there, Chrome DevTools (and Firebug) will treat this as a "real file".
Much more explanation here and HTML5 Rocks has an article and a sourceURL demo.


text:
Q: MySQL - How do I horizontally fill columns Say I have a dataframe that looks like this
|------|------|------|------|------|------|------|------|------|------|------|
| t_0  | t_1  | t_2  | t_3  | t_4  | t_5  | t_6  | t_7  | t_8  | t_9  | t_10 |
|------|------|------|------|------|------|------|------|------|------|------|
|  1   | N/A  | N/A  | N/A  |  6   | N/A  | N/A  |  8   |  14  |  3   | N/A  |
|------|------|------|------|------|------|------|------|------|------|------|
| N/A  |  6   |  9   |  2   |  5   | N/A  |  8   |  8   |  8   | N/A  |  N/A |
|------|------|------|------|------|------|------|------|------|------|------|
|  6   | N/A  | N/A  | N/A  | N/A  | N/A  | N/A  | N/A  | N/A  | N/A  | N/A  |
|------|------|------|------|------|------|------|------|------|------|------|
|  N/A | N/A  |  9   | N/A  | N/A  |  3   | N/A  | N/A  | N/A  | N/A  | N/A  |
|------|------|------|------|------|------|------|------|------|------|------|

And I want to do a horizontal fill left to right
|------|------|------|------|------|------|------|------|------|------|------|
| t_0  | t_1  | t_2  | t_3  | t_4  | t_5  | t_6  | t_7  | t_8  | t_9  | t_10 |
|------|------|------|------|------|------|------|------|------|------|------|
|  1   |  1   |  1   |  1   |  6   |  6   |  6   |  8   |  14  |  3   |  3   |
|------|------|------|------|------|------|------|------|------|------|------|
| N/A  |  6   |  9   |  2   |  5   |  5   |  8   |  8   |  8   |  8   |   8  |
|------|------|------|------|------|------|------|------|------|------|------|
|  6   |  6   |  6   |  6   |  6   |  6   |  6   |  6   |  6   |  6   |  6   |
|------|------|------|------|------|------|------|------|------|------|------|
|  N/A | N/A  |  9   |  9   |  9   |  3   |  3   |  3   |  3   |  3   |  3   |
|------|------|------|------|------|------|------|------|------|------|------|

Such that the code can be generalized to any number of columns (shown here are 11, but I'd need it to work for any number)
Edit: The raw data is normalized, but I'm making an algorithm that used to be spark only run outside of spark, which is why the data is spread out the way it is

A: Keep in mind that is very slow query.
Don't use it if you have a choice
SELECT
   @x:=t_0,
   IF(t_1 IS NULL,@x, @x:=t_1),
   IF(t_2 IS NULL,@x, @x:=t_2),
   IF(t_3 IS NULL,@x, @x:=t_3),
   IF(t_4 IS NULL,@x, @x:=t_4),
   IF(t_5 IS NULL,@x, @x:=t_5),
   IF(t_6 IS NULL,@x, @x:=t_6),
   IF(t_7 IS NULL,@x, @x:=t_7),
   IF(t_8 IS NULL,@x, @x:=t_8),
   IF(t_9 IS NULL,@x, @x:=t_9),
   IF(t_10 IS NULL,@x, t_10),
FROM t

In most cases you should apply this kind of calculation and replacement on your backend language (php, java, .net, whatever). Try to get only raw data from MySQL but not to use it as regular language or Excel sheet. Split getting data process from transformation and representation data process. These are two different things. That could seem not obvious to you at the beginning but with time you will love this separation (I hope and I wish to you :-))

A: Here's an expanded version of @Alex's answer that will work for any given table. As everyone has mentioned so far, the data should be normalized.  Seeing how convoluted all of this is should hopefully clarify why it's a bad idea.
SET @db = 'demo';
SET @table = 'test';
SET @firstColumn = (SELECT column_name FROM information_schema.columns WHERE table_schema=@db AND table_name=@table ORDER BY ordinal_position LIMIT 1);
SET @query = CONCAT('SELECT @x:=',@firstColumn,',');
SELECT @query := CONCAT(@query,'IF(',column_name,' IS NULL,@x, @x:=',column_name,'),') FROM information_schema.columns WHERE table_schema=@db AND table_name=@table ORDER BY ordinal_position;
SET @query = CONCAT( MID(@query,1,LENGTH(@query)-1),' FROM ',@db,'.',@table);
PREPARE statement FROM @query;
EXECUTE statement;


text:
Q: Login screen recording in JMeter repeating url issue I need your help, I have recorded a login script in blaze meter and importing it into JMeter what I noticed that browsing URL is repeating like site.com/0, site.com/1,site.com/2 and so on. Please suggest what to do to fix it asap help required. thanks.
I am trying to record a login script in blaze meter when I imported the script in JMeter I found that the browsing URL is repeating. like example.com/0, example.com/1,and so on. please help me.

A: We cannot "help" without knowing what are your expectations.
When it comes to performance testing of web applications you need to ensure that JMeter is properly configured to behave exactly like a real browser.
It means that JMeter should send the same requests and in the same manner as the real browser does.
In case if the network footprint generated by JMeter matches the one which the real browser produces - you don't need any "help" there. If it doesn't - we need to see:

*

*the dump of requests from "Network" tab of your browser's developer tools

*how did you configure the BlazeMeter Chrome Extension, i.e. choosing "Only top level requests" might "help" you

Normally these numeric postfixes are used as the naming convention for the Transaction Controller to all nested redirects, embedded resources and so on would be considered an integral part of the parent "transaction"


text:
Q: invalid number format model oracle error inserting a char I am trying to create an Oracle stored procedure that simply inserts a row into a table.  There is a column in the table (MEAS_IND) that is type char(1 byte) and cannot be null.  When I try to insert any one character into the column/table I get the error:

ORA-01481: invalid number format model
ORA-06512: at "IFDC.PKG_FIELD_ASSISTANT", line 326
ORA-06512: at line 3
01481. 00000 -  "invalid number format model"
*Cause:    The user is attempting to either convert a number to a string
           via TO_CHAR or a string to a number via TO_NUMBER and has
           supplied an invalid number format model parameter.
*Action:   Consult your manual.

I have tried inserting ' ', 'N' and to_char(' ').  There are other columns that cannot be null and seem to work fine.  When I comment out MEAS_IND I get the error that it cannot be null, so I am assuming that the other columns are fine. Here is the code:
INSERT INTO myTable
          (
            cont_id
            , cms_uid
            , dwr_dt
            , prj_nbr
            , ln_itm_nbr
            , loc_seq_nbr
            , loc_instld
            , vend_id
            , rpt_qty
            , itm_cd
            , last_modfd_uid
            , last_modfd_dt
            , catg_nbr
            , rmrks_id, plan_pg_ref_nbr, ref_doc, fr_sta_itm, fr_sta_dstnc, fr_sta_offst_t, fr_sta_offst_dstnc
            , to_sta_itm, to_sta_dstnc, to_sta_offst_t, to_sta_offst_dstnc, meas_ind
          )
       VALUES
          (
            pContractId
            , pUSER_ID
            , pDRW_DATE
            , pProject_num
            , pPLN
            , vMaxLocSeq
            , pLocation
            , pVend_id
            , pAmount
            , pItemCode
            , pUSER_ID
            , to_number(sysdate, 'YYYYMMDD')
            , vCatigoryNumber
            , ' ', ' ', ' ', ' ', 0, ' ', 0
            , ' ', 0, ' ', 0, ' '
          ) ;

Thanks in advance

A: Instead of to_number(sysdate, 'YYYYMMDD'), do this:
to_number(to_char(sysdate, 'YYYYMMDD'))

Better yet, if it's not too late in the project then change the last_modfd_dt column to a DATE type. The DATE type will include the date and the time of day (hours, minutes, seconds but no fractional seconds). If you just want the date without the time, set it as trunc(sysdate).


text:
Q: How to store a random value and call it from a click function in selenium webdriver by Jasmine JS? I want to save a random number between 1 to 31 and use it from a 'click' function in order to click about the saved random number by a 'linkText' locator.
Is it possible?
I need something like:
 var randomDay = Math.floor(31*Math.random() + 1);
 element(by.linkText(randomDay)).click();

The full test is below:
describe('Selenium Test Case', function() {

beforeEach(function(){
    browser.ignoreSynchronization = true;
});

afterEach(function(){
    browser.ignoreSynchronization = false;
});

  it('should execute test case without errors', function() {
    var text, value, bool, source, url, title;
    var TestVars = {};
    var randomDay = Math.floor(31*Math.random() + 1);

browser.get("https://www.mywebsite.com/");
    captureScreen();
browser.driver.sleep(3000);
element(by.xpath("//div[@class='actions-row']//a[.='Schedule Now']")).click();
    captureScreen();
browser.driver.sleep(3000);
element(by.css("div.service-info")).click();
    captureScreen();
browser.driver.sleep(3000);
element(by.css("span.gray-button-style")).click();
browser.driver.sleep(3000);
element(by.linkText("Next")).click();
browser.driver.sleep(3000);
    element(by.linkText(randomDay)).click();
browser.driver.sleep(3000);
element(by.id("class=icon")).click();
browser.driver.sleep(3000);
element(by.linkText("Continue")).click();
element(by.name("email")).sendKeys("idanvcita@gmail.com");
element(by.xpath("(//textarea[@id='agenda'])[2]")).sendKeys("hello again");
element(by.linkText("Submit")).click();
element(by.linkText("Done")).click();
    captureScreen();
browser.driver.sleep(3000);
  });
});

The error is below:
Failures:
 1) Selenium Test Case should execute test case without errors
   Message:
     UnknownError: java.lang.Long cannot be cast to java.lang.String
   Stacktrace:
     UnknownError: java.lang.Long cannot be cast to java.lang.String
    at new bot.Error (C:\Users\idan\AppData\Roaming\npm\node_modules\protractor\
node_modules\selenium-webdriver\lib\atoms\error.js:113:18)
    at Object.bot.response.checkResponse (C:\Users\idan\AppData\Roaming\npm\node
_modules\protractor\node_modules\selenium-webdriver\lib\atoms\response.js:106:9)

 at C:\Users\idan\AppData\Roaming\npm\node_modules\protractor\node_modules\se
lenium-webdriver\lib\webdriver\webdriver.js:377:20
    at [object Object].promise.ControlFlow.runInFrame_ (C:\Users\idan\AppData\Ro
aming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\
promise.js:1877:20)
    at [object Object].promise.Callback_.goog.defineClass.notify (C:\Users\idan\
AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\
webdriver\promise.js:2464:25)
    at [object Object].promise.Promise.notify_ (C:\Users\idan\AppData\Roaming\np
m\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\promise.
js:563:12)
    at Array.forEach (native)
    at Object.goog.array.forEach (C:\Users\idan\AppData\Roaming\npm\node_modules
\protractor\node_modules\selenium-webdriver\lib\goog\array\array.js:203:43)
    at [object Object].promise.Promise.notifyAll_ (C:\Users\idan\AppData\Roaming
\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\promi
se.js:552:16)
    at goog.async.run.processWorkQueue (C:\Users\idan\AppData\Roaming\npm\node_m
odules\protractor\node_modules\selenium-webdriver\lib\goog\async\run.js:125:21)
Error
    at [object Object].ElementArrayFinder.applyAction_ (C:\Users\idan\AppData\Ro
aming\npm\node_modules\protractor\lib\element.js:403:21)
    at [object Object].self.(anonymous function) [as click] (C:\Users\idan\AppDa
ta\Roaming\npm\node_modules\protractor\lib\element.js:76:19)
    at [object Object].self.(anonymous function) [as click] (C:\Users\idan\AppDa
ta\Roaming\npm\node_modules\protractor\lib\element.js:733:11)
    at [object Object].<anonymous> (c:\automation\tests\meeting.js:30:41)
    at C:\Users\idan\AppData\Roaming\npm\node_modules\protractor\node_modules\ja
sminewd\index.js:94:14
    at [object Object].promise.ControlFlow.runInFrame_ (C:\Users\idan\AppData\Ro
aming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\
promise.js:1877:20)
    at [object Object].promise.ControlFlow.runEventLoop_ (C:\Users\idan\AppData\
Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdrive
r\promise.js:1755:8)
    at [object Object].<anonymous> (C:\Users\idan\AppData\Roaming\npm\node_modul
es\protractor\node_modules\selenium-webdriver\lib\webdriver\promise.js:2056:12)
    at goog.async.run.processWorkQueue (C:\Users\idan\AppData\Roaming\npm\node_m
odules\protractor\node_modules\selenium-webdriver\lib\goog\async\run.js:125:21)
From: Task: Asynchronous test function: it()
    at [object Object].<anonymous> (C:\Users\idan\AppData\Roaming\npm\node_modul
es\protractor\node_modules\jasminewd\index.js:93:33)
    at [object Object].<anonymous> (C:\Users\idan\AppData\Roaming\npm\node_modul
es\protractor\node_modules\minijasminenode\lib\async-callback.js:45:37)
    at [object Object].jasmine.Block.execute (C:\Users\idan\AppData\Roaming\npm\
node_modules\protractor\node_modules\minijasminenode\lib\jasmine-1.3.1.js:1174:1
7)
 at [object Object].jasmine.Queue.next_ (C:\Users\idan\AppData\Roaming\npm\no
de_modules\protractor\node_modules\minijasminenode\lib\jasmine-1.3.1.js:2209:31)

at onComplete (C:\Users\idan\AppData\Roaming\npm\node_modules\protractor\nod
e_modules\minijasminenode\lib\jasmine-1.3.1.js:2205:18)
    at [object Object].jasmine.WaitsForBlock.execute (C:\Users\idan\AppData\Roam
ing\npm\node_modules\protractor\node_modules\minijasminenode\lib\jasmine-1.3.1.j
s:2704:5)
    at [object Object]._onTimeout (C:\Users\idan\AppData\Roaming\npm\node_module
s\protractor\node_modules\minijasminenode\lib\jasmine-1.3.1.js:2718:12)
Error
    at [object Object].<anonymous> (c:\automation\tests\meeting.js:11:3)
    at [object Object].jasmine.Env.describe_ (C:\Users\idan\AppData\Roaming\npm\
node_modules\protractor\node_modules\minijasminenode\lib\jasmine-1.3.1.js:913:21
)
    at [object Object].jasmine.Env.describe (C:\Users\idan\AppData\Roaming\npm\n
ode_modules\protractor\node_modules\minijasminenode\lib\jasmine-1.3.1.js:898:15)

 at describe (C:\Users\idan\AppData\Roaming\npm\node_modules\protractor\node_
modules\minijasminenode\lib\jasmine-1.3.1.js:658:27)
    at Object.<anonymous> (c:\automation\tests\meeting.js:1:63)

A: It seems you have a casting error. Try to pass the number as string.

A: It should be like this:
var randomDay = Math.floor(31*Math.random() + 1);
var randomDayLink = randomDay.toString();
element(by.linkText(randomDayLink)).click();


text:
Q: I want to designate a specific version for apt-upgrade We would like to use the /etc/apt/sources.list file to fix the apt-upgrade to version 20.04.2.
My current file looks like this.
deb http://archive.ubuntu.com/ubuntu/ focal main restricted universe
deb http://security.ubuntu.com/ubuntu/ focal-security main restricted universe
deb http://archive.ubuntu.com/ubuntu/ focal-updates main restricted universe
I think I'm getting a package info that 20.04.4, so I want to fix it to 20.04.2. What should I do?


text:
Q: Struggling to use upper and lower cases within my code I can not find a way for the code to work with both upper and lower case letters, i can only find a way for it to run for one or the other... Been trying for a while and still haven't managed, pretty new to this you see! Thanks in advance!
import java.util.*;
public class LectureTimes {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System. in );
        char letter;
        System.out.println("Enter your class and" + " you will recieve your lecture time");

        do {
            letter = sc.next().charAt(0);
        } while (letter < 'a' || letter > 'd');

        if (letter == 'A') {
            System.out.println("Your class is at 10:00");
        } else {
            if (letter == 'a') {
                System.out.println("Your class is at 10:00");
            } else {
                if (letter == 'B') {
                    System.out.println("Your class is at 12:00");
                } else {
                    if (letter == 'b') {
                        System.out.println("Your class is at 12:00");
                    } else {
                    }
                    if (letter == 'C') {
                        System.out.println("Your class is at 14:00");
                    } else {
                        if (letter == 'c') {
                            System.out.println("Your class is at 14:00");
                        } else {
                            System.out.println("Your group does not exist, please select one that does...");
                        }
                    }
                }
            }
        }
    }
}

A: Since no one has posted the switch case solution yet, here it is:
switch (letter) {
        case 'A':
        case 'a':
            System.out.println("Your class is at 10:00");
            break;
        case 'B':
        case 'b':
            System.out.println("Your class is at 12:00");
            break;
        case 'C':
        case 'c':
            System.out.println("Your class is at 14:00");
            break;
        default:
            System.out.println("Your group does not exist, please select one that does...");
            break;
}

Personally, I find this to be the most readable solution.

A: Why you don't use String method toUpperCase() and check only for upper-case variants?
String myClass = (letter + "").toUpperCase();

    if (myClass.equals("A")) {
        System.out.println("Your class is at 10:00");
    } else {
        if (myClass.equals("B")) {
            System.out.println("Your class is at 12:00");
        } else
        if (myClass.equals("C")) {
            System.out.println("Your class is at 14:00");
        } else {
            System.out.println("Your group does not exist, please select one that does...");
        }

    }

You also can use regex Pattern for this:

A: Use String.toLowerCase() or String.toUpperCase() methods.  Like
 if (letter.toLowerCase().equals("a")) {
       System.out.println("Your class is at 10:00");
 }

One more thing, use equals() method to check for equality!

A: you can try changing the while loop like below. Your current loop is only checking a to d. Below loop will keep running if its
- < A
- > d
- between D and a

do .. while((letter <'a' && letter > 'D') || letter < 'A' || letter > 'd');

A: if(letter == 'A' || letter == 'a'){
    System.out.println("Your class is at 10:00");
} else if(letter == 'B' || letter == 'b'){
    System.out.println("Your class is at 12:00");
} else if (letter == 'C' || letter == 'c'){
    System.out.println("Your class is at 14:00");
} else {
    System.out.println("Your group does not exist, please select one that does...")
}

this is my way to look your code cleaner and does not need to use String function which consume more resource.