text:
Q: Test::Unit should equivalent of RSpec should_receive I am writing some unit tests for my Ruby on Rails application. I would like to test that my model received a message to a particular method. In RSpec this is done with the should_receive incantation.
Is there an equivalent to Test::Unit that can do the same? If Test::Unit cannot do it, is there a tool I can use in concert with it to get that functionality?

A: Check out mocha. It is a gem that you can use with Test::Unit or Rspec (but I prefer the native rspeck mocking). It allows you to write something like
@post.stubs(:something).returns(:bla)
@post.expects(:something_else).raises(StandardError, "failed")

Hope this helps


text:
Q: Error in python after 'import tensorflow' on windows After install TensorFlow for Python3 and type "import tensorflow" it wrote this long error.
Any ideas how to fix it?
C:\Users\marsa>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
Traceback (most recent call last):
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: Proces inicializace dynamicky připojované knihovny (DLL) se nezdařil.

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 28, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\marsa\AppData\Local\Programs\Python\Python37\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: Proces inicializace dynamicky připojované knihovny (DLL) se nezdařil.

Failed to load the native TensorFlow runtime.

A: What operating system are you using? Are you in a virtualenv? Please make sure the same python interpreter used for installing is also used for testing. For example, you could do:
python -m pip install tensorflow
python -c "import tensorflow"

And this should not fail.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does the separator get changed by Path parentPath = Paths.get(strPath)? In my Windows app I want to delete a directory structure on the server with FTP using SimpleFileVisitor<Path>. It fails with "File not found" because in the code below the separator gets changed to backslash. Obviously, the server wants it to be forward slash. How can I make it stay as forward slash?
public class FTPTest {
static String server ;
static int port ;
static String user ;
static String pass;
static FTPClient theFtpClient;
public FTPTest(){
    server = "nx.dnslinks.net";
    port = 21;
    user = "xxxx";
    pass = "#xxxxx";
    theFtpClient = new FTPClient();
}
static void deleteDirectoryWalkTree(Path path) throws IOException {
FileVisitor visitor = new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }
    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }
    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      if (exc != null) {
        throw exc;
      }
      Files.delete(dir);
      return FileVisitResult.CONTINUE;
    }
};
    Files.walkFileTree(path, visitor);
}
public static void main(String[] args) {
    FTPTest     theFTPTest = new FTPTest();
    Path Path = Paths.get("/httpdocs/manual-uploads/TestingFTPUtil/SubDir_1/SubDir_2");
    try {
        theFTPTest.deleteDirectoryWalkTree(Path);
    } catch (IOException ex) {
        Logger.getLogger(FTPTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

A: Path/Paths classes are to isolate your code from the path syntax of the local operating system.
While you want to use the path for a remote FTP system, which may (does) use a different syntax. And mainly the same syntax, no matter on what local operating system your code happens to run.
So you should not use Path/Paths classes for FTP paths.


text:
Q: Does Oracle Database Express Edition 21c have GUI or a browser view on Windows? I have downloaded and installed Oracle DB EX 21c on Windows and it seems the only way to interact with it is using the command prompt. Some older versions like 11g have a gui which for a student make it easier to understand.
Thank you


text:
Q: Use of uninitialized value $key_value in print at This is my first post. So please excuse me of any irregularities. I am newbie to Perl and I have got the following issue. I get the error "Use of uninitialized value ...at" when I use the param function in Perl. Here's the code.
use CGI qw(param);

print "Content-type: text/plain \n\n";

$key_value=param('sososo');

print $key_value;

and my html file is
<input type="radio" name="rate" id="sososo" value="1"/>
so

In other words I want the value 1 to be displayed. But obviously it does not assign the value to $key_value. I don't know why. Thank you in advance.

A: To get the value of an input field, you have to use the name of the element, not the id.
use
$key_value=param('rate');

instead of
$key_value=param('sososo');


text:
Q: SSIS 2012 Deploy Package.... One ETL Used for Many Sites Currently have 1 ETL that is ran through the day for different sites. The etl is launched with different jobs for different sites, so each job has a different config file.
Deploying a project has parameters, so what should I be looking up/reading to find out how to replicate how we normally do it but using the project deployment.

A: Just walking through the steps would have showed me that it's held in the sql agent job as. duh.


text:
Q: Consulta sql, obtener último registro Tengo la siguiente consulta. ¿Cómo obtengo el último registro, ya que ct_contrato_cuenta, obtiene dos registros cuando hace el join con ct_factura
SELECT  *
FROM ct_contrato_cuenta,ct_factura
WHERE ct_contrato_cuenta.n_id_factura = ct_factura.n_id
and ct_factura.n_id = 23000

A: Para hacerlo funcional, yo utilizaria tu consulta pero tal que así
    SELECT count(*)
FROM ct_contrato_cuenta,ct_factura
WHERE ct_contrato_cuenta.n_id_factura = ct_factura.n_id
and ct_factura.n_id = 23000

De esta forma primero obtendrás el número de registros que tendrá esta consulta y luego cuando tenga este número que imagino que podrá variar, volvería a relizar la misma consulta pero así.
SELECT  *
FROM ct_contrato_cuenta,ct_factura
WHERE ct_contrato_cuenta.n_id_factura = ct_factura.n_id
and ct_factura.n_id = 23000 and "INDICE DE LA TABLA" = "VALOR OBTENIDO ANTERIOR POR LA FUNCION COUNT()"

Otra solución si quieres evitarte otra consulta a la bbd sería guardar el resultado de la consulta count() en una variable y, utilizarlo posteriormente para buscar la posición en la lista o arrays donde recojas los datos, dependiendo del lenguaje que trabajes en el servidor se trata de una manera o de otra.
Espero te sirva un saludo.


text:
Q: Probability formula, a value chosen at random is greater than another chosen value. Say I have two number ranges, whole numbers only.
Range 1: [-3,16]
Range 2: [3,22]
I choose randomly one number from Range 1 and one number from Range 2.
Lets call them x and y.
How do I find the probability that the number x will be greater than the number y?

A: $$P(x > y) = P(x,y \in [3,16])[1/2 *P(no\:\: tie \: | \: x,y \in [3,16])]$$
$$= (14/20)(14/20)(1/2 * 13/14)$$
$$ = 91/400.$$
To check your reasoning on these things, I suggest downloading the free program called R and doing a quick sim like this:

X = -3:16
Y = 3:22
sims = 0
count = 0
while(1) {
  x = sample(X,1)
  y = sample(Y,1)
  if (x > y) count = count + 1
  sims = sims + 1
}
p = count/sims
error = 3.29*sqrt(p*(1-p)/sims)
p
p-error
p+error
91/400
sims

Output:

> p
[1] 0.2276158
> p-error
[1] 0.2271114
> p+error
[1] 0.2281201
> 91/400
[1] 0.2275
> sims
[1] 7480549

Shown is the 99.9% confidence interval.  This runs until you break it, and you can restart it from the main while loop to have it continue until the confidence interval is as tight as you want.

A: One way you could do this is the following:
Let $X$ be the number from the first range, and let $Y$ be the number from the second.
$$\mathbb{P}(X>Y)=\sum_{y\in \{3;22\}}\mathbb{P}(X>Y \mid Y=y)\mathbb{P}(Y=y)$$
The probability that $X>Y$ given that $Y=y$ is easily determined by counting what fraction of the possible values of $X$ are larger than $y$.  This type of computation is easily implemented on a computer.  By hand, it could be pretty tedious.  In general of course you'd replace the sum $y\in \{3;22\}$ with $y\in \text{Range 2}$, i.e. $y$ is over all the possible values of $Y$.
If you write out what those conditional probabilities are you'll notice a pattern in how the values change from one term in the sum to the next.  This may lead you (with a little effort) to an easier-to-compute closed form...

A: *

*The sample space is $20\cdot20$ = 400

*Chances of x > y are only in the interval [3,16]

*In the $14\cdot14$ = 196 sample points, there will be 14 ties,
and by symmetry, for $\frac12$ of the rest , x > y, hence ans = $\frac{91}{400}$

A: Let us denote by R the rectangular region $[-3,16]\times[3,22]$. The required probability is $P(X>Y)=P((X,Y)\in D)$, where $D=\{(x,y)\in R, x>y\}$.
A short computation illustrates that D is the triangle of vertices (3,3), (16,3), (16,16), having the area equal to $13^2/2$.
Now we have  $P(X>Y)=P((X,Y)\in D)=\dfrac{area(D)}{area(R)}=\dfrac{13^2}{2\cdot 19^2}$.

Here is the Python code simulating $(X,Y)$:
import numpy as np
k=0
nr=0
N=5000
for k in range(N):
  x=-3+19*np.random.random()
  y=3+19*np.random.random()
  if x>y:
      nr+=1

    print 'Experimental prob=', float(nr)/N,  'Theoretical prob=', 13.0**2/(2*19**2),\
 '\nBruceZ probability=', float(91)/400

    >>> Experimental prob= 0.231 Theoretical prob= 0.234072022161
 BruceZ probability= 0.2275


text:
Q: How do I make 'import x' return a subclass of types.ModuleType? Can Python's import statement return a subclass of types.ModuleType using import hooks? I would like to override __getattribute__ to display a runtime warning when code outside a certain module reference names that aren't in __all__.
I know how to replace sys.modules['foo'] after it's been imported. What I want is to instrument modules that match a pattern as they are imported so the importing code has an opportunity to trigger the warning.
Python frowns on the idea of making things public and private. This idea isn't about preventing your module's users from typing from somemodule import sys; instead, it is a documentation tool. This kind of instrumentation should make it much easier to document your module's API by including a correct  __all__. It should help you avoid accidentally referencing sys as somemodule.sys instead of simply import sys.

A: Since I missed the point of your question before you edited it, I thought I'd take another whack (while leaving my original answer for posterity).
Here's an alternative that also doesn't need the import hook. It can easily be used on a module-by-module basis: a module that includes this code will have the special __getattribute__() behavior, while other modules will behave as usual.
class StrictModule(types.ModuleType):

    def __getattribute__(self, key):
        if key is "__dict__":  # fake __dict__ with only visible attributes
            return dict((k, v) for k, v in globals().iteritems()
                        if k.startswith("__") or k in __all__)
        if (key.startswith("__") or key in __all__) and key in globals():
            return globals()[key]
        else:
            raise AttributeError("'module' object has no attribute '%s'"  % key)

    def __setattr__(self, key, value):
        globals()[key] = value

sys.modules[__name__] = StrictModule(__name__)

Keep in mind this "restriction" is easy to get around by simply calling the regular module type's __getattribute__() (or for that matter, the object type's). I get the impression that you are trying to provide some kind of "private member" restriction for your modules. There's almost never any point to this.

A: You don't even need an import hook. Simply put a reference to the object in Python's module registry sys.modules under the desired name, and any future import statement in the Python session (even in other modules) will import a reference to that entity.
import types, sys

class MyModuleType(types.ModuleType):
    pass

sys.modules["foo"] = MyModuleType("foo")

import foo

print type(foo)   # MyModuleType

Python does not even care whether the objects in sys.modules are actually modules or some other type of object entirely. You could chuck an int in there and not a single f*** would be given.
sys.modules["answer"] = 42
import answer

A: You could adapt this ActiveState recipe, perhaps something like this:
# safemodule.py
import sys
import types
import warnings

class EncapsulationWarning(RuntimeWarning): pass

class ModuleWrapper(types.ModuleType):
    def __init__(self, context):
        self.context = context
        super(ModuleWrapper, self).__init__(
                context.__name__,
                context.__doc__)

    def __getattribute__(self, key):
        context = object.__getattribute__(self, 'context')
        if hasattr(context, '__all__') and key not in context.__all__:
            warnings.warn('%s not in %s.__all__' % (key, context.__name__),
                          EncapsulationWarning,
                          2)
        return context.__getattribute__(key)

if 'old_import' not in globals():
    old_import = __import__

    def safe_import(*args, **kwargs):
        m = old_import(*args, **kwargs)
        return ModuleWrapper(m)

    __builtins__['__import__'] = safe_import

Then, use it like this:
C:\temp>python
ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import safemodule
>>> import sys
>>> type(sys)
<class 'safemodule.ModuleWrapper'>
>>>

You can, of course, adapt this to wrap certain modules only, etc.


text:
Q: How to interpret this definition of adjoint functors? Firstly consider the four definitions in the question: How to define rigorously [...].
Also consider the following definition:

Definition: Let $C,D$ be two categories and $F,G:[C]\to [D]$ be two functors. Suppose that $\alpha:F\to G$ is a morphism of functors
  $F$ and $G$. We say that $\alpha$ is a functorial in $S$ if, for
  all $T\in \text{Obj}(C)$ and $f\in \text{Hom}_C(T,S)$, the following
  diagram commutes:

The book "Manifolds, Sheaves, and Cohomology" (written by Torsten Wedhorn) gives the following definition of adjoint functors:

Definition: Let $C,D$ be two categories and let $F:[C]\to [D]$ and $G:[D]\to [C]$ be functors. Then $G$ is said to be right adjoint
  to $F$ and $F$ is said to be left adjoint to $G$ if for all
  $X\in\text{Obj}(C)$ and $Y\in\text{Obj}(D)$ there is a bijection
$$\text{Hom}_C(X,G(Y))\cong \text{Hom}_D(F(X),Y),$$
which is functional in $X$ and in $Y$.

Sincerely, I didn't understand the definition above. I tried to use a bijection $\Gamma:\text{Hom}_C(X,G(Y))\to \text{Hom}_D(F(X),Y)$ to construct a morfism of functors which is functorial in $X$ but I was unable to do this.
In view of the definitions of morphism of functors and functorial in a set, the definition above makes no sense to me.
MY QUESTION: What, possibly, did the author of that book mean by that definition?

A: A correction to start: you've copied the first definition incorrectly. $\alpha$ is not assumed to be a morphism of functors. Instead, $\alpha$ is assumed to be a family of morphisms (in $D$) $\alpha(S)\colon F(S)\to G(S)$, for all objects $S$ in $C$. If the family $\alpha$ is functorial in $S$, then we call $\alpha$ a morphism of functors $F\to G$.
Another comment here: What Wedhorn calls "functorial in $S$" is what most people would call "natural in $S$". A morphism of functors is often called a "natural transformation".
Now based on the very very brief introduction to categories and functors given in the pages leading up to the definition of adjoint functors, you're right to be confused at this point by what Wedhorn means when he writes that a bijection is "functorial in $X$ and $Y$". Here's what's going on:
Given a pair of functors $F$ and $G$ and objects $X$ in $C$ and $Y$ in $D$, we can consider the set $\text{Hom}_C(X,G(Y))$. If we fix $X$ and let $Y$ vary, we can check that we get a functor $\text{Hom}_C(X,G(-))\colon D\to \mathsf{Set}$.
Edit: More precisely, this functor sends an object $Y$ in $D$ to the set $\text{Hom}_C(X,G(Y))$. Given a morphism $\psi\colon Y\to Z$ in $D$, the functor $G$ gives us a morphism $G(\psi)\colon G(Y)\to G(Z)$ in $C$, and we can compose an arbitrary morphism $f\colon X\to G(Y)$ with $G(\psi)$ to get a morphism $G(\psi)\circ f\colon X\to G(Z)$. This is how the functor acts on morphisms: it sends $\psi\colon Y\to Z$ to the map of sets $\text{Hom}_C(X,G(Y))\to \text{Hom}_C(X,G(Z))$ given by $f\mapsto G(\psi)\circ f$.
On the other hand, if we fix $Y$ and let $X$ vary, then we get a functor $\text{Hom}_C(-,G(Y))\colon C^{\text{op}}\to \mathsf{Set}$. (Note the $\text{op}$! This is a contravariant functor from $C$ to $\mathsf{Set}$, with the action on morphisms $\psi$ given by precomposition with $F(\psi)$ instead of postcomposition.)
You can also think of $\text{Hom}_C(-,G(-))$ as a functor $C^{\text{op}}\times D\to \mathsf{Set}$, where the domain is the product category - but it's not necessary.
Similarly, $\text{Hom}_D(F(X),-)$ is a functor $D\to \mathsf{Set}$ for fixed $X$, $\text{Hom}_D(F(-),Y)$ is a functor $C^{\text{op}}\to \mathsf{Set}$ for fixed $Y$, and $\text{Hom}_D(F(-),-)$ is a functor $C^{\text{op}}\times D\to \mathsf{Set}$.
Ok, now we have a bijection $\alpha(X,Y)\colon \text{Hom}_C(X,G(Y))\to \text{Hom}_D(F(X),Y)$ for all $X$ and $Y$. To say that this family of bijections is natural in $Y$ is to say that for fixed $X$, the family $\alpha(X,-)\colon \text{Hom}_C(X,G(-))\to \text{Hom}_D(F(X),-)$ is a morphism of functors (i.e. it's "functorial"/"natural" in $Y$: lots of "naturality squares" squares commute). Similarly, "natural in $X$" means that for fixed $Y$, the family $\alpha(-,Y)\colon \text{Hom}_C(-,G(Y))\to \text{Hom}_D(F(-),Y)$ is a morphism of functors.
Getting your mind wrapped around all of this takes some doing, and it's best to look at a bunch of examples. This is why I recommended in my comment on your previous question that you pick up an introductory category theory book, which will  probably be much easier to learn from.

A: In this answer I will show how I am interpreting that definition after seeing Alex Kruckman's answer.
First, I will make small changes to two definitions that I gave.

Definition 1: Let $C,D$ be two categories and $F,G:[C]\to [D]$ be two functors. A correspondence $\alpha:\text{Obj}(C)\to \text{Mor}(D)$
  is said to be a family of morphisms between $F$ and $G$ if,
  for all $X\in\text{Obj}(C)$, we have $\alpha(X)\in\text{Hom}_D(F(X),G(X))$. In this case we denote $\alpha$ by
  $\alpha:F\to G$.

Definition 2: Let $C,D$ be two categories and $F,G:[C]\to [D]$ be two functors. Suppose that $\alpha:F\to G$ is family of morphisms
  between $F$ and $G$. We say that $\alpha$ is a functorial in $S$
  if, for all $T\in \text{Obj}(C)$ and $f\in \text{Hom}_C(T,S)$, the
  following diagram commutes:

Now I'll show how I'm interpreting that definition in the question.
Notation: To simplify the notation I'll write $C(A,B)$ in the place of $\text{Hom}_C(A,B)$.
Definition 3: Let $C,D$ be two categories. Suppose that $F:[C]\to [D]$ and $G:[D]\to[C]$ are two functors. Observe that, given any $X\in\text{Obj}(C)$ and $Y\in\text{Obj}(D)$, we have that
I) The correspondence $C(X,G(-)):[D]\to \left[\text{Set}\right]$ defined by
$C(X,G(\psi))=\begin{cases}
C(X,G(\psi)),&\psi \in \text{Obj}(D)\\
C(X,G(Y))\to C(X,G(Z)),\, f\mapsto G(\psi)\circ f,&\psi \in D(Y,Z)
\end{cases}$
is a functor between $D$ and $\text{Set}$;
II) The correspondence $C(-,G(Y)):[C^{op}]\to \left[\text{Set}\right]$ defined by
$C(\psi,G(Y))=
\begin{cases}
C(\psi,G(Y)),&\psi\in \text{Obj}(C^{op})\\
D(F(Z),Y)\to D(F(X),Y),\, f\mapsto f\circ F(\psi),&\psi \in C^{op}(Z,X)
\end{cases}$
is a functor between $C^{\text{op}}$ and $\text{Set}$;
III) The correspondence $D(F(X),-):[D]\to \left[\text{Set}\right]$, defined analogously to item I, is a functor between $D$ and $\text{Set}$;
IV) The correspondence $D(F(-),Y):[C^{op}]\to\left[\text{Set}\right]$, defined analogously to item II, is a functor between $C^{\text{op}}$ and $\text{Set}$.
Then, $G$ is said to be right adjoint to $F$ and $F$ is said to be left adjoint to $G$ if, for all $X\in\text{Obj}(C)$ and $Y\in\text{Obj}(D)$,

*

*There is a family $\alpha:C(-,G(Y))\to D(F(-),Y)$ of morphisms between $C(-,G(Y))$ and $D(F(-),Y)$ such that $\alpha$ is functorial in $X$ and $\alpha(X):C(X,G(Y))\to D(F(X),Y)$ is a bijection;

*There is a family $\beta:C(X,G(-))\to D(F(X),-)$ of morphisms between $C(X,G(-))$ and $D(F(X),-)$ such that $\beta$ is functorial in $Y$ and $\beta(Y)=\alpha(X)$.

A: I might be off topic since I am not focusing on this particular definition of an adjoint pair. But let me add something to the big picture by explaining other related concepts. I teach  this subject (and stile learning) myself and though, sharing my view would be beneficial for you as well. Suppose we have two categories $\mathcal{C}$ and $\mathcal{D}$ that looks similar to each others. Now we need to compare them and say whether they are actually equal or not. So, first we need a notion of equality for categories. Roughly, there are few different way to establish such a notion. If you like an analogy think of homeomorphisms, homotopies and continuous maps between topological spaces.

*

*Isomorphism of categories
I will begin with the strongest notion which is literally the meaning of an isomorphism. In this case we have pair of functors $\mathcal{F} :\mathcal{C}\to\mathcal{D}$ and $\mathcal{G} :\mathcal{D}\to\mathcal{C}$  which are mutually inverse to each other. That is, once we compose them we get what we would expect  $\mathcal{F}\mathcal{G}=1_{\mathcal{D}}$ and $1_{\mathcal{C}}=\mathcal{G}\mathcal{F},$ where $1\text{_}$ means the identity functor.

*Equivalence of categories
Isomorpihsm is a very expensive condition on two categories and it occurs rarely in category theory. One the guiding principal in category theory is we should not speak about equality, but isomorphisms. Hence in this diluted notion of isomorphisms, we replace above two equalities by two isomorphisms of functors. Thus we have two natural isomorphisms $\epsilon :\mathcal{F}\mathcal{G}\to1_{\mathcal{D}}$ and $\eta:1_{\mathcal{C}}\to\mathcal{G}\mathcal{F}.$ Given two categories and a candidate functor between them, there is an easy way to determine whether they are equivalent without actually finding the weak inverse.

*Adjoint functors
In this final, very weak, but the most common notion we replace above two natural isomorphisms by two natural transformations (+ a mild compatibility condition) called "unit" and "counit" respectively. Furthermore, every adjunction induces an equivalence between certain subcategories. There are few equivalent ways to say whether two functors and adjoint to each others and each way reveals a different prospective of the underlying phenomena. The definition subject to your question is a one such formulation of adjoint pairs. Some times adjoint functors behaves in unexpected ways.
This is by no mean an answer to your question, obviously too long for a comment. Good luck with your studies.


text:
Q: Working with processes, I don't get why this isn't working foreach (Process pro in Process.GetProcesses())
{
    int i = 0;
    if (pro.ProcessName == "notepad")
    {
        i++;
        textBox1.Text = Convert.ToString(i);

    }
}

what this code supposed to do is making textbox1.text, "2" if 2 notepad is running etc., however it doesn't do anything at all.
I can't see any problem looking at this code, so I am here.

A: your process name might be "notepad.exe" or something...instead of doing
if (pro.ProcessName == "notepad")

try
if (pro.ProcessName.StartsWith("notepad", StringComparison.OrdinalIgnoreCase))

This way you can isolate the problem, and figure out what the full text name is.

A: First, if no notepads is running - you code won't do anything. Probably it should write 0 to textBox?
I'll suggest rewriting code like that:
var processes = Process.GetProcesses().Select(p => p.ProcessName).ToList();
int count = processes.Count(name => String.Compare(name, "notepad", StringComparison.OrdinalIgnoreCase) == 0);
textBox1.Text = Convert.ToString(count);

You will have ability to debug easily and see which elements are in your processes list.
Moreover, your process could be "Notepad" not "notepad". Thus I replaced your equality check with String.Compare call.

A: CWell, first of all, you should move the declaration of the variable outside of the foreach cycle.
And second, you should do as alexD and agent-j say, change the way you are comparing the string:
int i = 0;
foreach (Process pro in Process.GetProcesses())
{
    if (pro.ProcessName.StartsWith("notepad", Stringcomparison.CurrentCultureIgnoreCase))
    {
        i++;
        textBox1.Text = Convert.ToString(i);
    }
}

Hope this helps


text:
Q: How can I initialization String array set null in java? Title is all.
How can I initialization String array set null in Java?
for example,
String[] arr;
arr = sqlite.select(1);
//here I want to set null arr!

A: Assuming that you want array like
String[] arr = {"foo", "bar"};

to become
[null, null]

and do it in one line, then you can use
Arrays.fill(arr, null);

or create new array with same size as previous one
arr = new String[arr.length];


text:
Q: Define Groovy closure with kwargs and varargs I've come across an inconsistency between Groovy functions and closures that has me stumped.
I can define a function with signature def foo(Map kwargs=[:], ... varargs){...} that does pretty much exactly what I expect it to. It takes pretty much every named and unnamed argument I give it. It also takes no arguments and works correctly.
I cannot find a similar way of defining a closure that has an identical signature. As a quick demonstration, when I run the following four lines:
def foo(Map kwargs=[:], ...args ){"kwargs=${kwargs.toString()} args=${args.toString()}"}
def bar = { Map kwargs=[:], ...args -> "kwargs=${kwargs.toString()} args=${args.toString()}"}
println foo(1:1,2:2)
println bar(1:1,2:2)

I get the following output:
> groovy test.groovy
kwargs=[1:1, 2:2] args=[]
Caught: groovy.lang.MissingMethodException: No signature of method: test$_run_closure1.call() is applicable for argument types: (java.util.LinkedHashMap) values: [[1:1, 2:2]]
Possible solutions: any(), any(), doCall([Ljava.lang.Object;), any(groovy.lang.Closure), each(groovy.lang.Closure), any(groovy.lang.Closure) groovy.lang.MissingMethodException: No signature of method: test$_run_closure1.call() is applicable for argument types: (java.util.LinkedHashMap) values: [[1:1, 2:2]]
Possible solutions: any(), any(), doCall([Ljava.lang.Object;), any(groovy.lang.Closure), each(groovy.lang.Closure), any(groovy.lang.Closure)
    at test.run(test.groovy:4)

Running with Groovy Version: 1.8.6 JVM: 1.8.0_131 Vendor: Oracle Corporation OS: Linux
I would like to write a closure that can take any number of named or unnamed arguments, including no arguments at all. Is this possible?

A: Investigation
I've played around a little bit with your example and I've found out what is going on in this case.
def bar = { Map kwargs = [:], ... args -> "kwargs=${kwargs.toString()} args=${args.toString()}" }
bar.class.methods.findAll { it.name == 'doCall' }.each { println it }

This is the closure you've defined and here is the output of the println (we iterate over all methods defined in this anonymous class and print only those with name doCall):
public java.lang.Object cls$_run_closure1.doCall(java.lang.Object[])
public java.lang.Object cls$_run_closure1.doCall(java.util.Map,java.lang.Object[])

Here we have only two possible signatures for calling the closure - we are missing a signature with single java.util.Map parameter to satisfy your expectation.
Solution
If we do a small change - apply a default value to ...args array parameter, like:
def bar2 = { Map kwargs = [:], ... args = [] -> "kwargs=${kwargs.toString()} args=${args.toString()}" }
bar2.class.methods.findAll { it.name == 'doCall' }.each { println it }

Then this is the output of println:
public java.lang.Object cls$_run_closure4.doCall(java.util.Map)
public java.lang.Object cls$_run_closure4.doCall(java.util.Map,java.lang.Object[])
public java.lang.Object cls$_run_closure4.doCall()

As you can see there is a signature with single java.util.Map and you can call this bar2 closure as you expect:
bar2(1:1,2:2)

kwargs=[1:1, 2:2] args=[]

and
bar2(1:1,2:2,3,4)

kwargs=[1:1, 2:2] args=[3, 4]

Oh, and btw - I've tested it with Groovy 2.4.8, I don't have any older version to test it with. Please let us know if it works with 1.8.x as well.
This is quite interesting case I must admit. I'm also curious if this is a bug or is this a correct behavior designed for groovy's closures. Maybe someone with deep groovy internals knowledge can give us a hint :)

A: as workaround MethodClosure could be used:
def foo(Map kwargs=[:], ...args ){"kwargs=${kwargs.toString()} args=${args.toString()}"}
def cfoo = this.&foo
println cfoo.getClass()
println cfoo(1:1,2:2)

output:
class org.codehaus.groovy.runtime.MethodClosure
kwargs=[1:1, 2:2] args=[]


text:
Q: Derivate of $e^{-x\cdot x}$ with Hermite polynomials. Define the Hermite polynomial $H_n$ by
$$H_n=(-1)^n e^{x^2}\frac{d^2 e^{-x^2}}{dx^n}.$$
Now let $x\in\mathbb{R}^d$, $\alpha\in\mathbb{N}_0^d$ be a multi-index and
$\partial^\alpha=\frac{\partial^{\alpha_1}}{\partial x^{\alpha_1}}...\frac{\partial^{\alpha_d}}{\partial x^{\alpha_d}}$.
Now I have to show that
$$\partial^\alpha e^{-x\cdot x}=(-1)^{|\alpha|}\prod_{j=1}^d H_{\alpha_j}(x_j)e^{-x\cdot x}$$
Honestly I dont really know how to start, so help is very much appreciated!
Thank you.

A: It follows from the simple factorization property
$$
\frac{\partial^2}{\partial x\partial y} f(x)g(y)=f'(x)g'(y)\ .
$$


text:
Q: Is there non-english syntax of c++ I heard that there is a non-english syntax of c++, it seems to be as c++ style but with translated terms!
can we find a lang like this!

A: #define пока while
#define типа virtual
#define дай new
#define нах delete
...
#define бюст boost

A: I guess that you might be able to pull something like that with a preprocessor, but I would greatly advice against this approach. Programming languages are not English or Spanish or any other natural language, but rather a set of keywords with precise meanings in that language.
If you decide to translate the language, you would end up with a situation where either the compiler errors are completely alien to your code (if the language is pre translated before passing to the compiler) or in the best case with compiler support and error messages that you cannot use to ask for help in forums like StackOverflow.
This second approach has been taken in some cases (VBA, as the first example that comes to mind), and the result is a language that is still not natural to the native speakers and for which the available information is fragmented into the different languages. As a matter of fact, that already happens with current C++ compilers... I have disabled localization of the compiler for a long time on that grounds.

A: Sí; it lets you write code with Spanish keywords and then translate it into C++ or Python.


text:
Q: Multiple streams inside single gulp-if calling? In the below code, I do plugins.if(
  !config.isDevelopmentMode && config.compileBladeTemplates, /* task */) check twice (plugins.if is gulp-if package). Can I refactor below code with one check? Not sure that it possible just with gulp-if, so it's allowed to use additional plugins.
const   gulp = require('gulp'),
        plugins = require('gulp-load-plugins')();

// ...
.pipe(plugins.if(
  !config.isDevelopmentMode && config.compileBladeTemplates,
  plugins.replace(
     /<!--\s+@blade\s+namedRoute\(\s*(.+?)\s*\)\s*-->\s*(?:\r\n|\r|\n)?\s*(<.+href=")(?:.+?)(".*\/?>)/g,
     `$2{{ route('$1') }}$3`
  )
))
.pipe(plugins.if(
  !config.isDevelopmentMode && config.compileBladeTemplates,
  plugins.replace(
     /<!--\s+@blade\s+(yield|include)\s*-->/g,
     ` @$1('$2')`
  )
))
// ...

A: If I understand what you are trying to do I think a lazypipe would work for you.  See gulp-if with lazypipe.
var replaceChannel = lazypipe()
      plugins.replace(
     /<!--\s+@blade\s+namedRoute\(\s*(.+?)\s*\)\s*-->\s*(?:\r\n|\r|\n)?\s*(<.+href=")(?:.+?)(".*\/?>)/g,
     `$2{{ route('$1') }}$3`
    )
    plugins.replace(
     /<!--\s+@blade\s+(yield|include)\s*-->/g,
     ` @$1('$2')`
   );

and then in your task:
.pipe(plugins.if(
  !config.isDevelopmentMode && config.compileBladeTemplates, replaceChannel()))


text:
Q: How to resolve 'Foreign key constraint is incorrectly formed' issue I am trying to create a database table called wp_tokens with a foreign key relationship to another table called wp_users. However, every time I attempt to run the create table SQL, I get the error "Foreign key constraint is incorrectly formed". I have tried multiple re-edits of the same code, but I just cannot figure out what is going on.
This is the code for wp_users
CREATE TABLE `wp_users` (
    `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `user_login` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
    `user_pass` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
    `user_nicename` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
    `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
    `user_url` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
    `user_registered` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
    `user_activation_key` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
    `user_status` int(11) NOT NULL DEFAULT '0',
    `display_name` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
    PRIMARY KEY (`ID`),
    KEY `user_login_key` (`user_login`),
    KEY `user_nicename` (`user_nicename`),
    KEY `user_email` (`user_email`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci

This is the SQL for wp_tokens
CREATE TABLE `wp_tokens` (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    `user_id` bigint(20) NOT NULL,
    `token` varchar(255) NOT NULL,
    PRIMARY KEY  (id),
    FOREIGN KEY (user_id) REFERENCES wp_users (`ID`)
)

Any help would be greatly appreciated!

A: The unsigned is important -- the types need to be identical.  Try this:
CREATE TABLE `wp_tokens` (
      id mediumint(9) NOT NULL AUTO_INCREMENT,
      `user_id` bigint(20) unsigned NOT NULL,
      `token` varchar(255) NOT NULL,
      PRIMARY KEY  (id),
      FOREIGN KEY (user_id) REFERENCES wp_users (`ID`)
)

Here is a rextester.


text:
Q: How to get pixel values from Android Image I'm using the camera2 api to capture a burst of images. To ensure fastest capture speed, I am currently using yuv420888.
(jpeg results in approximately 3 fps capture while yuv results in approximately 30fps)
So what I'm asking is how can I access the yuv values for each pixel in the image.
i.e.
Image image = reader.AcquireNextImage();
Pixel pixel = image.getPixel(x,y);
pixel.y = ...
pixel.u = ...
pixel.v = ...

Also if another format would be faster please let me know.

A: If you look at the Image class you will see the immediate answer is simply the .getPlanes() method.
Of course, for YUV_420_888 this will yield three planes of YUV data which you will have to do a bit of work with in order to get the pixel value at any given location, because the U and V channels have been downsampled and may be interlaced in how they are stored in the Image.Planes. But that is beyond the scope of this question.
Also, you are correct that YUV will be the fastest available output for your camera. JPEG require extra time for encoding which will slow down the pipeline output, and RAW are very large and take a lot of time to read out because they are so large. YUV (of whatever type) is the data format that most camera pipelines work in so it is the 'native' output, and thus the fastest.


text:
Q: I seek a word for the expectation that any arbitrary group of people can be held morally accountable as though they're a single moral agent I think this must be a cognitive error of some kind. I just now read the phrase, "the hypocrisy of the left", and it occurred to me that hypocrisy is a moral action, which can be taken only by a moral agent, ie, a person. And "the left" (or "the left wing" or "the political right") are not persons; they don't have stable personalities, they're not moral agents, they can't engage in hypocrisy.
Is there a word for this kind of error, calling on a (usually ill-defined) group of people to exhibit a stable personality and moral accountability?
Single-word request requirements:

*

*Sample sentence: "You get an F for your paper entitled 'The Sins of The Right', because it's based entirely on a cognitive error known as homunculus-ex-vulgus."

*Not being sure where to start with a dictionary or thesaurus, I've tried googling misattribution of moral agency and cognitive error moral agency, also group single personality; I went through 50 Common Cognitive Distortions on Psychology Today. I haven't found anything that even sounds similar.

*My criteria for choosing the best word: If it's a clinical or technical word, then I guess the best word would be one that literally means what I'm talking about. If metaphor is the only thing available, I guess the best word would be the most neutral-sounding, the least baggage, the kind of word that wouldn't put people on the defensive.

*Words I've considered: honestly, homunculus-ex-vulgus fallacy is the only thing I've come up with.

*A compound word or phrase is fine. Cheers

P.S. I would be most grateful for any feedback concerning the downvotes.

A: I believe you are looking for the term metonymy, a word or phrase that represents a thing, or concept. The expression 'the left' simply stands for [members/supporters of] the left wing [political party].
Other examples of metonymy,

Crown - in place of a royal person
We will swear loyalty to the crown.

The White House or The Oval Office - used in place of the President or White House staff
The White House will be making an announcement around noon today.

Heart - to refer to love or emotion
My dear, you have all of my heart.

Dish - for an entire plate of food
  That fancy fish dish you made was the best of the evening.

Source: Your Dictionary   See also Merriam-Webster's explanation.
Whether or not you agree that members or supporters of the left are hypocrites that is a separate political issue.


text:
Q: How to merge values from multiple objects into an object of arrays? I have a two JSON something like below:
var obj1 = {
    " name ":"rencho",
    " age ":23,
    " occupation ":"SE"
}

var obj2 = {
    " name ":"manu",
    " age ":23,
    " country ":"india"
}

I want the expected output:
var result = {
    "name":["rencho", "manu"],
    "age":[23, 23],
    "country":["-", "india"],
    "occupation": ["SE", "-"],
}

However, I tried using below the code snippet:
let arrGlobal = []

arrGlobal.push(obj1);
arrGlobal.push(obj2);

let mergedResult = arrGlobal.reduce(function(r, e) {
            return Object.keys(e).forEach(function(k) {
            if(!r[k]) r[k] = [].concat(e[k])
            else r[k] = r[k].concat(e[k])
            }), r
        }, {})

console.log(mergedResult);

But that one doesn't print - in json object. I would appreciate any kind of help from your side.
HELP WOULD BE APPRECIATED!!!

A: First get a list of all keys (needed in advance to check whether you need to add - while iterating), then use reduce to iterate over each object and add its values to the accumulator:

var obj1 = {
    " name ":"rencho",
    " age ":23,
    " occupation ":"SE"
}

var obj2 = {
    " name ":"manu",
    " age ":23,
    " country ":"india"
}
const arr = [obj1, obj2];
const allKeys = arr.reduce((keys, obj) => {
  Object.keys(obj).forEach(key => keys.add(key))
  return keys;
}, new Set());
const merged = arr.reduce((merged, obj) => {
  allKeys.forEach((key) => {
    if (!merged[key]) merged[key] = [];
    merged[key].push(obj[key] || '-');
  });
  return merged;
}, {});
console.log(merged);

A: A slightly different approach by using a single loop for the outer array of objects and which generates all needed keys on the fly.

var obj1 = { name: "rencho", age: 23, occupation: "SE" },
    obj2 = { name: "manu", age: 23, country: "india" },
    hash = new Set,
    result = {};

[obj1, obj2].forEach((o, length) => {
    Object.keys(o).forEach(k => hash.add(k));
    hash.forEach(k => {
        result[k] = result[k] || Array.from({ length }).fill('-');
        result[k].push(k in o ? o[k] : '-');
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: quick and dirty way:
function merge(a,b) {
  var c = b
  for (key in a){
    c[key] = [c[key], a[key]]
  }
  console.log(c) //prints merged object
}

merge(obj1, obj2)


text:
Q: How to pass data to stateful widget When i try to pass data to a stateful widget i get this error :
A [State] object's configuration is the corresponding [StatefulWidget] instance. This property is initialized by the framework before calling [initState].
Only static members can be accessed in initializers.
Basically i'm trying to pass data from detail.dart to about.dart
detail.dart :
class PokemonDetail extends StatefulWidget {
PokemonDetail({this.pokemon});

@override
_PokemonDetailState createState() => _PokemonDetailState();
}

class _PokemonDetailState extends State<PokemonDetail> with SingleTickerProviderStateMixin{
final List<TabData> _tabs = [
TabData("About", PokemonAbout(pokemon: widget.pokemon)),
....];

@override
_PokemonAboutState createState() => _PokemonAboutState();
}

Widget _buildTabContent() {
return Expanded(
  child: TabBarView(
    children: _tabs.map((tab) => tab.child).toList(),
  ),
);
}

about.dart :
class PokemonAbout extends StatefulWidget {
final Pokemon pokemon;

const PokemonAbout({this.pokemon, key}) : super(key: key);

A: This line _PokemonAboutState createState() => _PokemonAboutState(); should not be called inside the State class. It is already defined in the StatefulWidget class. Try removing it and see what happens.

A: 'widget.pokemon' cannot be used in class-level field initialization. Try moving tabs declaration inside the initState:
class _PokemonDetailState extends State<PokemonDetail> with SingleTickerProviderStateMixin{
List<TabData> _tabs = [];

@override
void initState(){
   super.initState();
   _tabs = [ TabData("About", PokemonAbout(pokemon: widget.pokemon)), ....];
}

I hope this helps!


text:
Q: ASP.NET Web API - Passing a UserToken(string) to a LoginController using a DelegatingHandler I have an ASP.NET Web API project and on initial user login, the username and password are sent in an http header over SSL and validated by the server.
The server creates a database record with the UserId, a randmon 64 character string (UserToken), expiration date and the client IP address.
The UserToken is then sent back to the client and then be stored in a cookie.
All subsequent requests send the UserToken in an http header and that is validated using the calling IP address by the server.
This way, the username and password are only sent once, and all calls using the UserToken are logged.
I have created two custom DelegatingHandlers - LoginAuthenticationHandler, and TokenAuthenticationHandler - which process the http headers and send an appropriate 200 or 400 http response.
////////////////
Seems my only problem is that I want the LoginAuthenticationHandler to also return the UserToken to the client, so it can store the cookie.
Sorry for the verbosity :-\
Also - I'm new to Web API - so maybe this is not the best place for this to be done - but it would be very convenient if the UserToken can be passed back to the LoginController in this way.
Thanks for any input :-)
Some related SO posts:
DelegatingHandler for response in WebApi
Is it possible to pass data from DelegatingHandler to Controller in ASP.NET Web API?
////////////////
  public class LoginAuthenticationHandler : DelegatingHandler
      {
          public const string BasicScheme = "Basic";
          public const string ChallengeAuthenticationHeaderName = "WWW-Authenticate";
          public const char AuthorizationHeaderSeparator = ':';

          protected override Task<HttpResponseMessage> SendAsync(
              HttpRequestMessage request,
              CancellationToken cancellationToken)
          {
              // Get Authorization Http Header
              var authHeader = request.Headers.Authorization;
              if (authHeader == null)
              {
                  // Unauthorized
                  return CreateUnauthorizedResponse();
              }
              // Check if Basic Authentication
              if (authHeader.Scheme != BasicScheme)
              {
                  // Unauthorized
                  return CreateUnauthorizedResponse();
              }
              // Decode UserName + Password from Http Header
              var encodedCredentials = authHeader.Parameter;
              var credentialBytes = Convert.FromBase64String(encodedCredentials);
              var credentials = Encoding.ASCII.GetString(credentialBytes);
              var credentialParts = credentials.Split(AuthorizationHeaderSeparator);
              if (credentialParts.Length != 2)
              {
                  // Unauthorized
                  return CreateUnauthorizedResponse();
              }
              var username = credentialParts[0].Trim();
              var password = credentialParts[1].Trim();
              // Authenticate Username + Password and Return UserToken
              var userId = new Users().GetUserIdFromUserNamePassword(username, password);
              if (userId == 0)
              {
                  // Unauthorized
                  return CreateUnauthorizedResponse();
              }
              // User is Authorized - Create New UserToken
              var ipAddress = HttpContext.Current.Request.UserHostAddress;
              var userToken = new Users().CreateUserToken(ipAddress, userId);

              return base.SendAsync(request, cancellationToken).ContinueWith(task =>
                  {
                      var response = task.Result;
             //======================================================
             // Return UserToken to Login Controller to be Stored as Cookie on the Client
                      // response.Content = userToken ??
                      // maybe set header for userToken ??
                      // HttpRequestMessage Properties ??
                      return response;
             //======================================================
                  });
          }

          private static Task<HttpResponseMessage> CreateUnauthorizedResponse()
          {
              // Send Back Http Unauthorized if Authentication Fails
              var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
              response.Headers.Add(ChallengeAuthenticationHeaderName, BasicScheme);
              var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
              taskCompletionSource.SetResult(response);
              return taskCompletionSource.Task;
          }
      }
  }

A: Generally, HTTP services are stateless and the concept of login does not apply. LoginController is for the MVC controllers and not web API. What you are trying to do is not a good practice, even though it is technically possible to achieve.
If you really want to do what you are trying to do, do not think along the lines of sending the session data (what you call the user token) to LoginController. You can write the cookie into the response from your message handler itself. See this. You must only store encrypted data into a cookie in that case. Instead of creating your own cookie and all that, you can use Forms Authentication and create a cookie with FA ticket. See this.
BTW, it is possible and easy to spoof client IP addresses.

A: Perhaps you could login using the controller without using a DelegatingHandler:  you could return the token to the client to be added to the header of future API calls, or add it to the header in the controller using the Request.Headers.Add function.
Then you would not need two custom DelegatingHandlers, the TokenAuthenticationHandler would be sufficient.  But you would want to specify that all requests other than the initial login are funneled through the TokenAuthenticationHandler.
To do that, you will need to customize the WebAPI routes.  In the default Web API projects, this is currently done in the WebApiConfig.Register method in WebApiConfig.cs (called from Global.asax.cs).  First, have all your API calls route through your TokenAuthenticationHandler; then add the login route plainly such that it does not funnel through your TokenAuthenticationHandler:
//this message handler chain is used to put TokenAuthenticationHandleron all API requests and not Login
DelegatingHandler[] handlers = new DelegatingHandler[] {
    new TokenAuthenticationHandler()
};
var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers);
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}",
    defaults: null,
    constraints: null,
    handler: routeHandlers
 );

//login route
config.Routes.MapHttpRoute(
    name: "Login",
    routeTemplate: "login/{action}",
    defaults: new { Controller = "Login" }
);

Now, you can validate the token in the TokenAuthenticationHandler using request.Headers.TryGetValues to get it:
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
{
    //token validation
    IEnumerable<string> foundValues = null;
    if (request.Headers.TryGetValues("AuthenticationToken", out foundValues))
    {
        if (foundValues.Count() == 1)
        {
            string token = foundValues.Single();

            AuthenticationDAO dao = new AuthenticationDAO();
            if (dao.AuthenticateUser(token))
            {
                //add values to request.Properties for use in Web API controllers
                request.Properties.Add(new KeyValuePair<string, object>("SomeValue", 4));

                //Engage!
                return base.SendAsync(request, cancellationToken);
            }
        }
    }

    //fail if token not present or not valid
    var tcs = new TaskCompletionSource<HttpResponseMessage>();
    tcs.SetResult(new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
        Content = new StringContent("Missing or invalid authorization token.")
    });
    return tcs.Task;
}

As per your original question of passing values from the DelegatingHandler to the Controller, that is easily possible using the request.Properties.Add function as demonstrated above.
Some additional considerations:

*

*I am not sure that sending the login credentials in the header is any
more secure than just as content in the request, since it is all over
SSL.

*You should consider implementing an AntiForgeryToken.  This
article is a good starter, and this SO post points out how
you could use DelegatingHandler to also only check for it on web
requests (allowing your api to be accessed from native apps).

*You can easily add a DelegatingHandler that applies to all requests
that enforces HTTPS.
Hope that helps.  What I've outlined is the way I'm doing it, so I hope for some comments if it's wrong.


text:
Q: Using Firebase noSouchMethodError Before everyone jumps on me please read till the end.
I read all of the answers on StackOverflow and they are not working for me.
I trying to add FCM to my app.
I'm getting a run time error
03-22 10:29:53.096 15466-15466/? I/art: Late-enabling -Xcheck:jni
03-22 10:29:53.147 15466-15466/? W/System: ClassLoader referenced unknown path: /data/app/com.example.dr.hyphope-2/lib/arm64
03-22 10:29:53.150 15466-15466/? D/AndroidRuntime: Shutting down VM
03-22 10:29:53.150 15466-15466/? E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process: com.example.dr.hyphope, PID: 15466
                                               java.lang.NoSuchMethodError: No static method zzb(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzac; or its super classes (declaration of 'com.google.android.gms.common.internal.zzac' appears in /data/app/com.example.dr.hyphope-2/base.apk:classes6.dex)
                                                   at com.google.firebase.provider.FirebaseInitProvider.zza(Unknown Source)
                                                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                   at android.app.ActivityThread.installProvider(ActivityThread.java:5267)
                                                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:4862)
                                                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4802)
                                                   at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1417)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:148)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5551)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

this is my gradle file:
apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion '25.0.2'

defaultConfig {
    applicationId "com.example.example"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}

buildTypes {
    debug{
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
    }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-messaging:10.2.0'

}

as you can see my firebase-core and firebase-messaging are the same version.
So all the answers on StackOverflow do not work for me.
Please help,
Thanks


text:
Q: Text fields and Templating in Rails I have a rails 3 app and a weird problem that I'm having a lot of trouble working through.  I have a form with three fields: Title (Text Field), Lead in (Text Area), Body (Text Area), Kicker(Text Area).  I'd like to compile them into a an "Article" via a template of some sort.  The template would look something like this:
<b> [Title] </b>
<p> [Lead In] </p>
<p> [body] </p>
<p> [Kicker] </p>

This would be fine if it was static.  But I'd like to be able to offer multiple templates, and I'd like to autocreate forms based on those templates.  Is there something out there already that is a solution to this templating problem?  If not, any first steps would be way helpful.
Thanks!

A: https://github.com/defunkt/mustache
That is a pretty nifty templating tool to use.


text:
Q: What is the benefit of using multiple modules in angular? I'm a familiar person with Angular Js, recently I've seen that in some projects multiple angular modules are created and assembled in main module.
The code looks like.
angular.module("main",['main.sub1','main.sub2','main.sub2'])

angular.module("main.sub1",[])

angular.module("main.sub2",[])

angular.module("main.sub3",[])

My questions are

*

*When to approach such fashion of splitting modules ?

*How it is useful ?

*Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider for each separately)

*If i inject a dependency in sub modules are they by default injected in main modules ?

I read few blogs but I'm not able to get a clear perception.
Can you please guide me through.

A: A module is the kernel of functionality for Angular apps. Modules contain all of the code that we
write for our specific app and, thus, tend to grow huge in a monolithic way. Although this tendency
isn't bad (modules are a great way to reduce global scope noise), we can divide our modules.
There are several differing opinions about when to create a module and when to nest functionality
in a global module. Both of the following methods are valid ways to break up our functionality by
modules:
1. When to approach such fashion of splitting modules ?
When you want to sepereate your app logic by functionality or by routes, is needed because as your code separated on modules, it easy to understand, to tests and etc. angular module system implementation of Module Pattern.
Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.
2.How it is useful ?
For starters, it's a lot cleaner for developers coming from an object-oriented background than the idea of true encapsulation, at least from a JavaScript perspective.

*

*Your significant other is the new developer on the team who's been asked to fix a bug on one of the many screens in your app.

*

*The developer sifts through the directory structure and sees all the controllers, models and services neatly organized. Unfortunately it tells him/her nothing about which objects are related or have dependencies on one another.

*If at some point the developer wants to reuse some of the code, they need to collect files from a bunch of different folders and will invariably forget code from another folder somewhere else.
3.Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider for each separately)
Another method we can use to break up our app is to divide our modules by route. This breakdown
allows us to write isolated tests that focus on the functionality per route. Modularizing by route can
make more sense, depending upon the project; it allows us to divide our functionality efficiently
when we're dealing with a lot of independent routes.
For instance:
angular.module('myApp.home', []);
angular.module('myApp.login', []);
angular.module('myApp.account', []);
angular.module('myApp', [
'myApp.home',
'myApp.login',
'myApp.account'
]);

This modularization makes sense specifically when we're dealing with large numbers of routes
and/or when we don't have too much cross-over between routes
4.If i inject a dependency in sub modules are they by default injected in main modules ?
shortly:  yes. :)

A:
1.When to approach such fashion of splitting modules ?

Preferably, Always. But you don't really need to do it unless you have multiple apps that are using the exact same code, maybe the way you handle authentication in a few apps is identical, it would make sense to put the common code into a service and have that service as its own module. This offers code reuse, and we all know that code reuse is good.

2.How it is useful ?

Again, reusability is the key word here. You don't want to go around writing duplicate code. Code duplication is just plain wrong, and results in more expensive maintenance and more error prone code.
Another advantage is that modularising your applications explicitly outlines the dependencies of your application and separates the responsibilities of different parts of your app. Code reuse and separation of concerns are fundamental practices in writing maintainable code.
Another reason to separate your app into modules is performance. Right now I'm working on an app (web shop) which consists of 2 main sections: one section(app) for normal users/buyers/sellers, and another app for the admin. Now the users app needs some scripts/libraries the admin app doesn't, and vice versa. For example the admin app uses a kendo grid which requires a kendo.all.min.js script which when minified is 1.7MB! Now would it make sense to force all visitors to the site to download the heavy 1.7 MB script?

3.Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider
  for each separately)

Yes. Ideally your applications will have different route/state configurations, so each app would have their own app.config(), this means you could define separate routes for each app using the shared modules. To my experience the main things you want to move into their own modules are services and directives, not applications routings.

4.If i inject a dependency in sub modules are they by default injected in main modules ?

Yes. If you inject a dependency X into a module A, and module A will be used by another module B then B will also inherit the dependency X.


text:
Q: is this float values stored in .rodata or .data sections and how to find them in the disassembled code? I dumped an il2cpp.so with il2cppDumper and in the dump.cs I found that the variables I wanted to change its values, in turn which are somewhat constant floats. this is the snippet:
// Namespace:
public class GameConfig // TypeDefIndex: 6152
{
    // Fields
    public const float durationSlide = 1.2; // 0x0
    public const float durationBlockDame = 0.1; // 0x0
    public const float forceOnBreak = 2000; // 0x0
    public const float durationBombExp = 1.8; // 0x0
    public const float durationUpdateDistance = 0.1; // 0x0
    public const float durationCheckRange = 2; // 0x0

    // Methods
    // RVA: 0x3F5E98 Offset: 0x3F5E98 VA: 0x3F5E98
    public void .ctor() { }
}

And then loaded the lib into ghidra and then auto analyze command, while in my understanding those variables could be in that .rodata section but needed help of how can I identify those values like for example 1.8 which equals in hex 0x3fe66666 tried to search those values but not able to get it.
on the .rodata section contained so much data like this:
                                                  //
                                                  // .rodata
                                                  // SHT_PROGBITS  [0x16d1e10 - 0x18b4417]
                                                  // ram:016d1e10-ram:018b4417
                                                  //
                                                  DAT_016d1e10                                                                                XREF[144]:      01a78090(*), 01a78098(*), 01a780a0(*), 01a780a8(*), 01a780b0(*), 01a780b8(*),
                                                                                01a780c0(*), 01a780c8(*), 01a780d0(*), 01a780d8(*), 01a780e0(*), 01a780e8(*),
                                                                                01a780f0(*), 01a83ef4(*), 01bacdd4(*), 01bace2c(*), 01bace30(*), 01bace40(*),
                                                                                01bace80(*), 01bace84(*), [more]
     016d1e10  6b                          ??                                                    6Bh    k
      016d1e11 01                          ??                                                    01h
      016d1e12  00                          ??                                                    00h
      016d1e13  00                          ??                                                    00h
     016d1e14  00                          ??                                                    00h
      016d1e15  00                          ??                                                    00h
     016d1e16  1c                           ??                                                    1Ch
      016d1e17  00                          ??                                                    00h
                                                  DAT_016d1e18                                                                                XREF[1]:          01a94444(*)
     016d1e18  6b                          ??                                                    6Bh    k
     016d1e19  01                          ??                                                    01h
      016d1e1a  00                          ??                                                    00h
     016d1e1b  00                          ??                                                    00h
      016d1e1c 01                          ??                                                    01h
     016d1e1d  00                          ??                                                    00h
     016d1e1e  1c                           ??                                                    1Ch
      016d1e1f  00                          ??                                                    00h
                                                  DAT_016d1e20                                                                                XREF[1]:          01a946c0(*)
     016d1e20  6b                          ??                                                    6Bh    k
      016d1e21  01                          ??                                                    01h
     016d1e22  00                          ??                                                    00h
     016d1e23  00                          ??                                                    00h
     016d1e24  11                           ??                                                    11h
     016d1e25  00                          ??                                                    00h
     016d1e26  1c                           ??                                                    1Ch
     016d1e27  00                          ??                                                    00h
                                                  DAT_016d1e28                                                                                XREF[1]:          01a950a0(*)
     016d1e28  6b                          ??                                                    6Bh    k
     016d1e29  01                          ??                                                    01h
     016d1e2a  00                          ??                                                    00h
     016d1e2b  00                          ??                                                    00h
     016d1e2c 36                          ??                                                    36h    6
     016d1e2d  00                          ??                                                    00h
     016d1e2e  1c                           ??                                                    1Ch
     016d1e2f  00                          ??                                                    00h
                                                  DAT_016d1e30                                                                                XREF[1]:          01a9514c(*)
     016d1e30  6b                          ??                                                    6Bh    k
      016d1e31  01                          ??                                                    01h
     016d1e32  00                          ??                                                    00h
     016d1e33  00                          ??                                                    00h
     016d1e34  02                          ??                                                    02h
     016d1e35  00                          ??                                                    00h
     016d1e36  1c                           ??                                                    1Ch
     016d1e37  40                          ??                                                    40h    @
                                                  DAT_016d1e38                                                                                XREF[1]:          01a951dc(*)
     016d1e38  6b                          ??                                                    6Bh    k
     016d1e39  01                          ??                                                    01h
     016d1e3a  00                          ??                                                    00h
     016d1e3b  00                          ??                                                    00h
     016d1e3c 03                          ??                                                    03h
     016d1e3d  00                          ??                                                    00h
     016d1e3e  1c                           ??                                                    1Ch
     016d1e3f  00                          ??                                                    00h
                                                  DAT_016d1e40                                                                                XREF[1]:          01a95260(*)
     016d1e40  6b                          ??                                                    6Bh    k
     016d1e41  01                          ??                                                    01h
     016d1e42  00                          ??                                                    00h
     016d1e43  00                          ??                                                    00h
     016d1e44  33                          ??                                                    33h    3
     016d1e45  00                          ??                                                    00h
     016d1e46  1c                           ??                                                    1Ch
     016d1e47  00                          ??                                                    00h
                                                  DAT_016d1e48                                                                                XREF[1]:          01a95518(*)
     016d1e48  6b                          ??                                                    6Bh    k
     016d1e49  01                          ??                                                    01h
     016d1e4a  00                          ??                                                    00h
    016d1e4b  00                          ??                                                    00h
     016d1e4c 21                           ??                                                    21h    !
    016d1e4d  00                          ??                                                    00h
     016d1e4e  1c                           ??                                                    1Ch
     016d1e4f  00                          ??                                                    00h
                                                  DAT_016d1e50                                                                                XREF[1]:          01a95998(*)
     016d1e50  6b                          ??                                                    6Bh    k
      016d1e51  01                          ??                                                    01h
     016d1e52  00                          ??                                                    00h
     016d1e53  00                          ??                                                    00h
     016d1e54  81                          ??                                                    81h
     016d1e55  00                          ??                                                    00h
     016d1e56  1c                           ??                                                    1Ch
     016d1e57  00                          ??                                                    00h
                                                  DAT_016d1e58                                                                                XREF[1]:          01a95a40(*)
     016d1e58  6b                          ??                                                    6Bh    k
     016d1e59  01                          ??                                                    01h
     016d1e5a  00                          ??                                                    00h
     016d1e5b  00                          ??                                                    00h
     016d1e5c 00                          ??                                                    00h
     016d1e5d  00                          ??                                                    00h
     016d1e5e  1c                           ??                                                    1Ch
     016d1e5f  40                          ??                                                    40h    @
                                                  DAT_016d1e60                                                                                XREF[1]:          01a95b0c(*)
     016d1e60  6b                          ??                                                    6Bh    k
     016d1e61  01                          ??                                                    01h
     016d1e62  00                          ??                                                    00h
     016d1e63  00                          ??                                                    00h
     016d1e64  91                          ??                                                    91h
     016d1e65  00                          ??                                                    00h
     016d1e66  1c                           ??                                                    1Ch
     016d1e67  00                          ??                                                    00h
...

such data, tried using terminatedCstring option but still didn't do on all of it. because these are so much and don't know easy way to do this.
btw how can I search through and get the value 1.8 in the binary?
FYI : I had the feeling to share the apk game I was trying to reverse engineer. Hope it helps.


text:
Q: Class constructor called multiple times I have my own Google Maps class that deals with few things like calculating a distance etc. Its code looks like following:
class Map{
    constructor(options){
        this.mapcenter = [options.lat, options.lng];
    }
    ...other functions
}

in my main JavaScript file I call this after onload:
 $(window).on("load", function() {
    if($("#map").length > 0) {
        themap = new Map({
            lat : 46,
            lng : 7
        });
    }
});

It has been working for many months but today I got an error cannot read property lat of undefined, which is very strange.
Apparently one call onload calls the constructor three times, the second and third being without the options that are in the definition of the call.
I couldn't find anything similar and I believe it's not related to Google Maps API but rather something in the logic I'm missing.

A: you should use a diffrenet name for your Class, there's already a built-in new Map()


text:
Q: How does this strange JavaScript code work? Mystery colon I'm following the official Angular 2 tutorial and then I saw this piece of code:
const HEROES: Hero[] = ...
I don't understand how the colon can be after HEROES, I can't find any documentation on this colon usage in JavaScript and TypeScript. I thought the colon were only used in object "key: value" and ternary operators.
export class Hero {
  id: number;
  name: string;
}

const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

Can you help me understand this colon syntax?
The other questions answer does not explain about typescript and that it is a special syntax.

A: This is TypeScript code, and this is how you declare (annotate) the type of a variable in TypeScript. The declaration means that the type of HEROES should be Hero[], an array of Hero objects.
var HEROES: Hero[];

The TypeScript compiler will use this information to prevent incorrect assignments to this variable -- for example, you cannot assign a number to HEROES (not just because the latter is a constant in your code, but because it would be a type-error).

Type declarations can be found in strong-typed programming languages; for example, an equivalent in C# would be:
Hero[] HEROES;

A: It is basic typescript declaration and initilaization. refer to this link for more details
https://www.typescriptlang.org/docs/handbook/basic-types.html

A: const HEROES: Hero[] = [
...
];

The : is a way to specify the type of a variable in TypeScript language, here HEROES is an Array of Hero instance.
This notation is called type annotation, refer this.


text:
Q: What happened to the Help->Index menu item in VS2010? I've been using VS2010RC and I really miss the old help system. Is it coming back in the release version? Is this the way help will be in VisualStudio for the foreseeable future?
I miss incremental search more than anything else. Although I also miss independent scrolling of the help table of contents and the help content.
I also must admit that I can never find it in the taskbar since it is now just one tab of many in my browser.

A: According to Brian Harry's blog, there's going to be an add-on to put the help > index command back in sometime after RTM: http://blogs.msdn.com/bharry/archive/2010/01/25/help-with-help.aspx (see item #5).
Brian has another post two days later talking about help and addressing some more feedback (I can't post a hyperlink because I'm a new user, but it should be relatively straightforward to find).


text:
Q: EJS res.render() returning a 500 server error after logging in I'm trying to build a simple RSVP app for my wedding, and I am starting to implement a login functionality to hide certain pages like the RSVP form for our invitees and the guest list page for me and my fiancee (admins).
I'm having issues when it comes to redirecting to the guest list page after authenticating the user.
I've tried rendering other pages that exist in my view, and they work. Even directly loading the guest-list page works. It's rendering it after logging in that doesn't.
http://localhost:3000/guest-list

Below is my form for logging in. I have a register page that I've verified correctly stores the username/password to my usersTable in mongodb
          <form action="/admin-login" method="post">

              Username
              <input type="username" class="form-control" name="username">

              Password
              <input type="password" class="form-control" name="password">

            <button type="submit" class="btn btn-dark">Login</button>
          </form>

And below is code in my app.js that handles the routing. The console.log() you see before the res.render() works as it should.
app.post("/admin-login", function(req,res){
  const username = req.body.username;
  const password = req.body.password;

  User.findOne({username: username}, function(err, foundUser){
    if(err){
      console.log(err);
    }
    else{
          if(foundUser){
            if(foundUser.password === password){
              console.log("user: " + foundUser.username);
              res.render("guest-list");
            }
          }
    }
  });
});

The expected result is that I should be redirected to the guest-list page. But I am getting a server 500 error and this message:
{"error":{"path":"C:\\My Websites\\rsvp-app\\views\\guest-list.ejs"}}

I'm registering the views for ejs like this:
app.set('view engine', 'ejs');


text:
Q: Trouble changing ruby version for sh I'm having a little trouble configuring ruby in OSX.
Under bash, all is well, version 2.3.1 is running, my gems are installed in 2.3.1, all hunky dory
But in sh, version 2.3.0 is running. I can't see where that is set, having looked in the profiles.
This is an issue because I'm using an application that opens up a bourne shell to do some work.. and the work involves ruby.
I tried 'rvm use' but I get an "rvm is not a function" message.
typing ~/.rvm/scripts/rvm doesn't help

A: Try installing via homebrew, after it installs it should show you how to symlink it to the system install.


text:
Q: unexpected result sorting list with mixed items tuples and lists tmp = [
    (1, 2, 3),
    (4, 5, 6),
    [7, 8, 9],
    [10, 11, 12],
]

print tmp
tmp.sort()
print tmp

results in:
[(1, 2, 3), (4, 5, 6), [7, 8, 9], [10, 11, 12]]
[[7, 8, 9], [10, 11, 12], (1, 2, 3), (4, 5, 6)]

Apparently lists get precedence over tuples.
Is this correct?

A: In Python 2,
In the documentation https://docs.python.org/2/reference/expressions.html#not-in,

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

But I believe it's implementation independent:

Objects of different types except numbers are ordered by their type
  names; objects of the same types that don't support proper comparison
  are ordered by their address.

In Python 3, this is fixed, so that comparing tuples and lists gives
TypeError: unorderable types: tuple() > list().


text:
Q: Efficient resource usage in TPL continuations I'm interested in efficiently using system resources in conjunction with the Task Parallel Library and continuations.
Consider the following scenario which uses the GetResponseAsync() extension method defined in another recent question.
WebRequest request = HttpWebRequest.Create(uri);
Task<WebResponse> responseTask = request.GetResponseAsync(cancellationToken);
Func<Task<WebResponse>, WebResponse> continuation =
    task =>
    {
        WebRequest followup = HttpWebRequest.Create(uri2);
        return followup.GetResponseAsync(cancellationToken).Result;
    };
Task<WebResponse> finalResultTask = responseTask.ContinueWith(continuation, cancellationToken);

There are multiple problems with this configuration, and I'm wondering how this can best be handled. The major items I've identified so far are:

*

*The execution of the core of responseTask efficiently uses resources by not blocking a user thread during the asynchronous execution. However, since the continuation is defined as a Func lambda, the thread executing the continuation will block on the return line until the execution of the follow-up request is complete. A better situation would provide continuation-like behavior while not blocking a user thread.

*The behavior of responseTask and finalResultTask differ in regards to cancellation. If operation is cancelled while responseTask is executing, responseTask will enter the state TaskStatus.Canceled. However, if the operation is canceled while finalResultTask is executing, the attempt to access the Result property will result in an exception, causing the task to enter the TaskStatus.Failed state.

*

*The behavior may also differ in regards to failure. If an AggregateException is thrown when attempting to access the Result property when returning from the continuation, then finalResultTask may have a doubly-wrapped true inner exception (I'm not sure if a special case occurs here), where the InnerException property of responseTask.Exception would provide direct access to the actual exception should it fail during the first task.

A: I suspect that both your problems would be resolved if you use the Unwrap extension method. Your goal is to return a new task as a result of your continuation function; however, since the continuation itself is executed as a task, this would lead to an extra level of nesting (task returning task). Thus, you need to eliminate this nesting using Unwrap, which will give you a proxy task that is bound to the result of the inner task.
WebRequest request = HttpWebRequest.Create(uri);
Task<WebResponse> responseTask = request.GetResponseAsync(cancellationToken);
Func<Task<WebResponse>, Task<WebResponse> continuation =
    task =>
    {
        WebRequest followup = HttpWebRequest.Create(uri2);
        return followup.GetResponseAsync(cancellationToken);
    };

Task<Task<WebResponse>> finalResultTask = responseTask.ContinueWith(continuation);
Task<WebResponse> proxyTask = finalResultTask.Unwrap();

Quick optimization: Since your continuation function does little other than spawn off a new task through GetResponseAsync, you can reduce its execution overhead by specifying it as ExecuteSynchronously:
Task<Task<WebResponse>> finalResultTask = responseTask.ContinueWith(continuation,
    TaskContinuationOptions.ExecuteSynchronously);

Edit: Per Servy's suggestion, you should pass your CancellationToken to your continuation function too:
Task<Task<WebResponse>> finalResultTask = responseTask.ContinueWith(continuation,
    cancellationToken,
    TaskContinuationOptions.ExecuteSynchronously,
    TaskScheduler.Current);


text:
Q: How to tell linux retrain and scan PCIe bus? We have an embedded board that has an iMX8M-Plus Processor and Linux v5.4.161. This board has one PCIe bus and that one is connected to an FPGA. When we power up the board, the FPGA is not yet configured, so it acts as if it was not on the PCIe bus.
Once the Linux is fully booted, we configure the FPGA and only after that it starts acting as a PCIe endpoint (device).
At this point, when I run lspci -> it returns nothing.
When I first execute echo "1" > /sys/bus/pci/rescan as suggested here and here and then lspci, I still get nothing.
But if I reboot the linux without reseting the FPGA, it starts being visible in the lspci list. Rebooting the linux is not an option for us. Somehow I need to tell the linux that whatever it's doing at the boot time, please do it again at runtime. But I couldn't find a solution for this so far.
According to the Texas Instrument support forum, they said if the PCIe link is not trained at the boot time, rescan command never works.
At the boot time, while linux loads a pci driver, it tries to establish a PCIe link, I can see that with an oscilloscope, PERST pin is asserted and PCIE_CLK generated for a while and then stops if it can not detect any device. But the rescan command never does that.
Also in the system there is no pcie device to executeecho 1 > $pcidevice/remove in order to make rescan functional. Or there is no device or bus to set power off and on back like echo 0 > /sys/bus/pci/slots/.../power
I also learned that there was a method in old linux times (v2.6) called adding a Fake PCIe Device which physically doesn't exist to solve this problem. For that I took the fakephp.c driver from an old linux repo and ported it to ours. After solving a couple of deprecated function problems, it is compiled for Linux Kernel v5.4. modprobe fakephp worked and driver loaded but somehow I didn't get this fake device in my device list. Here it is mentioned that the fakephp driver was removed from mainstream linux since PCI core has similar functionality, but he never mentioned how.
Short of the story is that, I am stuck here, I need my FPGA to be visible in the lspci list without restarting the linux.

A: I recommend configuring the FPGA in u-boot to get away from these kinds of problems. Connect up SPI pins to FPGA's config pins & run it in Slave configuration mode.


text:
Q: mesh - Matrix dimensions must agree In matlab:
X = ones(10,10);
mesh(X,X,X);

gives:
Warning: Matrix dimensions must agree, not rendering mesh

All three parameters are exactly the same, but their dimensions do not agree? Agree to what? What is the problem? Thank you for your time & any help.

A: Restarting matlab solved the problem.


text:
Q: Chrome shifting divs downwards? I'm having some CSS issues that seem to only occur in chrome. The site in question is liveinthelead.com, and it's still being worked on so if you notice any other strange problems feel free to let me know, I won't be offended. My main problem is this though:
In all of the browsers I've tested except for chrome the site looks fine. However, in chrome, on the main page, the middle post in the three-post divs are shifted down about 20px. But when I open up the developer interface, they shift back to where they're supposed to be! Maybe it's just a local problem, but here are some pictures of what I'm talking about. If you don't experience the same issue then maybe it's just something weird going on with my computer. Cheers.
When I initially load the page
After I open the developer console

A: I'm unable to replicate on Chrome 15.
=\ could be a good thing! Try another computer!

A: One thing that I noticed is that in your div#three-post you set float:left to div.member1 but not to the remaining div.member2 or div.member3.
That's where I would start investigating the problem. Maybe you should set the remaining two divs to also float left. You may need to clear them afterwards too.
For the sake of convention — and so that you don't encounter this confusions again — use IDs for selecting specific elements, e.g., member1, member2, member3, and use classes for selecting multiple elements that should share the same attributes.


text:
Q: sqlite random file is encrypted or is not a database I have an application that frequently accesses a sqlite database.  It works great most of the time but occasionally in one of my database functions fails and returns:

file is encrypted or is not a database

I don't have any encryption enabled but I can't pinpoint how this is happening.  It's not consistently reproducible and from the crash logs, it happens on the main thread.
Thanks in advance.
@synchronized(self) {
    sqlite3 *database = mydb;
    int result = 0;

    static sqlite3_stmt *stmt = nil;
    if (stmt == nil) {
        const char *sql = "select sum(not isAvailable) from table1 e inner join table2 f on e.key=f.pk where f.pk=? AND e.isDeleting=0;";
        if (sqlite3_prepare_v2(database, sql, -1, &stmt, NULL) != SQLITE_OK) {
            NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        }
    }

    sqlite3_bind_int(stmt, 1, obj.primaryKey);

    if (sqlite3_step(stmt) == SQLITE_ROW) {
        int val = sqlite3_column_int(stmt, 0);
        result = val;
    } else {
        [NSException raise:@"SQL Fail" format:@"SQL Failed: %s", sqlite3_errmsg(database)];
    }
    // Reset the statement for future reuse.
    sqlite3_reset(stmt);

    return result;
}

A: To create a new encrypted SQLite database or to open an existing encrypted SQLite database you have to call the function sqlite3_key or to execute a "pragma key=" command immediately after opening the database before performing any other database operation.
I suspect that you tried to open an existing database, but not encrypted SQLite database and expected to encrypt it by using one of the above methods. This doesn't work but results in the error message you experienced.
To encrypt an existing not encrypted SQLite database you have to use function sqlite3_rekey or "pragma rekey=" command.
To change the encryption key of an existing encrypted SQLite database you have to open the database, then to use sqlite3_key (or "pragma key=") and then to apply sqlite3_rekey (or "pragma rekey=").

A: The error occurs when the DB file somehow becomes garbled.  Exactly why this might occur, though, is a bit of a puzzle.
If you are writing other files in your app, you may have accidentally overwritten the DB file.  And if you were to open the same DB file twice or do two "simultaneous" operations on the DB you might be able to create this scenario (but I think that most versions of SQLite are compiled with the code to detect this and error out if there's a conflict).  (Question:  Do you ever get the "database is locked" error instead?)

A: As unhelpful as the "version mismatch" advice often is, I was experiencing the same symptoms and found that the problem was fixed by updating the database from version 2 to 3.  Maybe one of the reasons this problem occurs is that the file extension for the database doesn't necessarily correctly reflect the real version number.
I could be mistaken, but when I created my first SQLite database using SQLite Administrator version 0.8.3.2 and accepted the default "Save as type" of SQLite3 DB, the file it created was apparently a version 2 DB despite having a .s3db name.  Under the Databases menu, the item "Migrate to SQLite3" was enabled but I figured this was a mistake in the GUI.  However, after employing that feature, my problem disappeared.
Subsequent use of the Database|New option in SQLite Administrator creates a DB of the version I choose, and the file-extension matches the convention for that version.  The erroneous behavior of SQL Administrator only occurred the first time I used the Database|New option.

A: I had this same problem today.
It turned out to be that, I was creating a column called Time in my database. Changed that to TimeStamp and it worked. I thought that somehow my file had been corrupt so i was looking at the sql code to generate the table (to redo it on a new file) when i noticed "Time" highlighted in blue indicating it was a reserved word.


text:
Q: Form validation using javascript, validates only the first field even though it should be validating both I have a simple form which is echoed using php:
echo '<form action="" method="POST" name="newTicket" onsubmit="return validateForm(this)">

Full name*:<input type="text" style="width:50%" name="ticket_user_fullname" placeholder="Full name..." >

Email address*:<input type="text" style="width:50%" name="ticket_user_email" placeholder="user@domain.com..." >

<input class="btn" type="submit" name="submit" value="submit" >

</form>';

The form calls the validateForm function correctly. This is the validateForm function and the relating functions:
function validateForm(form){

var reason = "";

reason += validateFullname(form.ticket_user_fullname);
reason += validateEmail(form.ticket_user_email);

  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }
  return true;
}

function validateFullname(ticket_user_fullname)
{
error = "";
var re = /^[a-zA-Z ]*$/;

if(ticket_user_fullname.value == "" || ticket_user_fullname.value == null) {
    error = "Full name must not be empty. \n";
    ticket_user_fullname.style.border="1px solid red";
}else if(!re.test(ticket_user_fullname.value)){
    error = "Your name cannot contain numbers or special characters. \n"
    ticket_user_fullname.style.border="1px solid red";
}else{
form.ticket_user_fullname.style.border="1px solid #cccccc";
}

return error;
}

function validateEmail(ticket_user_email)
{
error = "";
var re = /\S+@\S+\.\S+/;

if(ticket_user_email.value == "" || ticket_user_email.value == null) {
    error = "Email must not be empty. \n";
    ticket_user_email.style.border="1px solid red";
}else if(!re.test(ticket_user_email.value)){
    error = "Your email must be in the format: user@domain.com. \n"
}else{
ticket_user_email.style.border="1px solid #cccccc";
}

return error;
}

The form is validated correctly when nothing is entered into the full name field, or when there is a number entered into the full name field. When there is a correct string input, it ignores the validation on the rest of the form and the form is submitted.
what should happen is all data in all of the fields should be correct before submission.

A: In your function validateFullname(ticket_user_fullname)
form.ticket_user_fullname.style.border="1px solid #cccccc";
It should be ticket_user_fullname.style.border="1px solid #cccccc";
Some error should be made in your form.