text:
Q: ERROR: can't get the inverse laplace transform expression with sympy I've been trying to calculate the inverse laplace transform with sympy for the follow transfer function wlt:
                             -2⋅s
         (1.0e-8⋅s + 0.02)⋅ℯ
────────────────────────────────────────
  ⎛         2                           ⎞
s⋅⎝1.0e-11⋅s  + 2.0000003e-5⋅s + 0.00177⎠

with the next expression:
wtl_t = sp.inverse_laplace_transform(wtl, s, t, noconds=True)

where
s = sp.symbols('s')
t = sp.symbols('t', positive=True)

but when I run the code, this errors appears:
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 211, in _parallel_dict_from_expr_if_gens
    monom[indices[base]] = exp
KeyError: RisingFactorial(_t + 1, 1.0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/partfrac.py", line 81, in apart
    (P, Q), opt = parallel_poly_from_expr((P, Q), x, **options)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polytools.py", line 4340, in parallel_poly_from_expr
    return _parallel_poly_from_expr(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polytools.py", line 4393, in _parallel_poly_from_expr
    reps, opt = _parallel_dict_from_expr(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 332, in _parallel_dict_from_expr
    reps, gens = _parallel_dict_from_expr_if_gens(exprs, opt)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/polyutils.py", line 216, in _parallel_dict_from_expr_if_gens
    raise PolynomialError("%s contains an element of "
sympy.polys.polyerrors.PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/mnt/hgfs/FACULTAD/3er año/SDC/S&C_withPython/SDC_ex/GTP2_ex3.py", line 62, in <module>
    wtl_t = sp.inverse_laplace_transform(wtl, s, t, noconds=True)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1341, in inverse_laplace_transform
    return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 130, in doit
    return self._compute_transform(self.function,
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1287, in _compute_transform
    return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 218, in wrapper
    res = func(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 1213, in _inverse_laplace_transform
    f, cond = inverse_mellin_transform(F, s, exp(-t), (None, oo),
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 908, in inverse_mellin_transform
    return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 130, in doit
    return self._compute_transform(self.function,
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 846, in _compute_transform
    return _inverse_mellin_transform(F, s, x, strip, **hints)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 218, in wrapper
    res = func(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/integrals/transforms.py", line 773, in _inverse_mellin_transform
    h = hyperexpand(G)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2513, in hyperexpand
    return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1497, in replace
    rv = walk(self, rec_replace)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1481, in walk
    rv = F(rv)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1490, in rec_replace
    v = _value(expr, result)
  File "/usr/local/lib/python3.9/dist-packages/sympy/core/basic.py", line 1419, in <lambda>
    _value = lambda expr, result: value(*expr.args)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2509, in do_meijer
    r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2394, in _meijergexpand
    slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2320, in do_slater
    hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 2061, in _hyperexpand
    formula = try_lerchphi(func)
  File "/usr/local/lib/python3.9/dist-packages/sympy/simplify/hyperexpand.py", line 1799, in try_lerchphi
    part = apart(numer/denom, t)
  File "/usr/local/lib/python3.9/dist-packages/sympy/utilities/decorator.py", line 34, in threaded_func
    return func(expr, *args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/sympy/polys/partfrac.py", line 84, in apart
    raise PolynomialError(msg)
sympy.polys.polyerrors.PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.

I also tried with partial fractions and factorize the TF, but nothing happened.

A: I had a similar error with sp.inverse_laplace_transform(...) and downgrading Sympy from 1.9 to 1.7.1 helped.

A: I don't know what is the problem in your case but maybe try:
def invL(F):
return sympy.inverse_laplace_transform(F, s, t)

invL(wtl)

Also you need to define t as real:
t = sympy.Symbol('t', real=True)

A: There seems to be something...interesting...between ints and floats:
import sympy as sym
sym.init_printing()
sym.var('t', real=True)
sym.var('s')

# this works
F = 10/(2*s**3+5*s**2+s)
sym.inverse_laplace_transform(F, s, t)

# this works
G = F/5
sym.inverse_laplace_transform(G, s, t)

# this fails
H = F/5.0
sym.inverse_laplace_transform(H, s, t)

# this fails
I = 10.0/(2.0*s**3+5.0*s**2+1.0*s)
sym.inverse_laplace_transform(I, s, t)

Here's the fail (not for the faint of heart):
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\anaconda3_2021_05\lib\site-packages\sympy\polys\polyutils.py in _parallel_dict_from_expr_if_gens(exprs, opt)
    210
--> 211                         monom[indices[base]] = exp
    212                     except KeyError:

KeyError: RisingFactorial(_t + 1, 1.0)

During handling of the above exception, another exception occurred:

PolynomialError                           Traceback (most recent call last)
~\anaconda3_2021_05\lib\site-packages\sympy\polys\partfrac.py in apart(f, x, full, **options)
     80     try:
---> 81         (P, Q), opt = parallel_poly_from_expr((P, Q), x, **options)
     82     except PolynomialError as msg:

~\anaconda3_2021_05\lib\site-packages\sympy\polys\polytools.py in parallel_poly_from_expr(exprs, *gens, **args)
   4339     opt = options.build_options(gens, args)
-> 4340     return _parallel_poly_from_expr(exprs, opt)
   4341

~\anaconda3_2021_05\lib\site-packages\sympy\polys\polytools.py in _parallel_poly_from_expr(exprs, opt)
   4392
-> 4393     reps, opt = _parallel_dict_from_expr(exprs, opt)
   4394     if not opt.gens:

~\anaconda3_2021_05\lib\site-packages\sympy\polys\polyutils.py in _parallel_dict_from_expr(exprs, opt)
    331     if opt.gens:
--> 332         reps, gens = _parallel_dict_from_expr_if_gens(exprs, opt)
    333     else:

~\anaconda3_2021_05\lib\site-packages\sympy\polys\polyutils.py in _parallel_dict_from_expr_if_gens(exprs, opt)
    215                         else:
--> 216                             raise PolynomialError("%s contains an element of "
    217                                                   "the set of generators." % factor)

PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.

During handling of the above exception, another exception occurred:

PolynomialError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8232/971710189.py in <module>
      1 H = F/5.0
----> 2 sym.inverse_laplace_transform(H, s, t)

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in inverse_laplace_transform(F, s, t, plane, **hints)
   1420     if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'):
   1421         return F.applyfunc(lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints))
-> 1422     return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
   1423
   1424

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in doit(self, **hints)
    134         if try_directly:
    135             try:
--> 136                 return self._compute_transform(self.function,
    137                     self.function_variable, self.transform_variable, **hints)
    138             except IntegralTransformError:

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in _compute_transform(self, F, s, t, **hints)
   1366
   1367     def _compute_transform(self, F, s, t, **hints):
-> 1368         return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints)
   1369
   1370     def _as_integral(self, F, s, t):

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in wrapper(noconds, *args, **kwargs)
    222         @wraps(func)
    223         def wrapper(*args, noconds=default, **kwargs):
--> 224             res = func(*args, **kwargs)
    225             if noconds:
    226                 return res[0]

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in _inverse_laplace_transform(F, s, t_, plane, simplify)
   1285
   1286     if F.is_Add:
-> 1287         f = Add(*[_inverse_laplace_transform(X, s, t, plane, simplify)\
   1288                      for X in F.args])
   1289         return _simplify(f.subs(t, t_), simplify), True

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in <listcomp>(.0)
   1285
   1286     if F.is_Add:
-> 1287         f = Add(*[_inverse_laplace_transform(X, s, t, plane, simplify)\
   1288                      for X in F.args])
   1289         return _simplify(f.subs(t, t_), simplify), True

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in wrapper(noconds, *args, **kwargs)
    222         @wraps(func)
    223         def wrapper(*args, noconds=default, **kwargs):
--> 224             res = func(*args, **kwargs)
    225             if noconds:
    226                 return res[0]

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in _inverse_laplace_transform(F, s, t_, plane, simplify)
   1290
   1291     try:
-> 1292         f, cond = inverse_mellin_transform(F, s, exp(-t), (None, oo),
   1293                                            needeval=True, noconds=False)
   1294     except IntegralTransformError:

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in inverse_mellin_transform(F, s, x, strip, **hints)
    912     hankel_transform, inverse_hankel_transform
    913     """
--> 914     return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints)
    915
    916

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in doit(self, **hints)
    134         if try_directly:
    135             try:
--> 136                 return self._compute_transform(self.function,
    137                     self.function_variable, self.transform_variable, **hints)
    138             except IntegralTransformError:

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in _compute_transform(self, F, s, x, **hints)
    850                                      'Component %s not recognised.' % f)
    851         strip = self.fundamental_strip
--> 852         return _inverse_mellin_transform(F, s, x, strip, **hints)
    853
    854     def _as_integral(self, F, s, x):

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in wrapper(noconds, *args, **kwargs)
    222         @wraps(func)
    223         def wrapper(*args, noconds=default, **kwargs):
--> 224             res = func(*args, **kwargs)
    225             if noconds:
    226                 return res[0]

~\anaconda3_2021_05\lib\site-packages\sympy\integrals\transforms.py in _inverse_mellin_transform(F, s, x_, strip, as_meijerg)
    777         else:
    778             try:
--> 779                 h = hyperexpand(G)
    780             except NotImplementedError:
    781                 raise IntegralTransformError(

~\anaconda3_2021_05\lib\site-packages\sympy\simplify\hyperexpand.py in hyperexpand(f, allow_hyper, rewrite, place)
   2511         if not r.has(nan, zoo, oo, -oo):
   2512             return r
-> 2513     return f.replace(hyper, do_replace).replace(meijerg, do_meijer)

~\anaconda3_2021_05\lib\site-packages\sympy\core\basic.py in replace(self, query, value, map, simultaneous, exact)
   1496             return expr
   1497
-> 1498         rv = walk(self, rec_replace)
   1499         return (rv, mapping) if map else rv
   1500

~\anaconda3_2021_05\lib\site-packages\sympy\core\basic.py in walk(rv, F)
   1480                                 if rv == e and e != newargs[i]:
   1481                                     return rv
-> 1482                 rv = F(rv)
   1483             return rv
   1484

~\anaconda3_2021_05\lib\site-packages\sympy\core\basic.py in rec_replace(expr)
   1489             result = _query(expr)
   1490             if result or result == {}:
-> 1491                 v = _value(expr, result)
   1492                 if v is not None and v != expr:
   1493                     if map:

~\anaconda3_2021_05\lib\site-packages\sympy\core\basic.py in <lambda>(expr, result)
   1418                 _value = lambda expr, result: value(*expr.args)
   1419             elif callable(value):
-> 1420                 _value = lambda expr, result: value(*expr.args)
   1421             else:
   1422                 raise TypeError(

~\anaconda3_2021_05\lib\site-packages\sympy\simplify\hyperexpand.py in do_meijer(ap, bq, z)
   2507
   2508     def do_meijer(ap, bq, z):
-> 2509         r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
   2510                    allow_hyper, rewrite=rewrite, place=place)
   2511         if not r.has(nan, zoo, oo, -oo):

~\anaconda3_2021_05\lib\site-packages\sympy\simplify\hyperexpand.py in _meijergexpand(func, z0, allow_hyper, rewrite, place)
   2392     for op in ops:
   2393         op._poly = Poly(op._poly.subs({z: 1/t, _x: -_x}), _x)
-> 2394     slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
   2395                                t, 1/z0)
   2396

~\anaconda3_2021_05\lib\site-packages\sympy\simplify\hyperexpand.py in do_slater(an, bm, ap, bq, z, zfinal)
   2318                 #      t*k ... we are using polar numbers for consistency!
   2319                 premult = (t/k)**bh
-> 2320                 hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
   2321                                    t, premult, bh, rewrite=None)
   2322                 res += fac * hyp

~\anaconda3_2021_05\lib\site-packages\sympy\simplify\hyperexpand.py in _hyperexpand(func, z, ops0, z0, premult, prem, rewrite)
   2059     # Now try a lerch phi formula
   2060     if formula is None:
-> 2061         formula = try_lerchphi(func)
   2062
   2063     if formula is None:

~\anaconda3_2021_05\lib\site-packages\sympy\simplify\hyperexpand.py in try_lerchphi(func)
   1797     # a*t**b (b a non-negative integer), and a dict terms, where
   1798     # terms[a] = [(b, c)] means that there is a term b/(t-a)**c.
-> 1799     part = apart(numer/denom, t)
   1800     args = Add.make_args(part)
   1801     monomials = []

~\anaconda3_2021_05\lib\site-packages\sympy\utilities\decorator.py in threaded_func(expr, *args, **kwargs)
     32                                       func(expr.rhs, *args, **kwargs))
     33             else:
---> 34                 return func(expr, *args, **kwargs)
     35
     36     return threaded_func

~\anaconda3_2021_05\lib\site-packages\sympy\polys\partfrac.py in apart(f, x, full, **options)
     82     except PolynomialError as msg:
     83         if f.is_commutative:
---> 84             raise PolynomialError(msg)
     85         # non-commutative
     86         if f.is_Mul:

PolynomialError: RisingFactorial(_t + 1, 1.0) contains an element of the set of generators.


text:
Q: Weak solution to a parabolic equation I am facing problem to understand the notion of weak solution defined in page 3 of the article attached below: https://math.aalto.fi/~jkkinnun/papers/kuusi.pdf
My first question is:
1) On page 3 can you explain why the equation (2.2) acme?
2) In Lemma 3.1 why the test function $\eta=u^{2(1-p)}\phi$ is admissible?
Thank you very much.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does RewriteRule x y.php succeed, but RewriteRule x y.php/foo fail? I'm dockerizing a web application with existing .htaccess files. When running the application in a debian:stretch with Apache installed, I'm running into issues with RewriteRules.
I've boiled it down to an issue that can be illustrated here:
RewriteRule ^works$    /symfony/web/json.php       [QSA,L]
RewriteRule ^fails$    /symfony/web/json.php/user  [QSA,L]

The first RewriteRule sends the user to along to symfony/web/json.php, a file in a Symfony 1 project, where they get an appropriate 404 handled by Symfony.
The second RewriteRule does not send the user into Symfony land, where the trailing "/user" would normally then be given to a controller to handle. I just get a "File not found.".
Instead, it looks like the .htaccess in a deeper directory removes the beginning of the path and send the "/user" back to the .htaccess in the root directory.
Directory structure
root/
├── symfony/
│   ├── web/
│   │   ├── .htaccess
│   │   └── json.php
│   ├── .htaccess
└── .htacces

.htaccesses
root/.htaccess (relevant bits):
RewriteEngine On
RewriteBase /
RewriteRule ^works$    /symfony/web/json.php       [QSA,L]
RewriteRule ^fails$    /symfony/web/json.php/user  [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /symfony/web/index.php [QSA,L]

root/symfony/.htaccess (entire):
RewriteEngine On
RewriteRule ^(.*)$ /symfony/web/$1 [L]

root/symfony/web/.htaccess (relevant bits):
RewriteEngine On
RewriteBase /symfony/

RewriteCond %{REQUEST_URI} ^(/symfony/admin.php)
RewriteCond %{REMOTE_ADDR} !^10\.0
RewriteCond %{REMOTE_ADDR} !^10\.50
RewriteCond %{REMOTE_ADDR} !^10\.60
RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$
RewriteCond %{REMOTE_ADDR} !^::1$
RewriteRule .* / [L,R=403]

# we check if the .html version is here (caching)
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f

# no, so we redirect to our front web controller
RewriteRule ^(.*)$ index.php [QSA,L]

Rewrite logs
To debug, I set LogLevel debug rewrite:trace3. Here are the relevant bits from the log when attempting to go to /fail:
[rewrite:trace3] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] strip per-dir prefix: /home/wwwroot/root/fails -> fails
[rewrite:trace3] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] applying pattern '^works$' to uri 'fails'
[rewrite:trace3] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] strip per-dir prefix: /home/wwwroot/root/fails -> fails
[rewrite:trace3] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] applying pattern '^fails$' to uri 'fails'
[rewrite:trace2] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] rewrite 'fails' -> '/symfony/web/json.php/user'
[rewrite:trace2] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] trying to replace prefix /home/wwwroot/root/ with /
[rewrite:trace2] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] trying to replace context docroot /home/wwwroot/root with context prefix
[rewrite:trace1] [rid#7f8c7807d0a0/initial] [perdir /home/wwwroot/root/] internal redirect with /symfony/web/json.php/user [INTERNAL REDIRECT]
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] add path info postfix: /home/wwwroot/root/symfony/web/json.php -> /home/wwwroot/root/symfony/web/json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] strip per-dir prefix: /home/wwwroot/root/symfony/web/json.php/user -> json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] applying pattern '.*' to uri 'json.php/user'
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] add path info postfix: /home/wwwroot/root/symfony/web/json.php -> /home/wwwroot/root/symfony/web/json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] strip per-dir prefix: /home/wwwroot/root/symfony/web/json.php/user -> json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] applying pattern '^$' to uri 'json.php/user'
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] add path info postfix: /home/wwwroot/root/symfony/web/json.php -> /home/wwwroot/root/symfony/web/json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] strip per-dir prefix: /home/wwwroot/root/symfony/web/json.php/user -> json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] applying pattern '^([^.]+)$' to uri 'json.php/user'
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] add path info postfix: /home/wwwroot/root/symfony/web/json.php -> /home/wwwroot/root/symfony/web/json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] strip per-dir prefix: /home/wwwroot/root/symfony/web/json.php/user -> json.php/user
[rewrite:trace3] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] applying pattern '^(.*)$' to uri 'json.php/user'
[rewrite:trace1] [rid#7f8c7805c4a8/initial/redir#1] [perdir /home/wwwroot/root/symfony/web/] pass through /home/wwwroot/root/symfony/web/json.php
[rewrite:trace3] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] strip per-dir prefix: /home/wwwroot/root/user -> user
[rewrite:trace3] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] applying pattern '^works$' to uri 'user'
[rewrite:trace3] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] strip per-dir prefix: /home/wwwroot/root/user -> user
[rewrite:trace3] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] applying pattern '^fails$' to uri 'user'
[rewrite:trace3] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] strip per-dir prefix: /home/wwwroot/root/user -> user
[rewrite:trace3] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] applying pattern '^(.*)$' to uri 'user'
[rewrite:trace2] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] rewrite 'user' -> '/symfony/web/index.php'
[rewrite:trace2] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] trying to replace prefix /home/wwwroot/root/ with /
[rewrite:trace2] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] trying to replace context docroot /home/wwwroot/root with context prefix
[rewrite:trace1] [rid#7f8c780830a0/subreq] [perdir /home/wwwroot/root/] internal redirect with /symfony/web/index.php [INTERNAL REDIRECT]

So it looks like in the root .htaccess, RewriteRule ^fails$ /symfony/web/json.php/user matches and redirects the request to the .htaccess in symfony/web/, which finds to matches but strips the beginning of the url, sending "/user" back to the original root .htaccess.

A: The issue was caused by the Apache version.
My Apache container was using the debian:stretch Docker image, which includes Apache 2.4.25. I changed the base image to debian:buster, which includes Apache 2.4.38. That update solved my issue.


text:
Q: JavaScript Selector is Not working when condition changes I am facing an issue with JavaScript Selector here is the code
onChangeCustomGroup : function(){
    var element = this.model.get("customGroup"),
        that = this;

    if(element == "SECURITY") {
        that.ui.__el_string_Abc.xyzSelector();
    }

    if(element == "BENCHMARK") {
        that.ui.__el_string_Abc.dfgSelector();
    }
}

onChangeCustomGroup is a ModelEvent in Backbone
There are two fields 1.customGroup
                     2. filterCode
customgroup field having two values populate 1.SECURITY AND 2.BENCHMARK
securitySelector and benchmarkSelector are two functions which will returns a set of values in the form of html and appends with the filtercode region
The issue is here when i select SECURITY ,security fields are populating in the filtercode field but on change to BENCHMARK benchmark selector is not populating
It is something like working only with one condition.Not with two


text:
Q: Timeout for dropped packets (UDP) I'm trying to create a timeout using select() for UDP socket transfer. I want to send an int from client to server, wait 300ms, and if I don't get an ACK, resend the packet. I'm not sure how to set this up properly with the timeout. From what I've gathered online and on the notes I have from class, select should be used on the receiving end.
the client at the server send back and forth the numbers 1-100. I have a separate router simulated code that randomly drops packets
Here is the code i have for the client side
int sent = 1;
int received = 1;

    for (int i = 0; i < 100; i++)
    {
        string sent1 = to_string(sent);
        char const *pchar = sent1.c_str();
        if(!sendto(s, pchar, sizeof(pchar), 0, (struct  sockaddr*) &sa_in, sizeof(sa_in)))
            cout << "send NOT successful\n";
        else
        {
            cout << "Client sent " << sent << endl;
            sent++;
        }
        // receive
        fd_set readfds; //fd_set is a type
        FD_ZERO(&readfds); //initialize
        FD_SET(s, &readfds); //put the socket in the set

        if(!(outfds = select (1 , &readfds, NULL, NULL, & timeouts)))
            break;
        if (outfds == 1) //receive frame
        {
            if (!recvfrom(s, buffer2, sizeof(buffer2), 0, (struct sockaddr*) &client, &client_length))
                cout << "receive NOT successful\n";
            else
            {
                received = atoi(buffer2);
                cout << "Client received " << received << endl;
                received++;
            }
        }
    }

The code is identical for the receiving side except it is in reverse: receive first, then send
My code doesn't utilize the timeout at all. This is basically what I want to do:
send packet(N)
    if (timeout)
        resend packet(N)
    else
        send packet(N+1)

A: If the receiver gets a timeout it needs to tell the sender, or else not tell the sender. In other words you have to implement either a NACK-based protocol or an ACK-based protocol.


text:
Q: How to implement "open with" in a notepad application Getting straight to the point, I am basically creating a clone of notepad in java and I want to implement this functionality:
Assume I have a file like this with the .txt exention
I procede to right click and select the open with option, where notepad and vscode are also present
What I want is for my application to be here, and I know that I have to edit the registry and add the main executable of my app for every text file associations and I'm pretty confident I can do it with by running the reg command in batch (correct me if I'm wrong).
The part where my personal research was not good enough is actually how to physically implement the open with behavior in my java code, meaning I don't have any "entry points". If only I had the path of the selected file I could call my open() function with that path and the job would be done. However, I don't understand what's going on in the background.
Note: I am still learning batch and windows related topics so I apologize if this is a stupid question


text:
Q: C++ dependency injection with fruit I have class A and interface IInterface.
I need to inject 2 members IInterface into A.
So:
class A {
    IInterface* i1;
    IInterface* i2;
};

Can I inject 2 members (i1 and i2) into A using fruit DI framework?

A: I'm the Fruit author (thanks Alan for pointing me to this thread!).
The simplest way to inject that class would be constructor injection. Assuming that the two interfaces are the same (as in your example) and you want 2 different instances, you could use annotated injection, which would look like:
using namespace fruit;

struct FirstI {};
struct SecondI {};

class A {
    IInterface* i1;
    IInterface* i2;
public:
    INJECT(A(ANNOTATED( FirstI, IInterface*) i1,
             ANNOTATED(SecondI, IInterface*) i2))
    : i1(i1), i2(i2) {}
};

In your get*Component() function you will then have to bind both (to the same type, or different types, the two are completely independent since they have different annotations):
class FirstIImpl : public IInterface {
    ....
public:
    INJECT(FirstIImpl()) = default;
};

class SecondIImpl : public IInterface {
    ....
public:
    INJECT(SecondIImpl()) = default;
};

Component<A> getAComponent() {
    return createComponent()
        .bind<fruit::Annotated< FirstI, IInterface>,  FirstIImpl>()
        .bind<fruit::Annotated<SecondI, IInterface>, SecondIImpl>();
}

Annotated injection is a new feature in Fruit 2.x, I haven't had time to document it yet (sorry). Hopefully the example above should be what you wanted, if not let me know.
If you want to bind the two interfaces to the same type, you'll also have to annotate the implementation class, so that you'll have 2 nodes (objects) in the injection graph instead of 1. E.g.:
Component<A> getAComponent() {
    return createComponent()
        .bind<fruit::Annotated< FirstI, IInterface>,
              fruit::Annotated< FirstI, IImpl>>()
        .bind<fruit::Annotated<SecondI, IInterface>,
              fruit::Annotated<SecondI, IImpl>>();
}


text:
Q: Rolling mean based on conditions R Here is a brief description of my data: The first column is date by month, the second column is binary variable (0 or 1), the third column is stock return, so each month's stock return point to 1 or 0.
I want to calculate the 12-month rolling mean return separately based on the second column (0 or 1). There will be different number of 0s and 1s in the 12-month rolling base. There should be 2 outcome (mean_rolling_0, and mean_rolling_1).

A: Use rollmean() from the zoo package, and apply this per group with group_by() in dplyr.
Here's an example. I'm guessing at your data structure, but it will also work for similar structures.
library(tidyverse)
library(zoo)

# sample data
d = tibble(a = 1:100,
       b = sample(c(0,1), 100, replace = T),
       c = a/10 + rnorm(100))

# compute rolling mean
d2 = d %>%
    group_by(b) %>%
    mutate(roll = rollmean(c, 12, na.pad=TRUE, align="right"))

# plot to see the effect
ggplot(data = d2) + geom_line(aes(x = a, y = c, colour = factor(b))) +
    geom_line(aes(x = a, y = roll, colour = factor(b)), linetype = 'dashed')


text:
Q: Plus point on each click I am making a game with img´s each time that the user clic on the correct img win 100 points but i dont get the summations of the points i dont know why
The final score still 0
HTML

JS
const correctTool = document.getElementsByClassName("draggable")
let finalScore = 0 ;
for (i = 0; i < correctTool.length; i++){
    correctTool[i].addEventListener("click", e => {
        if (e.target.classList.contains("correct")){
            e.target.classList.add("correct-tool")
            finalScore = finalScore + 100;
        }
    });

    console.log(finalScore)

}

A: I have made the finalScore as global variable and moved the logic to a function. It is working as expected. Final score gets added each time a image is clicked with draggable class.
Option 1 is much cleaner approach. Logic is separated in a function. code must be divided into smaller functions so that it easy to understand.

var finalScore = 0;
var elements = document.getElementsByClassName("draggable");

var myFunction = function(e) {
    if (e.target.classList.contains("correct")) {
      e.target.classList.add("correct-tool");
      finalScore = finalScore + 100;
      console.log(finalScore);
    }
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);
}

Your code -

const correctTool = document.getElementsByClassName("draggable")
let finalScore = 0;
for (i = 0; i < correctTool.length; i++) {
  correctTool[i].addEventListener("click", (e) => {
    if (e.target.classList.contains("correct")) {
      if(e.target.classList.contains("correct-tool")){ return; }
      else { e.target.classList.add("correct-tool");
      finalScore = finalScore + 100;}
      console.log(finalScore) // here
    }
  });
}


text:
Q: Why my codeigniter code about transaction does not work? My code is liked this:
$this->db->trans_strict(FALSE); //close Strict Mode
$this->db->trans_begin();
$updateArr = array('name'=>'test', 'age'=>22);
$this->db->where('user_id', $user_id);
$this->db->limit(1);
$this->db->update('user_table', $updateArr);
$logArr = array('created'=>'2015-07-30', 'content'=>'test' );
$this->db->set($logArr)->insert('log_table');
if ($this->db->trans_status() === FALSE) {
    $this->db->trans_rollback();
    return false;
} else {
    $this->db->trans_commit();
    return true;
}

*

*Does codeigniter transactions support  activerecord?

*When the first query return false, why does the second query return true ?

what am I doing wrong ? Please help me.
I use MySQL InnoDB


text:
Q: Powershell move user\appdata(roaming) folders to user\appdata\roaming I am moving my folder redirection store to a new server.
However the structure for appdata appears to now be users\AppData\Roaming\ as opposed to the old structure
users\AppData(Roaming)\
I am trying to move all the folders from the old structure to the new structure for a bunch of users folders.
I am assuming i need to use some sort of loop to check each folder.
Would something like this work?
$folderlist = ("foldertwo", "folderthree")
foreach ($folder in $folderlist)
{
if (!(Test-Path "P:\users$\%username%\AppData\Roaming"))
{
    mkdir ("P:\users$\%username%\AppData\Roaming") | Out-Null
}
Copy-Item P:\users$\%username%\AppData(Roaming)\* P:\users$\%username%\AppData\Roaming\ -recurse -Container
}

I am pretty new to powershell so scripting is not my best.

A: Having read the comments, here a partial piece of code, as I think you best use RoboCopy to do the heavy lifting of copying all from the AppData(Roaming) folders to the new AppData\Roaming folder.
Please test on a dummy user first to figure out what switches to use on robocopy.
Then of course also test if the user permissions on the new path are correct (inherited from the P:\Users$\<username> folder)
$userShare = 'P:\Users$'      # if running on the server, otherwise best use the UNC path

# loop through tyhe folders inside the user share (1st level only)
Get-ChildItem -Path $userShare -Directory | ForEach-Object {
    Write-Host "Processing user $($_.Name)"
    $destinationDir = Join-Path $_.FullName -ChildPath ('AppData\Roaming')
    if (!(Test-Path -Path $destinationDir -PathType Container)) {
        Write-Host "Creating folder '$destinationDir'"
        $null = New-Item -Path $destinationDir -ItemType Directory
    }
    $wrongRoamingDir = Join-Path $_.FullName -ChildPath ('AppData(Roaming)')
    if (Test-Path -Path $wrongRoamingDir -PathType Container) {
        #############################################################################################
        # here is where you start copying everything from the $wrongRoamingDir to the $destinationDir.
        # I would suggest using RoboCopy for that using switches like
        # Robocopy /MIR $wrongRoamingDir  $destinationDir
        # or
        # Robocopy /S /E $wrongRoamingDir  $destinationDir
        #
        # Please test on a dummy user first. For more robocopy switches, have a look at
        # https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy
        # https://www.windows-commandline.com/robocopy-command-syntax-examples/
        #############################################################################################
    }
}


text:
Q: How to get this backbone route to work? CI'm having problems with making one route works. I have list view with items, single item html looks like this:

number/h4>
  A

my router code:
var AppRouter = Backbone.Router.extend({

    routes:{
        "": "login",
        "login": "login",
        "my_clients": "myClients",
        "my_clients/:id": "myClientDetails"

    },

    initialize:function () {
        // Handle back button throughout the application
        $('.back').live('click', function(event) {
            window.history.back();
            return false;
        });
        this.firstPage = true;
    },

    login: function () {
        this.changePage(new LoginView({ model: new User() }));
    },

    myClients: function() {
        this.changePage(new MyClientsView({ model: new MyClientsCollection() }));
    },

    myClientDetails: function(id) {
        var client = new Client({ id: id });
        self = this;
        client.fetch({
            success: function(data) {
                self.changePage(new MyClientDetailsView({ model: data }));
            }
        });
    },

    changePage:function (page) {
        $(page.el).attr('data-role', 'page');
        page.render();
        $('body').append($(page.el));
        var transition = $.mobile.defaultPageTransition;
        // We don't want to slide the first page
        if (this.firstPage) {
            transition = 'none';
            this.firstPage = false;
        }
        $.mobile.changePage($(page.el), {changeHash:false, transition: transition});
    }

});

Login and MyClients pages works ok, but when I click on link in list view item to show individual client details I see get call in my firebug console and route is not working.
What am I missing?

A: Change  to   (in other words, add / after #).
See the example: http://jsfiddle.net/theotheo/sz6y8/


text:
Q: How to get POS tagging on GATE How to get the features of words using GATE embedded (Java code) as in the following example:
type=Token;
features={category=VBG, kind=word, orth=lowercase, length=7, string=lacking};
start=NodeImpl;
id=21453;

A: If you use the opennlp pos tagging it should be something like this, given that "Token" is your annotation for tokens:
 token.getFeatures().get("category").toString()
should give you the string corresponding to the pos tag.

A: Phase: Find_Features
Input:  Token
Options: control = First

Rule: get_Token_features

(
 {Token}
):label

 -->

 :label
 {

 AnnotationSet tokens = inputAS.get("Token");

 for(Annotation t : tokens)
  {
   FeatureMap fm = t.getFeatures();
   System.out.println(fm);

 /*
  If looking for specific features go for
  System.out.println( t.getFeatures().get("FeatureName").toString() );
 */

 System.out.println(t.getFeatures().get("category").toString());
  }

}


text:
Q: Extract intermediate representation of MiDaS neural network in pytorch? Pytorch documentation provides a concise way to apply MiDaS monocular depth estimation network for depth extraction. But how should I modify their code to extract network representation at some intermediate layer? I know that I could download the model from github and modify forward function to return what I want, but I am interested in the simplest solution, leaving outer code as is.
I'm aware of subclassing the model class and writing my own forward function, like here, but I don't know how to access the class in the code. The model instance is created straight away with midas = torch.hub.load("intel-isl/MiDaS", model_type). Maybe an example of using  a forward hook will be easier.

A: As you said, using a forward hook on a nn.Module is the easiest way to go about it. Consider the documentation: https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_forward_hook
Basically you just have to define a function that takes three inputs (module, input, output) and then does whatever you want with that data. To find at what Module you want to place that hook you obviously need to be familiar with the structure of the model. You can just print(midas) to get a pretty-printed representation of all the modules available. I just chose some random one, and used the print() function as a hook:
midas.pretrained.model.blocks[3].mlp.fc2.register_forward_hook(print)

This means whenever we call midas(some_input), the hook (print in this case) will be called with the corresponding arguments. Of course instead of print you can write a function that saves those files to e.g. a list that you can access from the outside, or write them to a file etc.


text:
Q: "Error: [vuex] do not mutate vuex store state outside mutation handlers." If I edit or add contract in my code i got error

[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers."

How can I resolve It? If I press button NewContract or Edit contract it runs onSave function in EditorCreate.vue
**MyParent  Contracts.vue**
<template>

        <Create-Or-Edit-Contract
            :is-open.sync="dialog"
            :selectedObject.sync="selectedItem"
            :arrContracts.sync="contracts"
        />

            <v-app id="inspire">
                <v-data-table
                    :headers="headers"
                    :items="contracts"
                    sort-by="createdAt"
                    class="elevation-1"
                >
                    <template v-slot:top>
                        <v-toolbar flat color="white">
                            <v-toolbar-title>CONTRACTS</v-toolbar-title>
                            <v-divider class="mx-4" inset vertical></v-divider>
                            <v-spacer></v-spacer>
                            <v-btn
                                color="primary"
                                dark
                                class="mb-2"
                                @click="onOpenCreateOrUpdateDialog()"
                            >New Contract</v-btn>
                        </v-toolbar>
                    </template>

                    <template v-slot:item.actions="{ item }">
                        <v-icon small class="mr-2" @click="editItem(item)">mdi-pencil</v-icon>
                        <v-icon small @click="showDeleteDialog(item)">mdi-delete</v-icon>

                    </template>
                </v-data-table>

                <v-dialog v-model="isDialogDeleteVisible" max-width="500px">
                    <v-card>
                        <v-card-title>Remove</v-card-title>
                        <v-card-text>Are you sure to delete?</v-card-text>
                        <v-card-actions >
                            <v-btn color="primary" text @click="isDialogDeleteVisible = false">Close</v-btn>
                            <v-btn color="primary" text @click="onDeleteItem">Delete</v-btn>
                        </v-card-actions>
                    </v-card>
                </v-dialog>
            </v-app>

</template>

Mychildren EditorCreate.vue
<template v-slot:top>
    <v-toolbar flat color="white">
        <v-dialog v-model="open" max-width="500px">
            <v-card>
                <v-card-title>
                    {{ formTitle }}
                </v-card-title>

                <v-card-text>
                    <v-container>
                        <v-row>
                            <v-col cols="12" sm="6" md="4">
                                <v-text-field
                                    v-model="selectedItem.startDate"
                                    label="Start Contract"
                                    name="name"
                                    prepend-icon="person"
                                    placeholder="YYYY-MM-DD"
                                    type="text"
                                    required
                                    :rules="nameErrors"
                                    @input="$v.selectedItem.startDate.$touch()"
                                    @blur="$v.selectedItem.startDate.$touch()"
                                    @keyup="clearServerErrors('name')"
                                />
                            </v-col>

                            <v-col cols="12" sm="6">
                                <v-select
                                    v-model="selectedItem.duration"
                                    :items="[1, 2, 3, 6, 12]"
                                    label="Duration Contract."
                                    required
                                />
                            </v-col>

                            <v-col cols="12" sm="6" md="4">
                                <v-select
                                    v-model="selectedItem.leave"
                                    :items="[20, 26]"
                                    label="Days off"
                                />
                            </v-col>
                        </v-row>
                    </v-container>
                </v-card-text>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" text @click="close">Cancel</v-btn>
                    <v-btn color="blue darken-1" text @click="onSave" :disabled="!isValid">Save</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-toolbar>
</template>

And My store.js:
import Vuex from 'vuex';
import { router } from '../router';
import ContractService from '@/services/ContractService';
import UserService from '@/services/UserService.js';
import UserContractsService from '../services/UserContractsService';

Vue.use(Vuex);

export default new Vuex.Store({
    strict: true,
    state: {
        token: null,
        user: [],
        index: null,
        roles: [],
        contracts: [],
        userId: null,
        selectedItem: null
    },
    getters: {
        isAuthenticated(state) {
            return state.token !== null;
        },
        isAdmin(state) {
            return !!state.roles.find((r) => r.name === 'admin');
        },
        isUser(state) {
            return !!state.roles.find((r) => r.name === 'user');
        },
        getUser(state) {
            return state.user;
        },
        getRoles(state) {
            return state.roles;
        }
    },
    mutations: {
        setToken(state, token) {
            state.token = token;
            localStorage.setItem('token', token);
        },
        setUser(state, user) {
            state.user = user;
            localStorage.setItem('user', JSON.stringify(user));
        },
        setRoles(state, roles) {
            state.roles = roles;
            localStorage.setItem('roles', JSON.stringify(roles));
        },
        clearAuthData(state) {
            state.token = null;
            state.user = null;
            state.roles = [];
            localStorage.removeItem('expirationDate');
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            localStorage.removeItem('roles');
        },
        setContract(state, contracts) {
            state.contracts = contracts;
        },

        setUsers(state, payload) {
            state.user = payload.user;
        },

        DELETE_CONTRACT(state, contractId) {
            const index = state.contracts.findIndex((contract) => contract.id === contractId);

            state.contracts.splice(index, 1);
        },

        setUserId(state, userId) {
            state.userId = userId;
        }
    },

    actions: {
        async login({ commit, dispatch }, data) {
            try {
                const now = new Date();
                const expirationDate = new Date(now.getTime() + 600 * 1000); //take from backend

                localStorage.setItem('expirationDate', expirationDate);

                commit('setUser', data.user);
                commit('setToken', data.token);
                commit('setRoles', data.user.roles);

                dispatch('setLogoutTimer', 6000);
            } catch (error) {
                console.error(error);
            }
        },

        setLogoutTimer({ commit }, expirationTime) {
            setTimeout(() => {
                commit('clearAuthData');
                localStorage.removeItem('expirationDate');
                localStorage.removeItem('token');
                router.push('/login');
            }, expirationTime * 6000);
        },

        tryAutoLogin({ commit, dispatch }) {
            const token = localStorage.getItem('token');

            if (!token) {
                return;
            }

            const expirationDate = localStorage.getItem('expirationDate');
            const now = new Date();

            if (now >= expirationDate) {
                return;
            }
            dispatch('setLogoutTimer', 6000);
            const user = JSON.parse(localStorage.getItem('user'));
            const roles = JSON.parse(localStorage.getItem('roles'));

            commit('setToken', token);
            commit('setUser', user);
            commit('setRoles', roles);
            router.push('/user');
        },

        logout({ commit }) {
            commit('clearAuthData');
        },

        async removeContract({ commit }, contractId) {
            //     const index = payload.contracts.findIndex((contract) => contract.id === payload.selectedItemlete.id);
            //     payload.contracts.splice(index, 1);

            await ContractService.delete(contractId.id);
            commit('DELETE_CONTRACT', contractId.id);
        },

        async removeUser({ commit }, payload) {
            commit('setUsers', payload.users);

            const index = payload.users.findIndex((user) => user.id === payload.selectedItem.id);
            payload.users.splice(index, 1);

            await UserService.delete(payload.selectedItem.id);
        },

        async getContracts({ commit }, userId) {
            const { data } = await UserContractsService.index(userId);

            commit('setUserId', userId);
            commit('setContract', data);

            return data;
        }
    }
});

A: It is because you are mutating vuex state outside a mutation. In your store either move the mutating part in a mutation or change
export default new Vuex.Store({ strict: true,
to
export default new Vuex.Store({ strict: false,
https://vuex.vuejs.org/guide/strict.html#strict-mode


text:
Q: Need smaller pullups on i2c lines, but design is low power, what is best?
The pullups on my i2c lines are 4.7k. People are afraid of draining the battery by fixing this waveform with smaller pullups, like 2.2k. It doesn't seem much power is wasted considering the short duration of the bus being low (2-4 byte transfers) and the 400k bus speed. I am concerned about reliability with the waveform this distorted. What is the effect of the curving leading edge? It would seem to delay sampling of sda on the rising edge of scl.

A: Short answer: You are absolutely right not to worry about the smaller pullup resistors, since your bus will be in a high state the vast majority of the time.  Moreover, the slow rise times will probably increase the power consumption significantly. Just use the 2.4kΩ resistors.
Long Answer
Very slow edge rates will actually cause CMOS inputs to consume more power than faster edge rates. Let's take a look at a typical CMOS input stage:

When the input voltage is in an intermediate state, both the PMOS and NMOS transistors will be partially on, resulting in a surge current (typically on the order of several milliamps). This current will be drawn by every device on the bus as long as the voltage is in an intermediate state.
It is reasonable to assume that most I2C devices use Schmitt trigger inputs, which are designed to handle slow input transitions. However, do Schmitt trigger inputs consume less power? Unfortunately, no. This is a common misconception, so let's look at a typical CMOS Schmitt trigger:

Note that the basic structure stays the same, meaning that surge current is still a problem.
So, long story short: the slow rise times from the weak pullup resistors will most likely increase power consumption. This is especially true if there are multiple devices on the bus.
Take a look at these articles from Texas Instruments for more information:

*

*Implications of Slow or Floating CMOS Inputs (source for first image)

*Solving CMOS Transition Rate Issues Using Schmitt Triggers (source for second image)

*Understanding Schmitt Triggers


text:
Q: partial layout did not change when change the screen orientation changed I have a app stated well, but when I change the orientation some view's layout in the viewpager's fragment is still use the before orientation. like this(the tabbar is OK, but the image view and the text is not working well,I guess the fragment did not have onLayout() step?):

I have set the android:configChanges like this below to the corresponding activity in activity tag
android:configChanges="keyboardHidden|orientation|screenSize

I have searched a lot in google and stackoverflow, but seems there is no solution. so please suggest me a solution.
the layout file is like this(sorry for some reason, I can't paste my xml code, so I descripe it as explicit as I can):
activity has a viewpager, view pager has two fragments, the fragement's view has a linearlayout use gravity="center",and the linear layout has a vertical orientation with a imageView and textView.

A: I could have been much easier if I see your xml. But let me give you simple solution by making ConstraintLayout as new parent.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    tools:context=".HomeFragment">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@android:drawable/btn_star"
        app:layout_constraintBottom_toTopOf="@id/hor_guide"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="ContentDescription" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/hor_guide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My Custom Title"
        android:textSize="32sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/hor_guide" />

</androidx.constraintlayout.widget.ConstraintLayout>

ConstraintLayout works in all scenarious. So test your orientation changes with this.
In this layout I made use of Guideline which is not visible to the user, but helps us constraint the other views with respect to it.


text:
Q: PostgreSQL Performance: Query to find stocks reaching 52 week highs (joining rows of max values) I have a very simple database structure with "end of day" stock prices which look similar to:
finalyzer_pricedata=> \d pdEndOfDayPricEentity
              Table "public.pdendofdaypriceentity"
    Column     |     Type      | Collation | Nullable | Default
---------------+---------------+-----------+----------+---------
 id            | uuid          |           | not null |
 close         | numeric(19,2) |           | not null |
 day           | date          |           | not null |
 instrument_id | uuid          |           | not null |

(instrument_id is the unique ID of the stock)
I now want to select all instrument_id which reach their 52 week high in the current week. (ie. all stocks where the close column in the last 7 days is higher than in the 52 week before that)
I have tried many different approaches: group by and max(), select distinct on, window functions (row_number) but i did not manage to get it below 150 seconds. My best (and simplest) approach currently is:
select CAST(weekHigh.instrument_id AS VARCHAR) instrumentId,
                       weekHigh.maxClose                       weekHighValue,
                       yearHigh.maxClose                       yearHighValue,
                       yearHigh.maxDay                         yearHighDay
                from
                     (select distinct on (eod.instrument_id) instrument_id,
                                         eod.close  maxClose,
                                         eod.day as maxDay
                                  from pdendofdaypriceentity eod
                                  where eod.day BETWEEN (CAST('2018-11-12' AS date) - interval '52 weeks') AND (CAST('2018-11-12' AS date) - interval '1 day')
                                  order by eod.instrument_id, close desc) yearHigh
                       inner join (select eod.instrument_id instrument_id, max(eod.close) maxClose
                                   from pdendofdaypriceentity eod
                                   where eod.day BETWEEN CAST('2018-11-12' AS date) AND CAST('2018-11-18' AS date)
                                   group by eod.instrument_id) weekHigh
                         on weekHigh.instrument_id = yearHigh.instrument_id
                where weekHigh.maxClose > yearHigh.maxClose;

I am very aware that there are dozens of similar questions, but those approaches got me to a working solution, but none helped me improve the performance. The table contains 10 Million Rows from different 28000 stocks. And this is just going to become larger. Is there a way to implement this requirement with a sub-2 second query without denormalization? Any kind of indexes, etc. would be fine obviously.
The query plan for the above approach:
                                                                  QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Hash Join  (cost=148153.45..1136087.99 rows=6112 width=74) (actual time=3056.748..144632.288 rows=411 loops=1)
   Hash Cond: (eod.instrument_id = eod_1.instrument_id)
   Join Filter: ((max(eod_1.close)) > eod.close)
   Rows Removed by Join Filter: 27317
   ->  Unique  (cost=0.56..987672.73 rows=18361 width=26) (actual time=2.139..141494.533 rows=28216 loops=1)
         ->  Index Scan using test3 on pdendofdaypriceentity eod  (cost=0.56..967290.80 rows=8152771 width=26) (actual time=2.117..79396.893 rows=8181608 loops=1)
               Filter: ((day >= '2017-11-13 00:00:00'::timestamp without time zone) AND (day <= '2018-11-11 00:00:00'::timestamp without time zone))
               Rows Removed by Filter: 1867687
   ->  Hash  (cost=147923.68..147923.68 rows=18337 width=48) (actual time=2793.633..2793.639 rows=27917 loops=1)
         Buckets: 32768  Batches: 1  Memory Usage: 1739kB
         ->  HashAggregate  (cost=147556.94..147740.31 rows=18337 width=48) (actual time=2301.968..2550.387 rows=27917 loops=1)
               Group Key: eod_1.instrument_id
               ->  Bitmap Heap Scan on pdendofdaypriceentity eod_1  (cost=2577.01..146949.83 rows=121422 width=22) (actual time=14.264..1146.610 rows=115887 loops=1)
                     Recheck Cond: ((day >= '2018-11-12'::date) AND (day <= '2018-11-18'::date))
                     Heap Blocks: exact=11992
                     ->  Bitmap Index Scan on idx5784y3l3mqprlmeyyrmwnkt3n  (cost=0.00..2546.66 rows=121422 width=0) (actual time=12.784..12.791 rows=115887 loops=1)
                           Index Cond: ((day >= '2018-11-12'::date) AND (day <= '2018-11-18'::date))
 Planning time: 13.758 ms
 Execution time: 144635.973 ms
(19 rows)

my current (basically random) indexes:
Indexes:
    "pdendofdaypriceentity_pkey" PRIMARY KEY, btree (id)
    "ukcaddwp8kcx2uox18vss7o5oly" UNIQUE CONSTRAINT, btree (instrument_id, day)
    "idx5784y3l3mqprlmeyyrmwnkt3n" btree (day)
    "idx5vqqjfube2j1qkstc741ll19u" btree (close)
    "idxcaddwp8kcx2uox18vss7o5oly" btree (instrument_id, day)
    "test1" btree (close DESC, instrument_id, day)
    "test2" btree (instrument_id, day, close DESC)
    "test3" btree (instrument_id, close DESC)

A: Try the following query
select weekHigh.instrument_id,
       weekHigh.maxClose                       weekLowValue,
       yearHigh.maxClose                       yearLowValue
from (
    select instrument_id,
         max(eod.close)  maxClose
    from pdendofdaypriceentity eod
    where eod.day BETWEEN (CAST('2018-11-12' AS date) - interval '52 weeks') AND (CAST('2018-11-12' AS date) - interval '1 day')
    group by eod.instrument_id
) yearHigh
inner join (
    select eod.instrument_id instrument_id, max(eod.close) maxClose
    from pdendofdaypriceentity eod
    where eod.day BETWEEN CAST('2018-11-12' AS date) AND CAST('2018-11-18' AS date)
    group by eod.instrument_id
) weekHigh on weekHigh.instrument_id = yearHigh.instrument_id
where weekHigh.maxClose > yearHigh.maxClose;

with the index pdendofdaypriceentity(day, instrument_id, close). Note, that it is missing the maxDay that you have in your query.
It is possible to add the maxDay by another join with pdendofdaypriceentity, however, I would start with the query above without distinct on and order by in the first subquery.

A: The query could potentially become much faster if you queried on fixed windows rather than a dynamic range.
E.g.

*

*This year (calendar)

*This quarter

*This month

This is because it allows you to use an index which can find the highest close for an instrument without having to read a range of values.
E.g. If we wanted to find the highest value in 2017
Day-first index
|day|instrument|close|
|31-12-2016|1|12.00|
|01-01-2017|1|19.00|    <-- start scan here
...
|06-01-2017|1|31.00|    <-- highest
...
|31-12-2017|1|11.00|    <-- end scan here
|01-01-2018|1|13.00|

Note: close is effectively unordered, hence the scan
Year-first index
|extract(year from day)|instrument|close|day|
|2016|1|12.00|31-12-2016|
|2017|1|31.00|06-01-2017|  <-- highest close for that year at the top
...
|2017|1|19.00|01-01-2017|
...
|2017|1|11.00|31-12-2017|
|2018|1|13.00|01-01-2018|

So, potentially, you get to scan 365 times less records.  And you could still request the day.
Note:  Your filter would need to use the same date function as the index

A:
Would you consider doing your data analysis somewhere else? The dimensions you mention are not that much for a sensible R or Python approach. Below example works on a table of 20 million rows (28,000 instrument ID's with 720 observations each) and needs ±1 second on a current Macbook Pro. I produced some mock data to go with it.
With R and data.table:
# Filter data for the past 52 weeks
result <-
    data[day >= max(day) - 52*7 & day <= max(day)]

# Get all instances where close was at max
result_52max <-
    result[result[, .I[close == max(close)], by = instrument_id]$V1]

# Get all instances where this happened last week
result_7max <-
    result_52max[day >= max(day) - 7 & day <= max(day)]

Average runtime: < 1 second.

Reproduction
Data
# Attention: takes a couple of minutes
library(data.table)
set.seed(1701)
data <- NULL
id <- 1
n <- 1000
obs <- 720
for(j in 1:28){
  dt <- NULL
  dates <- seq.Date(from = as.Date("2017-01-01"), by = "day", length.out = obs)
  for(i in (1+(j-1)*n):(n*j)){
    start <- sample(1:200, 1)
    dt <- rbindlist(list(dt,
                         data.table(id = id:(id+obs-1),
                                    close = abs(start + cumsum(sample(c(-1, 1), obs, TRUE))),
                                    day = dates,
                                    instrument_id = rep(i, obs))))
    id <- id+obs
  }
  data <- rbindlist(list(data, dt))
}

Structure
> str(data)
Classes 'data.table' and 'data.frame':  20160000 obs. of  4 variables:
 $ id           : int  1 2 3 4 5 6 7 8 9 10 ...
 $ close        : num  27 26 27 28 27 28 29 28 29 30 ...
 $ day          : Date, format: "2017-01-01" "2017-01-02" "2017-01-03" ...
 $ instrument_id: int  1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, ".internal.selfref")=<externalptr>

Plot for the first five instrument id's

library(ggplot2)
ggplot(subset(data, data$instrument_id <= 5),
       aes(day, close, color = as.factor(instrument_id),
           group = as.factor(instrument_id))) +
    geom_line()


text:
Q: JMeter Performance bench mark criteria Could any team assist me for sharing standard all J-Meter performance mark criteria while performing J-Meter Performance testing for min 1000 user .it means that how we can decide what parameter(or threshold) caused for deciding load /performance testing with route cause and proposed solution after generating html report with non-GUI with completed scenario.
Thanks
Amit G

A: There is no "standard", the acceptance criteria normally are being dictated by the business requirements which might differ depending on the nature of the application

*

*for real-time trading a couple of milliseconds delay is critical, companies invest into locating their highly performing servers physically close to exchange servers because even light speed matters for their scenarios

*for normal applications used by people (i.e. news portals, e-commerce websites, etc.) the accepted load time would be 2-3 seconds, if people have to wait more - most probably they will switch somewhere else and never return. Moreover, search engines tend to rank slow websites lower

*for internal applications which are being used inside the company response time doesn't really matter cause people will have to use particular this application, but you still might report large response times like: "if a person who earns $18 per hour has to wait for 10 seconds for each operation and the number of operations per day is 100 and number of personnel is 3000 the organization looses $15 000 every single day or $5 475 000 a year"

So I would recommend taking the following steps:

*

*Check for existing SLAs or NFRs, it might be the case the document, you got these 1000 users contains some information regarding maximum response time or minimum throughput (requests per unit of time)

*If there are no formal acceptance criteria defined you could go for other performance testing types:

*

*Soak testing - putting your application under the prolonged load to see whether it performs consistently and there are no obvious memory leaks

*Stress testing - starting with low number of users and gradually increasing the load until errors start occurring. This way you will be able to report correlation between increasing number of users and increasing response time/number of errors, identify saturation point (the maximum number of users which application can efficiently support), bottleneck (breaking point), etc.


text:
Q: How to get the actual values from Euler's Phi function I would like to get the list of actual values from Euler's Phi function.
For example:
$$\phi(12) = |1,5,7,11| = 4 $$
and I would like to get the actual list
$$[1,5,7,11]$$
Of course the naive way is to calculate all the gcd values, but I'm looking to something faster.
I tried using the following property:
$$p \in PRIMES, k \in \mathbb{N}  => \phi(p^k) = p^{k-1}(p-1)$$
$$\phi(n) = \phi(\prod{p_1^{k_1}\cdot\cdot\cdot p_m^{k_m}}) =  \phi(p_1^{k_1})...\phi(p_m^{k_m}) = p_1^{k_1-1}(p_1-1)\cdot\cdot\cdot p_m^{k_m-1}(p_m-1) $$
but even in the simple case of
$$\phi(12)$$
it is not clear to me how to get the list.
Is there such an algorithm?

A: Well, a number smaller than $n$ is relatively prime to $n$ if and only if it is not divisible by any of $n$'s prime factors. That gives you a simple algorithm to find the numbers relatively prime to $n$.
1) Find all primes dividing $n$.
2) Go through all numbers $1,2,3,...,(n-1)$ and see if they are divisible by any of the primes which divide $n$.
In your example you have $1,5,7,11$, these are just the numbers smaller than $12$ which are not divisible by $2$ and $3$.

A: Using the *Chinese Reaminder theorem`, you come down todetermine the units $\mathbf Z/p^r\mathbf Z$ for  prime $p$.
If $p=2$, it's very simple: all odd numbers in $[1 , p^r-1]$ are units.
If $p$ is an odd prime, the group of units is cyclic. Hence you can test all integers $a$, starting with $2$, computing their powers, until you find one with order $p^{r-1}(p-1)$. This should be faster than computing all g.c.d.s, all the more so as often a generator is obtained for a small value of $a$.


text:
Q: Strange trigonometric proof. I was trying to find out how to prove
$$ \sin(A-\arcsin(0.3 \ \sin \ A)) \ \cdot \ \sin(A+\arcsin(0.3 \ \sin \ A)) \ = \ 0.91 \ \sin^2 \ A \ \ . $$
When I put this equation into my calculator both sides appear to be exactly the same, but I have no idea how to prove it.

A: $$\sin { \left( A-\arcsin { \left( 0.3\sin { \left( A \right)  }  \right)  }  \right)  } \cdot \sin { \left( A+\arcsin { \left( 0.3\sin { \left( A \right)  }  \right)  }  \right) =0.91\sin ^{ 2 }{ \left( A \right)  }  }$$
Solution
 :
$$\left( \sin { A\cos { \left( \arcsin { \left( 0.3\sin { \left( A \right)  }  \right)  }  \right)  } -\cos { A } \sin { \left( \arcsin { \left( 0.3\sin { \left( A \right)  }  \right)  }  \right)  }  }  \right) \ast \left( \sin { A\cos { \left( \arcsin { \left( 0.3\sin { \left( A \right)  }  \right)  }  \right)  } +\cos { A } \sin { \left( \arcsin { \left( 0.3\sin { \left( A \right)  }  \right)  }  \right)  }  }  \right) =0.91\sin ^{ 2 }{ A } \\ \left( \sin { A\sqrt { 1-0.09\sin ^{ 2 }{ A }  } -0.3\cos { A } \sin { A }  }  \right) \ast \left( \sin { A\sqrt { 1-0.09\sin ^{ 2 }{ A }  } +0.3\cos { A } \sin { A }  }  \right) =\sin ^{ 2 }{ A\left( 1-0.09\sin ^{ 2 }{ A }  \right) -0.09\cos ^{ 2 }{ A } \sin ^{ 2 }{ A } = } \\ =\sin ^{ 2 }{ A } \left( 1-0.09\sin ^{ 2 }{ A } -0.09\cos ^{ 2 }{ A }  \right) =\sin ^{ 2 }{ A } \left( 1-0.09\left( \sin ^{ 2 }{ A } +\cos ^{ 2 }{ A }  \right)  \right) =\sin ^{ 2 }{ A\left( 1-0.09 \right) =091\sin ^{ 2 }{ A }  } $$

A: [I thought of another way since I left my comment above.]
Applying the "product-to-sum" formula for two sine factors,
$$ \sin \ \alpha  \ \cdot \ \sin \ \beta \ = \ \frac{1}{2} \ [ \ \cos(\alpha \ - \ \beta) \ - \ \cos(\alpha \ + \ \beta) \ ] \ \ , $$
with $ \ \alpha \ \ \text{and} \ \ \beta \ $ being sums and differences of angles, we can write
$$ \sin (\theta \ + \ \phi)  \ \cdot \ \sin \ (\theta \ - \ \phi) \ = \ \frac{1}{2} \ [ \ \cos \ 2 \phi \ - \ \cos \ 2 \theta \ ] \ \ . $$
So the left-hand side of your equation becomes
$$ \sin(A-\arcsin(0.3 \ \sin \ A)) \ \cdot \ \sin(A+\arcsin(0.3 \ \sin \ A)) \ = \ \frac{1}{2} \ [ \ \cos  ( 2 \ \cdot \arcsin \ [0.3 \ \sin \ A]) \ - \ \cos \ 2 A \ ] \ \ . $$
We're looking ultimately for an expression which has a factor of $ \ \sin^2  A \ $ , so we'll use the "double-angle" formula for cosine, $ \ \cos \ 2 \theta \ = \ \cos^2 \ \theta \ - \ \sin^2 \ \theta \ = \ 1 \ - \ 2 \ \sin^2 \ \theta \ $ . The left-hand side becomes
$$ = \ \frac{1}{2} \ [ \   ( 1 \ - \ 2 \ \sin^2 ( \ \arcsin \ [0.3 \ \sin \ A] \ ) \ ) \ - \ ( 1  \ - \ 2 \ \sin^2  A ) \ ]  $$
$$ = \ \frac{1}{2} \ [ \   2 \ \sin^2  A \  - \ 2 \ \sin^2 ( \ \arcsin \ [0.3 \ \sin \ A] \ ) \ ] \ = \     \sin^2  A \  - \   \sin^2 ( \ \arcsin \ [0.3 \ \sin \ A]  \ ) \ \ . $$
Now we need to consider the angle in the second term.  [Since arcsine has as its domain $ \ -\frac{\pi}{2} \ \le \ \theta \ \le \ \frac{\pi}{2} \ $ , we would have to deal with negative as well as positive angles.  But we can restrict the discussion to positive angles, since the argument for negative angles is similar.]  Suppose angle $ \ A \ $ has a sine value of $ \frac{y}{1} \ $ ; then the angle in the second term has a sine value of $ \ 0.3 \ y \ $ .  That angle has measure $ \ \arcsin \ (0.3 \ y ) \ $ , but we don't care what that number is, since we are going to take the sine of that angle and square it.  [You don't indicate at level you're familiar with working with trigonometric functions; if you are used to the inverse functions, this is something you already know and I apologize for the explanantion.]
Hence, the expression reduces to
$$  \sin^2  A \  - \   ( \ 0.3 \ \sin \ A \ )^2  \ = \ \sin^2  A \  - \    0.09 \ \sin^2 \ A  \  = \ 0.91 \ \sin^2 \ A \  \ . $$


text:
Q: Problem with pip install mariadb - mariadb_config not found I have been trying to run pip3 install mariadb on my raspberry pi running ubuntu 18.04 and I was unsuccessful.
I have tried installing following packages as suggested in other answers:
sudo apt-get install mariadb-server
sudo apt-get install libmariadbclient-dev
sudo apt-get install libmysqlclient-dev

pip3 install mysqlclient
pip3 install mysql-connector-python-rf

However, I'm still running intto the problem as shown:
ubuntu@ubuntu:~$ pip3 install mariadb
Collecting mariadb
  Using cached https://files.pythonhosted.org/packages/8f/c9/7050899dc1066409a17e1147d3afe1b078e582afdb755c6d3cb9c9a5c3ab/mariadb-1.0.0.tar.gz
    Complete output from command python setup.py egg_info:
    /bin/sh: 1: mariadb_config: not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-2gdw_t_r/mariadb/setup.py", line 26, in <module>
        cfg = get_config(options)
      File "/tmp/pip-build-2gdw_t_r/mariadb/mariadb_posix.py", line 49, in get_config
        cc_version = mariadb_config(config_prg, "cc_version")
      File "/tmp/pip-build-2gdw_t_r/mariadb/mariadb_posix.py", line 27, in mariadb_config
        "mariadb_config not found.\nPlease make sure, that MariaDB Connector/C is installed on your system, edit the configuration file 'site.cfg' and set the 'mariadb_config'\noption, which should point to the mariadb_config utility.")
    OSError: mariadb_config not found.
    Please make sure, that MariaDB Connector/C is installed on your system, edit the configuration file 'site.cfg' and set the 'mariadb_config'
    option, which should point to the mariadb_config utility.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-2gdw_t_r/mariadb/

I do have /etc/mysql/my.cnf file.

A: You probably need to install MariaDB database development files: https://packages.debian.org/unstable/libmariadb-dev. You need this package for your python connector to work properly in linux. You need to follow this steps:

*

*sudo apt-get update -y

*sudo apt-get install -y libmariadb-dev

*pip3 install mariadb
Here you are first updating the list of packages that need an upgrade for your system. Then you are installing the previously mentioned dev library. The last step is to install mariadb with pip3 which should now work as expected.

A: On a Mac you need to first install mariadb-connector-c which can be done using brew:
brew install mariadb-connector-c

Then you can install mysqlclient:
pip3 install mysqlclient

A: It looks like that you didn't install MariaDB Connector/C properly, on Ubuntu mariadb_config should be found in /usr/bin.
Please also note, that MariaDB Connector/Python requires MariaDB Connector/C 3.1.5 or newer, afaik Ubuntu 18.04 provides 3.0.3 - so simplest way would be to download the Connector/C sources and build it manually.


text:
Q: mod rewrite .htaccess query string # Turn Rewrite Engine On
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

RewriteRule ^watch/([a-zA-Z0-9-_]+) watch.php?m=$1 [NC,L]

Okay, so I have this code in my .htaccess file, and the result I want to retrieve is:

*

*You can go to the url: http://example.com/whateverhere/we're-a-website
without retrieving Object not found

*And the url: http://example.com/whateverhere/this-is-Bat-Man
What I want to retrieve with the second url, is that in my database, the title would say: Bat-Man and not Bat Man, so I want it to show - even if it already was in the database.

A: [a-z] means only match a - z
[A-Z]  means only match A - Z
[0-9] means only match 0 - 9
[-_] means only match - or _
Combined together [a-zA-Z0-9-_] matches only those characters.  So if you don't really want to limit to those characters, use . which matches any character.
RewriteRule ^watch/(.+) watch.php?m=$1 [NC,L]


text:
Q: Advantage of MLE over LS or other estimator Is there any advantage of a maximum-likelihood estimator over another estimator (for example least squares) assuming both methods of estimation are efficient, unbiased, and consistent?
I have been taught that maximum-likelihood methods are generally superior but I don't know why.

A: The MLE is more efficient when the distributional assumptions are correctly specified. For instance, if the linear model satisfies, $Y = b X + \epsilon$ where $\epsilon$ comes from, say, a shifted 0 meanWeibull distribution, the MLE will account for the skewness of the errors and the LS will not. It happens to be the case that when $\epsilon$ is normally distributed, you arrive at the least squares estimator anyway.


text:
Q: How to clear global mocks for individual tests in React testing I tried to test an if-else scenario that requires me to mock a module import in my testing. For some reason, there's already a mock for that module globally that I can not remove, but I need to skip that for my particular test case.
I tried clearAllMocks() which doesn't work, what would be a proper way to do this?
Here's the react code that I tried to test
import Highcharts from 'highcharts';
import factory from 'highcharts/highcharts-more';

componentDidMount() {
        if (typeof Highcharts === 'object') {
            factory(Highcharts);
        }
}

Here's the test I wrote so far
import Highcharts from 'highcharts';
import factory from 'highcharts/highcharts-more';

jest.mock('highcharts', () => {
    const chart = {
        update: jest.fn(),
        destroy: jest.fn(),
        series: [],
    };

    return {
        chart: jest.fn(() => chart),
    };
});

jest.mock('highcharts/highcharts-more', () => jest.fn());

describe('<HighchartsReact />', () => {

it('call factory if the module is not initialized', async () => {
        // update the mock so the typeof Highcharts is not an object
        jest.mock('highcharts', () => []);
        render(<HighchartsReact config={{}} />);
        expect(factory).not.toHaveBeenCalledWith(Highcharts);
    });
});


text:
Q: Process A leave MemoryMapFile available for Process B Been Googling, but can't find an answer to this. Have not used MemoryMappedFile before. Have just been reading about them with a view to implementing basic IPC. Before I invest time prototyping can anyone tell me whether the following logic will work?
I had in mind to use a non-persisted memory-mapped file, so that it is automatically cleaned up after use.

*

*Process A opens MemoryMappedFile and writes to it.

*Process A launches process B

*Process A quits

*Process B performs OpenExisting on MemoryMappedFile created by process A

*Process B reads data from MemoryMappedFile and does processing...

Process A & B will both know the name of the file.
Will the file created by Process A remain until process B has disposed of it?
What are the mechanics, should process A not Dispose the file and let Process B do that?
If this logic will not work then I was considering that Process A wait for Process B to complete, but this is not ideal.
Thanks for any shedding of light ;)

A: That will work, except process B needs to open a handle to the memory mapped file before process A closes its handle. The reason is that the memory mapped file is destroyed when the last handle is closed.
(I assume we're talking Windows here.)

Edit: I got interested in this and did a bit more reading…
Probably the most correct and robust way to do this would be for process B to inherit a handle to to the memory mapping. Some links:

*

*Handle Inheritance in Windows

*Programmatically controlling which handles are inherited by new processes in Win32

*How do I pass a lot of data to a process when it starts up?
I think this last link provides you with a model answer by one of the most knowledgeable Windows programmers in the world. Do read the comments below the article as well.


text:
Q: linux "watch -c" (with color parameter), but commands display colorless output. Why? When I do 'ls', or 'service some_service_name status', or any other command with colored output, it, "surprisingly" :), shows it's output in color, but when I run them with 'watch' and even with 'watch -c' command with a color enabling parameter, they still show without colors.
Why?, and how to fix it?

A: ls and others see that they are run from a script so they go to the default mode (without colors):

With --color=auto, ls emits color codes only when standard output  is  connected  to  a terminal.

try forcing the color output:
watch -c ls --color


text:
Q: Possible paths to convert windows form application - hybrid of controls and html - to web The existing application mixture of native and third party controls and hosts IE in a webbrowser control for rendering html. Also  there is bi-directional update of UI - selecting anything in native controls ( e.g. treeview ) updates html , and vice verse javascript or hyperlinks in a webrowser may cause certain actions which update UI on a form or an application level.
I see 3 possible paths for conversion:

*

*Silverlight seems to be the best candidate for conversion, but if try to mimic existing interface we can only do it in SL4 and also only in out of browser mode which makes this conversion a bit pointless. I know about existence of controls which will display HTML not in windowless mode such as C1RichTextBox, but quite clearly it is not going to happen in a near future that such a control will be able to render any arbitrary html properly as IE does ( not all html under my control ) . Plus as I mentioned before in Windows Forms it is possible to call external C# methods from Javascript ( selecting row in a table by mouse ) ) and update UI accordingly ( webrowser in SL4 does it , but as mentioned it out of browser mode).

*I guess, all can be done purely in ASP.Net ( Web Forms or MVC ) with AJAX and jQuery UI, but, I believe, it is MUCH more work.

*Possibly ASP.Net facade as a main site/application to show HMTL and self-contained Silverlight modules spawn in a separate browser tabs ( I am not sure whether it makes things simpler than 2).

Perhaps, I am missing something, and there is another better and easier way for such a conversion for all-rounder who has some familiarity with all these technologies, but no real application delivered yet ?

A: My comments for the 3 points:

*

*Keep in mind there'll be a huge change of user experience. Even thought it might look similar visiually, SL gives a more desktop feel than typical app. User who are used to using browser 'back, forward, refresh' buttons will be 'disappointed' of course unless you can address it which can be painful.

*Definitely do-able. How much work? That's quite subjective. I'll go for this though as it might be 'more-work, but likely to be more straight-forward and easier to manage.

*This might just blow up the cons of 1 and 2 and not so much or the pros. I might be wrong :P


text:
Q: How to evaluate integral solutions of a permutation inequality Find the number of integral solutions of $$x_1+x_2+x_3<36$$ such that $x_i$ (for i= $\{1,2,3\}$) varies as $$1\le x_i\le23$$

My initial attempt in this problem was to introduce a 'dummy' variable to remove the inequality such that $x_1+x_2+x_3+y_4=35$.   $y_4$ being the dummy variable. Now since $x_1,x_2,x_3$ has restrictions I tried to replace $x_i\rightarrow y_i+1$ transforming my equation into $$y_1+y_2+y_3+y_4=32$$ with the restriction now that $0\le y_i \le 22$ And again there is no such restriction on $y_4$ and the number of solutions of such equations is generally, Coefficient of $x^{32}$ in $$(x^0+x^1+x^2....x^{22})^3(x^0+x^1+x^2....x^{33})^1 $$

$$\Rightarrow \frac{(x^{23}-1)^3}{(x-1)^3}.\frac{(x^{33}-1)}{(x-1)}$$
$$\Rightarrow (x^{23}-1)^3(x^{33}-1)(x-1)^{-4}$$
which leaves us to find the coefficient of $x^{32}$ and $x^{9}$ we shall invoke the formula $\binom{n+r-1}{r}$ But my answer was off by a mile.
Where did I go wrong with this method? is this method wrong for such problems, if so, why?

A: In your answer of $6225$, for $\binom{35}2$, I think you meant $\binom{35}3$
I am getting a somewhat different answer though, starting from
$y_1+y_2+y_3+y_4=32, 0\leq y_i\leq22$
Using the normal stars and bars formula, and applying PIE we get
$\binom{32+4-1}{4-1} - \binom31\binom{9+4-1}{4-1}$
$=\binom{35}3 - \binom31\binom{12}3 = 5885$


text:
Q: Only one application working in the DOM As I understand of the guide on scopes, I'm supposed to be able to host the application in a DOM element, such as a div (as opposed to hosting it globally by ng-app attribute in the HTML tag).
It seems to work for the first application but not the other. I have the following example and I expected AppUno and AppDuo to work, while AppTri would fail. The case is, though, that only the first one behaves as expected.

Uno {{someHolder}}!

Duo {{someHolder}}!

Tri {{someHolder}}!

var uno = angular.module('AppUno', []);
var duo = angular.module('AppDuo', []);

uno.run(function ($rootScope) {
  $rootScope.someHolder = "Blipp";
});

duo.run(function ($rootScope) {
  $rootScope.someHolder = "Blopp";
});

Am I misunderstanding the compartmentalization paradigm? Is it a syntax error that my eyes refuse to see? Anything else?
The output is as follows.

Uno Blipp!
  Duo {{someHolder}}!
  Tri {{someHolder}}!

A: The problem is you can only have one ng-app directive;
You could run multiple applications but only one can be bootstrapped with ng-app ( for other apps you would need to manually bootstrap them using angular.bootstrap).

As far as compartmentalization paradigm is concerned there are many way to create child scopes, using you're structure you can consider ng-controller.


text:
Q: Ubuntu running on vmware-kvm with Dual Screens I'm trying to find a way to use Ubuntu 64-bit on vmware-kvm.exe with dual screens. Ubuntu runs perfectly fine but I can't use my two monitors unless I use VMware workstation player. I've been searching online for so long but I still can't find a solution.
I found someone who asked the same question on the official vmware website in 2014 but an admin answered "vmware-kvm currently does not support VMs using multiple monitors. It's certainly something that we can consider[...]".
And a post on r/vmware with only one comment saying it's impossible unless you use VMware workstation.
Also, there's no option for dual monitors when I run --preferences.

So now that I have accepted the fact that VMware-kvm doesn't support multiple monitors. (According to what an admin said in 2014) I'm trying to find another solution. I don't know if the solution is to modify my current setup or if I should just use something else instead of vmware-kvm. I would like to have true full screen (without the top bar appearing when I let my mouse at the top of the screen for too long) and I would like to be able to switch between my host (windows) and my virtual machine (Ubuntu) with a key. I have already found that by editing
%APPDATA%\VMware\preferences.ini

and adding
pref.vmplayer.fullscreen.nobar = "TRUE"

The top bar disappear but exiting isn't as simple as pressing a single key, you need to do Ctrl+Alt and then Ctrl+Alt+Enter. You also doesn't get the performance of kvm.


text:
Q: Inserting Formula in Formula Bar Anyone knows what's the problem with my code?
Sub reFormat()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Admin")
    ws.Range("C21").Formula = "=""S4&""AA5&""AA6&""AA7&""AA8&""AA9&""AA10" 'returns applica-
    tion defined or object-defined error
End Sub

And I want the output of this code to be: =S4&(AA5&AA6&AA7&AA8&AA9&AA10)
Thanks for the help!

A: Your formula is fundamentally invalid. The string evaluates to this:
="S4&"AA5&"AA6&"AA7&"AA8&"AA9&"AA10

Which isn't a valid Excel formula.
You have too many quotes. If these are cell references and your formula intends to concatenate them, and you want your string to evaluate to this:

=S4&(AA5&AA6&AA7&AA8&AA9&AA10)

Then you could just do this:
.Formula = "=S4&(AA5&AA6&AA7&AA8&AA9&AA10)"


text:
Q: How to run shell script (.sh files) in Gulp 4? Hello to everyone and Happy New Year!
Since Gulp version 4 I can't run a shell script.
I have simple shell script.
if application id "com.adobe.estoolkit-4.0" is running then
    display dialog "Close The App!" buttons {"OK"} default button 1
end if

When I run it this way, it works
const { exec } = require('child_process');

function checkAppisOpen() {
    return exec('./utils/check.sh');
};

exports.run = checkAppisOpen;

But when I'm trying to use npm gulp-shell plugin it won't work.

Error: Did you forget to signal async completion?

See the code:
const shell = require('gulp-shell');

function checkAppisOpen() {
    return shell('./utils/check.sh');
};

exports.run = checkAppisOpen;

I know I'm doing something wrong. Could please someone explain how this async completion works under the hood. Or at least where I could read about it. Because it seems like gulp documentation is not enough for me https://gulpjs.com/docs/en/getting-started/async-completion


text:
Q: String vibration and damping In case of a home experiment about string vibration under the boundary condition
$$y(l,t)=y(0,t)=0$$
Where $y=$ the displacement of the string at spatial co-ordinate $x$ and at time $t$,
I observed that under any kind of arbitrary initial condition as the wave damps out with time ultimately it vibrates in the first normal mode for some time after all other modes having been damped out before stopping.
Physically it can be argued that as the frequency corresponding to higher normal modes are higher the velocity of the different portions of the string due to the higher normal modes will also be higher and due to high velocity it will be damped very fast as the damping in real life is proportional to velocity.
But I am failing to mathematically model this problem to have a quantitative idea about the damping of the individual normal modes.
Now,how can I mathematically model this damping?

A: The free vibration of a string can be modelled with the partial differential equation:
$$T\frac{\partial^2 y(x,t)}{\partial x^2}-\rho \frac{\partial^2 y(x,t)}{\partial t^2} = 0$$
Where $T$ is the axial tension on the string, $\rho$ is the mass density, $y$ is your transverse displacement, and $x$ is the position along the string length. The solution of this equation can be obtained using, for instance, the method of separation of vibrations ($y(x,t) = Y(x)\exp(\omega t)$), and later applying your boundary conditions.
Damping can be very difficult to predict, but a viscous type damping model can be incorporated in this model as
$$T\frac{\partial^2 y(x,t)}{\partial x^2} + \beta\frac{\partial y(x,t)}{\partial t}-\rho \frac{\partial^2 y(x,t)}{\partial t^2} = 0$$.
Where $\beta$ is a viscous damping coefficient, and since the damping forces are proportional to the velocity, the higher is the frequency, the higher are the damping forces. So each mode of vibration is affected differently by damping.

A: Try the following:
1. compare the test between vertical and horizontal settings, to see the gravitation effect, which is most likely in play in your test;
2. plug in different initial modes: first mode, plug the midpoint; second mode, plug two points with an offset but in opposite direction; so on;
3. change the rigidity of your boundary condition: your BC may be not rigid enough


text:
Q: kafka for consuming subscription data sent by a webservice Scenario:
I have a north bound web service(say A) and a south bound application(say C).
And I am creating a micro service (say B) which transforms data received by A in a format that is readable by C.
A can send data any random time intervals, and as B receives it, it has to transform.
What I think :
Once B subscribes to A, and A starts sending data via a callback url. Save the data in mongodb and after some interval process the data and push to C.
Question:
1. Since A is streaming a type of data to B, Can I use KAFKA for consuming the data ?
2. If no, what are the other alternatives?
3. I want to know, is there any other efficient way of doing this ?

A: What you are describing sounds to me like a typical stream transformation application. You can definitely use Kafka for this, but you can probably also use any other pub/sub service out there.
Setting up Kafka just for this seems like overkill and I would rather look into simpler pub/sub services offered online.


text:
Q: requireJS - with ajax requests index.html
<link href="Styles/bootstrap.css" rel="stylesheet" />

button 0

app.js
require({
    paths : {
        jQuery : 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
        tooltip : 'bootstrap-tooltip'
    }
});

require([ 'jQuery' ], function() {
    require(['tooltip' ], function() {
        $(".btn0").click(function() {
            $(".target").load('btn0.html');
        });

        $('[rel=tooltip]').tooltip();
    });
});

btn0.html
 Wouldn't it be nice to see a Tooltip here?

In this situation, the tooltip doesn't work. Only works if i cut $('[rel=tooltip]').tooltip(); and paste in btn0.html like:

My question is. How organize the javascript code that is needed in btn0.html? It is possible put the JS content of btn0.html in app.js?

A: You have to call tooltip() function when btn0.html is loaded.
Element with rel="tooltip" does not exist when inicializing that page.
require([ 'jQuery' ], function() {
  require(['tooltip' ], function() {
    $(".btn0").click(function() {
      $(".target").load('btn0.html', function ()
      {
        $('[rel=tooltip]').tooltip();
      })
    });
  });
});


text:
Q: Maven Deploy - Issue while uploading a 3rd party artifact I am trying to deploy my jar file to Azure maven repo(Azure artifacts) using the below command
mvn deploy:deploy-file -Dpackaging="jar" -DrepositoryId="id" -Durl="/Users/myname/.m2" -DgroupId="com.alexgilleran" -DartifactId="icesoap" -Dversion="2.2.0" -Dfile="/Users/myname/.m2/repository/com/alexgilleran/icesoap/2.2.0/icesoap-2.2.0.jar"

I get the below message
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy-file (default-cli) on project icesoap: No transfer protocol found. -> [Help 1]

I researched a lot to understand what might cause this issue, with no luck. Could someone please let me know what can cause this issue, and solution for the same?
I have my credentials in Settings.xml as below, and I do mvn clean install before trying to deploy using the above command
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              https://maven.apache.org/xsd/settings-1.0.0.xsd">
  <servers>
    <server>
      <id>test003</id>
      <username>MyUsername</username>
      <password>[MY_PERSONAL_ACCESS_TOKEN]</password>
    </server>
  </servers>
</settings>