cypress check color of css background - cypress

I have this assertion :
cy.get('.myelement').should('have.css', 'background-color','rgb(75, 221, 51)')
I want to replace it with hexadecimal representation as following:
cy.get('.myelement').should('have.css', 'background-color','#4BDD33')
but I get this error from cypress :
expected <.myelement> to have CSS property background-color with the value #4BDD33, but the value was rgb(75, 221, 51)
any help

You can do something like this:
Install the rgb-hex package
npm install rgb-hex
In your test suite file import the package
import rgbHex from 'rgb-hex';
In your test write:
cy.get('.myelement')
.invoke('css', 'background-color')
.then((bgcolor) => {
expect(rgbHex(bgcolor)).to.eq('4bdd33')
})

I'd take the reverse approach of Alapan -- I prefer to modify my expected and leave my actual values alone. To do this, you'd need a way to turn your expected Hex value into the rgb() format.
const hexToRgb = (hex) => {
const rValue = ParseInt(hex.substring(0, 2), 16);
const gValue = ParseInt(hex.substring(2, 4), 16);
const bValue = ParseInt(hex.substring(4), 16);
return `rgb(${rValue}, ${gValue}, ${bValue})`;
}
cy.get('.myelement').should('have.css', 'background-color', hexToRgb('4BDD33'));
If you wanted to include the # in the hex string, you would just need to ignore it in setting the values, most likely by increasing every number in the substring() functions by one.
Overall, I think that Alapan's solution is easier, but this is just something to consider.

Related

Latex nested loop not displaying correctly

Hi I'm new to latex I use here the Algorithmic package to write my pseudo code the problem I faced is that 'some text' is displayed correctly under the second loop but the 'return' statement which needs to be outside the first for loop isn't showing correctly also it does not mark the end of each loop (the vertical tic is missing), the execution result is shown in the image:
\documentclass{article}
\usepackage[utf8,linesnumbered,ruled,vlined]{algorithm2e}
\usepackage {algpseudocode}
\usepackage{algorithmicx}
\usepackage{algcompatible}
\begin{document}
\begin{algorithm}
\ContinuedFloat
\caption{My algorithm}
\textbf{Input:} solution,bound, data\_matrix, vehicle\_capacity, demand\_data,k\_max,operations\_data, move\_type,tenure, max\_number\_of\_moves,max\_iter,non\_improvement\_maxiter,itermax,epsilon\\
\textbf{Output:} $best$ $solution$ \\[0.1in]
routes = extract routes from \textbf{solution}\\
oldfitness = fitness(\textbf{solution})\\
ls\_move\_type = inversion\\
best\_solution = routes\\[0.1in]
\For{0 \leq i \leq itermax}{
new\_routes = [ ]\\
desc = 'normal route'\\
\For{route \textbf{in} routes}{
n=length(route)\\
comb = int($\frac{n!}{(n-2)!}$)\\
\If{n \geq 4}{
tabu\_list\_tenure = $\frac{comb}{5}$\\
ls\_maxiteration = 50 \\
ls\_move\_type = 'inversion'\\
}
\If{3 \leq n \leq 4}{
tabu\_list_tenure = $\frac{comb}{4}$ \\
ls\_maxiteration = 25\\
ls\_move\_type = 'relocation'\\
}
\Else{
append \textbf{route} to \textbf{new\_routes}\\
desc = 'short route'\\
}\\[0.1in]
}
some action
}
return
\end{algorithm}
\end{document}
There is no point in wondering about the output as long as you get errors in your .log file. After an error, latex only recovers enough to syntax check the rest of the document, not necessarily producing sensible output.
Some of the most critical problems:
never ignore error messages!
utf8 isn't a valid option for the algorithm2e package
\ContinuedFloat is not defined by default. If you want to use it, you need a package which defines it. Maybe you want to use the caption package?
never ever use math mode to fake italic text as in $best$ $solution$. This completely messes up the kerning
some of your _ are not escaped
you mustn't use math commands like 0 \leq i \leq outside of math mode
use something like \Return to properly format it
using \\ for line breaks is already quite questionable, but using them two times in a row is simply an error.
because one can't say it often enough: never ignore error messages!
\documentclass{article}
\usepackage[
%utf8,
linesnumbered,ruled,vlined]{algorithm2e}
\usepackage {algpseudocode}
\usepackage{algorithmicx}
\usepackage{algcompatible}
\begin{document}
\begin{algorithm}
%\ContinuedFloat
\caption{My algorithm}
\textbf{Input:} solution,bound, data\_matrix, vehicle\_capacity, demand\_data,k\_max,operations\_data, move\_type,tenure, max\_number\_of\_moves,max\_iter,non\_improvement\_maxiter,itermax,epsilon
\textbf{Output:} \emph{best solution}
\medskip
routes = extract routes from \textbf{solution}
oldfitness = fitness(\textbf{solution})
ls\_move\_type = inversion
best\_solution = routes
\medskip
\For{$0 \leq i \leq$ itermax}{
new\_routes = [ ]
desc = 'normal route'
\For{route \textbf{in} routes}{
n=length(route)
comb = int($\frac{n!}{(n-2)!}$)
\If{$n \geq 4$}{
tabu\_list\_tenure = $\frac{comb}{5}$
ls\_maxiteration = 50
ls\_move\_type = 'inversion'
}
\If{$3 \leq n \leq 4$}{
tabu\_list\_tenure = $\frac{comb}{4}$
ls\_maxiteration = 25
ls\_move\_type = 'relocation'
}
\Else{
append \textbf{route} to \textbf{new\_routes}
desc = 'short route'
}
\medskip
}
some action
}
\Return
\end{algorithm}
\end{document}

With ruamel.yaml how can I conditionally convert flow maps to block maps based on line length?

I'm working on a ruamel.yaml (v0.17.4) based YAML reformatter (using the RoundTrip variant to preserve comments).
I want to allow a mix of block- and flow-style maps, but in some cases, I want to convert a flow-style map to use block-style.
In particular, if the flow-style map would be longer than the max line length^, I want to convert that to a block-style map instead of wrapping the line somewhere in the middle of the flow-style map.
^ By "max line length" I mean the best_width that I configure by setting something like yaml.width = 120 where yaml is a ruamel.yaml.YAML instance.
What should I extend to achieve this? The emitter is where the line-length gets calculated so wrapping can occur, but I suspect that is too late to convert between block- and flow-style. I'm also concerned about losing comments when I switch the styles. Here are some possible extension points, can you give me a pointer on where I'm most likely to have success with this?
Emitter.expect_flow_mapping() probably too late for converting flow->block
Serializer.serialize_node() probably too late as it consults node.flow_style
RoundTripRepresenter.represent_mapping() maybe? but this has no idea about line length
I could also walk the data before calling yaml.dump(), but this has no idea about line length.
So, where should I and where can I adjust the flow_style whether a flow-style map would trigger line wrapping?
What I think the most accurate approach is when you encounter a flow-style mapping in the dumping process is to first try to emit it to a buffer and then get the length of the buffer and if that combined with the column that you are in, actually emit block-style.
Any attempt to guesstimate the length of the output without actually trying to write that part of a tree is going to be hard, if not impossible to do without doing the actual emit. Among other things the dumping process actually dumps scalars and reads them back to make sure no quoting needs to be forced (e.g. when you dump a string that reads back like a date). It also handles single key-value pairs in a list in a special way ( [1, a: 42, 3] instead of the more verbose [1, {a: 42}, 3]. So a simple calculation of the length of the scalars that are the keys and values and separating comma, colon and spaces is not going to be precise.
A different approach is to dump your data with a large line width and parse the output and make a set of line numbers for which the line is too long according to the width that you actually want to use. After loading that output back you can walk over the data structure recursively, inspect the .lc attribute to determine the line number on which a flow style mapping (or sequence) started and if that line number is in the set you built beforehand change the mapping to block style. If you have nested flow-style collections, you might have to repeat this process.
If you run the following, the initial dumped value for quote will be on one line.
The change_to_block method as presented changes all mappings/sequences that are too long
that are on one line.
import sys
import ruamel.yaml
yaml_str = """\
movie: bladerunner
quote: {[Batty, Roy]: [
I have seen things you people wouldn't believe.,
Attack ships on fire off the shoulder of Orion.,
I watched C-beams glitter in the dark near the Tannhäuser Gate.,
]}
"""
class Blockify:
def __init__(self, width, only_first=False, verbose=0):
self._width = width
self._yaml = None
self._only_first = only_first
self._verbose = verbose
#property
def yaml(self):
if self._yaml is None:
self._yaml = y = ruamel.yaml.YAML(typ=['rt', 'string'])
y.preserve_quotes = True
y.width = 2**16
return self._yaml
def __call__(self, d):
pass_nr = 0
changed = [True]
while changed[0]:
changed[0] = False
try:
s = self.yaml.dumps(d)
except AttributeError:
print("use 'pip install ruamel.yaml.string' to install plugin that gives 'dumps' to string")
sys.exit(1)
if self._verbose > 1:
print(s)
too_long = set()
max_ll = -1
for line_nr, line in enumerate(s.splitlines()):
if len(line) > self._width:
too_long.add(line_nr)
if len(line) > max_ll:
max_ll = len(line)
if self._verbose > 0:
print(f'pass: {pass_nr}, lines: {sorted(too_long)}, longest: {max_ll}')
sys.stdout.flush()
new_d = self.yaml.load(s)
self.change_to_block(new_d, too_long, changed, only_first=self._only_first)
d = new_d
pass_nr += 1
return d, s
#staticmethod
def change_to_block(d, too_long, changed, only_first):
if isinstance(d, dict):
if d.fa.flow_style() and d.lc.line in too_long:
d.fa.set_block_style()
changed[0] = True
return # don't convert nested flow styles, might not be necessary
# don't change keys if any value is changed
for v in d.values():
Blockify.change_to_block(v, too_long, changed, only_first)
if only_first and changed[0]:
return
if changed[0]: # don't change keys if value has changed
return
for k in d:
Blockify.change_to_block(k, too_long, changed, only_first)
if only_first and changed[0]:
return
if isinstance(d, (list, tuple)):
if d.fa.flow_style() and d.lc.line in too_long:
d.fa.set_block_style()
changed[0] = True
return # don't convert nested flow styles, might not be necessary
for elem in d:
Blockify.change_to_block(elem, too_long, changed, only_first)
if only_first and changed[0]:
return
blockify = Blockify(96, verbose=2) # set verbose to 0, to suppress progress output
yaml = ruamel.yaml.YAML(typ=['rt', 'string'])
data = yaml.load(yaml_str)
blockified_data, string_output = blockify(data)
print('-'*32, 'result:', '-'*32)
print(string_output) # string_output has no final newline
which gives:
movie: bladerunner
quote: {[Batty, Roy]: [I have seen things you people wouldn't believe., Attack ships on fire off the shoulder of Orion., I watched C-beams glitter in the dark near the Tannhäuser Gate.]}
pass: 0, lines: [1], longest: 186
movie: bladerunner
quote:
[Batty, Roy]: [I have seen things you people wouldn't believe., Attack ships on fire off the shoulder of Orion., I watched C-beams glitter in the dark near the Tannhäuser Gate.]
pass: 1, lines: [2], longest: 179
movie: bladerunner
quote:
[Batty, Roy]:
- I have seen things you people wouldn't believe.
- Attack ships on fire off the shoulder of Orion.
- I watched C-beams glitter in the dark near the Tannhäuser Gate.
pass: 2, lines: [], longest: 67
-------------------------------- result: --------------------------------
movie: bladerunner
quote:
[Batty, Roy]:
- I have seen things you people wouldn't believe.
- Attack ships on fire off the shoulder of Orion.
- I watched C-beams glitter in the dark near the Tannhäuser Gate.
Please note that when using ruamel.yaml<0.18 the sequence [Batty, Roy] never will be in block style
because the tuple subclass CommentedKeySeq does never get a line number attached.

sort_values() got multiple values for argument 'axis'

sort_values() got multiple values for argument 'axis'
I am trying to sort this series using sort_values
Item Per Capita GSDP (Rs.)
Andhra_avg 102803
Arunachal_avg 100745
Assam_avg 55650.6
Bihar_avg 30030.6
Chattisgarh_avg 82046.7
Gujrat_avg 128755
Himachal_avg 126650
Jharkhand_avg 56385
Jammu_avg 73422.8
Karnataka_avg 128959
Kerala_avg 139140
MP_avg 61122.2
Maharashtra_avg 133512
my code:
dfGDP_percapita.sort_values("Item", axis = 0, ascending = True, inplace = True, na_position ='first')
Expected result should give "Per Capita GSDP (Rs.)" in the decreasing order with Nan on top
Try changing your code to
dfGDP_percapita.sort_values("Item", inplace=True, na_position ='first')
Some of the arguments are by default - I'm not sure why the error occurs, but my code works like this.

Using a complex likelihood in PyMC3

pymc.__version__ = '3.0'
theano.__version__ = '0.6.0.dev-RELEASE'
I'm trying to use PyMC3 with a complex likelihood function:
First question: Is this possible?
Here's my attempt using Thomas Wiecki's post as a guide:
import numpy as np
import theano as th
import pymc as pm
import scipy as sp
# Actual data I'm trying to fit
x = np.array([52.08, 58.44, 60.0, 65.0, 65.10, 66.0, 70.0, 87.5, 110.0, 126.0])
y = np.array([0.522, 0.659, 0.462, 0.720, 0.609, 0.696, 0.667, 0.870, 0.889, 0.919])
yerr = np.array([0.104, 0.071, 0.138, 0.035, 0.102, 0.096, 0.136, 0.031, 0.024, 0.035])
th.config.compute_test_value = 'off'
a = th.tensor.dscalar('a')
with pm.Model() as model:
# Priors
alpha = pm.Normal('alpha', mu=0.3, sd=5)
sig_alpha = pm.Normal('sig_alpha', mu=0.03, sd=5)
t_double = pm.Normal('t_double', mu=4, sd=20)
t_delay = pm.Normal('t_delay', mu=21, sd=20)
nu = pm.Uniform('nu', lower=0, upper=20)
# Some functions needed for calculation of the y estimator
def T(eqd):
doses = np.array([52.08, 58.44, 60.0, 65.0, 65.10,
66.0, 70.0, 87.5, 110.0, 126.0])
tmt_times = np.array([29,29,43,29,36,48,22,11,7,8])
return np.interp(eqd, doses, tmt_times)
def TCP(a):
time = T(x)
BCP = pm.exp(-1E7*pm.exp(-alpha*x*1.2 + 0.69315/t_delay(time-t_double)))
return pm.prod(BCP)
def normpdf(a, alpha, sig_alpha):
return 1./(sig_alpha*pm.sqrt(2.*np.pi))*pm.exp(-pm.sqr(a-alpha)/(2*pm.sqr(sig_alpha)))
def normcdf(a, alpha, sig_alpha):
return 1./2.*(1+pm.erf((a-alpha)/(sig_alpha*pm.sqrt(2))))
def integrand(a):
return normpdf(a,alpha,sig_alpha)/(1.-normcdf(0,alpha,sig_alpha))*TCP(a)
func = th.function([a,alpha,sig_alpha,t_double,t_delay], integrand(a))
y_est = sp.integrate.quad(func(a, alpha, sig_alpha,t_double,t_delay), 0, np.inf)[0]
likelihood = pm.T('TCP', mu=y_est, nu=nu, observed=y_tcp)
start = pm.find_MAP()
step = pm.NUTS(state=start)
trace = pm.sample(2000, step, start=start, progressbar=True)
which produces the following message regarding the expression for y_est:
TypeError: ('Bad input argument to theano function with name ":42" at index 0(0-based)', 'Expected an array-like object, but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?')
I've overcome various other hurdles to get this far, and this is where I'm stuck. So, provided the answer to my first question is 'yes', then am I on the right track? Any guidance would be helpful!
N.B. Here is a similar question I found, and another.
Disclaimer: I'm very new at this. My only previous experience is successfully reproducing the linear regression example in Thomas' post. I've also successfully run the Theano test suite, so I know it works.
Yes, its possible to make something with a complex or arbitrary likelihood. Though that doesn't seem like what you're doing here. It looks like you have a complex transformation of one variable into another, the integration step.
Your particular exception is that integrate.quad is expecting a numpy array, not a pymc Variable. If you want to do quad within pymc, you'll have to make a custom theano Op (with derivative) for it.

How to control lineno in sourcecode directive?

I want to write a document which includes a part of source code with line numbers.
Example(whitch I expected):
123. int myFunc() {
124. return 100;
125. }
When I use sourcecode/code-block directive, line number is always started from 1.
Currently, I tried following methods, but these are not worked.
Is there any way to control line numbers?
A: use 'linenostart' option.
.. sourcecode:: cpp
:linenos:
:linenostart: 123
int myFunc() {
return 100;
}
=> it was result in error "unknown option: lineno"
B: use literal include.
.. literalinclude:: my_func.cpp
:language: cpp
:linenos:
:lines: 123-125
=> it was result in no error, but line number is start from 1.
Thanks in advance.

Resources